diff --git a/.github/workflows/label.yml b/.github/workflows/label.yml new file mode 100644 index 000000000..7c724a62a --- /dev/null +++ b/.github/workflows/label.yml @@ -0,0 +1,19 @@ +# This workflow will triage pull requests and apply a label based on the +# paths that are modified in the pull request. +# +# To use this workflow, you will need to set up a .github/labeler.yml +# file with configuration. For more information, see: +# https://github.com/actions/labeler + +name: Labeler +on: [pull_request] + +jobs: + label: + + runs-on: ubuntu-latest + + steps: + - uses: actions/labeler@v2 + with: + repo-token: "${{ secrets.GITHUB_TOKEN }}" diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml new file mode 100644 index 000000000..bae69483d --- /dev/null +++ b/.github/workflows/php.yml @@ -0,0 +1,37 @@ +name: PHP Composer + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + + - name: Validate composer.json and composer.lock + run: composer validate + + - name: Cache Composer packages + id: composer-cache + uses: actions/cache@v2.1.1 + with: + path: vendor + key: ${{ runner.os }}-php-${{ hashFiles('**composer.lock') }} + restore-keys: | + ${{ runner.os }}-php- + + - name: Install dependencies + if: steps.composer-cache.outputs.cache-hit != 'true' + run: composer install --prefer-dist --no-progress --no-suggest + + # Add a test script to composer.json, for instance: "test": "vendor/bin/phpunit" + # Docs: https://getcomposer.org/doc/articles/scripts.md + + # - name: Run test suite + # run: composer run-script test diff --git a/.gitignore b/.gitignore index b8ffd50ed..853f48f82 100644 --- a/.gitignore +++ b/.gitignore @@ -9,8 +9,9 @@ src/bb-config* src/bb-data/log/* src/bb-data/cache/* src/bb-data/tmp.txt -src/bb-vendor src/bb-test.php +src/bb-vendor/* +bb-test.php build composer.phar public @@ -24,4 +25,4 @@ puphpet/files/dot/ssh/* ### node_moduels ### node_modules npm-debug.log -.history/ \ No newline at end of file +.history/ diff --git a/README.md b/README.md index 407d16432..739e4c473 100644 --- a/README.md +++ b/README.md @@ -7,8 +7,11 @@ Open Source billing software Requirements ================================================================================ -* PHP 7.2 -* Linux Operating System (64-bit) | Does not support Windows Operating Systems. +* PHP 7.4.9 (cli) (built: Aug 7 2020 14:29:36) ( NTS ) +Copyright (c) The PHP Group +Zend Engine v3.4.0, Copyright (c) Zend Technologies + with Zend OPcache v7.4.9, Copyright (c), by Zend Technologies +* Ubuntu Codename:bionic (x86_64) Release:18.04| Does not support Windows Operating Systems. * PHP extensions: * openssl * curl @@ -20,7 +23,7 @@ Requirements Recommended ================================================================================ -* PHP 7.2 +* PHP 7.4.9 * CentOS 64-bit Operating System * PHP Extensions * openssl @@ -48,8 +51,8 @@ Contributing Roadmap ================================================================================ -* [ ] Support latest PHP version 7.3 -* [ ] Add support for composer package manager +* [*] Support latest PHP version 7.3 +* [*] Add support for composer package manager Using Vagrant ================================================================================ diff --git a/src/.gitignore b/src/.gitignore new file mode 100644 index 000000000..c37ea55cd --- /dev/null +++ b/src/.gitignore @@ -0,0 +1,27 @@ +.idea +._* +.DS_Store +.vagrant* +tmp +src/.htaccess +src/bb-config* +!src/bb-config-sample.php +src/bb-data/log/* +src/bb-data/cache/* +src/bb-data/tmp.txt +src/bb-test.php +src/bb-vendor/ +build +composer.phar +public +report/* + +### Vagrant & puphpet ### +.vagrant/ +puphpet/files/dot/ssh/* +!puphpet/files/dot/ssh/insecure_private_key + +### node_moduels ### +node_modules +npm-debug.log +.history/ diff --git a/src/.travis.yml b/src/.travis.yml new file mode 100644 index 000000000..af93b7631 --- /dev/null +++ b/src/.travis.yml @@ -0,0 +1,62 @@ +# http://docs.travis-ci.com/user/build-configuration/ + +language: php + +dist: trusty + +php: + - 5.4 + - 5.5 + - 5.6 + - 7.0 + - 7.1 + - 7.2 + +matrix: + allow_failures: + - php: 7.0 + - php: 7.1 + - php: 7.2 + +sudo: false + +install: + - ant + - composer self-update + - composer require --dev phpunit/phpunit ^6.0 php-coveralls/php-coveralls ^2.1 + - composer install --dev + +before_script: + - mysql --user=root -e "CREATE USER 'foo'@'localhost' IDENTIFIED BY 'foo';" + - mysql --user=root -e "GRANT ALL PRIVILEGES ON *.* TO 'foo'@'localhost'" + - mysql -e 'create database IF NOT EXISTS boxbilling' + - mysql -D boxbilling < src/install/structure.sql + - mysql -D boxbilling < src/install/content.sql + - mv ./src/bb-config-sample.php ./src/bb-config.php + +script: + - ./vendor/bin/phpunit --coverage-clover ./tests/logs/clover.xml + +after_script: + - php vendor/bin/coveralls -v + +notifications: + email: false + slack: boxbilling:vsdKszFU9Pm308ye5rNSpr8n + +before_deploy: + - npm install -g grunt-cli + - npm install + - grunt + - ant release + +deploy: + provider: releases + api-key: + secure: tVzZ+3U0ndBGvoUpFqA6ikg6fDKnPgMoNqK1pvTdEp0xmrFtjMP/fuc8+awObhj89iEC+MyzfsOP57CZbHR/UjmUSHPQew+BvTwxYmTUzgUeyUrYsTEI7WJgB7tsL35aRgrpxk102tlSmlX7EonufUT0svPOAQ1p4NgZRm3GI3A= + file: ./build/distribution/BoxBilling.zip + skip_cleanup: true + on: + tags: true + all_branches: true + php: 5.6 diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md new file mode 100644 index 000000000..a92a7265d --- /dev/null +++ b/src/CHANGELOG.md @@ -0,0 +1,405 @@ +Release 4.19 +------------------------------------------------------------------------------ +* Cron job memory optimizations +* Remove convertToModels() function as it uses too much RAM +* Fixed issue with custom fields of client +* Forum search fix +* Product and admin area icons will be using absolute path in order to avoid issues when BoxBilling installed in subfolder +* Domain privacy button issue fixed +* Various bug fixes and improvements + +Release 4.18 +------------------------------------------------------------------------------ +* Select TLDs for free domain registration on shared hosting product +* Add grunt task runner for developers (creates minified js and css files in admin_default theme) +* Updated Stripe payment gateway; +* Updated Serviceboxbillinglicense module; +* Improved batch paid invoice activation process; +* Updated 2checkout payment adapter; +* Domain transfer option added to `huraga` theme #327 +* Updated Paypal payment gateway to avoid 403 forbidden error on IPN request +* Added phone code filter; +* Various bug fixes and improvements + +Release 4.17 +------------------------------------------------------------------------------ +* Added Stripe payment adapter +* Send email notification to helpdesk email address (created new mod_support_helpdesk_ticket_open email template) +* Added `Cookieconsent` extension for displaying notification about cookies which is required by EU cookie law +* Updated Plesk server manager to Plesk 12 +* Updated mod_email_queue and queue tables columns. Removed MySql reserved words. +* Updated domain product type startingFromPrice value calculation. +* Updated SolusVM module +* Updated Ispconfig3 server manager +* Implemented license collision protection +* Updated ResellerClub and all of it's derived registrars to cope with changed authentication logic (from now on only API key is supported) +* Various bug fixes and improvements + +Release 4.16 +------------------------------------------------------------------------------ +* Compatibility with MySQL 5.6 Datetime values updated to meet MySQL STRICT_TRANS_TABLES mode rules. +* Fixed add funds issue when admin marked invoice as paid. +* Invoices can be downloaded as PDF in boxbilling theme +* Added language picker for client in huraga theme +* Updated translations: + * merged admin.po into messages.po + * added language selector in admin area +* Bluepay payment adapter no longer supported. Adapter file moved to boxbilling/extensions repository +* Added direct link to "support ticket message" +* Added new gateway - Pay with Client Balance. +* Implemented Google Recaptcha v2 - Tough on bots Easy on humans +* BoxBilling API improvements +* Updated orderbutton popup style in mobile view +* Seo module updates +* Users must verify theirs emails after email confirmations setting is enabled +* Compatibility with PHP7 +* Generate VAT rules for each EU country according to it's standart rate +* Various bug fixes and improvements + +Release 4.15 (2015-02-19) +------------------------------------------------------------------------------ +* New module: + * paidsupport +* Module orderbutton javascript code improvements +* ResellerClub adapter supports API-KEY as authorization option. +* Fix admin area prefix issue. +* Added getEuVat() method which returns standard tax rate for each EU country +* Tax rules edit option added +* Notification message shown when email confirmed. +* Tax rules can be generated automatically for all EU countries +* Fix UTF-8 currency symbols issue in PDF and print invoice view. +* Fixed onAfterGuestPublicTicketReply and onAfterGuestPublicTicketOpen hooks. Incorrect public ticket subject was sent to staff members. +* Added option to approve client email for admin +* DotTk registrar adapter is not supported. +* Initiate translation DI object after bb-di is included +* Spamchecker module updated +* When removing product from cart it's addons will remove automatically +* Missing email queue table after upgrade fixed +* admin/currency/get API call returns array +* Admin can generate invoice PDF from admin area +* Scheduled tasks fix +* Spyc package moved to composer +* Countries list updated +* Missing `mod_cron_check` file fixed for custom templates +* Various bug fixes and improvements + +Release 4.14 (2015-02-03) +------------------------------------------------------------------------------ + +* New event hook: + * onBeforeThemeSettingsSave +* New API(client) calls: + * invoice_get_tax_rate + * client_is_taxable + * client_balance_get_total +* Taxes are shown in the cart checkout summary +* Email templates are generated after install +* Footer links fix for Huraga theme +* Only one coupon code name can be created and used; +* Fixed CKEditor issue with canned responses +* Custom payment gateway render error fixed +* Fixed Centova Cast module +* Password hash in email resolved +* Orderbutton module popup improved +* Client email confirmation logic updated +* Variables in email templates list fixed +* Generating email templates just after installing of BoxBilling +* Allow only text in Notification module messages +* Fixed constantly regenerating invoices issue +* Add funds logic updated +* Settings of footer links updated +* Security and performance fixes and updates + +Release 4.13 (2015-01-15) +------------------------------------------------------------------------------ + +* Vagrant configuration added +* Interkassa payment adapter updated to v2 +* Interlaced images support added to invoice pdf +* Fixed email template rendering +* Web cron removed +* Fixed file manager module. +* Fixed date format in emails +* Added button to remove item from cart popup +* tag added for news/blog posts +* WebMoney payment adapter updated +* Ability to set how many hours user needs to wait until consequent support ticket submission +* Added search in canned responses +* Code improvements and optimisations +* YouHosting module rewritten to work with open source version +* Translation implementation reworked. +* Bug fixes + + +Release 4.12 (2014-12-02) +------------------------------------------------------------------------------ + +* Client password hashing updated (php password_* functions are being used) +* Added mass delete functionality in admin area +* Ability to set promotional code for client groups +* Ability for administrator to edit order config +* ResellerClub adapter updated +* Pagination fixed +* Bug fixes + +Release 4.11.3 (2014-11-03) +------------------------------------------------------------------------------ + +* BoxBilling going open source +* Removed Doctrine in favor of RedBean and PDO +* URL changes. Now urls are index.php?_url=/slug instead of index.php/slug +* Bug fixes +* Requires PHP >5.3 +* Changed modules logic + +Release 3.3.20 (2013-03-20) +------------------------------------------------------------------------------ + +* Service license unable to order if not configured issue fix +* Select first payment option for cart checkout as default +* IDR currency rate update fix +* PayPal IPN fix. Was not able to add amount to balance if currency was not USD + +Release 2.12.5 (2012-12-05) +------------------------------------------------------------------------------ + +* Fixes issue when domain order is activated for 2 years instead of 1 +* Approved invoice issue fix on Windows servers +* Show transactions list for client +* Enable multisite support by determining hostname and config file +* Do not show payment gateway select box if cart total is 0 + +Release 2.11.28 (2012-11-28) +------------------------------------------------------------------------------ + +* All modules settings moved to global settings page +* Ability to edit countries list in system settings page +* YouHosting API support. Now you can sell YouHosting services with BoxBilling +* BoxBilling theme can now have settings page. Settings are globally available in client area theme +* New theme filters: + * asset_url - {{ 'style.css' | asset_url | stylesheet_tag }} + * img_tag - {{ company.logo_url | img_tag }} + * script_tag - {{ 'jquery.min.js' | asset_url | script_tag }} + * stylesheet_tag - {{ 'style.css' | asset_url | stylesheet_tag }} + * money - {{ '40' | money }} + * money_without_currency - {{ '40' | money_without_currency }} + * money_convert - {{ '40' | money_convert }} + * money_convert_without_currency - {{ '40' | money_convert_without_currency }} +* Updating Twig to 1.10.3 +* Cron option: Enable web based cron. This method requires that site has visitors and special theme tag support +* Major admin area theme update. Using fluid layout. Added breadcrumbs +* News module updates +* Ability to change payment gateway in invoice payment page +* Immediately redirect to payment gateway after checkout if payment gateway was selected +* Defautl theme update: Show client login/signup form before checkout button in shopping cart +* Search can be made by order meta keys +* Added new database table *client_order_meta* to store custom order data +* new statistic method to get number of sales by country +* new statistic method to get number of clients in country +* Do not use ajax when loading statistics in admin dashboard +* Show Last month statistics in dashboard +* Render mod_page_login.phtml instead of mod_client_login.phtml template if template exists +* Allow create any template mod_client_*.phtml to be accessed by client only +* Added redirects module. Usefull to redirect deprecated URLs to new ones +* Simplified payment gateway logic. Now it is a simple file, no need to extend any class. +* New event hooks: + * onBeforeAdminExtensionConfigSave + * onAfterAdminExtensionConfigSave + * onBeforeProductAddedToCart + * onAfterProductAddedToCart +* Removed hostinger branding +* Option to enable/disable ability for client to change his email +* Ability to require email confirmation in welcome email +* Ability to define required fields for client registration form +* Ability to disable new client registrations +* Invoices are not generated for 0 amount orders +* Performance and multiple bug fixes + +Release 2.9.14 (2012-09-14) +------------------------------------------------------------------------------ + +* Added new field for service license - checked_at +* Support tickets canned responses are grouped +* Support settings option: auto responder and delay message +* Preview ticket notes in tickets listing page +* Ticket page updates in admin area +* Ability to generate email templates for enabled extensions before first event occurrence +* Ability to define which IPs are allowed to login to admin area +* Redesigned settings page. All configurable extensions are listed in this page. +* Simplified payment gateway adapters transaction processing logic. + Now you can use API inside payment gateway method **processTransaction** + Requires new parameter (new_transaction_process_logic) to be added to settings table to enable this option +* Option to skip calling event hook in order suspend and cancel actions + +Release 2.9.10 (2012-09-10) +------------------------------------------------------------------------------ + +* Search clients by company name in clients listing page +* Ability to define staff member permissions +* New parameter in bb-config.php file BB_LOCALE_TIME_FORMAT - to define localized time format +* Add: New filter to display translatable date with time: bb_datetime +* Update: Search clients by company name in clients listing page +* Fix: Use PDO::MYSQL_ATTR_USE_BUFFERED_QUERY for PDO connection +* Fix: Order created from admin area do not match clients currency +* Update: If order total after discount is 0 and product activation is set to after payment, activate order after checkout +* Fix: Show total amount in print invoice page +* Update: onAfterAdminClientPasswordChange receives password parameter +* If order total after discount is 0 and product activation is set to after payment, activate order after checkout +* Simplified installer app. Now works smoothly with nginx +* Admin navigation is displayed according to staff member permissions +* Currency converter in currency management page +* No country detected flag fix +* Print invoice total issue fix +* Do not show help desks grouping in admin area support tickets listing +* Forums has new attribute - category +* Forum messages can now be rated with points +* RedBean update to 3.2.3 + +Release 2.8.2 (2012-08-02) +------------------------------------------------------------------------------ + +* Email template subject not updating fix +* Ability to import existing hosting accounts without activation from admin area +* Ability to automatically setup EU VAT rules from admin area +* Invoice not marked as paid if client balance is equal to amount of invoice +* Admin area client listing update. Shows clients country. +* Added Queue manager. Gives ability to execute long running tasks in background +* Added Mass mailer tool to send email to filtered list of clients. +* Added Centova cast module to sell shout cast servers. +* Added file editor to edit any file on BoxBilling. +* Show Admin API key in admin profile +* New fields in client profile: referred_by, company_vat, company_number, type +* New fields for invoice: seller_company_vat, seller_company_number, buyer_phone_cc, buyer_company_vat, buyer_company_number, text_1, text_2 +* Added Tanzania to country list +* Transfer code is not mandatory in domain order form +* Country flag is visible in admin area clients listing page +* Added country translations to default locale pot + +Release 2.7.4 (2012-07-04) +------------------------------------------------------------------------------ + +* Update script issue fix when did not update from 2.4.30 +* Payza payment gateway +* Bug fix when shopping cart did not generate subscribable invoices +* 2Checkout gateway updates +* Does not list hidden products by default in guest/product/get_list call +* Ability to remove order with addons. + +Release 2.7.2 (2012-07-02) +------------------------------------------------------------------------------ + +* Pass hosting account password to email template as variable +* Whm server manager updates +* Set default currency if clients currency is not defined when preparing invoice for client +* Ability to call custom event hook on invoice item activation. New invoice item type - hook_call +* Parameter **execute** in admin/invoice/mark_as_paid now can activate related services immediately +* Order renewal logic parameter. Can select how renewal date is calculated +* added new field in client database to define authorization type +* admin/client/create password is not mandatory +* admin/client/get can now find client by email +* Invoices duplicate listing issue fix +* Added Akismet checking for forum posts in spamChecker module +* Support for php-gettext if gettext extension is not installed on server. +* AliPay payment gateway updates +* Added Thank You page. Clients can be redirected after payment instead of invoice. + +Release 2.6.22 (2012-06-22) +------------------------------------------------------------------------------ + +* Invoice tax calculation bug fix +* Whm/Cpanel invalid body response issue updates +* Fixed order event hooks +* Can not create currency issue fix. Change currency price format from %price% to {{price}}. Solving an for servers where mod_security is enabled. +* Fix for issue: Email templates are cached and does not auto refresh if BB_DEBUG mode is false +* Add message to notification center after client makes post to forum topic. Notification center extension must be enabled. + +Release 2.6.17 (2012-06-17) +------------------------------------------------------------------------------ + +* New SolusVM VPS product type. Ability to import clients and existing servers from SolusVM master server. Full control from admin and client area. +* New product type BoxBiling license. Ability to sell BoxBilling licenses from any BoxBilling installation. Enable +* Email templates are generated on first event occurrence. Until then it can not be managed. +* Ability to filter orders by invoice option: issue invoice manually or automatically. +* Ability to preview email templates. Old email templates are deprecated. +* Ability to place new order for clients from admin area +* Ability to change currency price format +* Deprecated bb-library/Hook bindings. Now event hooks are binded from modules Service.php class +* php mcrypt extension is now mandatory +* Email settings are now stored in encrypted format +* Added ability to reset email template to default +* Moved email sending settings from *general settings* to *email templates* menu +* New dashboard widget to show active orders count grouped by products +* Updated Twig to 1.8.2 version +* Added ability to disable/enable automatic invoice issuing for orders +* SpamChecker is a module. Google recapthca and stopforumspam.com database checks can be simply enabled or disabled as any other module +* All extensions can call other extension event hooks +* All extensions can hook into cron job event +* Added new API methods **extension_config_get** and **extension_config_save** to store encrypted extension configuration data +* Admin layout contains more blocks. Gives more freedom for extensions developers. +* Admin area dashboard statistics links now filters data for today and yesterday +* Ability to load custom listing template file for order index page +* Check if template file exists function for guest API guest.system_template_exists({"file":"mod_index_dashboard.phtml"}) +* Ability to create admin account if none exists from admin area interface instead of login form. +* Default sort order for new products +* Products grouped by type can now be ordered on *slider* type form +* Bug fix when installed in subfolder named same as one of the modules +* Client profile management page updates - split to sections +* Adding dotTk domain registrar to official version +* Adding Interkassa payment gateway +* Email registrar bug fixes +* Internetbs registrar bug fixes +* Ability to create custom products. These products can now be enabled and disabled as an extension +* Added loader spinner to admin area login form +* Added weekly pricing option for products +* Currency rate is saved in invoice on payment event +* Google Recaptcha now uses https +* Ability to add/remove forum topic to favorites +* Ability to subscribe/unsubscribe to forum message notifications +* Adding new field to extensions meta table - client_id + +Release v2.4.30 (2012-04-30) +------------------------------------------------------------------------------ + +* Fixed bug when admin was not able to update order creation date in admin area +* Promo code can be recurrent or applied to first order only +* Promo code validation once per client +* PayPal gateway validates non latin characters IPNs correctly +* Ability to change how many times promo code was used +* Added ability for admin to issue new invoice for order +* Setup price promo code issue fix. +* More translations made available +* Show ticket notes counter in list and ticket +* Order renewal invoice due date is same a order expiration date +* Added version param to js and css files to avoid clear cache on update +* https links updates +* https://github.com/boxbilling/BoxBilling/issues/115 fix +* Password issue fix: https://github.com/boxbilling/BoxBilling/issues/114 +* Including http://redbeanphp.com/ ORM in bb-library/rb.php For extensions as a helper +* Simplifie nginx server support. Routing includes only 2 simple rules +* Adding new core module mod_api. Api is now accessible from yourdomain.com/api/role/module/method. bb-api is deprecated and will be removed in 2.6 version +* Gravatar url uses ssl if BoxBilling is on https +* Selectable refunds logic: generate refund invoice with paid invoice numbering or generate credit note +* New invoice status: "canceled". Invoice with canceled status are not counted into income. +* Invoice mark as paid with credits fix. +* Show task status and charge icons for invoice items for approved invoices +* Ability to remove clients balance +* Adding exception to PayPal gateway for HUF currency. +* Ability to install module from extensions site +* Ability to filter invoices by paid_at date in url param +* Adding config field for license service for more possibilities +* https://github.com/boxbilling/BoxBilling/issues/113 update +* Mail issue fix when port number was not recognized +* Stats module update: Income is counted on paid_at date not created_at date +* onBeforeClientProfileUpdate Event updates. Now receives currently logged in client data. +* Invoice API returns more information +* Display currency selector only if more than one currency is available +* Hosting account password is generated on order activation action +* Removing favicon to avoid overwriting on update +* Added zip code management to invoice client credentials +* Whm/Cpanel server manager update. Do not try to exceute command again if response failed +* Translations fix +* Typo fix in order management page +* WebToPay payment adapter updates +* Admin area dashboard updates. Clickable titles. +* Adding missing email templates for closing ticket event +* Client area popup close button style fix diff --git a/src/CODE_OF_CONDUCT.md b/src/CODE_OF_CONDUCT.md new file mode 100644 index 000000000..daefff88e --- /dev/null +++ b/src/CODE_OF_CONDUCT.md @@ -0,0 +1,46 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [info@boxbilling.com](mailto:info@boxbilling.com). All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [https://contributor-covenant.org/version/1/4][version] + +[homepage]: https://contributor-covenant.org +[version]: https://contributor-covenant.org/version/1/4/ diff --git a/src/bb-config-heroku.php b/src/bb-config-heroku.php deleted file mode 100755 index a37ba81d7..000000000 --- a/src/bb-config-heroku.php +++ /dev/null @@ -1,118 +0,0 @@ - getenv('BB_LICENSE'), - - 'salt' => getenv('BB_SALT'), - - /** - * Full URL where BoxBilling is installed with trailing slash - */ - 'url' => getenv('BB_URL'), - - 'admin_area_prefix' => '/bb-admin', - - /** - * Enable or Disable the display of notices - */ - 'debug' => getenv('BB_DEBUG'), - - /** - * Enable or Disable search engine friendly urls. - * Configure .htaccess file before enabling this feature - * Set to TRUE if using nginx - */ - 'sef_urls' => getenv('BB_SEF_URLS'), - - /** - * Application timezone - */ - 'timezone' => 'UTC', - - /** - * Set BoxBilling locale - */ - 'locale' => 'en_US', - - /** - * Set default date format for localized strings - * Format information: http://php.net/manual/en/function.strftime.php - */ - 'locale_date_format' => '%A, %d %B %G', - - /** - * Set default time format for localized strings - * Format information: http://php.net/manual/en/function.strftime.php - */ - 'locale_time_format' => ' %T', - - /** - * Set location to store sensitive data - */ - 'path_data' => dirname(__FILE__) . '/bb-data', - - 'path_logs' => dirname(__FILE__) . '/bb-data/log/application.log', - - 'log_to_db' => true, - - 'db' => array( - /** - * Database type. Don't change this if in doubt. - */ - 'type' =>getenv('BB_DB_TYPE'), - - /** - * Database hostname. Don't change this if in doubt. - */ - 'host' => getenv('BB_DB_HOST'), - - /** - * The name of the database for BoxBilling - */ - 'name' =>getenv('BB_DB_NAME'), - - /** - * Database username - */ - 'user' =>getenv('BB_DB_USER'), - - /** - * Database password - */ - 'password' =>getenv('BB_DB_PASSWORD'), - ), - - 'twig' => array( - 'debug' => false, - 'auto_reload' => false, - 'cache' => dirname(__FILE__) . '/bb-data/cache', - ), - - 'api' => array( - // all requests made to API must have referrer request header with the same url as BoxBilling installation - 'require_referrer_header' => false, - - // empty array will allow all IPs to access API - 'allowed_ips' => array(), - - // Time span for limit in seconds - 'rate_span' => 60 * 60, - - // How many requests allowed per time span - 'rate_limit' => 1000, - ), -); diff --git a/src/bb-library/Box/Log.php b/src/bb-library/Box/Log.php index 2c8f9f7a2..8ec2fffcb 100644 --- a/src/bb-library/Box/Log.php +++ b/src/bb-library/Box/Log.php @@ -120,6 +120,7 @@ class Box_Log } //do not log debug level messages if debug is OFF + if($this->di['config']['debug'] === FALSE && $event['priority'] > self::INFO) { return ; } @@ -162,4 +163,4 @@ class Box_Log $this->_min_priority = $priority; return $this; } -} \ No newline at end of file +} diff --git a/src/bb-library/FAQ.htm b/src/bb-library/FAQ.htm new file mode 100644 index 000000000..cb2c3d315 --- /dev/null +++ b/src/bb-library/FAQ.htm @@ -0,0 +1,272 @@ + + + + +FAQ + + + + +

FAQ

+ + + + + diff --git a/src/bb-library/PDF_ImageAlpha.php b/src/bb-library/PDF_ImageAlpha.php deleted file mode 100644 index 62dada8c6..000000000 --- a/src/bb-library/PDF_ImageAlpha.php +++ /dev/null @@ -1,269 +0,0 @@ -images[$file])) { - //First use of image, get info - if ($type == '') { - $pos = strrpos($file, '.'); - if (!$pos) - $this->Error('Image file has no extension and no type was specified: ' . $file); - $type = substr($file, $pos + 1); - } - $type = strtolower($type); - if ($type == 'jpg' || $type == 'jpeg') - $info = $this->_parsejpg($file); - elseif ($type == 'png') { - $info = $this->_parsepng($file); - if ($info == 'alpha') return $this->ImagePngWithAlpha($file, $x, $y, $w, $h, $link); - } else { - //Allow for additional formats - $mtd = '_parse' . $type; - if (!method_exists($this, $mtd)) - $this->Error('Unsupported image type: ' . $type); - $info = $this->$mtd($file); - } - - if ($isMask) { - $info['cs'] = "DeviceGray"; // try to force grayscale (instead of indexed) - } - $info['i'] = count($this->images) + 1; - if ($maskImg > 0) $info['masked'] = $maskImg;### - $this->images[$file] = $info; - } else - $info = $this->images[$file]; - //Automatic width and height calculation if needed - if ($w == 0 && $h == 0) { - //Put image at 72 dpi - $w = $info['w'] / $this->k; - $h = $info['h'] / $this->k; - } - if ($w == 0) - $w = $h * $info['w'] / $info['h']; - if ($h == 0) - $h = $w * $info['h'] / $info['w']; - - // embed hidden, ouside the canvas - if ((float)$this->PDFVersion >= 1.7) { - if ($isMask) $x = ($this->CurOrientation == 'P' ? $this->CurPageSize[0] : $this->CurPageSize[1]) + 10; - } else { - if ($isMask) $x = ($this->CurOrientation == 'P' ? $this->CurPageSize[0] : $this->CurPageSize[1]) + 10; - } - - $this->_out(sprintf('q %.2f 0 0 %.2f %.2f %.2f cm /I%d Do Q', $w * $this->k, $h * $this->k, $x * $this->k, ($this->h - ($y + $h)) * $this->k, $info['i'])); - - if ($link) - $this->Link($x, $y, $w, $h, $link); - - return $info['i']; - } - -// needs GD 2.x extension -// pixel-wise operation, not very fast - function ImagePngWithAlpha($file, $x, $y, $w = 0, $h = 0, $link = '') - { - $tmp_alpha = tempnam('.', 'mska'); - $this->tmpFiles[] = $tmp_alpha; - $tmp_plain = tempnam('.', 'mskp'); - $this->tmpFiles[] = $tmp_plain; - - list($wpx, $hpx) = getimagesize($file); - $img = imagecreatefrompng($file); - $alpha_img = imagecreate($wpx, $hpx); - - // generate gray scale pallete - for ($c = 0; $c < 256; $c++) ImageColorAllocate($alpha_img, $c, $c, $c); - - // extract alpha channel - $xpx = 0; - while ($xpx < $wpx) { - $ypx = 0; - while ($ypx < $hpx) { - $color_index = imagecolorat($img, $xpx, $ypx); - $alpha = 255 - ($color_index >> 24) * 255 / 127; // GD alpha component: 7 bit only, 0..127! - imagesetpixel($alpha_img, $xpx, $ypx, $alpha); - ++$ypx; - } - ++$xpx; - } - - imagepng($alpha_img, $tmp_alpha); - imagedestroy($alpha_img); - - // extract image without alpha channel - $plain_img = imagecreatetruecolor($wpx, $hpx); - imagecopy($plain_img, $img, 0, 0, 0, 0, $wpx, $hpx); - imagepng($plain_img, $tmp_plain); - imagedestroy($plain_img); - - //first embed mask image (w, h, x, will be ignored) - $maskImg = $this->Image($tmp_alpha, 0, 0, 0, 0, 'PNG', '', true); - - //embed image, masked with previously embedded mask - $this->Image($tmp_plain, $x, $y, $w, $h, 'PNG', $link, false, $maskImg); - } - - function Close() - { - parent::Close(); - // clean up tmp files - foreach ($this->tmpFiles as $tmp) @unlink($tmp); - } - - /******************************************************************************* - * * - * Private methods * - * * - *******************************************************************************/ - function _putimages() - { - $filter = ($this->compress) ? '/Filter /FlateDecode ' : ''; - reset($this->images); - while (list($file, $info) = each($this->images)) { - $this->_newobj(); - $this->images[$file]['n'] = $this->n; - $this->_out('<_out('/Subtype /Image'); - $this->_out('/Width ' . $info['w']); - $this->_out('/Height ' . $info['h']); - - if (isset($info["masked"])) $this->_out('/SMask ' . ($this->n - 1) . ' 0 R'); ### - - if ($info['cs'] == 'Indexed') - $this->_out('/ColorSpace [/Indexed /DeviceRGB ' . (strlen($info['pal']) / 3 - 1) . ' ' . ($this->n + 1) . ' 0 R]'); - else { - $this->_out('/ColorSpace /' . $info['cs']); - if ($info['cs'] == 'DeviceCMYK') - $this->_out('/Decode [1 0 1 0 1 0 1 0]'); - } - $this->_out('/BitsPerComponent ' . $info['bpc']); - if (isset($info['f'])) - $this->_out('/Filter /' . $info['f']); - if (isset($info['parms'])) - $this->_out($info['parms']); - if (isset($info['trns']) && is_array($info['trns'])) { - $trns = ''; - for ($i = 0; $i < count($info['trns']); $i++) - $trns .= $info['trns'][$i] . ' ' . $info['trns'][$i] . ' '; - $this->_out('/Mask [' . $trns . ']'); - } - $this->_out('/Length ' . strlen($info['data']) . '>>'); - $this->_putstream($info['data']); - unset($this->images[$file]['data']); - $this->_out('endobj'); - //Palette - if ($info['cs'] == 'Indexed') { - $this->_newobj(); - $pal = ($this->compress) ? gzcompress($info['pal']) : $info['pal']; - $this->_out('<<' . $filter . '/Length ' . strlen($pal) . '>>'); - $this->_putstream($pal); - $this->_out('endobj'); - } - } - } - -// this method overwriing the original version is only needed to make the Image method support PNGs with alpha channels. -// if you only use the ImagePngWithAlpha method for such PNGs, you can remove it from this script. - function _parsepng($file) - { - //Extract info from a PNG file - $f = fopen($file, 'rb'); - if (!$f) - $this->Error('Can\'t open image file: ' . $file); - //Check signature - if (fread($f, 8) != chr(137) . 'PNG' . chr(13) . chr(10) . chr(26) . chr(10)) - $this->Error('Not a PNG file: ' . $file); - //Read header chunk - fread($f, 4); - if (fread($f, 4) != 'IHDR') - $this->Error('Incorrect PNG file: ' . $file); - $w = $this->_readint($f); - $h = $this->_readint($f); - $bpc = ord(fread($f, 1)); - if ($bpc > 8) - $this->Error('16-bit depth not supported: ' . $file); - $ct = ord(fread($f, 1)); - if ($ct == 0) - $colspace = 'DeviceGray'; - elseif ($ct == 2) - $colspace = 'DeviceRGB'; - elseif ($ct == 3) - $colspace = 'Indexed'; - else { - fclose($f); // the only changes are - return 'alpha'; // made in those 2 lines - } - if (ord(fread($f, 1)) != 0) - $this->Error('Unknown compression method: ' . $file); - if (ord(fread($f, 1)) != 0) - $this->Error('Unknown filter method: ' . $file); - if (ord(fread($f, 1)) != 0) - $this->Error('Interlacing not supported: ' . $file); - fread($f, 4); - $parms = '/DecodeParms <>'; - //Scan chunks looking for palette, transparency and image data - $pal = ''; - $trns = ''; - $data = ''; - do { - $n = $this->_readint($f); - $type = fread($f, 4); - if ($type == 'PLTE') { - //Read palette - $pal = fread($f, $n); - fread($f, 4); - } elseif ($type == 'tRNS') { - //Read transparency info - $t = fread($f, $n); - if ($ct == 0) - $trns = array(ord(substr($t, 1, 1))); - elseif ($ct == 2) - $trns = array(ord(substr($t, 1, 1)), ord(substr($t, 3, 1)), ord(substr($t, 5, 1))); - else { - $pos = strpos($t, chr(0)); - if ($pos !== false) - $trns = array($pos); - } - fread($f, 4); - } elseif ($type == 'IDAT') { - //Read image data block - $data .= fread($f, $n); - fread($f, 4); - } elseif ($type == 'IEND') - break; - else - fread($f, $n + 4); - } while ($n); - if ($colspace == 'Indexed' && empty($pal)) - $this->Error('Missing palette in ' . $file); - fclose($f); - - return array('w' => $w, 'h' => $h, 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'FlateDecode', 'parms' => $parms, 'pal' => $pal, 'trns' => $trns, 'data' => $data); - } - -} diff --git a/src/bb-data/log/index.html b/src/bb-library/README.md old mode 100755 new mode 100644 similarity index 100% rename from src/bb-data/log/index.html rename to src/bb-library/README.md diff --git a/src/bb-library/Server/Manager/Plesk.php b/src/bb-library/Server/Manager/Plesk.php index 28e0cabf3..8f6538a2d 100644 --- a/src/bb-library/Server/Manager/Plesk.php +++ b/src/bb-library/Server/Manager/Plesk.php @@ -599,8 +599,8 @@ class Server_Manager_Plesk extends Server_Manager curl_setopt ($ch, CURLOPT_URL, $this->getLoginUrl()); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt ($ch, CURLOPT_TIMEOUT, 60); - curl_setopt ($ch, CURLOPT_POST, count($xml)); curl_setopt ($ch, CURLOPT_POSTFIELDS, $xml); + curl_setopt ($ch, CURLOPT_POST, count($xml)); $result = curl_exec($ch); @@ -962,4 +962,4 @@ class Server_Manager_Plesk extends Server_Manager return false; } } -} \ No newline at end of file +} diff --git a/src/bb-library/changelog.htm b/src/bb-library/changelog.htm new file mode 100644 index 000000000..1f6e49477 --- /dev/null +++ b/src/bb-library/changelog.htm @@ -0,0 +1,167 @@ + + + + +Changelog + + + + +

Changelog

+
+
v1.82 (2019-12-07)
+
+- Removed a deprecation notice under PHP 7.4.
+
+
v1.81 (2015-12-20)
+
+- Added GetPageWidth() and GetPageHeight().
+- Fixed a bug in SetXY().
+
+
v1.8 (2015-11-29)
+
+- PHP 5.1.0 or higher is now required.
+- The MakeFont utility now subsets fonts, which can greatly reduce font sizes.
+- Added ToUnicode CMaps to improve text extraction.
+- Added a parameter to AddPage() to rotate the page.
+- Added a parameter to SetY() to indicate whether the x position should be reset or not.
+- Added a parameter to Output() to specify the encoding of the name, and special characters are now properly encoded. Additionally the order of the first two parameters was reversed to be more logical (however the old order is still supported for compatibility).
+- The Error() method now throws an exception.
+- Adding contents before the first AddPage() or after Close() now raises an error.
+- Outputting text with no font selected now raises an error.
+
+
v1.7 (2011-06-18)
+
+- The MakeFont utility has been completely rewritten and doesn't depend on ttf2pt1 anymore.
+- Alpha channel is now supported for PNGs.
+- When inserting an image, it's now possible to specify its resolution.
+- Default resolution for images was increased from 72 to 96 dpi.
+- When inserting a GIF image, no temporary file is used anymore if the PHP version is 5.1 or higher.
+- When output buffering is enabled and the PDF is about to be sent, the buffer is now cleared if it contains only a UTF-8 BOM and/or whitespace (instead of throwing an error).
+- Symbol and ZapfDingbats fonts now support underline style.
+- Custom page sizes are now checked to ensure that width is smaller than height.
+- Standard font files were changed to use the same format as user fonts.
+- A bug in the embedding of Type1 fonts was fixed.
+- A bug related to SetDisplayMode() and the current locale was fixed.
+- A display issue occurring with the Adobe Reader X plug-in was fixed.
+- An issue related to transparency with some versions of Adobe Reader was fixed.
+- The Content-Length header was removed because it caused an issue when the HTTP server applies compression.
+
+
v1.6 (2008-08-03)
+
+- PHP 4.3.10 or higher is now required.
+- GIF image support.
+- Images can now trigger page breaks.
+- Possibility to have different page formats in a single document.
+- Document properties (author, creator, keywords, subject and title) can now be specified in UTF-8.
+- Fixed a bug: when a PNG was inserted through a URL, an error sometimes occurred.
+- An automatic page break in Header() doesn't cause an infinite loop any more.
+- Removed some warning messages appearing with recent PHP versions.
+- Added HTTP headers to reduce problems with IE.
+
+
v1.53 (2004-12-31)
+
+- When the font subdirectory is in the same directory as fpdf.php, it's no longer necessary to define the FPDF_FONTPATH constant.
+- The array $HTTP_SERVER_VARS is no longer used. It could cause trouble on PHP5-based configurations with the register_long_arrays option disabled.
+- Fixed a problem related to Type1 font embedding which caused trouble to some PDF processors.
+- The file name sent to the browser could not contain a space character.
+- The Cell() method could not print the number 0 (you had to pass the string '0').
+
+
v1.52 (2003-12-30)
+
+- Image() now displays the image at 72 dpi if no dimension is given.
+- Output() takes a string as second parameter to indicate destination.
+- Open() is now called automatically by AddPage().
+- Inserting remote JPEG images doesn't generate an error any longer.
+- Decimal separator is forced to dot in the constructor.
+- Added several encodings (Turkish, Thai, Hebrew, Ukrainian and Vietnamese).
+- The last line of a right-aligned MultiCell() was not correctly aligned if it was terminated by a carriage return.
+- No more error message about already sent headers when outputting the PDF to the standard output from the command line.
+- The underlining was going too far for text containing characters \, ( or ).
+- $HTTP_ENV_VARS has been replaced by $HTTP_SERVER_VARS.
+
+
v1.51 (2002-08-03)
+
+- Type1 font support.
+- Added Baltic encoding.
+- The class now works internally in points with the origin at the bottom in order to avoid two bugs occurring with Acrobat 5:
  * The line thickness was too large when printed under Windows 98 SE and ME.
  * TrueType fonts didn't appear immediately inside the plug-in (a substitution font was used), one had to cause a window refresh to make them show up.
+- It's no longer necessary to set the decimal separator as dot to produce valid documents.
+- The clickable area in a cell was always on the left independently from the text alignment.
+- JPEG images in CMYK mode appeared in inverted colors.
+- Transparent PNG images in grayscale or true color mode were incorrectly handled.
+- Adding new fonts now works correctly even with the magic_quotes_runtime option set to on.
+
+
v1.5 (2002-05-28)
+
+- TrueType font (AddFont()) and encoding support (Western and Eastern Europe, Cyrillic and Greek).
+- Added Write() method.
+- Added underlined style.
+- Internal and external link support (AddLink(), SetLink(), Link()).
+- Added right margin management and methods SetRightMargin(), SetTopMargin().
+- Modification of SetDisplayMode() to select page layout.
+- The border parameter of MultiCell() now lets choose borders to draw as Cell().
+- When a document contains no page, Close() now calls AddPage() instead of causing a fatal error.
+
+
v1.41 (2002-03-13)
+
+- Fixed SetDisplayMode() which no longer worked (the PDF viewer used its default display).
+
+
v1.4 (2002-03-02)
+
+- PHP3 is no longer supported.
+- Page compression (SetCompression()).
+- Choice of page format and possibility to change orientation inside document.
+- Added AcceptPageBreak() method.
+- Ability to print the total number of pages (AliasNbPages()).
+- Choice of cell borders to draw.
+- New mode for Cell(): the current position can now move under the cell.
+- Ability to include an image by specifying height only (width is calculated automatically).
+- Fixed a bug: when a justified line triggered a page break, the footer inherited the corresponding word spacing.
+
+
v1.31 (2002-01-12)
+
+- Fixed a bug in drawing frame with MultiCell(): the last line always started from the left margin.
+- Removed Expires HTTP header (gives trouble in some situations).
+- Added Content-disposition HTTP header (seems to help in some situations).
+
+
v1.3 (2001-12-03)
+
+- Line break and text justification support (MultiCell()).
+- Color support (SetDrawColor(), SetFillColor(), SetTextColor()). Possibility to draw filled rectangles and paint cell background.
+- A cell whose width is declared null extends up to the right margin of the page.
+- Line width is now retained from page to page and defaults to 0.2 mm.
+- Added SetXY() method.
+- Fixed a passing by reference done in a deprecated manner for PHP4.
+
+
v1.2 (2001-11-11)
+
+- Added font metric files and GetStringWidth() method.
+- Centering and right-aligning text in cells.
+- Display mode control (SetDisplayMode()).
+- Added methods to set document properties (SetAuthor(), SetCreator(), SetKeywords(), SetSubject(), SetTitle()).
+- Possibility to force PDF download by browser.
+- Added SetX() and GetX() methods.
+- During automatic page break, current abscissa is now retained.
+
+
v1.11 (2001-10-20)
+
+- PNG support doesn't require PHP4/zlib any more. Data are now put directly into PDF without any decompression/recompression stage.
+- Image insertion now works correctly even with magic_quotes_runtime option set to on.
+
+
v1.1 (2001-10-07)
+
+- JPEG and PNG image support.
+
+
v1.01 (2001-10-03)
+
+- Fixed a bug involving page break: in case when Header() doesn't specify a font, the one from previous page was not restored and produced an incorrect document.
+
+
v1.0 (2001-09-17)
+
+- First version.
+
+
+ + diff --git a/src/bb-library/doc/__construct.htm b/src/bb-library/doc/__construct.htm new file mode 100644 index 000000000..5d76dd271 --- /dev/null +++ b/src/bb-library/doc/__construct.htm @@ -0,0 +1,63 @@ + + + + +__construct + + + +

__construct

+__construct([string orientation [, string unit [, mixed size]]]) +

Description

+This is the class constructor. It allows to set up the page size, the orientation and the +unit of measure used in all methods (except for font sizes). +

Parameters

+
+
orientation
+
+Default page orientation. Possible values are (case insensitive): + +Default value is P. +
+
unit
+
+User unit. Possible values are: + +A point equals 1/72 of inch, that is to say about 0.35 mm (an inch being 2.54 cm). This +is a very common unit in typography; font sizes are expressed in that unit. +
+
+Default value is mm. +
+
size
+
+The size used for pages. It can be either one of the following values (case insensitive): + +or an array containing the width and the height (expressed in the unit given by unit).
+
+Default value is A4. +
+
+

Example

+Example with a custom 100x150 mm page size: +
+
$pdf = new FPDF('P','mm',array(100,150));
+
+
+
Index
+ + diff --git a/src/bb-library/doc/acceptpagebreak.htm b/src/bb-library/doc/acceptpagebreak.htm new file mode 100644 index 000000000..79c4a4915 --- /dev/null +++ b/src/bb-library/doc/acceptpagebreak.htm @@ -0,0 +1,63 @@ + + + + +AcceptPageBreak + + + +

AcceptPageBreak

+boolean AcceptPageBreak() +

Description

+Whenever a page break condition is met, the method is called, and the break is issued or not +depending on the returned value. The default implementation returns a value according to the +mode selected by SetAutoPageBreak(). +
+This method is called automatically and should not be called directly by the application. +

Example

+The method is overriden in an inherited class in order to obtain a 3 column layout: +
+
class PDF extends FPDF
+{
+var $col = 0;
+
+function SetCol($col)
+{
+    // Move position to a column
+    $this->col = $col;
+    $x = 10+$col*65;
+    $this->SetLeftMargin($x);
+    $this->SetX($x);
+}
+
+function AcceptPageBreak()
+{
+    if($this->col<2)
+    {
+        // Go to next column
+        $this->SetCol($this->col+1);
+        $this->SetY(10);
+        return false;
+    }
+    else
+    {
+        // Go back to first column and issue page break
+        $this->SetCol(0);
+        return true;
+    }
+}
+}
+
+$pdf = new PDF();
+$pdf->AddPage();
+$pdf->SetFont('Arial','',12);
+for($i=1;$i<=300;$i++)
+    $pdf->Cell(0,5,"Line $i",0,1);
+$pdf->Output();
+
+

See also

+SetAutoPageBreak +
+
Index
+ + diff --git a/src/bb-library/doc/addfont.htm b/src/bb-library/doc/addfont.htm new file mode 100644 index 000000000..b1bca0c58 --- /dev/null +++ b/src/bb-library/doc/addfont.htm @@ -0,0 +1,55 @@ + + + + +AddFont + + + +

AddFont

+AddFont(string family [, string style [, string file]]) +

Description

+Imports a TrueType, OpenType or Type1 font and makes it available. It is necessary to generate a font +definition file first with the MakeFont utility. +
+The definition file (and the font file itself when embedding) must be present in the font directory. +If it is not found, the error "Could not include font definition file" is raised. +

Parameters

+
+
family
+
+Font family. The name can be chosen arbitrarily. If it is a standard family name, it will +override the corresponding font. +
+
style
+
+Font style. Possible values are (case insensitive): + +The default value is regular. +
+
file
+
+The font definition file. +
+By default, the name is built from the family and style, in lower case with no space. +
+
+

Example

+
+
$pdf->AddFont('Comic','I');
+
+is equivalent to: +
+
$pdf->AddFont('Comic','I','comici.php');
+
+

See also

+SetFont +
+
Index
+ + diff --git a/src/bb-library/doc/addlink.htm b/src/bb-library/doc/addlink.htm new file mode 100644 index 000000000..9bc327688 --- /dev/null +++ b/src/bb-library/doc/addlink.htm @@ -0,0 +1,26 @@ + + + + +AddLink + + + +

AddLink

+int AddLink() +

Description

+Creates a new internal link and returns its identifier. An internal link is a clickable area +which directs to another place within the document. +
+The identifier can then be passed to Cell(), Write(), Image() or Link(). The destination is +defined with SetLink(). +

See also

+Cell, +Write, +Image, +Link, +SetLink +
+
Index
+ + diff --git a/src/bb-library/doc/addpage.htm b/src/bb-library/doc/addpage.htm new file mode 100644 index 000000000..7d9ebe105 --- /dev/null +++ b/src/bb-library/doc/addpage.htm @@ -0,0 +1,61 @@ + + + + +AddPage + + + +

AddPage

+AddPage([string orientation [, mixed size [, int rotation]]]) +

Description

+Adds a new page to the document. If a page is already present, the Footer() method is called +first to output the footer. Then the page is added, the current position set to the top-left +corner according to the left and top margins, and Header() is called to display the header. +
+The font which was set before calling is automatically restored. There is no need to call +SetFont() again if you want to continue with the same font. The same is true for colors and +line width. +
+The origin of the coordinate system is at the top-left corner and increasing ordinates go +downwards. +

Parameters

+
+
orientation
+
+Page orientation. Possible values are (case insensitive): + +The default value is the one passed to the constructor. +
+
size
+
+Page size. It can be either one of the following values (case insensitive): + +or an array containing the width and the height (expressed in user unit).
+
+The default value is the one passed to the constructor. +
+
rotation
+
+Angle by which to rotate the page. It must be a multiple of 90; positive values +mean clockwise rotation. The default value is 0. +
+
+

See also

+__construct, +Header, +Footer, +SetMargins +
+
Index
+ + diff --git a/src/bb-library/doc/aliasnbpages.htm b/src/bb-library/doc/aliasnbpages.htm new file mode 100644 index 000000000..3768cf7a7 --- /dev/null +++ b/src/bb-library/doc/aliasnbpages.htm @@ -0,0 +1,45 @@ + + + + +AliasNbPages + + + +

AliasNbPages

+AliasNbPages([string alias]) +

Description

+Defines an alias for the total number of pages. It will be substituted as the document is +closed. +

Parameters

+
+
alias
+
+The alias. Default value: {nb}. +
+
+

Example

+
+
class PDF extends FPDF
+{
+function Footer()
+{
+    // Go to 1.5 cm from bottom
+    $this->SetY(-15);
+    // Select Arial italic 8
+    $this->SetFont('Arial','I',8);
+    // Print current and total page numbers
+    $this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
+}
+}
+
+$pdf = new PDF();
+$pdf->AliasNbPages();
+
+

See also

+PageNo, +Footer +
+
Index
+ + diff --git a/src/bb-library/doc/cell.htm b/src/bb-library/doc/cell.htm new file mode 100644 index 000000000..d46359a90 --- /dev/null +++ b/src/bb-library/doc/cell.htm @@ -0,0 +1,104 @@ + + + + +Cell + + + +

Cell

+Cell(float w [, float h [, string txt [, mixed border [, int ln [, string align [, boolean fill [, mixed link]]]]]]]) +

Description

+Prints a cell (rectangular area) with optional borders, background color and character string. +The upper-left corner of the cell corresponds to the current position. The text can be aligned +or centered. After the call, the current position moves to the right or to the next line. It is +possible to put a link on the text. +
+If automatic page breaking is enabled and the cell goes beyond the limit, a page break is +done before outputting. +

Parameters

+
+
w
+
+Cell width. If 0, the cell extends up to the right margin. +
+
h
+
+Cell height. +Default value: 0. +
+
txt
+
+String to print. +Default value: empty string. +
+
border
+
+Indicates if borders must be drawn around the cell. The value can be either a number: + +or a string containing some or all of the following characters (in any order): + +Default value: 0. +
+
ln
+
+Indicates where the current position should go after the call. Possible values are: + +Putting 1 is equivalent to putting 0 and calling Ln() just after. +Default value: 0. +
+
align
+
+Allows to center or align the text. Possible values are: + +
+
fill
+
+Indicates if the cell background must be painted (true) or transparent (false). +Default value: false. +
+
link
+
+URL or identifier returned by AddLink(). +
+
+

Example

+
+
// Set font
+$pdf->SetFont('Arial','B',16);
+// Move to 8 cm to the right
+$pdf->Cell(80);
+// Centered text in a framed 20*10 mm cell and line break
+$pdf->Cell(20,10,'Title',1,1,'C');
+
+

See also

+SetFont, +SetDrawColor, +SetFillColor, +SetTextColor, +SetLineWidth, +AddLink, +Ln, +MultiCell, +Write, +SetAutoPageBreak +
+
Index
+ + diff --git a/src/bb-library/doc/close.htm b/src/bb-library/doc/close.htm new file mode 100644 index 000000000..933eaba7e --- /dev/null +++ b/src/bb-library/doc/close.htm @@ -0,0 +1,21 @@ + + + + +Close + + + +

Close

+Close() +

Description

+Terminates the PDF document. It is not necessary to call this method explicitly because Output() +does it automatically. +
+If the document contains no page, AddPage() is called to prevent from getting an invalid document. +

See also

+Output +
+
Index
+ + diff --git a/src/bb-library/doc/error.htm b/src/bb-library/doc/error.htm new file mode 100644 index 000000000..95b02c696 --- /dev/null +++ b/src/bb-library/doc/error.htm @@ -0,0 +1,26 @@ + + + + +Error + + + +

Error

+Error(string msg) +

Description

+This method is automatically called in case of a fatal error; it simply throws an exception +with the provided message.
+An inherited class may override it to customize the error handling but the method should +never return, otherwise the resulting document would probably be invalid. +

Parameters

+
+
msg
+
+The error message. +
+
+
+
Index
+ + diff --git a/src/bb-library/doc/footer.htm b/src/bb-library/doc/footer.htm new file mode 100644 index 000000000..a3a2018aa --- /dev/null +++ b/src/bb-library/doc/footer.htm @@ -0,0 +1,35 @@ + + + + +Footer + + + +

Footer

+Footer() +

Description

+This method is used to render the page footer. It is automatically called by AddPage() and +Close() and should not be called directly by the application. The implementation in FPDF is +empty, so you have to subclass it and override the method if you want a specific processing. +

Example

+
+
class PDF extends FPDF
+{
+function Footer()
+{
+    // Go to 1.5 cm from bottom
+    $this->SetY(-15);
+    // Select Arial italic 8
+    $this->SetFont('Arial','I',8);
+    // Print centered page number
+    $this->Cell(0,10,'Page '.$this->PageNo(),0,0,'C');
+}
+}
+
+

See also

+Header +
+
Index
+ + diff --git a/src/bb-library/doc/getpageheight.htm b/src/bb-library/doc/getpageheight.htm new file mode 100644 index 000000000..5150072dd --- /dev/null +++ b/src/bb-library/doc/getpageheight.htm @@ -0,0 +1,18 @@ + + + + +GetPageHeight + + + +

GetPageHeight

+float GetPageHeight() +

Description

+Returns the current page height. +

See also

+GetPageWidth +
+
Index
+ + diff --git a/src/bb-library/doc/getpagewidth.htm b/src/bb-library/doc/getpagewidth.htm new file mode 100644 index 000000000..2ae306bf4 --- /dev/null +++ b/src/bb-library/doc/getpagewidth.htm @@ -0,0 +1,18 @@ + + + + +GetPageWidth + + + +

GetPageWidth

+float GetPageWidth() +

Description

+Returns the current page width. +

See also

+GetPageHeight +
+
Index
+ + diff --git a/src/bb-library/doc/getstringwidth.htm b/src/bb-library/doc/getstringwidth.htm new file mode 100644 index 000000000..38b487560 --- /dev/null +++ b/src/bb-library/doc/getstringwidth.htm @@ -0,0 +1,23 @@ + + + + +GetStringWidth + + + +

GetStringWidth

+float GetStringWidth(string s) +

Description

+Returns the length of a string in user unit. A font must be selected. +

Parameters

+
+
s
+
+The string whose length is to be computed. +
+
+
+
Index
+ + diff --git a/src/bb-library/doc/getx.htm b/src/bb-library/doc/getx.htm new file mode 100644 index 000000000..86550a3a9 --- /dev/null +++ b/src/bb-library/doc/getx.htm @@ -0,0 +1,20 @@ + + + + +GetX + + + +

GetX

+float GetX() +

Description

+Returns the abscissa of the current position. +

See also

+SetX, +GetY, +SetY +
+
Index
+ + diff --git a/src/bb-library/doc/gety.htm b/src/bb-library/doc/gety.htm new file mode 100644 index 000000000..e1b387aa0 --- /dev/null +++ b/src/bb-library/doc/gety.htm @@ -0,0 +1,20 @@ + + + + +GetY + + + +

GetY

+float GetY() +

Description

+Returns the ordinate of the current position. +

See also

+SetY, +GetX, +SetX +
+
Index
+ + diff --git a/src/bb-library/doc/header.htm b/src/bb-library/doc/header.htm new file mode 100644 index 000000000..3c3da968b --- /dev/null +++ b/src/bb-library/doc/header.htm @@ -0,0 +1,37 @@ + + + + +Header + + + +

Header

+Header() +

Description

+This method is used to render the page header. It is automatically called by AddPage() and +should not be called directly by the application. The implementation in FPDF is empty, so +you have to subclass it and override the method if you want a specific processing. +

Example

+
+
class PDF extends FPDF
+{
+function Header()
+{
+    // Select Arial bold 15
+    $this->SetFont('Arial','B',15);
+    // Move to the right
+    $this->Cell(80);
+    // Framed title
+    $this->Cell(30,10,'Title',1,0,'C');
+    // Line break
+    $this->Ln(20);
+}
+}
+
+

See also

+Footer +
+
Index
+ + diff --git a/src/bb-library/doc/image.htm b/src/bb-library/doc/image.htm new file mode 100644 index 000000000..96ab90775 --- /dev/null +++ b/src/bb-library/doc/image.htm @@ -0,0 +1,99 @@ + + + + +Image + + + +

Image

+Image(string file [, float x [, float y [, float w [, float h [, string type [, mixed link]]]]]]) +

Description

+Puts an image. The size it will take on the page can be specified in different ways: + +Supported formats are JPEG, PNG and GIF. The GD extension is required for GIF. +
+
+For JPEGs, all flavors are allowed: + +For PNGs, are allowed: + +For GIFs: in case of an animated GIF, only the first frame is displayed.
+
+Transparency is supported.
+
+The format can be specified explicitly or inferred from the file extension.
+
+It is possible to put a link on the image.
+
+Remark: if an image is used several times, only one copy is embedded in the file. +

Parameters

+
+
file
+
+Path or URL of the image. +
+
x
+
+Abscissa of the upper-left corner. If not specified or equal to null, the current abscissa +is used. +
+
y
+
+Ordinate of the upper-left corner. If not specified or equal to null, the current ordinate +is used; moreover, a page break is triggered first if necessary (in case automatic page breaking is enabled) +and, after the call, the current ordinate is moved to the bottom of the image. +
+
w
+
+Width of the image in the page. There are three cases: + +
+
h
+
+Height of the image in the page. There are three cases: + +
+
type
+
+Image format. Possible values are (case insensitive): JPG, JPEG, PNG and GIF. +If not specified, the type is inferred from the file extension. +
+
link
+
+URL or identifier returned by AddLink(). +
+
+

Example

+
+
// Insert a logo in the top-left corner at 300 dpi
+$pdf->Image('logo.png',10,10,-300);
+// Insert a dynamic image from a URL
+$pdf->Image('http://chart.googleapis.com/chart?cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World',60,30,90,0,'PNG');
+
+

See also

+AddLink +
+
Index
+ + diff --git a/src/bb-library/doc/index.htm b/src/bb-library/doc/index.htm new file mode 100644 index 000000000..c51756792 --- /dev/null +++ b/src/bb-library/doc/index.htm @@ -0,0 +1,59 @@ + + + + +FPDF 1.82 Reference Manual + + + +

FPDF 1.82 Reference Manual

+__construct - constructor
+AcceptPageBreak - accept or not automatic page break
+AddFont - add a new font
+AddLink - create an internal link
+AddPage - add a new page
+AliasNbPages - define an alias for number of pages
+Cell - print a cell
+Close - terminate the document
+Error - fatal error
+Footer - page footer
+GetPageHeight - get current page height
+GetPageWidth - get current page width
+GetStringWidth - compute string length
+GetX - get current x position
+GetY - get current y position
+Header - page header
+Image - output an image
+Line - draw a line
+Link - put a link
+Ln - line break
+MultiCell - print text with line breaks
+Output - save or send the document
+PageNo - page number
+Rect - draw a rectangle
+SetAuthor - set the document author
+SetAutoPageBreak - set the automatic page breaking mode
+SetCompression - turn compression on or off
+SetCreator - set document creator
+SetDisplayMode - set display mode
+SetDrawColor - set drawing color
+SetFillColor - set filling color
+SetFont - set font
+SetFontSize - set font size
+SetKeywords - associate keywords with document
+SetLeftMargin - set left margin
+SetLineWidth - set line width
+SetLink - set internal link destination
+SetMargins - set margins
+SetRightMargin - set right margin
+SetSubject - set document subject
+SetTextColor - set text color
+SetTitle - set document title
+SetTopMargin - set top margin
+SetX - set current x position
+SetXY - set current x and y positions
+SetY - set current y position and optionally reset x
+Text - print a string
+Write - print flowing text
+ + diff --git a/src/bb-library/doc/line.htm b/src/bb-library/doc/line.htm new file mode 100644 index 000000000..e232b4e6e --- /dev/null +++ b/src/bb-library/doc/line.htm @@ -0,0 +1,38 @@ + + + + +Line + + + +

Line

+Line(float x1, float y1, float x2, float y2) +

Description

+Draws a line between two points. +

Parameters

+
+
x1
+
+Abscissa of first point. +
+
y1
+
+Ordinate of first point. +
+
x2
+
+Abscissa of second point. +
+
y2
+
+Ordinate of second point. +
+
+

See also

+SetLineWidth, +SetDrawColor +
+
Index
+ + diff --git a/src/bb-library/doc/link.htm b/src/bb-library/doc/link.htm new file mode 100644 index 000000000..f3df2fb8c --- /dev/null +++ b/src/bb-library/doc/link.htm @@ -0,0 +1,46 @@ + + + + +Link + + + +

Link

+Link(float x, float y, float w, float h, mixed link) +

Description

+Puts a link on a rectangular area of the page. Text or image links are generally put via Cell(), +Write() or Image(), but this method can be useful for instance to define a clickable area inside +an image. +

Parameters

+
+
x
+
+Abscissa of the upper-left corner of the rectangle. +
+
y
+
+Ordinate of the upper-left corner of the rectangle. +
+
w
+
+Width of the rectangle. +
+
h
+
+Height of the rectangle. +
+
link
+
+URL or identifier returned by AddLink(). +
+
+

See also

+AddLink, +Cell, +Write, +Image +
+
Index
+ + diff --git a/src/bb-library/doc/ln.htm b/src/bb-library/doc/ln.htm new file mode 100644 index 000000000..04dbe372d --- /dev/null +++ b/src/bb-library/doc/ln.htm @@ -0,0 +1,28 @@ + + + + +Ln + + + +

Ln

+Ln([float h]) +

Description

+Performs a line break. The current abscissa goes back to the left margin and the ordinate +increases by the amount passed in parameter. +

Parameters

+
+
h
+
+The height of the break. +
+By default, the value equals the height of the last printed cell. +
+
+

See also

+Cell +
+
Index
+ + diff --git a/src/bb-library/doc/multicell.htm b/src/bb-library/doc/multicell.htm new file mode 100644 index 000000000..9f136ae3b --- /dev/null +++ b/src/bb-library/doc/multicell.htm @@ -0,0 +1,76 @@ + + + + +MultiCell + + + +

MultiCell

+MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]]) +

Description

+This method allows printing text with line breaks. They can be automatic (as soon as the +text reaches the right border of the cell) or explicit (via the \n character). As many cells +as necessary are output, one below the other. +
+Text can be aligned, centered or justified. The cell block can be framed and the background +painted. +

Parameters

+
+
w
+
+Width of cells. If 0, they extend up to the right margin of the page. +
+
h
+
+Height of cells. +
+
txt
+
+String to print. +
+
border
+
+Indicates if borders must be drawn around the cell block. The value can be either a number: + +or a string containing some or all of the following characters (in any order): + +Default value: 0. +
+
align
+
+Sets the text alignment. Possible values are: + +
+
fill
+
+Indicates if the cell background must be painted (true) or transparent (false). +Default value: false. +
+
+

See also

+SetFont, +SetDrawColor, +SetFillColor, +SetTextColor, +SetLineWidth, +Cell, +Write, +SetAutoPageBreak +
+
Index
+ + diff --git a/src/bb-library/doc/output.htm b/src/bb-library/doc/output.htm new file mode 100644 index 000000000..229e0a75e --- /dev/null +++ b/src/bb-library/doc/output.htm @@ -0,0 +1,46 @@ + + + + +Output + + + +

Output

+string Output([string dest [, string name [, boolean isUTF8]]]) +

Description

+Send the document to a given destination: browser, file or string. In the case of a browser, the +PDF viewer may be used or a download may be forced. +
+The method first calls Close() if necessary to terminate the document. +

Parameters

+
+
dest
+
+Destination where to send the document. It can be one of the following: + +The default value is I. +
+
name
+
+The name of the file. It is ignored in case of destination S.
+The default value is doc.pdf. +
+
isUTF8
+
+Indicates if name is encoded in ISO-8859-1 (false) or UTF-8 (true). +Only used for destinations I and D.
+The default value is false. +
+
+

See also

+Close +
+
Index
+ + diff --git a/src/bb-library/doc/pageno.htm b/src/bb-library/doc/pageno.htm new file mode 100644 index 000000000..95400bef0 --- /dev/null +++ b/src/bb-library/doc/pageno.htm @@ -0,0 +1,18 @@ + + + + +PageNo + + + +

PageNo

+int PageNo() +

Description

+Returns the current page number. +

See also

+AliasNbPages +
+
Index
+ + diff --git a/src/bb-library/doc/rect.htm b/src/bb-library/doc/rect.htm new file mode 100644 index 000000000..febc9ae21 --- /dev/null +++ b/src/bb-library/doc/rect.htm @@ -0,0 +1,48 @@ + + + + +Rect + + + +

Rect

+Rect(float x, float y, float w, float h [, string style]) +

Description

+Outputs a rectangle. It can be drawn (border only), filled (with no border) or both. +

Parameters

+
+
x
+
+Abscissa of upper-left corner. +
+
y
+
+Ordinate of upper-left corner. +
+
w
+
+Width. +
+
h
+
+Height. +
+
style
+
+Style of rendering. Possible values are: + +
+
+

See also

+SetLineWidth, +SetDrawColor, +SetFillColor +
+
Index
+ + diff --git a/src/bb-library/doc/setauthor.htm b/src/bb-library/doc/setauthor.htm new file mode 100644 index 000000000..374134b48 --- /dev/null +++ b/src/bb-library/doc/setauthor.htm @@ -0,0 +1,33 @@ + + + + +SetAuthor + + + +

SetAuthor

+SetAuthor(string author [, boolean isUTF8]) +

Description

+Defines the author of the document. +

Parameters

+
+
author
+
+The name of the author. +
+
isUTF8
+
+Indicates if the string is encoded in ISO-8859-1 (false) or UTF-8 (true).
+Default value: false. +
+
+

See also

+SetCreator, +SetKeywords, +SetSubject, +SetTitle +
+
Index
+ + diff --git a/src/bb-library/doc/setautopagebreak.htm b/src/bb-library/doc/setautopagebreak.htm new file mode 100644 index 000000000..8c0c6f2ef --- /dev/null +++ b/src/bb-library/doc/setautopagebreak.htm @@ -0,0 +1,33 @@ + + + + +SetAutoPageBreak + + + +

SetAutoPageBreak

+SetAutoPageBreak(boolean auto [, float margin]) +

Description

+Enables or disables the automatic page breaking mode. When enabling, the second parameter is +the distance from the bottom of the page that defines the triggering limit. By default, the +mode is on and the margin is 2 cm. +

Parameters

+
+
auto
+
+Boolean indicating if mode should be on or off. +
+
margin
+
+Distance from the bottom of the page. +
+
+

See also

+Cell, +MultiCell, +AcceptPageBreak +
+
Index
+ + diff --git a/src/bb-library/doc/setcompression.htm b/src/bb-library/doc/setcompression.htm new file mode 100644 index 000000000..ec506d931 --- /dev/null +++ b/src/bb-library/doc/setcompression.htm @@ -0,0 +1,31 @@ + + + + +SetCompression + + + +

SetCompression

+SetCompression(boolean compress) +

Description

+Activates or deactivates page compression. When activated, the internal representation of +each page is compressed, which leads to a compression ratio of about 2 for the resulting +document. +
+Compression is on by default. +
+
+Note: the Zlib extension is required for this feature. If not present, compression +will be turned off. +

Parameters

+
+
compress
+
+Boolean indicating if compression must be enabled. +
+
+
+
Index
+ + diff --git a/src/bb-library/doc/setcreator.htm b/src/bb-library/doc/setcreator.htm new file mode 100644 index 000000000..1cf2ed848 --- /dev/null +++ b/src/bb-library/doc/setcreator.htm @@ -0,0 +1,34 @@ + + + + +SetCreator + + + +

SetCreator

+SetCreator(string creator [, boolean isUTF8]) +

Description

+Defines the creator of the document. This is typically the name of the application that +generates the PDF. +

Parameters

+
+
creator
+
+The name of the creator. +
+
isUTF8
+
+Indicates if the string is encoded in ISO-8859-1 (false) or UTF-8 (true).
+Default value: false. +
+
+

See also

+SetAuthor, +SetKeywords, +SetSubject, +SetTitle +
+
Index
+ + diff --git a/src/bb-library/doc/setdisplaymode.htm b/src/bb-library/doc/setdisplaymode.htm new file mode 100644 index 000000000..e9deb56c7 --- /dev/null +++ b/src/bb-library/doc/setdisplaymode.htm @@ -0,0 +1,45 @@ + + + + +SetDisplayMode + + + +

SetDisplayMode

+SetDisplayMode(mixed zoom [, string layout]) +

Description

+Defines the way the document is to be displayed by the viewer. The zoom level can be set: pages can be +displayed entirely on screen, occupy the full width of the window, use real size, be scaled by a +specific zooming factor or use viewer default (configured in the Preferences menu of Adobe Reader). +The page layout can be specified too: single at once, continuous display, two columns or viewer +default. +

Parameters

+
+
zoom
+
+The zoom to use. It can be one of the following string values: + +or a number indicating the zooming factor to use. +
+
layout
+
+The page layout. Possible values are: + +Default value is default. +
+
+
+
Index
+ + diff --git a/src/bb-library/doc/setdrawcolor.htm b/src/bb-library/doc/setdrawcolor.htm new file mode 100644 index 000000000..fc5a093a3 --- /dev/null +++ b/src/bb-library/doc/setdrawcolor.htm @@ -0,0 +1,41 @@ + + + + +SetDrawColor + + + +

SetDrawColor

+SetDrawColor(int r [, int g, int b]) +

Description

+Defines the color used for all drawing operations (lines, rectangles and cell borders). It +can be expressed in RGB components or gray scale. The method can be called before the first +page is created and the value is retained from page to page. +

Parameters

+
+
r
+
+If g et b are given, red component; if not, indicates the gray level. +Value between 0 and 255. +
+
g
+
+Green component (between 0 and 255). +
+
b
+
+Blue component (between 0 and 255). +
+
+

See also

+SetFillColor, +SetTextColor, +Line, +Rect, +Cell, +MultiCell +
+
Index
+ + diff --git a/src/bb-library/doc/setfillcolor.htm b/src/bb-library/doc/setfillcolor.htm new file mode 100644 index 000000000..9e18343b8 --- /dev/null +++ b/src/bb-library/doc/setfillcolor.htm @@ -0,0 +1,40 @@ + + + + +SetFillColor + + + +

SetFillColor

+SetFillColor(int r [, int g, int b]) +

Description

+Defines the color used for all filling operations (filled rectangles and cell backgrounds). +It can be expressed in RGB components or gray scale. The method can be called before the first +page is created and the value is retained from page to page. +

Parameters

+
+
r
+
+If g and b are given, red component; if not, indicates the gray level. +Value between 0 and 255. +
+
g
+
+Green component (between 0 and 255). +
+
b
+
+Blue component (between 0 and 255). +
+
+

See also

+SetDrawColor, +SetTextColor, +Rect, +Cell, +MultiCell +
+
Index
+ + diff --git a/src/bb-library/doc/setfont.htm b/src/bb-library/doc/setfont.htm new file mode 100644 index 000000000..a1de05c6a --- /dev/null +++ b/src/bb-library/doc/setfont.htm @@ -0,0 +1,92 @@ + + + + +SetFont + + + +

SetFont

+SetFont(string family [, string style [, float size]]) +

Description

+Sets the font used to print character strings. It is mandatory to call this method +at least once before printing text or the resulting document would not be valid. +
+The font can be either a standard one or a font added via the AddFont() method. Standard fonts +use the Windows encoding cp1252 (Western Europe). +
+The method can be called before the first page is created and the font is kept from page +to page. +
+If you just wish to change the current font size, it is simpler to call SetFontSize(). +
+
+Note: the font definition files must be accessible. They are searched successively in: + +Example using FPDF_FONTPATH: +
+
define('FPDF_FONTPATH','/home/www/font');
+require('fpdf.php');
+
+If the file corresponding to the requested font is not found, the error "Could not include font +definition file" is raised. +

Parameters

+
+
family
+
+Family font. It can be either a name defined by AddFont() or one of the standard families (case +insensitive): + +It is also possible to pass an empty string. In that case, the current family is kept. +
+
style
+
+Font style. Possible values are (case insensitive): + +or any combination. The default value is regular. +Bold and italic styles do not apply to Symbol and ZapfDingbats. +
+
size
+
+Font size in points. +
+The default value is the current size. If no size has been specified since the beginning of +the document, the value taken is 12. +
+
+

Example

+
+
// Times regular 12
+$pdf->SetFont('Times');
+// Arial bold 14
+$pdf->SetFont('Arial','B',14);
+// Removes bold
+$pdf->SetFont('');
+// Times bold, italic and underlined 14
+$pdf->SetFont('Times','BIU');
+
+

See also

+AddFont, +SetFontSize, +Cell, +MultiCell, +Write +
+
Index
+ + diff --git a/src/bb-library/doc/setfontsize.htm b/src/bb-library/doc/setfontsize.htm new file mode 100644 index 000000000..70d002da1 --- /dev/null +++ b/src/bb-library/doc/setfontsize.htm @@ -0,0 +1,25 @@ + + + + +SetFontSize + + + +

SetFontSize

+SetFontSize(float size) +

Description

+Defines the size of the current font. +

Parameters

+
+
size
+
+The size (in points). +
+
+

See also

+SetFont +
+
Index
+ + diff --git a/src/bb-library/doc/setkeywords.htm b/src/bb-library/doc/setkeywords.htm new file mode 100644 index 000000000..4952cc6a9 --- /dev/null +++ b/src/bb-library/doc/setkeywords.htm @@ -0,0 +1,33 @@ + + + + +SetKeywords + + + +

SetKeywords

+SetKeywords(string keywords [, boolean isUTF8]) +

Description

+Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'. +

Parameters

+
+
keywords
+
+The list of keywords. +
+
isUTF8
+
+Indicates if the string is encoded in ISO-8859-1 (false) or UTF-8 (true).
+Default value: false. +
+
+

See also

+SetAuthor, +SetCreator, +SetSubject, +SetTitle +
+
Index
+ + diff --git a/src/bb-library/doc/setleftmargin.htm b/src/bb-library/doc/setleftmargin.htm new file mode 100644 index 000000000..efa9c4e79 --- /dev/null +++ b/src/bb-library/doc/setleftmargin.htm @@ -0,0 +1,30 @@ + + + + +SetLeftMargin + + + +

SetLeftMargin

+SetLeftMargin(float margin) +

Description

+Defines the left margin. The method can be called before creating the first page. +
+If the current abscissa gets out of page, it is brought back to the margin. +

Parameters

+
+
margin
+
+The margin. +
+
+

See also

+SetTopMargin, +SetRightMargin, +SetAutoPageBreak, +SetMargins +
+
Index
+ + diff --git a/src/bb-library/doc/setlinewidth.htm b/src/bb-library/doc/setlinewidth.htm new file mode 100644 index 000000000..b60b3b929 --- /dev/null +++ b/src/bb-library/doc/setlinewidth.htm @@ -0,0 +1,29 @@ + + + + +SetLineWidth + + + +

SetLineWidth

+SetLineWidth(float width) +

Description

+Defines the line width. By default, the value equals 0.2 mm. The method can be called before +the first page is created and the value is retained from page to page. +

Parameters

+
+
width
+
+The width. +
+
+

See also

+Line, +Rect, +Cell, +MultiCell +
+
Index
+ + diff --git a/src/bb-library/doc/setlink.htm b/src/bb-library/doc/setlink.htm new file mode 100644 index 000000000..6160dc8a1 --- /dev/null +++ b/src/bb-library/doc/setlink.htm @@ -0,0 +1,34 @@ + + + + +SetLink + + + +

SetLink

+SetLink(int link [, float y [, int page]]) +

Description

+Defines the page and position a link points to. +

Parameters

+
+
link
+
+The link identifier returned by AddLink(). +
+
y
+
+Ordinate of target position; -1 indicates the current position. +The default value is 0 (top of page). +
+
page
+
+Number of target page; -1 indicates the current page. This is the default value. +
+
+

See also

+AddLink +
+
Index
+ + diff --git a/src/bb-library/doc/setmargins.htm b/src/bb-library/doc/setmargins.htm new file mode 100644 index 000000000..01e32f714 --- /dev/null +++ b/src/bb-library/doc/setmargins.htm @@ -0,0 +1,37 @@ + + + + +SetMargins + + + +

SetMargins

+SetMargins(float left, float top [, float right]) +

Description

+Defines the left, top and right margins. By default, they equal 1 cm. Call this method to change +them. +

Parameters

+
+
left
+
+Left margin. +
+
top
+
+Top margin. +
+
right
+
+Right margin. Default value is the left one. +
+
+

See also

+SetLeftMargin, +SetTopMargin, +SetRightMargin, +SetAutoPageBreak +
+
Index
+ + diff --git a/src/bb-library/doc/setrightmargin.htm b/src/bb-library/doc/setrightmargin.htm new file mode 100644 index 000000000..b55941bf3 --- /dev/null +++ b/src/bb-library/doc/setrightmargin.htm @@ -0,0 +1,28 @@ + + + + +SetRightMargin + + + +

SetRightMargin

+SetRightMargin(float margin) +

Description

+Defines the right margin. The method can be called before creating the first page. +

Parameters

+
+
margin
+
+The margin. +
+
+

See also

+SetLeftMargin, +SetTopMargin, +SetAutoPageBreak, +SetMargins +
+
Index
+ + diff --git a/src/bb-library/doc/setsubject.htm b/src/bb-library/doc/setsubject.htm new file mode 100644 index 000000000..5df7fd41a --- /dev/null +++ b/src/bb-library/doc/setsubject.htm @@ -0,0 +1,33 @@ + + + + +SetSubject + + + +

SetSubject

+SetSubject(string subject [, boolean isUTF8]) +

Description

+Defines the subject of the document. +

Parameters

+
+
subject
+
+The subject. +
+
isUTF8
+
+Indicates if the string is encoded in ISO-8859-1 (false) or UTF-8 (true).
+Default value: false. +
+
+

See also

+SetAuthor, +SetCreator, +SetKeywords, +SetTitle +
+
Index
+ + diff --git a/src/bb-library/doc/settextcolor.htm b/src/bb-library/doc/settextcolor.htm new file mode 100644 index 000000000..2db3b0dcf --- /dev/null +++ b/src/bb-library/doc/settextcolor.htm @@ -0,0 +1,40 @@ + + + + +SetTextColor + + + +

SetTextColor

+SetTextColor(int r [, int g, int b]) +

Description

+Defines the color used for text. It can be expressed in RGB components or gray scale. The +method can be called before the first page is created and the value is retained from page to +page. +

Parameters

+
+
r
+
+If g et b are given, red component; if not, indicates the gray level. +Value between 0 and 255. +
+
g
+
+Green component (between 0 and 255). +
+
b
+
+Blue component (between 0 and 255). +
+
+

See also

+SetDrawColor, +SetFillColor, +Text, +Cell, +MultiCell +
+
Index
+ + diff --git a/src/bb-library/doc/settitle.htm b/src/bb-library/doc/settitle.htm new file mode 100644 index 000000000..75cb9aa1d --- /dev/null +++ b/src/bb-library/doc/settitle.htm @@ -0,0 +1,33 @@ + + + + +SetTitle + + + +

SetTitle

+SetTitle(string title [, boolean isUTF8]) +

Description

+Defines the title of the document. +

Parameters

+
+
title
+
+The title. +
+
isUTF8
+
+Indicates if the string is encoded in ISO-8859-1 (false) or UTF-8 (true).
+Default value: false. +
+
+

See also

+SetAuthor, +SetCreator, +SetKeywords, +SetSubject +
+
Index
+ + diff --git a/src/bb-library/doc/settopmargin.htm b/src/bb-library/doc/settopmargin.htm new file mode 100644 index 000000000..5ea6ebc2f --- /dev/null +++ b/src/bb-library/doc/settopmargin.htm @@ -0,0 +1,28 @@ + + + + +SetTopMargin + + + +

SetTopMargin

+SetTopMargin(float margin) +

Description

+Defines the top margin. The method can be called before creating the first page. +

Parameters

+
+
margin
+
+The margin. +
+
+

See also

+SetLeftMargin, +SetRightMargin, +SetAutoPageBreak, +SetMargins +
+
Index
+ + diff --git a/src/bb-library/doc/setx.htm b/src/bb-library/doc/setx.htm new file mode 100644 index 000000000..39d37966b --- /dev/null +++ b/src/bb-library/doc/setx.htm @@ -0,0 +1,29 @@ + + + + +SetX + + + +

SetX

+SetX(float x) +

Description

+Defines the abscissa of the current position. If the passed value is negative, it is relative +to the right of the page. +

Parameters

+
+
x
+
+The value of the abscissa. +
+
+

See also

+GetX, +GetY, +SetY, +SetXY +
+
Index
+ + diff --git a/src/bb-library/doc/setxy.htm b/src/bb-library/doc/setxy.htm new file mode 100644 index 000000000..005acd469 --- /dev/null +++ b/src/bb-library/doc/setxy.htm @@ -0,0 +1,31 @@ + + + + +SetXY + + + +

SetXY

+SetXY(float x, float y) +

Description

+Defines the abscissa and ordinate of the current position. If the passed values are negative, +they are relative respectively to the right and bottom of the page. +

Parameters

+
+
x
+
+The value of the abscissa. +
+
y
+
+The value of the ordinate. +
+
+

See also

+SetX, +SetY +
+
Index
+ + diff --git a/src/bb-library/doc/sety.htm b/src/bb-library/doc/sety.htm new file mode 100644 index 000000000..7ee94ea00 --- /dev/null +++ b/src/bb-library/doc/sety.htm @@ -0,0 +1,33 @@ + + + + +SetY + + + +

SetY

+SetY(float y [, boolean resetX]) +

Description

+Sets the ordinate and optionally moves the current abscissa back to the left margin. If the value +is negative, it is relative to the bottom of the page. +

Parameters

+
+
y
+
+The value of the ordinate. +
+
resetX
+
+Whether to reset the abscissa. Default value: true. +
+
+

See also

+GetX, +GetY, +SetX, +SetXY +
+
Index
+ + diff --git a/src/bb-library/doc/text.htm b/src/bb-library/doc/text.htm new file mode 100644 index 000000000..0ef618711 --- /dev/null +++ b/src/bb-library/doc/text.htm @@ -0,0 +1,39 @@ + + + + +Text + + + +

Text

+Text(float x, float y, string txt) +

Description

+Prints a character string. The origin is on the left of the first character, on the baseline. +This method allows to place a string precisely on the page, but it is usually easier to use +Cell(), MultiCell() or Write() which are the standard methods to print text. +

Parameters

+
+
x
+
+Abscissa of the origin. +
+
y
+
+Ordinate of the origin. +
+
txt
+
+String to print. +
+
+

See also

+SetFont, +SetTextColor, +Cell, +MultiCell, +Write +
+
Index
+ + diff --git a/src/bb-library/doc/write.htm b/src/bb-library/doc/write.htm new file mode 100644 index 000000000..0c7914c6a --- /dev/null +++ b/src/bb-library/doc/write.htm @@ -0,0 +1,51 @@ + + + + +Write + + + +

Write

+Write(float h, string txt [, mixed link]) +

Description

+This method prints text from the current position. When the right margin is reached (or the \n +character is met) a line break occurs and text continues from the left margin. Upon method exit, +the current position is left just at the end of the text. +
+It is possible to put a link on the text. +

Parameters

+
+
h
+
+Line height. +
+
txt
+
+String to print. +
+
link
+
+URL or identifier returned by AddLink(). +
+
+

Example

+
+
// Begin with regular font
+$pdf->SetFont('Arial','',14);
+$pdf->Write(5,'Visit ');
+// Then put a blue underlined link
+$pdf->SetTextColor(0,0,255);
+$pdf->SetFont('','U');
+$pdf->Write(5,'www.fpdf.org','http://www.fpdf.org');
+
+

See also

+SetFont, +SetTextColor, +AddLink, +MultiCell, +SetAutoPageBreak +
+
Index
+ + diff --git a/src/bb-library/font/DejaVuSansCondensed.ttf b/src/bb-library/font/DejaVuSansCondensed.ttf new file mode 100644 index 000000000..826e619b7 Binary files /dev/null and b/src/bb-library/font/DejaVuSansCondensed.ttf differ diff --git a/src/bb-library/font/courier.php b/src/bb-library/font/courier.php new file mode 100644 index 000000000..bc8478eb3 --- /dev/null +++ b/src/bb-library/font/courier.php @@ -0,0 +1,10 @@ +array(0,128),128=>8364,130=>8218,131=>402,132=>8222,133=>8230,134=>array(8224,2),136=>710,137=>8240,138=>352,139=>8249,140=>338,142=>381,145=>array(8216,2),147=>array(8220,2),149=>8226,150=>array(8211,2),152=>732,153=>8482,154=>353,155=>8250,156=>339,158=>382,159=>376,160=>array(160,96)); +?> diff --git a/src/bb-library/font/courierb.php b/src/bb-library/font/courierb.php new file mode 100644 index 000000000..97ecd701c --- /dev/null +++ b/src/bb-library/font/courierb.php @@ -0,0 +1,10 @@ +array(0,128),128=>8364,130=>8218,131=>402,132=>8222,133=>8230,134=>array(8224,2),136=>710,137=>8240,138=>352,139=>8249,140=>338,142=>381,145=>array(8216,2),147=>array(8220,2),149=>8226,150=>array(8211,2),152=>732,153=>8482,154=>353,155=>8250,156=>339,158=>382,159=>376,160=>array(160,96)); +?> diff --git a/src/bb-library/font/courierbi.php b/src/bb-library/font/courierbi.php new file mode 100644 index 000000000..c4bfff881 --- /dev/null +++ b/src/bb-library/font/courierbi.php @@ -0,0 +1,10 @@ +array(0,128),128=>8364,130=>8218,131=>402,132=>8222,133=>8230,134=>array(8224,2),136=>710,137=>8240,138=>352,139=>8249,140=>338,142=>381,145=>array(8216,2),147=>array(8220,2),149=>8226,150=>array(8211,2),152=>732,153=>8482,154=>353,155=>8250,156=>339,158=>382,159=>376,160=>array(160,96)); +?> diff --git a/src/bb-library/font/courieri.php b/src/bb-library/font/courieri.php new file mode 100644 index 000000000..015a15adf --- /dev/null +++ b/src/bb-library/font/courieri.php @@ -0,0 +1,10 @@ +array(0,128),128=>8364,130=>8218,131=>402,132=>8222,133=>8230,134=>array(8224,2),136=>710,137=>8240,138=>352,139=>8249,140=>338,142=>381,145=>array(8216,2),147=>array(8220,2),149=>8226,150=>array(8211,2),152=>732,153=>8482,154=>353,155=>8250,156=>339,158=>382,159=>376,160=>array(160,96)); +?> diff --git a/src/bb-library/font/helvetica.php b/src/bb-library/font/helvetica.php new file mode 100644 index 000000000..927759b9a --- /dev/null +++ b/src/bb-library/font/helvetica.php @@ -0,0 +1,21 @@ +278,chr(1)=>278,chr(2)=>278,chr(3)=>278,chr(4)=>278,chr(5)=>278,chr(6)=>278,chr(7)=>278,chr(8)=>278,chr(9)=>278,chr(10)=>278,chr(11)=>278,chr(12)=>278,chr(13)=>278,chr(14)=>278,chr(15)=>278,chr(16)=>278,chr(17)=>278,chr(18)=>278,chr(19)=>278,chr(20)=>278,chr(21)=>278, + chr(22)=>278,chr(23)=>278,chr(24)=>278,chr(25)=>278,chr(26)=>278,chr(27)=>278,chr(28)=>278,chr(29)=>278,chr(30)=>278,chr(31)=>278,' '=>278,'!'=>278,'"'=>355,'#'=>556,'$'=>556,'%'=>889,'&'=>667,'\''=>191,'('=>333,')'=>333,'*'=>389,'+'=>584, + ','=>278,'-'=>333,'.'=>278,'/'=>278,'0'=>556,'1'=>556,'2'=>556,'3'=>556,'4'=>556,'5'=>556,'6'=>556,'7'=>556,'8'=>556,'9'=>556,':'=>278,';'=>278,'<'=>584,'='=>584,'>'=>584,'?'=>556,'@'=>1015,'A'=>667, + 'B'=>667,'C'=>722,'D'=>722,'E'=>667,'F'=>611,'G'=>778,'H'=>722,'I'=>278,'J'=>500,'K'=>667,'L'=>556,'M'=>833,'N'=>722,'O'=>778,'P'=>667,'Q'=>778,'R'=>722,'S'=>667,'T'=>611,'U'=>722,'V'=>667,'W'=>944, + 'X'=>667,'Y'=>667,'Z'=>611,'['=>278,'\\'=>278,']'=>278,'^'=>469,'_'=>556,'`'=>333,'a'=>556,'b'=>556,'c'=>500,'d'=>556,'e'=>556,'f'=>278,'g'=>556,'h'=>556,'i'=>222,'j'=>222,'k'=>500,'l'=>222,'m'=>833, + 'n'=>556,'o'=>556,'p'=>556,'q'=>556,'r'=>333,'s'=>500,'t'=>278,'u'=>556,'v'=>500,'w'=>722,'x'=>500,'y'=>500,'z'=>500,'{'=>334,'|'=>260,'}'=>334,'~'=>584,chr(127)=>350,chr(128)=>556,chr(129)=>350,chr(130)=>222,chr(131)=>556, + chr(132)=>333,chr(133)=>1000,chr(134)=>556,chr(135)=>556,chr(136)=>333,chr(137)=>1000,chr(138)=>667,chr(139)=>333,chr(140)=>1000,chr(141)=>350,chr(142)=>611,chr(143)=>350,chr(144)=>350,chr(145)=>222,chr(146)=>222,chr(147)=>333,chr(148)=>333,chr(149)=>350,chr(150)=>556,chr(151)=>1000,chr(152)=>333,chr(153)=>1000, + chr(154)=>500,chr(155)=>333,chr(156)=>944,chr(157)=>350,chr(158)=>500,chr(159)=>667,chr(160)=>278,chr(161)=>333,chr(162)=>556,chr(163)=>556,chr(164)=>556,chr(165)=>556,chr(166)=>260,chr(167)=>556,chr(168)=>333,chr(169)=>737,chr(170)=>370,chr(171)=>556,chr(172)=>584,chr(173)=>333,chr(174)=>737,chr(175)=>333, + chr(176)=>400,chr(177)=>584,chr(178)=>333,chr(179)=>333,chr(180)=>333,chr(181)=>556,chr(182)=>537,chr(183)=>278,chr(184)=>333,chr(185)=>333,chr(186)=>365,chr(187)=>556,chr(188)=>834,chr(189)=>834,chr(190)=>834,chr(191)=>611,chr(192)=>667,chr(193)=>667,chr(194)=>667,chr(195)=>667,chr(196)=>667,chr(197)=>667, + chr(198)=>1000,chr(199)=>722,chr(200)=>667,chr(201)=>667,chr(202)=>667,chr(203)=>667,chr(204)=>278,chr(205)=>278,chr(206)=>278,chr(207)=>278,chr(208)=>722,chr(209)=>722,chr(210)=>778,chr(211)=>778,chr(212)=>778,chr(213)=>778,chr(214)=>778,chr(215)=>584,chr(216)=>778,chr(217)=>722,chr(218)=>722,chr(219)=>722, + chr(220)=>722,chr(221)=>667,chr(222)=>667,chr(223)=>611,chr(224)=>556,chr(225)=>556,chr(226)=>556,chr(227)=>556,chr(228)=>556,chr(229)=>556,chr(230)=>889,chr(231)=>500,chr(232)=>556,chr(233)=>556,chr(234)=>556,chr(235)=>556,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>556,chr(241)=>556, + chr(242)=>556,chr(243)=>556,chr(244)=>556,chr(245)=>556,chr(246)=>556,chr(247)=>584,chr(248)=>611,chr(249)=>556,chr(250)=>556,chr(251)=>556,chr(252)=>556,chr(253)=>500,chr(254)=>556,chr(255)=>500); +$enc = 'cp1252'; +$uv = array(0=>array(0,128),128=>8364,130=>8218,131=>402,132=>8222,133=>8230,134=>array(8224,2),136=>710,137=>8240,138=>352,139=>8249,140=>338,142=>381,145=>array(8216,2),147=>array(8220,2),149=>8226,150=>array(8211,2),152=>732,153=>8482,154=>353,155=>8250,156=>339,158=>382,159=>376,160=>array(160,96)); +?> diff --git a/src/bb-library/font/helveticab.php b/src/bb-library/font/helveticab.php new file mode 100644 index 000000000..bcd736723 --- /dev/null +++ b/src/bb-library/font/helveticab.php @@ -0,0 +1,21 @@ +278,chr(1)=>278,chr(2)=>278,chr(3)=>278,chr(4)=>278,chr(5)=>278,chr(6)=>278,chr(7)=>278,chr(8)=>278,chr(9)=>278,chr(10)=>278,chr(11)=>278,chr(12)=>278,chr(13)=>278,chr(14)=>278,chr(15)=>278,chr(16)=>278,chr(17)=>278,chr(18)=>278,chr(19)=>278,chr(20)=>278,chr(21)=>278, + chr(22)=>278,chr(23)=>278,chr(24)=>278,chr(25)=>278,chr(26)=>278,chr(27)=>278,chr(28)=>278,chr(29)=>278,chr(30)=>278,chr(31)=>278,' '=>278,'!'=>333,'"'=>474,'#'=>556,'$'=>556,'%'=>889,'&'=>722,'\''=>238,'('=>333,')'=>333,'*'=>389,'+'=>584, + ','=>278,'-'=>333,'.'=>278,'/'=>278,'0'=>556,'1'=>556,'2'=>556,'3'=>556,'4'=>556,'5'=>556,'6'=>556,'7'=>556,'8'=>556,'9'=>556,':'=>333,';'=>333,'<'=>584,'='=>584,'>'=>584,'?'=>611,'@'=>975,'A'=>722, + 'B'=>722,'C'=>722,'D'=>722,'E'=>667,'F'=>611,'G'=>778,'H'=>722,'I'=>278,'J'=>556,'K'=>722,'L'=>611,'M'=>833,'N'=>722,'O'=>778,'P'=>667,'Q'=>778,'R'=>722,'S'=>667,'T'=>611,'U'=>722,'V'=>667,'W'=>944, + 'X'=>667,'Y'=>667,'Z'=>611,'['=>333,'\\'=>278,']'=>333,'^'=>584,'_'=>556,'`'=>333,'a'=>556,'b'=>611,'c'=>556,'d'=>611,'e'=>556,'f'=>333,'g'=>611,'h'=>611,'i'=>278,'j'=>278,'k'=>556,'l'=>278,'m'=>889, + 'n'=>611,'o'=>611,'p'=>611,'q'=>611,'r'=>389,'s'=>556,'t'=>333,'u'=>611,'v'=>556,'w'=>778,'x'=>556,'y'=>556,'z'=>500,'{'=>389,'|'=>280,'}'=>389,'~'=>584,chr(127)=>350,chr(128)=>556,chr(129)=>350,chr(130)=>278,chr(131)=>556, + chr(132)=>500,chr(133)=>1000,chr(134)=>556,chr(135)=>556,chr(136)=>333,chr(137)=>1000,chr(138)=>667,chr(139)=>333,chr(140)=>1000,chr(141)=>350,chr(142)=>611,chr(143)=>350,chr(144)=>350,chr(145)=>278,chr(146)=>278,chr(147)=>500,chr(148)=>500,chr(149)=>350,chr(150)=>556,chr(151)=>1000,chr(152)=>333,chr(153)=>1000, + chr(154)=>556,chr(155)=>333,chr(156)=>944,chr(157)=>350,chr(158)=>500,chr(159)=>667,chr(160)=>278,chr(161)=>333,chr(162)=>556,chr(163)=>556,chr(164)=>556,chr(165)=>556,chr(166)=>280,chr(167)=>556,chr(168)=>333,chr(169)=>737,chr(170)=>370,chr(171)=>556,chr(172)=>584,chr(173)=>333,chr(174)=>737,chr(175)=>333, + chr(176)=>400,chr(177)=>584,chr(178)=>333,chr(179)=>333,chr(180)=>333,chr(181)=>611,chr(182)=>556,chr(183)=>278,chr(184)=>333,chr(185)=>333,chr(186)=>365,chr(187)=>556,chr(188)=>834,chr(189)=>834,chr(190)=>834,chr(191)=>611,chr(192)=>722,chr(193)=>722,chr(194)=>722,chr(195)=>722,chr(196)=>722,chr(197)=>722, + chr(198)=>1000,chr(199)=>722,chr(200)=>667,chr(201)=>667,chr(202)=>667,chr(203)=>667,chr(204)=>278,chr(205)=>278,chr(206)=>278,chr(207)=>278,chr(208)=>722,chr(209)=>722,chr(210)=>778,chr(211)=>778,chr(212)=>778,chr(213)=>778,chr(214)=>778,chr(215)=>584,chr(216)=>778,chr(217)=>722,chr(218)=>722,chr(219)=>722, + chr(220)=>722,chr(221)=>667,chr(222)=>667,chr(223)=>611,chr(224)=>556,chr(225)=>556,chr(226)=>556,chr(227)=>556,chr(228)=>556,chr(229)=>556,chr(230)=>889,chr(231)=>556,chr(232)=>556,chr(233)=>556,chr(234)=>556,chr(235)=>556,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>611,chr(241)=>611, + chr(242)=>611,chr(243)=>611,chr(244)=>611,chr(245)=>611,chr(246)=>611,chr(247)=>584,chr(248)=>611,chr(249)=>611,chr(250)=>611,chr(251)=>611,chr(252)=>611,chr(253)=>556,chr(254)=>611,chr(255)=>556); +$enc = 'cp1252'; +$uv = array(0=>array(0,128),128=>8364,130=>8218,131=>402,132=>8222,133=>8230,134=>array(8224,2),136=>710,137=>8240,138=>352,139=>8249,140=>338,142=>381,145=>array(8216,2),147=>array(8220,2),149=>8226,150=>array(8211,2),152=>732,153=>8482,154=>353,155=>8250,156=>339,158=>382,159=>376,160=>array(160,96)); +?> diff --git a/src/bb-library/font/helveticabi.php b/src/bb-library/font/helveticabi.php new file mode 100644 index 000000000..0243cde4f --- /dev/null +++ b/src/bb-library/font/helveticabi.php @@ -0,0 +1,21 @@ +278,chr(1)=>278,chr(2)=>278,chr(3)=>278,chr(4)=>278,chr(5)=>278,chr(6)=>278,chr(7)=>278,chr(8)=>278,chr(9)=>278,chr(10)=>278,chr(11)=>278,chr(12)=>278,chr(13)=>278,chr(14)=>278,chr(15)=>278,chr(16)=>278,chr(17)=>278,chr(18)=>278,chr(19)=>278,chr(20)=>278,chr(21)=>278, + chr(22)=>278,chr(23)=>278,chr(24)=>278,chr(25)=>278,chr(26)=>278,chr(27)=>278,chr(28)=>278,chr(29)=>278,chr(30)=>278,chr(31)=>278,' '=>278,'!'=>333,'"'=>474,'#'=>556,'$'=>556,'%'=>889,'&'=>722,'\''=>238,'('=>333,')'=>333,'*'=>389,'+'=>584, + ','=>278,'-'=>333,'.'=>278,'/'=>278,'0'=>556,'1'=>556,'2'=>556,'3'=>556,'4'=>556,'5'=>556,'6'=>556,'7'=>556,'8'=>556,'9'=>556,':'=>333,';'=>333,'<'=>584,'='=>584,'>'=>584,'?'=>611,'@'=>975,'A'=>722, + 'B'=>722,'C'=>722,'D'=>722,'E'=>667,'F'=>611,'G'=>778,'H'=>722,'I'=>278,'J'=>556,'K'=>722,'L'=>611,'M'=>833,'N'=>722,'O'=>778,'P'=>667,'Q'=>778,'R'=>722,'S'=>667,'T'=>611,'U'=>722,'V'=>667,'W'=>944, + 'X'=>667,'Y'=>667,'Z'=>611,'['=>333,'\\'=>278,']'=>333,'^'=>584,'_'=>556,'`'=>333,'a'=>556,'b'=>611,'c'=>556,'d'=>611,'e'=>556,'f'=>333,'g'=>611,'h'=>611,'i'=>278,'j'=>278,'k'=>556,'l'=>278,'m'=>889, + 'n'=>611,'o'=>611,'p'=>611,'q'=>611,'r'=>389,'s'=>556,'t'=>333,'u'=>611,'v'=>556,'w'=>778,'x'=>556,'y'=>556,'z'=>500,'{'=>389,'|'=>280,'}'=>389,'~'=>584,chr(127)=>350,chr(128)=>556,chr(129)=>350,chr(130)=>278,chr(131)=>556, + chr(132)=>500,chr(133)=>1000,chr(134)=>556,chr(135)=>556,chr(136)=>333,chr(137)=>1000,chr(138)=>667,chr(139)=>333,chr(140)=>1000,chr(141)=>350,chr(142)=>611,chr(143)=>350,chr(144)=>350,chr(145)=>278,chr(146)=>278,chr(147)=>500,chr(148)=>500,chr(149)=>350,chr(150)=>556,chr(151)=>1000,chr(152)=>333,chr(153)=>1000, + chr(154)=>556,chr(155)=>333,chr(156)=>944,chr(157)=>350,chr(158)=>500,chr(159)=>667,chr(160)=>278,chr(161)=>333,chr(162)=>556,chr(163)=>556,chr(164)=>556,chr(165)=>556,chr(166)=>280,chr(167)=>556,chr(168)=>333,chr(169)=>737,chr(170)=>370,chr(171)=>556,chr(172)=>584,chr(173)=>333,chr(174)=>737,chr(175)=>333, + chr(176)=>400,chr(177)=>584,chr(178)=>333,chr(179)=>333,chr(180)=>333,chr(181)=>611,chr(182)=>556,chr(183)=>278,chr(184)=>333,chr(185)=>333,chr(186)=>365,chr(187)=>556,chr(188)=>834,chr(189)=>834,chr(190)=>834,chr(191)=>611,chr(192)=>722,chr(193)=>722,chr(194)=>722,chr(195)=>722,chr(196)=>722,chr(197)=>722, + chr(198)=>1000,chr(199)=>722,chr(200)=>667,chr(201)=>667,chr(202)=>667,chr(203)=>667,chr(204)=>278,chr(205)=>278,chr(206)=>278,chr(207)=>278,chr(208)=>722,chr(209)=>722,chr(210)=>778,chr(211)=>778,chr(212)=>778,chr(213)=>778,chr(214)=>778,chr(215)=>584,chr(216)=>778,chr(217)=>722,chr(218)=>722,chr(219)=>722, + chr(220)=>722,chr(221)=>667,chr(222)=>667,chr(223)=>611,chr(224)=>556,chr(225)=>556,chr(226)=>556,chr(227)=>556,chr(228)=>556,chr(229)=>556,chr(230)=>889,chr(231)=>556,chr(232)=>556,chr(233)=>556,chr(234)=>556,chr(235)=>556,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>611,chr(241)=>611, + chr(242)=>611,chr(243)=>611,chr(244)=>611,chr(245)=>611,chr(246)=>611,chr(247)=>584,chr(248)=>611,chr(249)=>611,chr(250)=>611,chr(251)=>611,chr(252)=>611,chr(253)=>556,chr(254)=>611,chr(255)=>556); +$enc = 'cp1252'; +$uv = array(0=>array(0,128),128=>8364,130=>8218,131=>402,132=>8222,133=>8230,134=>array(8224,2),136=>710,137=>8240,138=>352,139=>8249,140=>338,142=>381,145=>array(8216,2),147=>array(8220,2),149=>8226,150=>array(8211,2),152=>732,153=>8482,154=>353,155=>8250,156=>339,158=>382,159=>376,160=>array(160,96)); +?> diff --git a/src/bb-library/font/helveticai.php b/src/bb-library/font/helveticai.php new file mode 100644 index 000000000..06ec735b8 --- /dev/null +++ b/src/bb-library/font/helveticai.php @@ -0,0 +1,21 @@ +278,chr(1)=>278,chr(2)=>278,chr(3)=>278,chr(4)=>278,chr(5)=>278,chr(6)=>278,chr(7)=>278,chr(8)=>278,chr(9)=>278,chr(10)=>278,chr(11)=>278,chr(12)=>278,chr(13)=>278,chr(14)=>278,chr(15)=>278,chr(16)=>278,chr(17)=>278,chr(18)=>278,chr(19)=>278,chr(20)=>278,chr(21)=>278, + chr(22)=>278,chr(23)=>278,chr(24)=>278,chr(25)=>278,chr(26)=>278,chr(27)=>278,chr(28)=>278,chr(29)=>278,chr(30)=>278,chr(31)=>278,' '=>278,'!'=>278,'"'=>355,'#'=>556,'$'=>556,'%'=>889,'&'=>667,'\''=>191,'('=>333,')'=>333,'*'=>389,'+'=>584, + ','=>278,'-'=>333,'.'=>278,'/'=>278,'0'=>556,'1'=>556,'2'=>556,'3'=>556,'4'=>556,'5'=>556,'6'=>556,'7'=>556,'8'=>556,'9'=>556,':'=>278,';'=>278,'<'=>584,'='=>584,'>'=>584,'?'=>556,'@'=>1015,'A'=>667, + 'B'=>667,'C'=>722,'D'=>722,'E'=>667,'F'=>611,'G'=>778,'H'=>722,'I'=>278,'J'=>500,'K'=>667,'L'=>556,'M'=>833,'N'=>722,'O'=>778,'P'=>667,'Q'=>778,'R'=>722,'S'=>667,'T'=>611,'U'=>722,'V'=>667,'W'=>944, + 'X'=>667,'Y'=>667,'Z'=>611,'['=>278,'\\'=>278,']'=>278,'^'=>469,'_'=>556,'`'=>333,'a'=>556,'b'=>556,'c'=>500,'d'=>556,'e'=>556,'f'=>278,'g'=>556,'h'=>556,'i'=>222,'j'=>222,'k'=>500,'l'=>222,'m'=>833, + 'n'=>556,'o'=>556,'p'=>556,'q'=>556,'r'=>333,'s'=>500,'t'=>278,'u'=>556,'v'=>500,'w'=>722,'x'=>500,'y'=>500,'z'=>500,'{'=>334,'|'=>260,'}'=>334,'~'=>584,chr(127)=>350,chr(128)=>556,chr(129)=>350,chr(130)=>222,chr(131)=>556, + chr(132)=>333,chr(133)=>1000,chr(134)=>556,chr(135)=>556,chr(136)=>333,chr(137)=>1000,chr(138)=>667,chr(139)=>333,chr(140)=>1000,chr(141)=>350,chr(142)=>611,chr(143)=>350,chr(144)=>350,chr(145)=>222,chr(146)=>222,chr(147)=>333,chr(148)=>333,chr(149)=>350,chr(150)=>556,chr(151)=>1000,chr(152)=>333,chr(153)=>1000, + chr(154)=>500,chr(155)=>333,chr(156)=>944,chr(157)=>350,chr(158)=>500,chr(159)=>667,chr(160)=>278,chr(161)=>333,chr(162)=>556,chr(163)=>556,chr(164)=>556,chr(165)=>556,chr(166)=>260,chr(167)=>556,chr(168)=>333,chr(169)=>737,chr(170)=>370,chr(171)=>556,chr(172)=>584,chr(173)=>333,chr(174)=>737,chr(175)=>333, + chr(176)=>400,chr(177)=>584,chr(178)=>333,chr(179)=>333,chr(180)=>333,chr(181)=>556,chr(182)=>537,chr(183)=>278,chr(184)=>333,chr(185)=>333,chr(186)=>365,chr(187)=>556,chr(188)=>834,chr(189)=>834,chr(190)=>834,chr(191)=>611,chr(192)=>667,chr(193)=>667,chr(194)=>667,chr(195)=>667,chr(196)=>667,chr(197)=>667, + chr(198)=>1000,chr(199)=>722,chr(200)=>667,chr(201)=>667,chr(202)=>667,chr(203)=>667,chr(204)=>278,chr(205)=>278,chr(206)=>278,chr(207)=>278,chr(208)=>722,chr(209)=>722,chr(210)=>778,chr(211)=>778,chr(212)=>778,chr(213)=>778,chr(214)=>778,chr(215)=>584,chr(216)=>778,chr(217)=>722,chr(218)=>722,chr(219)=>722, + chr(220)=>722,chr(221)=>667,chr(222)=>667,chr(223)=>611,chr(224)=>556,chr(225)=>556,chr(226)=>556,chr(227)=>556,chr(228)=>556,chr(229)=>556,chr(230)=>889,chr(231)=>500,chr(232)=>556,chr(233)=>556,chr(234)=>556,chr(235)=>556,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>556,chr(241)=>556, + chr(242)=>556,chr(243)=>556,chr(244)=>556,chr(245)=>556,chr(246)=>556,chr(247)=>584,chr(248)=>611,chr(249)=>556,chr(250)=>556,chr(251)=>556,chr(252)=>556,chr(253)=>500,chr(254)=>556,chr(255)=>500); +$enc = 'cp1252'; +$uv = array(0=>array(0,128),128=>8364,130=>8218,131=>402,132=>8222,133=>8230,134=>array(8224,2),136=>710,137=>8240,138=>352,139=>8249,140=>338,142=>381,145=>array(8216,2),147=>array(8220,2),149=>8226,150=>array(8211,2),152=>732,153=>8482,154=>353,155=>8250,156=>339,158=>382,159=>376,160=>array(160,96)); +?> diff --git a/src/bb-library/font/symbol.php b/src/bb-library/font/symbol.php new file mode 100644 index 000000000..f8f0c3309 --- /dev/null +++ b/src/bb-library/font/symbol.php @@ -0,0 +1,20 @@ +250,chr(1)=>250,chr(2)=>250,chr(3)=>250,chr(4)=>250,chr(5)=>250,chr(6)=>250,chr(7)=>250,chr(8)=>250,chr(9)=>250,chr(10)=>250,chr(11)=>250,chr(12)=>250,chr(13)=>250,chr(14)=>250,chr(15)=>250,chr(16)=>250,chr(17)=>250,chr(18)=>250,chr(19)=>250,chr(20)=>250,chr(21)=>250, + chr(22)=>250,chr(23)=>250,chr(24)=>250,chr(25)=>250,chr(26)=>250,chr(27)=>250,chr(28)=>250,chr(29)=>250,chr(30)=>250,chr(31)=>250,' '=>250,'!'=>333,'"'=>713,'#'=>500,'$'=>549,'%'=>833,'&'=>778,'\''=>439,'('=>333,')'=>333,'*'=>500,'+'=>549, + ','=>250,'-'=>549,'.'=>250,'/'=>278,'0'=>500,'1'=>500,'2'=>500,'3'=>500,'4'=>500,'5'=>500,'6'=>500,'7'=>500,'8'=>500,'9'=>500,':'=>278,';'=>278,'<'=>549,'='=>549,'>'=>549,'?'=>444,'@'=>549,'A'=>722, + 'B'=>667,'C'=>722,'D'=>612,'E'=>611,'F'=>763,'G'=>603,'H'=>722,'I'=>333,'J'=>631,'K'=>722,'L'=>686,'M'=>889,'N'=>722,'O'=>722,'P'=>768,'Q'=>741,'R'=>556,'S'=>592,'T'=>611,'U'=>690,'V'=>439,'W'=>768, + 'X'=>645,'Y'=>795,'Z'=>611,'['=>333,'\\'=>863,']'=>333,'^'=>658,'_'=>500,'`'=>500,'a'=>631,'b'=>549,'c'=>549,'d'=>494,'e'=>439,'f'=>521,'g'=>411,'h'=>603,'i'=>329,'j'=>603,'k'=>549,'l'=>549,'m'=>576, + 'n'=>521,'o'=>549,'p'=>549,'q'=>521,'r'=>549,'s'=>603,'t'=>439,'u'=>576,'v'=>713,'w'=>686,'x'=>493,'y'=>686,'z'=>494,'{'=>480,'|'=>200,'}'=>480,'~'=>549,chr(127)=>0,chr(128)=>0,chr(129)=>0,chr(130)=>0,chr(131)=>0, + chr(132)=>0,chr(133)=>0,chr(134)=>0,chr(135)=>0,chr(136)=>0,chr(137)=>0,chr(138)=>0,chr(139)=>0,chr(140)=>0,chr(141)=>0,chr(142)=>0,chr(143)=>0,chr(144)=>0,chr(145)=>0,chr(146)=>0,chr(147)=>0,chr(148)=>0,chr(149)=>0,chr(150)=>0,chr(151)=>0,chr(152)=>0,chr(153)=>0, + chr(154)=>0,chr(155)=>0,chr(156)=>0,chr(157)=>0,chr(158)=>0,chr(159)=>0,chr(160)=>750,chr(161)=>620,chr(162)=>247,chr(163)=>549,chr(164)=>167,chr(165)=>713,chr(166)=>500,chr(167)=>753,chr(168)=>753,chr(169)=>753,chr(170)=>753,chr(171)=>1042,chr(172)=>987,chr(173)=>603,chr(174)=>987,chr(175)=>603, + chr(176)=>400,chr(177)=>549,chr(178)=>411,chr(179)=>549,chr(180)=>549,chr(181)=>713,chr(182)=>494,chr(183)=>460,chr(184)=>549,chr(185)=>549,chr(186)=>549,chr(187)=>549,chr(188)=>1000,chr(189)=>603,chr(190)=>1000,chr(191)=>658,chr(192)=>823,chr(193)=>686,chr(194)=>795,chr(195)=>987,chr(196)=>768,chr(197)=>768, + chr(198)=>823,chr(199)=>768,chr(200)=>768,chr(201)=>713,chr(202)=>713,chr(203)=>713,chr(204)=>713,chr(205)=>713,chr(206)=>713,chr(207)=>713,chr(208)=>768,chr(209)=>713,chr(210)=>790,chr(211)=>790,chr(212)=>890,chr(213)=>823,chr(214)=>549,chr(215)=>250,chr(216)=>713,chr(217)=>603,chr(218)=>603,chr(219)=>1042, + chr(220)=>987,chr(221)=>603,chr(222)=>987,chr(223)=>603,chr(224)=>494,chr(225)=>329,chr(226)=>790,chr(227)=>790,chr(228)=>786,chr(229)=>713,chr(230)=>384,chr(231)=>384,chr(232)=>384,chr(233)=>384,chr(234)=>384,chr(235)=>384,chr(236)=>494,chr(237)=>494,chr(238)=>494,chr(239)=>494,chr(240)=>0,chr(241)=>329, + chr(242)=>274,chr(243)=>686,chr(244)=>686,chr(245)=>686,chr(246)=>384,chr(247)=>384,chr(248)=>384,chr(249)=>384,chr(250)=>384,chr(251)=>384,chr(252)=>494,chr(253)=>494,chr(254)=>494,chr(255)=>0); +$uv = array(32=>160,33=>33,34=>8704,35=>35,36=>8707,37=>array(37,2),39=>8715,40=>array(40,2),42=>8727,43=>array(43,2),45=>8722,46=>array(46,18),64=>8773,65=>array(913,2),67=>935,68=>array(916,2),70=>934,71=>915,72=>919,73=>921,74=>977,75=>array(922,4),79=>array(927,2),81=>920,82=>929,83=>array(931,3),86=>962,87=>937,88=>926,89=>936,90=>918,91=>91,92=>8756,93=>93,94=>8869,95=>95,96=>63717,97=>array(945,2),99=>967,100=>array(948,2),102=>966,103=>947,104=>951,105=>953,106=>981,107=>array(954,4),111=>array(959,2),113=>952,114=>961,115=>array(963,3),118=>982,119=>969,120=>958,121=>968,122=>950,123=>array(123,3),126=>8764,160=>8364,161=>978,162=>8242,163=>8804,164=>8725,165=>8734,166=>402,167=>9827,168=>9830,169=>9829,170=>9824,171=>8596,172=>array(8592,4),176=>array(176,2),178=>8243,179=>8805,180=>215,181=>8733,182=>8706,183=>8226,184=>247,185=>array(8800,2),187=>8776,188=>8230,189=>array(63718,2),191=>8629,192=>8501,193=>8465,194=>8476,195=>8472,196=>8855,197=>8853,198=>8709,199=>array(8745,2),201=>8835,202=>8839,203=>8836,204=>8834,205=>8838,206=>array(8712,2),208=>8736,209=>8711,210=>63194,211=>63193,212=>63195,213=>8719,214=>8730,215=>8901,216=>172,217=>array(8743,2),219=>8660,220=>array(8656,4),224=>9674,225=>9001,226=>array(63720,3),229=>8721,230=>array(63723,10),241=>9002,242=>8747,243=>8992,244=>63733,245=>8993,246=>array(63734,9)); +?> diff --git a/src/bb-library/font/times.php b/src/bb-library/font/times.php new file mode 100644 index 000000000..81f2a8b4b --- /dev/null +++ b/src/bb-library/font/times.php @@ -0,0 +1,21 @@ +250,chr(1)=>250,chr(2)=>250,chr(3)=>250,chr(4)=>250,chr(5)=>250,chr(6)=>250,chr(7)=>250,chr(8)=>250,chr(9)=>250,chr(10)=>250,chr(11)=>250,chr(12)=>250,chr(13)=>250,chr(14)=>250,chr(15)=>250,chr(16)=>250,chr(17)=>250,chr(18)=>250,chr(19)=>250,chr(20)=>250,chr(21)=>250, + chr(22)=>250,chr(23)=>250,chr(24)=>250,chr(25)=>250,chr(26)=>250,chr(27)=>250,chr(28)=>250,chr(29)=>250,chr(30)=>250,chr(31)=>250,' '=>250,'!'=>333,'"'=>408,'#'=>500,'$'=>500,'%'=>833,'&'=>778,'\''=>180,'('=>333,')'=>333,'*'=>500,'+'=>564, + ','=>250,'-'=>333,'.'=>250,'/'=>278,'0'=>500,'1'=>500,'2'=>500,'3'=>500,'4'=>500,'5'=>500,'6'=>500,'7'=>500,'8'=>500,'9'=>500,':'=>278,';'=>278,'<'=>564,'='=>564,'>'=>564,'?'=>444,'@'=>921,'A'=>722, + 'B'=>667,'C'=>667,'D'=>722,'E'=>611,'F'=>556,'G'=>722,'H'=>722,'I'=>333,'J'=>389,'K'=>722,'L'=>611,'M'=>889,'N'=>722,'O'=>722,'P'=>556,'Q'=>722,'R'=>667,'S'=>556,'T'=>611,'U'=>722,'V'=>722,'W'=>944, + 'X'=>722,'Y'=>722,'Z'=>611,'['=>333,'\\'=>278,']'=>333,'^'=>469,'_'=>500,'`'=>333,'a'=>444,'b'=>500,'c'=>444,'d'=>500,'e'=>444,'f'=>333,'g'=>500,'h'=>500,'i'=>278,'j'=>278,'k'=>500,'l'=>278,'m'=>778, + 'n'=>500,'o'=>500,'p'=>500,'q'=>500,'r'=>333,'s'=>389,'t'=>278,'u'=>500,'v'=>500,'w'=>722,'x'=>500,'y'=>500,'z'=>444,'{'=>480,'|'=>200,'}'=>480,'~'=>541,chr(127)=>350,chr(128)=>500,chr(129)=>350,chr(130)=>333,chr(131)=>500, + chr(132)=>444,chr(133)=>1000,chr(134)=>500,chr(135)=>500,chr(136)=>333,chr(137)=>1000,chr(138)=>556,chr(139)=>333,chr(140)=>889,chr(141)=>350,chr(142)=>611,chr(143)=>350,chr(144)=>350,chr(145)=>333,chr(146)=>333,chr(147)=>444,chr(148)=>444,chr(149)=>350,chr(150)=>500,chr(151)=>1000,chr(152)=>333,chr(153)=>980, + chr(154)=>389,chr(155)=>333,chr(156)=>722,chr(157)=>350,chr(158)=>444,chr(159)=>722,chr(160)=>250,chr(161)=>333,chr(162)=>500,chr(163)=>500,chr(164)=>500,chr(165)=>500,chr(166)=>200,chr(167)=>500,chr(168)=>333,chr(169)=>760,chr(170)=>276,chr(171)=>500,chr(172)=>564,chr(173)=>333,chr(174)=>760,chr(175)=>333, + chr(176)=>400,chr(177)=>564,chr(178)=>300,chr(179)=>300,chr(180)=>333,chr(181)=>500,chr(182)=>453,chr(183)=>250,chr(184)=>333,chr(185)=>300,chr(186)=>310,chr(187)=>500,chr(188)=>750,chr(189)=>750,chr(190)=>750,chr(191)=>444,chr(192)=>722,chr(193)=>722,chr(194)=>722,chr(195)=>722,chr(196)=>722,chr(197)=>722, + chr(198)=>889,chr(199)=>667,chr(200)=>611,chr(201)=>611,chr(202)=>611,chr(203)=>611,chr(204)=>333,chr(205)=>333,chr(206)=>333,chr(207)=>333,chr(208)=>722,chr(209)=>722,chr(210)=>722,chr(211)=>722,chr(212)=>722,chr(213)=>722,chr(214)=>722,chr(215)=>564,chr(216)=>722,chr(217)=>722,chr(218)=>722,chr(219)=>722, + chr(220)=>722,chr(221)=>722,chr(222)=>556,chr(223)=>500,chr(224)=>444,chr(225)=>444,chr(226)=>444,chr(227)=>444,chr(228)=>444,chr(229)=>444,chr(230)=>667,chr(231)=>444,chr(232)=>444,chr(233)=>444,chr(234)=>444,chr(235)=>444,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>500,chr(241)=>500, + chr(242)=>500,chr(243)=>500,chr(244)=>500,chr(245)=>500,chr(246)=>500,chr(247)=>564,chr(248)=>500,chr(249)=>500,chr(250)=>500,chr(251)=>500,chr(252)=>500,chr(253)=>500,chr(254)=>500,chr(255)=>500); +$enc = 'cp1252'; +$uv = array(0=>array(0,128),128=>8364,130=>8218,131=>402,132=>8222,133=>8230,134=>array(8224,2),136=>710,137=>8240,138=>352,139=>8249,140=>338,142=>381,145=>array(8216,2),147=>array(8220,2),149=>8226,150=>array(8211,2),152=>732,153=>8482,154=>353,155=>8250,156=>339,158=>382,159=>376,160=>array(160,96)); +?> diff --git a/src/bb-library/font/timesb.php b/src/bb-library/font/timesb.php new file mode 100644 index 000000000..7db704fd4 --- /dev/null +++ b/src/bb-library/font/timesb.php @@ -0,0 +1,21 @@ +250,chr(1)=>250,chr(2)=>250,chr(3)=>250,chr(4)=>250,chr(5)=>250,chr(6)=>250,chr(7)=>250,chr(8)=>250,chr(9)=>250,chr(10)=>250,chr(11)=>250,chr(12)=>250,chr(13)=>250,chr(14)=>250,chr(15)=>250,chr(16)=>250,chr(17)=>250,chr(18)=>250,chr(19)=>250,chr(20)=>250,chr(21)=>250, + chr(22)=>250,chr(23)=>250,chr(24)=>250,chr(25)=>250,chr(26)=>250,chr(27)=>250,chr(28)=>250,chr(29)=>250,chr(30)=>250,chr(31)=>250,' '=>250,'!'=>333,'"'=>555,'#'=>500,'$'=>500,'%'=>1000,'&'=>833,'\''=>278,'('=>333,')'=>333,'*'=>500,'+'=>570, + ','=>250,'-'=>333,'.'=>250,'/'=>278,'0'=>500,'1'=>500,'2'=>500,'3'=>500,'4'=>500,'5'=>500,'6'=>500,'7'=>500,'8'=>500,'9'=>500,':'=>333,';'=>333,'<'=>570,'='=>570,'>'=>570,'?'=>500,'@'=>930,'A'=>722, + 'B'=>667,'C'=>722,'D'=>722,'E'=>667,'F'=>611,'G'=>778,'H'=>778,'I'=>389,'J'=>500,'K'=>778,'L'=>667,'M'=>944,'N'=>722,'O'=>778,'P'=>611,'Q'=>778,'R'=>722,'S'=>556,'T'=>667,'U'=>722,'V'=>722,'W'=>1000, + 'X'=>722,'Y'=>722,'Z'=>667,'['=>333,'\\'=>278,']'=>333,'^'=>581,'_'=>500,'`'=>333,'a'=>500,'b'=>556,'c'=>444,'d'=>556,'e'=>444,'f'=>333,'g'=>500,'h'=>556,'i'=>278,'j'=>333,'k'=>556,'l'=>278,'m'=>833, + 'n'=>556,'o'=>500,'p'=>556,'q'=>556,'r'=>444,'s'=>389,'t'=>333,'u'=>556,'v'=>500,'w'=>722,'x'=>500,'y'=>500,'z'=>444,'{'=>394,'|'=>220,'}'=>394,'~'=>520,chr(127)=>350,chr(128)=>500,chr(129)=>350,chr(130)=>333,chr(131)=>500, + chr(132)=>500,chr(133)=>1000,chr(134)=>500,chr(135)=>500,chr(136)=>333,chr(137)=>1000,chr(138)=>556,chr(139)=>333,chr(140)=>1000,chr(141)=>350,chr(142)=>667,chr(143)=>350,chr(144)=>350,chr(145)=>333,chr(146)=>333,chr(147)=>500,chr(148)=>500,chr(149)=>350,chr(150)=>500,chr(151)=>1000,chr(152)=>333,chr(153)=>1000, + chr(154)=>389,chr(155)=>333,chr(156)=>722,chr(157)=>350,chr(158)=>444,chr(159)=>722,chr(160)=>250,chr(161)=>333,chr(162)=>500,chr(163)=>500,chr(164)=>500,chr(165)=>500,chr(166)=>220,chr(167)=>500,chr(168)=>333,chr(169)=>747,chr(170)=>300,chr(171)=>500,chr(172)=>570,chr(173)=>333,chr(174)=>747,chr(175)=>333, + chr(176)=>400,chr(177)=>570,chr(178)=>300,chr(179)=>300,chr(180)=>333,chr(181)=>556,chr(182)=>540,chr(183)=>250,chr(184)=>333,chr(185)=>300,chr(186)=>330,chr(187)=>500,chr(188)=>750,chr(189)=>750,chr(190)=>750,chr(191)=>500,chr(192)=>722,chr(193)=>722,chr(194)=>722,chr(195)=>722,chr(196)=>722,chr(197)=>722, + chr(198)=>1000,chr(199)=>722,chr(200)=>667,chr(201)=>667,chr(202)=>667,chr(203)=>667,chr(204)=>389,chr(205)=>389,chr(206)=>389,chr(207)=>389,chr(208)=>722,chr(209)=>722,chr(210)=>778,chr(211)=>778,chr(212)=>778,chr(213)=>778,chr(214)=>778,chr(215)=>570,chr(216)=>778,chr(217)=>722,chr(218)=>722,chr(219)=>722, + chr(220)=>722,chr(221)=>722,chr(222)=>611,chr(223)=>556,chr(224)=>500,chr(225)=>500,chr(226)=>500,chr(227)=>500,chr(228)=>500,chr(229)=>500,chr(230)=>722,chr(231)=>444,chr(232)=>444,chr(233)=>444,chr(234)=>444,chr(235)=>444,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>500,chr(241)=>556, + chr(242)=>500,chr(243)=>500,chr(244)=>500,chr(245)=>500,chr(246)=>500,chr(247)=>570,chr(248)=>500,chr(249)=>556,chr(250)=>556,chr(251)=>556,chr(252)=>556,chr(253)=>500,chr(254)=>556,chr(255)=>500); +$enc = 'cp1252'; +$uv = array(0=>array(0,128),128=>8364,130=>8218,131=>402,132=>8222,133=>8230,134=>array(8224,2),136=>710,137=>8240,138=>352,139=>8249,140=>338,142=>381,145=>array(8216,2),147=>array(8220,2),149=>8226,150=>array(8211,2),152=>732,153=>8482,154=>353,155=>8250,156=>339,158=>382,159=>376,160=>array(160,96)); +?> diff --git a/src/bb-library/font/timesbi.php b/src/bb-library/font/timesbi.php new file mode 100644 index 000000000..089f21ab3 --- /dev/null +++ b/src/bb-library/font/timesbi.php @@ -0,0 +1,21 @@ +250,chr(1)=>250,chr(2)=>250,chr(3)=>250,chr(4)=>250,chr(5)=>250,chr(6)=>250,chr(7)=>250,chr(8)=>250,chr(9)=>250,chr(10)=>250,chr(11)=>250,chr(12)=>250,chr(13)=>250,chr(14)=>250,chr(15)=>250,chr(16)=>250,chr(17)=>250,chr(18)=>250,chr(19)=>250,chr(20)=>250,chr(21)=>250, + chr(22)=>250,chr(23)=>250,chr(24)=>250,chr(25)=>250,chr(26)=>250,chr(27)=>250,chr(28)=>250,chr(29)=>250,chr(30)=>250,chr(31)=>250,' '=>250,'!'=>389,'"'=>555,'#'=>500,'$'=>500,'%'=>833,'&'=>778,'\''=>278,'('=>333,')'=>333,'*'=>500,'+'=>570, + ','=>250,'-'=>333,'.'=>250,'/'=>278,'0'=>500,'1'=>500,'2'=>500,'3'=>500,'4'=>500,'5'=>500,'6'=>500,'7'=>500,'8'=>500,'9'=>500,':'=>333,';'=>333,'<'=>570,'='=>570,'>'=>570,'?'=>500,'@'=>832,'A'=>667, + 'B'=>667,'C'=>667,'D'=>722,'E'=>667,'F'=>667,'G'=>722,'H'=>778,'I'=>389,'J'=>500,'K'=>667,'L'=>611,'M'=>889,'N'=>722,'O'=>722,'P'=>611,'Q'=>722,'R'=>667,'S'=>556,'T'=>611,'U'=>722,'V'=>667,'W'=>889, + 'X'=>667,'Y'=>611,'Z'=>611,'['=>333,'\\'=>278,']'=>333,'^'=>570,'_'=>500,'`'=>333,'a'=>500,'b'=>500,'c'=>444,'d'=>500,'e'=>444,'f'=>333,'g'=>500,'h'=>556,'i'=>278,'j'=>278,'k'=>500,'l'=>278,'m'=>778, + 'n'=>556,'o'=>500,'p'=>500,'q'=>500,'r'=>389,'s'=>389,'t'=>278,'u'=>556,'v'=>444,'w'=>667,'x'=>500,'y'=>444,'z'=>389,'{'=>348,'|'=>220,'}'=>348,'~'=>570,chr(127)=>350,chr(128)=>500,chr(129)=>350,chr(130)=>333,chr(131)=>500, + chr(132)=>500,chr(133)=>1000,chr(134)=>500,chr(135)=>500,chr(136)=>333,chr(137)=>1000,chr(138)=>556,chr(139)=>333,chr(140)=>944,chr(141)=>350,chr(142)=>611,chr(143)=>350,chr(144)=>350,chr(145)=>333,chr(146)=>333,chr(147)=>500,chr(148)=>500,chr(149)=>350,chr(150)=>500,chr(151)=>1000,chr(152)=>333,chr(153)=>1000, + chr(154)=>389,chr(155)=>333,chr(156)=>722,chr(157)=>350,chr(158)=>389,chr(159)=>611,chr(160)=>250,chr(161)=>389,chr(162)=>500,chr(163)=>500,chr(164)=>500,chr(165)=>500,chr(166)=>220,chr(167)=>500,chr(168)=>333,chr(169)=>747,chr(170)=>266,chr(171)=>500,chr(172)=>606,chr(173)=>333,chr(174)=>747,chr(175)=>333, + chr(176)=>400,chr(177)=>570,chr(178)=>300,chr(179)=>300,chr(180)=>333,chr(181)=>576,chr(182)=>500,chr(183)=>250,chr(184)=>333,chr(185)=>300,chr(186)=>300,chr(187)=>500,chr(188)=>750,chr(189)=>750,chr(190)=>750,chr(191)=>500,chr(192)=>667,chr(193)=>667,chr(194)=>667,chr(195)=>667,chr(196)=>667,chr(197)=>667, + chr(198)=>944,chr(199)=>667,chr(200)=>667,chr(201)=>667,chr(202)=>667,chr(203)=>667,chr(204)=>389,chr(205)=>389,chr(206)=>389,chr(207)=>389,chr(208)=>722,chr(209)=>722,chr(210)=>722,chr(211)=>722,chr(212)=>722,chr(213)=>722,chr(214)=>722,chr(215)=>570,chr(216)=>722,chr(217)=>722,chr(218)=>722,chr(219)=>722, + chr(220)=>722,chr(221)=>611,chr(222)=>611,chr(223)=>500,chr(224)=>500,chr(225)=>500,chr(226)=>500,chr(227)=>500,chr(228)=>500,chr(229)=>500,chr(230)=>722,chr(231)=>444,chr(232)=>444,chr(233)=>444,chr(234)=>444,chr(235)=>444,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>500,chr(241)=>556, + chr(242)=>500,chr(243)=>500,chr(244)=>500,chr(245)=>500,chr(246)=>500,chr(247)=>570,chr(248)=>500,chr(249)=>556,chr(250)=>556,chr(251)=>556,chr(252)=>556,chr(253)=>444,chr(254)=>500,chr(255)=>444); +$enc = 'cp1252'; +$uv = array(0=>array(0,128),128=>8364,130=>8218,131=>402,132=>8222,133=>8230,134=>array(8224,2),136=>710,137=>8240,138=>352,139=>8249,140=>338,142=>381,145=>array(8216,2),147=>array(8220,2),149=>8226,150=>array(8211,2),152=>732,153=>8482,154=>353,155=>8250,156=>339,158=>382,159=>376,160=>array(160,96)); +?> diff --git a/src/bb-library/font/timesi.php b/src/bb-library/font/timesi.php new file mode 100644 index 000000000..f958b5b67 --- /dev/null +++ b/src/bb-library/font/timesi.php @@ -0,0 +1,21 @@ +250,chr(1)=>250,chr(2)=>250,chr(3)=>250,chr(4)=>250,chr(5)=>250,chr(6)=>250,chr(7)=>250,chr(8)=>250,chr(9)=>250,chr(10)=>250,chr(11)=>250,chr(12)=>250,chr(13)=>250,chr(14)=>250,chr(15)=>250,chr(16)=>250,chr(17)=>250,chr(18)=>250,chr(19)=>250,chr(20)=>250,chr(21)=>250, + chr(22)=>250,chr(23)=>250,chr(24)=>250,chr(25)=>250,chr(26)=>250,chr(27)=>250,chr(28)=>250,chr(29)=>250,chr(30)=>250,chr(31)=>250,' '=>250,'!'=>333,'"'=>420,'#'=>500,'$'=>500,'%'=>833,'&'=>778,'\''=>214,'('=>333,')'=>333,'*'=>500,'+'=>675, + ','=>250,'-'=>333,'.'=>250,'/'=>278,'0'=>500,'1'=>500,'2'=>500,'3'=>500,'4'=>500,'5'=>500,'6'=>500,'7'=>500,'8'=>500,'9'=>500,':'=>333,';'=>333,'<'=>675,'='=>675,'>'=>675,'?'=>500,'@'=>920,'A'=>611, + 'B'=>611,'C'=>667,'D'=>722,'E'=>611,'F'=>611,'G'=>722,'H'=>722,'I'=>333,'J'=>444,'K'=>667,'L'=>556,'M'=>833,'N'=>667,'O'=>722,'P'=>611,'Q'=>722,'R'=>611,'S'=>500,'T'=>556,'U'=>722,'V'=>611,'W'=>833, + 'X'=>611,'Y'=>556,'Z'=>556,'['=>389,'\\'=>278,']'=>389,'^'=>422,'_'=>500,'`'=>333,'a'=>500,'b'=>500,'c'=>444,'d'=>500,'e'=>444,'f'=>278,'g'=>500,'h'=>500,'i'=>278,'j'=>278,'k'=>444,'l'=>278,'m'=>722, + 'n'=>500,'o'=>500,'p'=>500,'q'=>500,'r'=>389,'s'=>389,'t'=>278,'u'=>500,'v'=>444,'w'=>667,'x'=>444,'y'=>444,'z'=>389,'{'=>400,'|'=>275,'}'=>400,'~'=>541,chr(127)=>350,chr(128)=>500,chr(129)=>350,chr(130)=>333,chr(131)=>500, + chr(132)=>556,chr(133)=>889,chr(134)=>500,chr(135)=>500,chr(136)=>333,chr(137)=>1000,chr(138)=>500,chr(139)=>333,chr(140)=>944,chr(141)=>350,chr(142)=>556,chr(143)=>350,chr(144)=>350,chr(145)=>333,chr(146)=>333,chr(147)=>556,chr(148)=>556,chr(149)=>350,chr(150)=>500,chr(151)=>889,chr(152)=>333,chr(153)=>980, + chr(154)=>389,chr(155)=>333,chr(156)=>667,chr(157)=>350,chr(158)=>389,chr(159)=>556,chr(160)=>250,chr(161)=>389,chr(162)=>500,chr(163)=>500,chr(164)=>500,chr(165)=>500,chr(166)=>275,chr(167)=>500,chr(168)=>333,chr(169)=>760,chr(170)=>276,chr(171)=>500,chr(172)=>675,chr(173)=>333,chr(174)=>760,chr(175)=>333, + chr(176)=>400,chr(177)=>675,chr(178)=>300,chr(179)=>300,chr(180)=>333,chr(181)=>500,chr(182)=>523,chr(183)=>250,chr(184)=>333,chr(185)=>300,chr(186)=>310,chr(187)=>500,chr(188)=>750,chr(189)=>750,chr(190)=>750,chr(191)=>500,chr(192)=>611,chr(193)=>611,chr(194)=>611,chr(195)=>611,chr(196)=>611,chr(197)=>611, + chr(198)=>889,chr(199)=>667,chr(200)=>611,chr(201)=>611,chr(202)=>611,chr(203)=>611,chr(204)=>333,chr(205)=>333,chr(206)=>333,chr(207)=>333,chr(208)=>722,chr(209)=>667,chr(210)=>722,chr(211)=>722,chr(212)=>722,chr(213)=>722,chr(214)=>722,chr(215)=>675,chr(216)=>722,chr(217)=>722,chr(218)=>722,chr(219)=>722, + chr(220)=>722,chr(221)=>556,chr(222)=>611,chr(223)=>500,chr(224)=>500,chr(225)=>500,chr(226)=>500,chr(227)=>500,chr(228)=>500,chr(229)=>500,chr(230)=>667,chr(231)=>444,chr(232)=>444,chr(233)=>444,chr(234)=>444,chr(235)=>444,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>500,chr(241)=>500, + chr(242)=>500,chr(243)=>500,chr(244)=>500,chr(245)=>500,chr(246)=>500,chr(247)=>675,chr(248)=>500,chr(249)=>500,chr(250)=>500,chr(251)=>500,chr(252)=>500,chr(253)=>444,chr(254)=>500,chr(255)=>444); +$enc = 'cp1252'; +$uv = array(0=>array(0,128),128=>8364,130=>8218,131=>402,132=>8222,133=>8230,134=>array(8224,2),136=>710,137=>8240,138=>352,139=>8249,140=>338,142=>381,145=>array(8216,2),147=>array(8220,2),149=>8226,150=>array(8211,2),152=>732,153=>8482,154=>353,155=>8250,156=>339,158=>382,159=>376,160=>array(160,96)); +?> diff --git a/src/bb-library/font/zapfdingbats.php b/src/bb-library/font/zapfdingbats.php new file mode 100644 index 000000000..7c2cb5e4c --- /dev/null +++ b/src/bb-library/font/zapfdingbats.php @@ -0,0 +1,20 @@ +0,chr(1)=>0,chr(2)=>0,chr(3)=>0,chr(4)=>0,chr(5)=>0,chr(6)=>0,chr(7)=>0,chr(8)=>0,chr(9)=>0,chr(10)=>0,chr(11)=>0,chr(12)=>0,chr(13)=>0,chr(14)=>0,chr(15)=>0,chr(16)=>0,chr(17)=>0,chr(18)=>0,chr(19)=>0,chr(20)=>0,chr(21)=>0, + chr(22)=>0,chr(23)=>0,chr(24)=>0,chr(25)=>0,chr(26)=>0,chr(27)=>0,chr(28)=>0,chr(29)=>0,chr(30)=>0,chr(31)=>0,' '=>278,'!'=>974,'"'=>961,'#'=>974,'$'=>980,'%'=>719,'&'=>789,'\''=>790,'('=>791,')'=>690,'*'=>960,'+'=>939, + ','=>549,'-'=>855,'.'=>911,'/'=>933,'0'=>911,'1'=>945,'2'=>974,'3'=>755,'4'=>846,'5'=>762,'6'=>761,'7'=>571,'8'=>677,'9'=>763,':'=>760,';'=>759,'<'=>754,'='=>494,'>'=>552,'?'=>537,'@'=>577,'A'=>692, + 'B'=>786,'C'=>788,'D'=>788,'E'=>790,'F'=>793,'G'=>794,'H'=>816,'I'=>823,'J'=>789,'K'=>841,'L'=>823,'M'=>833,'N'=>816,'O'=>831,'P'=>923,'Q'=>744,'R'=>723,'S'=>749,'T'=>790,'U'=>792,'V'=>695,'W'=>776, + 'X'=>768,'Y'=>792,'Z'=>759,'['=>707,'\\'=>708,']'=>682,'^'=>701,'_'=>826,'`'=>815,'a'=>789,'b'=>789,'c'=>707,'d'=>687,'e'=>696,'f'=>689,'g'=>786,'h'=>787,'i'=>713,'j'=>791,'k'=>785,'l'=>791,'m'=>873, + 'n'=>761,'o'=>762,'p'=>762,'q'=>759,'r'=>759,'s'=>892,'t'=>892,'u'=>788,'v'=>784,'w'=>438,'x'=>138,'y'=>277,'z'=>415,'{'=>392,'|'=>392,'}'=>668,'~'=>668,chr(127)=>0,chr(128)=>390,chr(129)=>390,chr(130)=>317,chr(131)=>317, + chr(132)=>276,chr(133)=>276,chr(134)=>509,chr(135)=>509,chr(136)=>410,chr(137)=>410,chr(138)=>234,chr(139)=>234,chr(140)=>334,chr(141)=>334,chr(142)=>0,chr(143)=>0,chr(144)=>0,chr(145)=>0,chr(146)=>0,chr(147)=>0,chr(148)=>0,chr(149)=>0,chr(150)=>0,chr(151)=>0,chr(152)=>0,chr(153)=>0, + chr(154)=>0,chr(155)=>0,chr(156)=>0,chr(157)=>0,chr(158)=>0,chr(159)=>0,chr(160)=>0,chr(161)=>732,chr(162)=>544,chr(163)=>544,chr(164)=>910,chr(165)=>667,chr(166)=>760,chr(167)=>760,chr(168)=>776,chr(169)=>595,chr(170)=>694,chr(171)=>626,chr(172)=>788,chr(173)=>788,chr(174)=>788,chr(175)=>788, + chr(176)=>788,chr(177)=>788,chr(178)=>788,chr(179)=>788,chr(180)=>788,chr(181)=>788,chr(182)=>788,chr(183)=>788,chr(184)=>788,chr(185)=>788,chr(186)=>788,chr(187)=>788,chr(188)=>788,chr(189)=>788,chr(190)=>788,chr(191)=>788,chr(192)=>788,chr(193)=>788,chr(194)=>788,chr(195)=>788,chr(196)=>788,chr(197)=>788, + chr(198)=>788,chr(199)=>788,chr(200)=>788,chr(201)=>788,chr(202)=>788,chr(203)=>788,chr(204)=>788,chr(205)=>788,chr(206)=>788,chr(207)=>788,chr(208)=>788,chr(209)=>788,chr(210)=>788,chr(211)=>788,chr(212)=>894,chr(213)=>838,chr(214)=>1016,chr(215)=>458,chr(216)=>748,chr(217)=>924,chr(218)=>748,chr(219)=>918, + chr(220)=>927,chr(221)=>928,chr(222)=>928,chr(223)=>834,chr(224)=>873,chr(225)=>828,chr(226)=>924,chr(227)=>924,chr(228)=>917,chr(229)=>930,chr(230)=>931,chr(231)=>463,chr(232)=>883,chr(233)=>836,chr(234)=>836,chr(235)=>867,chr(236)=>867,chr(237)=>696,chr(238)=>696,chr(239)=>874,chr(240)=>0,chr(241)=>874, + chr(242)=>760,chr(243)=>946,chr(244)=>771,chr(245)=>865,chr(246)=>771,chr(247)=>888,chr(248)=>967,chr(249)=>888,chr(250)=>831,chr(251)=>873,chr(252)=>927,chr(253)=>970,chr(254)=>918,chr(255)=>0); +$uv = array(32=>32,33=>array(9985,4),37=>9742,38=>array(9990,4),42=>9755,43=>9758,44=>array(9996,28),72=>9733,73=>array(10025,35),108=>9679,109=>10061,110=>9632,111=>array(10063,4),115=>9650,116=>9660,117=>9670,118=>10070,119=>9687,120=>array(10072,7),128=>array(10088,14),161=>array(10081,7),168=>9827,169=>9830,170=>9829,171=>9824,172=>array(9312,10),182=>array(10102,31),213=>8594,214=>array(8596,2),216=>array(10136,24),241=>array(10161,14)); +?> diff --git a/src/bb-library/install.txt b/src/bb-library/install.txt new file mode 100644 index 000000000..62d25e632 --- /dev/null +++ b/src/bb-library/install.txt @@ -0,0 +1,15 @@ +The FPDF library is made up of the following elements: + +- the main file, fpdf.php, which contains the class +- the font definition files located in the font directory + +The font definition files are necessary as soon as you want to output some text in a document. +If they are not accessible, the SetFont() method will produce the following error: + +FPDF error: Could not include font definition file + + +Remarks: + +- Only the files corresponding to the fonts actually used are necessary +- The tutorials provided in this package are ready to be executed diff --git a/src/bb-library/license.txt b/src/bb-library/license.txt new file mode 100644 index 000000000..6107ee477 --- /dev/null +++ b/src/bb-library/license.txt @@ -0,0 +1,6 @@ +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software to use, copy, modify, distribute, sublicense, and/or sell +copies of the software, and to permit persons to whom the software is furnished +to do so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. \ No newline at end of file diff --git a/src/bb-library/makefont/cp1250.map b/src/bb-library/makefont/cp1250.map new file mode 100644 index 000000000..ec110af06 --- /dev/null +++ b/src/bb-library/makefont/cp1250.map @@ -0,0 +1,251 @@ +!00 U+0000 .notdef +!01 U+0001 .notdef +!02 U+0002 .notdef +!03 U+0003 .notdef +!04 U+0004 .notdef +!05 U+0005 .notdef +!06 U+0006 .notdef +!07 U+0007 .notdef +!08 U+0008 .notdef +!09 U+0009 .notdef +!0A U+000A .notdef +!0B U+000B .notdef +!0C U+000C .notdef +!0D U+000D .notdef +!0E U+000E .notdef +!0F U+000F .notdef +!10 U+0010 .notdef +!11 U+0011 .notdef +!12 U+0012 .notdef +!13 U+0013 .notdef +!14 U+0014 .notdef +!15 U+0015 .notdef +!16 U+0016 .notdef +!17 U+0017 .notdef +!18 U+0018 .notdef +!19 U+0019 .notdef +!1A U+001A .notdef +!1B U+001B .notdef +!1C U+001C .notdef +!1D U+001D .notdef +!1E U+001E .notdef +!1F U+001F .notdef +!20 U+0020 space +!21 U+0021 exclam +!22 U+0022 quotedbl +!23 U+0023 numbersign +!24 U+0024 dollar +!25 U+0025 percent +!26 U+0026 ampersand +!27 U+0027 quotesingle +!28 U+0028 parenleft +!29 U+0029 parenright +!2A U+002A asterisk +!2B U+002B plus +!2C U+002C comma +!2D U+002D hyphen +!2E U+002E period +!2F U+002F slash +!30 U+0030 zero +!31 U+0031 one +!32 U+0032 two +!33 U+0033 three +!34 U+0034 four +!35 U+0035 five +!36 U+0036 six +!37 U+0037 seven +!38 U+0038 eight +!39 U+0039 nine +!3A U+003A colon +!3B U+003B semicolon +!3C U+003C less +!3D U+003D equal +!3E U+003E greater +!3F U+003F question +!40 U+0040 at +!41 U+0041 A +!42 U+0042 B +!43 U+0043 C +!44 U+0044 D +!45 U+0045 E +!46 U+0046 F +!47 U+0047 G +!48 U+0048 H +!49 U+0049 I +!4A U+004A J +!4B U+004B K +!4C U+004C L +!4D U+004D M +!4E U+004E N +!4F U+004F O +!50 U+0050 P +!51 U+0051 Q +!52 U+0052 R +!53 U+0053 S +!54 U+0054 T +!55 U+0055 U +!56 U+0056 V +!57 U+0057 W +!58 U+0058 X +!59 U+0059 Y +!5A U+005A Z +!5B U+005B bracketleft +!5C U+005C backslash +!5D U+005D bracketright +!5E U+005E asciicircum +!5F U+005F underscore +!60 U+0060 grave +!61 U+0061 a +!62 U+0062 b +!63 U+0063 c +!64 U+0064 d +!65 U+0065 e +!66 U+0066 f +!67 U+0067 g +!68 U+0068 h +!69 U+0069 i +!6A U+006A j +!6B U+006B k +!6C U+006C l +!6D U+006D m +!6E U+006E n +!6F U+006F o +!70 U+0070 p +!71 U+0071 q +!72 U+0072 r +!73 U+0073 s +!74 U+0074 t +!75 U+0075 u +!76 U+0076 v +!77 U+0077 w +!78 U+0078 x +!79 U+0079 y +!7A U+007A z +!7B U+007B braceleft +!7C U+007C bar +!7D U+007D braceright +!7E U+007E asciitilde +!7F U+007F .notdef +!80 U+20AC Euro +!82 U+201A quotesinglbase +!84 U+201E quotedblbase +!85 U+2026 ellipsis +!86 U+2020 dagger +!87 U+2021 daggerdbl +!89 U+2030 perthousand +!8A U+0160 Scaron +!8B U+2039 guilsinglleft +!8C U+015A Sacute +!8D U+0164 Tcaron +!8E U+017D Zcaron +!8F U+0179 Zacute +!91 U+2018 quoteleft +!92 U+2019 quoteright +!93 U+201C quotedblleft +!94 U+201D quotedblright +!95 U+2022 bullet +!96 U+2013 endash +!97 U+2014 emdash +!99 U+2122 trademark +!9A U+0161 scaron +!9B U+203A guilsinglright +!9C U+015B sacute +!9D U+0165 tcaron +!9E U+017E zcaron +!9F U+017A zacute +!A0 U+00A0 space +!A1 U+02C7 caron +!A2 U+02D8 breve +!A3 U+0141 Lslash +!A4 U+00A4 currency +!A5 U+0104 Aogonek +!A6 U+00A6 brokenbar +!A7 U+00A7 section +!A8 U+00A8 dieresis +!A9 U+00A9 copyright +!AA U+015E Scedilla +!AB U+00AB guillemotleft +!AC U+00AC logicalnot +!AD U+00AD hyphen +!AE U+00AE registered +!AF U+017B Zdotaccent +!B0 U+00B0 degree +!B1 U+00B1 plusminus +!B2 U+02DB ogonek +!B3 U+0142 lslash +!B4 U+00B4 acute +!B5 U+00B5 mu +!B6 U+00B6 paragraph +!B7 U+00B7 periodcentered +!B8 U+00B8 cedilla +!B9 U+0105 aogonek +!BA U+015F scedilla +!BB U+00BB guillemotright +!BC U+013D Lcaron +!BD U+02DD hungarumlaut +!BE U+013E lcaron +!BF U+017C zdotaccent +!C0 U+0154 Racute +!C1 U+00C1 Aacute +!C2 U+00C2 Acircumflex +!C3 U+0102 Abreve +!C4 U+00C4 Adieresis +!C5 U+0139 Lacute +!C6 U+0106 Cacute +!C7 U+00C7 Ccedilla +!C8 U+010C Ccaron +!C9 U+00C9 Eacute +!CA U+0118 Eogonek +!CB U+00CB Edieresis +!CC U+011A Ecaron +!CD U+00CD Iacute +!CE U+00CE Icircumflex +!CF U+010E Dcaron +!D0 U+0110 Dcroat +!D1 U+0143 Nacute +!D2 U+0147 Ncaron +!D3 U+00D3 Oacute +!D4 U+00D4 Ocircumflex +!D5 U+0150 Ohungarumlaut +!D6 U+00D6 Odieresis +!D7 U+00D7 multiply +!D8 U+0158 Rcaron +!D9 U+016E Uring +!DA U+00DA Uacute +!DB U+0170 Uhungarumlaut +!DC U+00DC Udieresis +!DD U+00DD Yacute +!DE U+0162 Tcommaaccent +!DF U+00DF germandbls +!E0 U+0155 racute +!E1 U+00E1 aacute +!E2 U+00E2 acircumflex +!E3 U+0103 abreve +!E4 U+00E4 adieresis +!E5 U+013A lacute +!E6 U+0107 cacute +!E7 U+00E7 ccedilla +!E8 U+010D ccaron +!E9 U+00E9 eacute +!EA U+0119 eogonek +!EB U+00EB edieresis +!EC U+011B ecaron +!ED U+00ED iacute +!EE U+00EE icircumflex +!EF U+010F dcaron +!F0 U+0111 dcroat +!F1 U+0144 nacute +!F2 U+0148 ncaron +!F3 U+00F3 oacute +!F4 U+00F4 ocircumflex +!F5 U+0151 ohungarumlaut +!F6 U+00F6 odieresis +!F7 U+00F7 divide +!F8 U+0159 rcaron +!F9 U+016F uring +!FA U+00FA uacute +!FB U+0171 uhungarumlaut +!FC U+00FC udieresis +!FD U+00FD yacute +!FE U+0163 tcommaaccent +!FF U+02D9 dotaccent diff --git a/src/bb-library/makefont/cp1251.map b/src/bb-library/makefont/cp1251.map new file mode 100644 index 000000000..de6a198d9 --- /dev/null +++ b/src/bb-library/makefont/cp1251.map @@ -0,0 +1,255 @@ +!00 U+0000 .notdef +!01 U+0001 .notdef +!02 U+0002 .notdef +!03 U+0003 .notdef +!04 U+0004 .notdef +!05 U+0005 .notdef +!06 U+0006 .notdef +!07 U+0007 .notdef +!08 U+0008 .notdef +!09 U+0009 .notdef +!0A U+000A .notdef +!0B U+000B .notdef +!0C U+000C .notdef +!0D U+000D .notdef +!0E U+000E .notdef +!0F U+000F .notdef +!10 U+0010 .notdef +!11 U+0011 .notdef +!12 U+0012 .notdef +!13 U+0013 .notdef +!14 U+0014 .notdef +!15 U+0015 .notdef +!16 U+0016 .notdef +!17 U+0017 .notdef +!18 U+0018 .notdef +!19 U+0019 .notdef +!1A U+001A .notdef +!1B U+001B .notdef +!1C U+001C .notdef +!1D U+001D .notdef +!1E U+001E .notdef +!1F U+001F .notdef +!20 U+0020 space +!21 U+0021 exclam +!22 U+0022 quotedbl +!23 U+0023 numbersign +!24 U+0024 dollar +!25 U+0025 percent +!26 U+0026 ampersand +!27 U+0027 quotesingle +!28 U+0028 parenleft +!29 U+0029 parenright +!2A U+002A asterisk +!2B U+002B plus +!2C U+002C comma +!2D U+002D hyphen +!2E U+002E period +!2F U+002F slash +!30 U+0030 zero +!31 U+0031 one +!32 U+0032 two +!33 U+0033 three +!34 U+0034 four +!35 U+0035 five +!36 U+0036 six +!37 U+0037 seven +!38 U+0038 eight +!39 U+0039 nine +!3A U+003A colon +!3B U+003B semicolon +!3C U+003C less +!3D U+003D equal +!3E U+003E greater +!3F U+003F question +!40 U+0040 at +!41 U+0041 A +!42 U+0042 B +!43 U+0043 C +!44 U+0044 D +!45 U+0045 E +!46 U+0046 F +!47 U+0047 G +!48 U+0048 H +!49 U+0049 I +!4A U+004A J +!4B U+004B K +!4C U+004C L +!4D U+004D M +!4E U+004E N +!4F U+004F O +!50 U+0050 P +!51 U+0051 Q +!52 U+0052 R +!53 U+0053 S +!54 U+0054 T +!55 U+0055 U +!56 U+0056 V +!57 U+0057 W +!58 U+0058 X +!59 U+0059 Y +!5A U+005A Z +!5B U+005B bracketleft +!5C U+005C backslash +!5D U+005D bracketright +!5E U+005E asciicircum +!5F U+005F underscore +!60 U+0060 grave +!61 U+0061 a +!62 U+0062 b +!63 U+0063 c +!64 U+0064 d +!65 U+0065 e +!66 U+0066 f +!67 U+0067 g +!68 U+0068 h +!69 U+0069 i +!6A U+006A j +!6B U+006B k +!6C U+006C l +!6D U+006D m +!6E U+006E n +!6F U+006F o +!70 U+0070 p +!71 U+0071 q +!72 U+0072 r +!73 U+0073 s +!74 U+0074 t +!75 U+0075 u +!76 U+0076 v +!77 U+0077 w +!78 U+0078 x +!79 U+0079 y +!7A U+007A z +!7B U+007B braceleft +!7C U+007C bar +!7D U+007D braceright +!7E U+007E asciitilde +!7F U+007F .notdef +!80 U+0402 afii10051 +!81 U+0403 afii10052 +!82 U+201A quotesinglbase +!83 U+0453 afii10100 +!84 U+201E quotedblbase +!85 U+2026 ellipsis +!86 U+2020 dagger +!87 U+2021 daggerdbl +!88 U+20AC Euro +!89 U+2030 perthousand +!8A U+0409 afii10058 +!8B U+2039 guilsinglleft +!8C U+040A afii10059 +!8D U+040C afii10061 +!8E U+040B afii10060 +!8F U+040F afii10145 +!90 U+0452 afii10099 +!91 U+2018 quoteleft +!92 U+2019 quoteright +!93 U+201C quotedblleft +!94 U+201D quotedblright +!95 U+2022 bullet +!96 U+2013 endash +!97 U+2014 emdash +!99 U+2122 trademark +!9A U+0459 afii10106 +!9B U+203A guilsinglright +!9C U+045A afii10107 +!9D U+045C afii10109 +!9E U+045B afii10108 +!9F U+045F afii10193 +!A0 U+00A0 space +!A1 U+040E afii10062 +!A2 U+045E afii10110 +!A3 U+0408 afii10057 +!A4 U+00A4 currency +!A5 U+0490 afii10050 +!A6 U+00A6 brokenbar +!A7 U+00A7 section +!A8 U+0401 afii10023 +!A9 U+00A9 copyright +!AA U+0404 afii10053 +!AB U+00AB guillemotleft +!AC U+00AC logicalnot +!AD U+00AD hyphen +!AE U+00AE registered +!AF U+0407 afii10056 +!B0 U+00B0 degree +!B1 U+00B1 plusminus +!B2 U+0406 afii10055 +!B3 U+0456 afii10103 +!B4 U+0491 afii10098 +!B5 U+00B5 mu +!B6 U+00B6 paragraph +!B7 U+00B7 periodcentered +!B8 U+0451 afii10071 +!B9 U+2116 afii61352 +!BA U+0454 afii10101 +!BB U+00BB guillemotright +!BC U+0458 afii10105 +!BD U+0405 afii10054 +!BE U+0455 afii10102 +!BF U+0457 afii10104 +!C0 U+0410 afii10017 +!C1 U+0411 afii10018 +!C2 U+0412 afii10019 +!C3 U+0413 afii10020 +!C4 U+0414 afii10021 +!C5 U+0415 afii10022 +!C6 U+0416 afii10024 +!C7 U+0417 afii10025 +!C8 U+0418 afii10026 +!C9 U+0419 afii10027 +!CA U+041A afii10028 +!CB U+041B afii10029 +!CC U+041C afii10030 +!CD U+041D afii10031 +!CE U+041E afii10032 +!CF U+041F afii10033 +!D0 U+0420 afii10034 +!D1 U+0421 afii10035 +!D2 U+0422 afii10036 +!D3 U+0423 afii10037 +!D4 U+0424 afii10038 +!D5 U+0425 afii10039 +!D6 U+0426 afii10040 +!D7 U+0427 afii10041 +!D8 U+0428 afii10042 +!D9 U+0429 afii10043 +!DA U+042A afii10044 +!DB U+042B afii10045 +!DC U+042C afii10046 +!DD U+042D afii10047 +!DE U+042E afii10048 +!DF U+042F afii10049 +!E0 U+0430 afii10065 +!E1 U+0431 afii10066 +!E2 U+0432 afii10067 +!E3 U+0433 afii10068 +!E4 U+0434 afii10069 +!E5 U+0435 afii10070 +!E6 U+0436 afii10072 +!E7 U+0437 afii10073 +!E8 U+0438 afii10074 +!E9 U+0439 afii10075 +!EA U+043A afii10076 +!EB U+043B afii10077 +!EC U+043C afii10078 +!ED U+043D afii10079 +!EE U+043E afii10080 +!EF U+043F afii10081 +!F0 U+0440 afii10082 +!F1 U+0441 afii10083 +!F2 U+0442 afii10084 +!F3 U+0443 afii10085 +!F4 U+0444 afii10086 +!F5 U+0445 afii10087 +!F6 U+0446 afii10088 +!F7 U+0447 afii10089 +!F8 U+0448 afii10090 +!F9 U+0449 afii10091 +!FA U+044A afii10092 +!FB U+044B afii10093 +!FC U+044C afii10094 +!FD U+044D afii10095 +!FE U+044E afii10096 +!FF U+044F afii10097 diff --git a/src/bb-library/makefont/cp1252.map b/src/bb-library/makefont/cp1252.map new file mode 100644 index 000000000..dd490e596 --- /dev/null +++ b/src/bb-library/makefont/cp1252.map @@ -0,0 +1,251 @@ +!00 U+0000 .notdef +!01 U+0001 .notdef +!02 U+0002 .notdef +!03 U+0003 .notdef +!04 U+0004 .notdef +!05 U+0005 .notdef +!06 U+0006 .notdef +!07 U+0007 .notdef +!08 U+0008 .notdef +!09 U+0009 .notdef +!0A U+000A .notdef +!0B U+000B .notdef +!0C U+000C .notdef +!0D U+000D .notdef +!0E U+000E .notdef +!0F U+000F .notdef +!10 U+0010 .notdef +!11 U+0011 .notdef +!12 U+0012 .notdef +!13 U+0013 .notdef +!14 U+0014 .notdef +!15 U+0015 .notdef +!16 U+0016 .notdef +!17 U+0017 .notdef +!18 U+0018 .notdef +!19 U+0019 .notdef +!1A U+001A .notdef +!1B U+001B .notdef +!1C U+001C .notdef +!1D U+001D .notdef +!1E U+001E .notdef +!1F U+001F .notdef +!20 U+0020 space +!21 U+0021 exclam +!22 U+0022 quotedbl +!23 U+0023 numbersign +!24 U+0024 dollar +!25 U+0025 percent +!26 U+0026 ampersand +!27 U+0027 quotesingle +!28 U+0028 parenleft +!29 U+0029 parenright +!2A U+002A asterisk +!2B U+002B plus +!2C U+002C comma +!2D U+002D hyphen +!2E U+002E period +!2F U+002F slash +!30 U+0030 zero +!31 U+0031 one +!32 U+0032 two +!33 U+0033 three +!34 U+0034 four +!35 U+0035 five +!36 U+0036 six +!37 U+0037 seven +!38 U+0038 eight +!39 U+0039 nine +!3A U+003A colon +!3B U+003B semicolon +!3C U+003C less +!3D U+003D equal +!3E U+003E greater +!3F U+003F question +!40 U+0040 at +!41 U+0041 A +!42 U+0042 B +!43 U+0043 C +!44 U+0044 D +!45 U+0045 E +!46 U+0046 F +!47 U+0047 G +!48 U+0048 H +!49 U+0049 I +!4A U+004A J +!4B U+004B K +!4C U+004C L +!4D U+004D M +!4E U+004E N +!4F U+004F O +!50 U+0050 P +!51 U+0051 Q +!52 U+0052 R +!53 U+0053 S +!54 U+0054 T +!55 U+0055 U +!56 U+0056 V +!57 U+0057 W +!58 U+0058 X +!59 U+0059 Y +!5A U+005A Z +!5B U+005B bracketleft +!5C U+005C backslash +!5D U+005D bracketright +!5E U+005E asciicircum +!5F U+005F underscore +!60 U+0060 grave +!61 U+0061 a +!62 U+0062 b +!63 U+0063 c +!64 U+0064 d +!65 U+0065 e +!66 U+0066 f +!67 U+0067 g +!68 U+0068 h +!69 U+0069 i +!6A U+006A j +!6B U+006B k +!6C U+006C l +!6D U+006D m +!6E U+006E n +!6F U+006F o +!70 U+0070 p +!71 U+0071 q +!72 U+0072 r +!73 U+0073 s +!74 U+0074 t +!75 U+0075 u +!76 U+0076 v +!77 U+0077 w +!78 U+0078 x +!79 U+0079 y +!7A U+007A z +!7B U+007B braceleft +!7C U+007C bar +!7D U+007D braceright +!7E U+007E asciitilde +!7F U+007F .notdef +!80 U+20AC Euro +!82 U+201A quotesinglbase +!83 U+0192 florin +!84 U+201E quotedblbase +!85 U+2026 ellipsis +!86 U+2020 dagger +!87 U+2021 daggerdbl +!88 U+02C6 circumflex +!89 U+2030 perthousand +!8A U+0160 Scaron +!8B U+2039 guilsinglleft +!8C U+0152 OE +!8E U+017D Zcaron +!91 U+2018 quoteleft +!92 U+2019 quoteright +!93 U+201C quotedblleft +!94 U+201D quotedblright +!95 U+2022 bullet +!96 U+2013 endash +!97 U+2014 emdash +!98 U+02DC tilde +!99 U+2122 trademark +!9A U+0161 scaron +!9B U+203A guilsinglright +!9C U+0153 oe +!9E U+017E zcaron +!9F U+0178 Ydieresis +!A0 U+00A0 space +!A1 U+00A1 exclamdown +!A2 U+00A2 cent +!A3 U+00A3 sterling +!A4 U+00A4 currency +!A5 U+00A5 yen +!A6 U+00A6 brokenbar +!A7 U+00A7 section +!A8 U+00A8 dieresis +!A9 U+00A9 copyright +!AA U+00AA ordfeminine +!AB U+00AB guillemotleft +!AC U+00AC logicalnot +!AD U+00AD hyphen +!AE U+00AE registered +!AF U+00AF macron +!B0 U+00B0 degree +!B1 U+00B1 plusminus +!B2 U+00B2 twosuperior +!B3 U+00B3 threesuperior +!B4 U+00B4 acute +!B5 U+00B5 mu +!B6 U+00B6 paragraph +!B7 U+00B7 periodcentered +!B8 U+00B8 cedilla +!B9 U+00B9 onesuperior +!BA U+00BA ordmasculine +!BB U+00BB guillemotright +!BC U+00BC onequarter +!BD U+00BD onehalf +!BE U+00BE threequarters +!BF U+00BF questiondown +!C0 U+00C0 Agrave +!C1 U+00C1 Aacute +!C2 U+00C2 Acircumflex +!C3 U+00C3 Atilde +!C4 U+00C4 Adieresis +!C5 U+00C5 Aring +!C6 U+00C6 AE +!C7 U+00C7 Ccedilla +!C8 U+00C8 Egrave +!C9 U+00C9 Eacute +!CA U+00CA Ecircumflex +!CB U+00CB Edieresis +!CC U+00CC Igrave +!CD U+00CD Iacute +!CE U+00CE Icircumflex +!CF U+00CF Idieresis +!D0 U+00D0 Eth +!D1 U+00D1 Ntilde +!D2 U+00D2 Ograve +!D3 U+00D3 Oacute +!D4 U+00D4 Ocircumflex +!D5 U+00D5 Otilde +!D6 U+00D6 Odieresis +!D7 U+00D7 multiply +!D8 U+00D8 Oslash +!D9 U+00D9 Ugrave +!DA U+00DA Uacute +!DB U+00DB Ucircumflex +!DC U+00DC Udieresis +!DD U+00DD Yacute +!DE U+00DE Thorn +!DF U+00DF germandbls +!E0 U+00E0 agrave +!E1 U+00E1 aacute +!E2 U+00E2 acircumflex +!E3 U+00E3 atilde +!E4 U+00E4 adieresis +!E5 U+00E5 aring +!E6 U+00E6 ae +!E7 U+00E7 ccedilla +!E8 U+00E8 egrave +!E9 U+00E9 eacute +!EA U+00EA ecircumflex +!EB U+00EB edieresis +!EC U+00EC igrave +!ED U+00ED iacute +!EE U+00EE icircumflex +!EF U+00EF idieresis +!F0 U+00F0 eth +!F1 U+00F1 ntilde +!F2 U+00F2 ograve +!F3 U+00F3 oacute +!F4 U+00F4 ocircumflex +!F5 U+00F5 otilde +!F6 U+00F6 odieresis +!F7 U+00F7 divide +!F8 U+00F8 oslash +!F9 U+00F9 ugrave +!FA U+00FA uacute +!FB U+00FB ucircumflex +!FC U+00FC udieresis +!FD U+00FD yacute +!FE U+00FE thorn +!FF U+00FF ydieresis diff --git a/src/bb-library/makefont/cp1253.map b/src/bb-library/makefont/cp1253.map new file mode 100644 index 000000000..4bd826fb2 --- /dev/null +++ b/src/bb-library/makefont/cp1253.map @@ -0,0 +1,239 @@ +!00 U+0000 .notdef +!01 U+0001 .notdef +!02 U+0002 .notdef +!03 U+0003 .notdef +!04 U+0004 .notdef +!05 U+0005 .notdef +!06 U+0006 .notdef +!07 U+0007 .notdef +!08 U+0008 .notdef +!09 U+0009 .notdef +!0A U+000A .notdef +!0B U+000B .notdef +!0C U+000C .notdef +!0D U+000D .notdef +!0E U+000E .notdef +!0F U+000F .notdef +!10 U+0010 .notdef +!11 U+0011 .notdef +!12 U+0012 .notdef +!13 U+0013 .notdef +!14 U+0014 .notdef +!15 U+0015 .notdef +!16 U+0016 .notdef +!17 U+0017 .notdef +!18 U+0018 .notdef +!19 U+0019 .notdef +!1A U+001A .notdef +!1B U+001B .notdef +!1C U+001C .notdef +!1D U+001D .notdef +!1E U+001E .notdef +!1F U+001F .notdef +!20 U+0020 space +!21 U+0021 exclam +!22 U+0022 quotedbl +!23 U+0023 numbersign +!24 U+0024 dollar +!25 U+0025 percent +!26 U+0026 ampersand +!27 U+0027 quotesingle +!28 U+0028 parenleft +!29 U+0029 parenright +!2A U+002A asterisk +!2B U+002B plus +!2C U+002C comma +!2D U+002D hyphen +!2E U+002E period +!2F U+002F slash +!30 U+0030 zero +!31 U+0031 one +!32 U+0032 two +!33 U+0033 three +!34 U+0034 four +!35 U+0035 five +!36 U+0036 six +!37 U+0037 seven +!38 U+0038 eight +!39 U+0039 nine +!3A U+003A colon +!3B U+003B semicolon +!3C U+003C less +!3D U+003D equal +!3E U+003E greater +!3F U+003F question +!40 U+0040 at +!41 U+0041 A +!42 U+0042 B +!43 U+0043 C +!44 U+0044 D +!45 U+0045 E +!46 U+0046 F +!47 U+0047 G +!48 U+0048 H +!49 U+0049 I +!4A U+004A J +!4B U+004B K +!4C U+004C L +!4D U+004D M +!4E U+004E N +!4F U+004F O +!50 U+0050 P +!51 U+0051 Q +!52 U+0052 R +!53 U+0053 S +!54 U+0054 T +!55 U+0055 U +!56 U+0056 V +!57 U+0057 W +!58 U+0058 X +!59 U+0059 Y +!5A U+005A Z +!5B U+005B bracketleft +!5C U+005C backslash +!5D U+005D bracketright +!5E U+005E asciicircum +!5F U+005F underscore +!60 U+0060 grave +!61 U+0061 a +!62 U+0062 b +!63 U+0063 c +!64 U+0064 d +!65 U+0065 e +!66 U+0066 f +!67 U+0067 g +!68 U+0068 h +!69 U+0069 i +!6A U+006A j +!6B U+006B k +!6C U+006C l +!6D U+006D m +!6E U+006E n +!6F U+006F o +!70 U+0070 p +!71 U+0071 q +!72 U+0072 r +!73 U+0073 s +!74 U+0074 t +!75 U+0075 u +!76 U+0076 v +!77 U+0077 w +!78 U+0078 x +!79 U+0079 y +!7A U+007A z +!7B U+007B braceleft +!7C U+007C bar +!7D U+007D braceright +!7E U+007E asciitilde +!7F U+007F .notdef +!80 U+20AC Euro +!82 U+201A quotesinglbase +!83 U+0192 florin +!84 U+201E quotedblbase +!85 U+2026 ellipsis +!86 U+2020 dagger +!87 U+2021 daggerdbl +!89 U+2030 perthousand +!8B U+2039 guilsinglleft +!91 U+2018 quoteleft +!92 U+2019 quoteright +!93 U+201C quotedblleft +!94 U+201D quotedblright +!95 U+2022 bullet +!96 U+2013 endash +!97 U+2014 emdash +!99 U+2122 trademark +!9B U+203A guilsinglright +!A0 U+00A0 space +!A1 U+0385 dieresistonos +!A2 U+0386 Alphatonos +!A3 U+00A3 sterling +!A4 U+00A4 currency +!A5 U+00A5 yen +!A6 U+00A6 brokenbar +!A7 U+00A7 section +!A8 U+00A8 dieresis +!A9 U+00A9 copyright +!AB U+00AB guillemotleft +!AC U+00AC logicalnot +!AD U+00AD hyphen +!AE U+00AE registered +!AF U+2015 afii00208 +!B0 U+00B0 degree +!B1 U+00B1 plusminus +!B2 U+00B2 twosuperior +!B3 U+00B3 threesuperior +!B4 U+0384 tonos +!B5 U+00B5 mu +!B6 U+00B6 paragraph +!B7 U+00B7 periodcentered +!B8 U+0388 Epsilontonos +!B9 U+0389 Etatonos +!BA U+038A Iotatonos +!BB U+00BB guillemotright +!BC U+038C Omicrontonos +!BD U+00BD onehalf +!BE U+038E Upsilontonos +!BF U+038F Omegatonos +!C0 U+0390 iotadieresistonos +!C1 U+0391 Alpha +!C2 U+0392 Beta +!C3 U+0393 Gamma +!C4 U+0394 Delta +!C5 U+0395 Epsilon +!C6 U+0396 Zeta +!C7 U+0397 Eta +!C8 U+0398 Theta +!C9 U+0399 Iota +!CA U+039A Kappa +!CB U+039B Lambda +!CC U+039C Mu +!CD U+039D Nu +!CE U+039E Xi +!CF U+039F Omicron +!D0 U+03A0 Pi +!D1 U+03A1 Rho +!D3 U+03A3 Sigma +!D4 U+03A4 Tau +!D5 U+03A5 Upsilon +!D6 U+03A6 Phi +!D7 U+03A7 Chi +!D8 U+03A8 Psi +!D9 U+03A9 Omega +!DA U+03AA Iotadieresis +!DB U+03AB Upsilondieresis +!DC U+03AC alphatonos +!DD U+03AD epsilontonos +!DE U+03AE etatonos +!DF U+03AF iotatonos +!E0 U+03B0 upsilondieresistonos +!E1 U+03B1 alpha +!E2 U+03B2 beta +!E3 U+03B3 gamma +!E4 U+03B4 delta +!E5 U+03B5 epsilon +!E6 U+03B6 zeta +!E7 U+03B7 eta +!E8 U+03B8 theta +!E9 U+03B9 iota +!EA U+03BA kappa +!EB U+03BB lambda +!EC U+03BC mu +!ED U+03BD nu +!EE U+03BE xi +!EF U+03BF omicron +!F0 U+03C0 pi +!F1 U+03C1 rho +!F2 U+03C2 sigma1 +!F3 U+03C3 sigma +!F4 U+03C4 tau +!F5 U+03C5 upsilon +!F6 U+03C6 phi +!F7 U+03C7 chi +!F8 U+03C8 psi +!F9 U+03C9 omega +!FA U+03CA iotadieresis +!FB U+03CB upsilondieresis +!FC U+03CC omicrontonos +!FD U+03CD upsilontonos +!FE U+03CE omegatonos diff --git a/src/bb-library/makefont/cp1254.map b/src/bb-library/makefont/cp1254.map new file mode 100644 index 000000000..829473b28 --- /dev/null +++ b/src/bb-library/makefont/cp1254.map @@ -0,0 +1,249 @@ +!00 U+0000 .notdef +!01 U+0001 .notdef +!02 U+0002 .notdef +!03 U+0003 .notdef +!04 U+0004 .notdef +!05 U+0005 .notdef +!06 U+0006 .notdef +!07 U+0007 .notdef +!08 U+0008 .notdef +!09 U+0009 .notdef +!0A U+000A .notdef +!0B U+000B .notdef +!0C U+000C .notdef +!0D U+000D .notdef +!0E U+000E .notdef +!0F U+000F .notdef +!10 U+0010 .notdef +!11 U+0011 .notdef +!12 U+0012 .notdef +!13 U+0013 .notdef +!14 U+0014 .notdef +!15 U+0015 .notdef +!16 U+0016 .notdef +!17 U+0017 .notdef +!18 U+0018 .notdef +!19 U+0019 .notdef +!1A U+001A .notdef +!1B U+001B .notdef +!1C U+001C .notdef +!1D U+001D .notdef +!1E U+001E .notdef +!1F U+001F .notdef +!20 U+0020 space +!21 U+0021 exclam +!22 U+0022 quotedbl +!23 U+0023 numbersign +!24 U+0024 dollar +!25 U+0025 percent +!26 U+0026 ampersand +!27 U+0027 quotesingle +!28 U+0028 parenleft +!29 U+0029 parenright +!2A U+002A asterisk +!2B U+002B plus +!2C U+002C comma +!2D U+002D hyphen +!2E U+002E period +!2F U+002F slash +!30 U+0030 zero +!31 U+0031 one +!32 U+0032 two +!33 U+0033 three +!34 U+0034 four +!35 U+0035 five +!36 U+0036 six +!37 U+0037 seven +!38 U+0038 eight +!39 U+0039 nine +!3A U+003A colon +!3B U+003B semicolon +!3C U+003C less +!3D U+003D equal +!3E U+003E greater +!3F U+003F question +!40 U+0040 at +!41 U+0041 A +!42 U+0042 B +!43 U+0043 C +!44 U+0044 D +!45 U+0045 E +!46 U+0046 F +!47 U+0047 G +!48 U+0048 H +!49 U+0049 I +!4A U+004A J +!4B U+004B K +!4C U+004C L +!4D U+004D M +!4E U+004E N +!4F U+004F O +!50 U+0050 P +!51 U+0051 Q +!52 U+0052 R +!53 U+0053 S +!54 U+0054 T +!55 U+0055 U +!56 U+0056 V +!57 U+0057 W +!58 U+0058 X +!59 U+0059 Y +!5A U+005A Z +!5B U+005B bracketleft +!5C U+005C backslash +!5D U+005D bracketright +!5E U+005E asciicircum +!5F U+005F underscore +!60 U+0060 grave +!61 U+0061 a +!62 U+0062 b +!63 U+0063 c +!64 U+0064 d +!65 U+0065 e +!66 U+0066 f +!67 U+0067 g +!68 U+0068 h +!69 U+0069 i +!6A U+006A j +!6B U+006B k +!6C U+006C l +!6D U+006D m +!6E U+006E n +!6F U+006F o +!70 U+0070 p +!71 U+0071 q +!72 U+0072 r +!73 U+0073 s +!74 U+0074 t +!75 U+0075 u +!76 U+0076 v +!77 U+0077 w +!78 U+0078 x +!79 U+0079 y +!7A U+007A z +!7B U+007B braceleft +!7C U+007C bar +!7D U+007D braceright +!7E U+007E asciitilde +!7F U+007F .notdef +!80 U+20AC Euro +!82 U+201A quotesinglbase +!83 U+0192 florin +!84 U+201E quotedblbase +!85 U+2026 ellipsis +!86 U+2020 dagger +!87 U+2021 daggerdbl +!88 U+02C6 circumflex +!89 U+2030 perthousand +!8A U+0160 Scaron +!8B U+2039 guilsinglleft +!8C U+0152 OE +!91 U+2018 quoteleft +!92 U+2019 quoteright +!93 U+201C quotedblleft +!94 U+201D quotedblright +!95 U+2022 bullet +!96 U+2013 endash +!97 U+2014 emdash +!98 U+02DC tilde +!99 U+2122 trademark +!9A U+0161 scaron +!9B U+203A guilsinglright +!9C U+0153 oe +!9F U+0178 Ydieresis +!A0 U+00A0 space +!A1 U+00A1 exclamdown +!A2 U+00A2 cent +!A3 U+00A3 sterling +!A4 U+00A4 currency +!A5 U+00A5 yen +!A6 U+00A6 brokenbar +!A7 U+00A7 section +!A8 U+00A8 dieresis +!A9 U+00A9 copyright +!AA U+00AA ordfeminine +!AB U+00AB guillemotleft +!AC U+00AC logicalnot +!AD U+00AD hyphen +!AE U+00AE registered +!AF U+00AF macron +!B0 U+00B0 degree +!B1 U+00B1 plusminus +!B2 U+00B2 twosuperior +!B3 U+00B3 threesuperior +!B4 U+00B4 acute +!B5 U+00B5 mu +!B6 U+00B6 paragraph +!B7 U+00B7 periodcentered +!B8 U+00B8 cedilla +!B9 U+00B9 onesuperior +!BA U+00BA ordmasculine +!BB U+00BB guillemotright +!BC U+00BC onequarter +!BD U+00BD onehalf +!BE U+00BE threequarters +!BF U+00BF questiondown +!C0 U+00C0 Agrave +!C1 U+00C1 Aacute +!C2 U+00C2 Acircumflex +!C3 U+00C3 Atilde +!C4 U+00C4 Adieresis +!C5 U+00C5 Aring +!C6 U+00C6 AE +!C7 U+00C7 Ccedilla +!C8 U+00C8 Egrave +!C9 U+00C9 Eacute +!CA U+00CA Ecircumflex +!CB U+00CB Edieresis +!CC U+00CC Igrave +!CD U+00CD Iacute +!CE U+00CE Icircumflex +!CF U+00CF Idieresis +!D0 U+011E Gbreve +!D1 U+00D1 Ntilde +!D2 U+00D2 Ograve +!D3 U+00D3 Oacute +!D4 U+00D4 Ocircumflex +!D5 U+00D5 Otilde +!D6 U+00D6 Odieresis +!D7 U+00D7 multiply +!D8 U+00D8 Oslash +!D9 U+00D9 Ugrave +!DA U+00DA Uacute +!DB U+00DB Ucircumflex +!DC U+00DC Udieresis +!DD U+0130 Idotaccent +!DE U+015E Scedilla +!DF U+00DF germandbls +!E0 U+00E0 agrave +!E1 U+00E1 aacute +!E2 U+00E2 acircumflex +!E3 U+00E3 atilde +!E4 U+00E4 adieresis +!E5 U+00E5 aring +!E6 U+00E6 ae +!E7 U+00E7 ccedilla +!E8 U+00E8 egrave +!E9 U+00E9 eacute +!EA U+00EA ecircumflex +!EB U+00EB edieresis +!EC U+00EC igrave +!ED U+00ED iacute +!EE U+00EE icircumflex +!EF U+00EF idieresis +!F0 U+011F gbreve +!F1 U+00F1 ntilde +!F2 U+00F2 ograve +!F3 U+00F3 oacute +!F4 U+00F4 ocircumflex +!F5 U+00F5 otilde +!F6 U+00F6 odieresis +!F7 U+00F7 divide +!F8 U+00F8 oslash +!F9 U+00F9 ugrave +!FA U+00FA uacute +!FB U+00FB ucircumflex +!FC U+00FC udieresis +!FD U+0131 dotlessi +!FE U+015F scedilla +!FF U+00FF ydieresis diff --git a/src/bb-library/makefont/cp1255.map b/src/bb-library/makefont/cp1255.map new file mode 100644 index 000000000..079e10c61 --- /dev/null +++ b/src/bb-library/makefont/cp1255.map @@ -0,0 +1,233 @@ +!00 U+0000 .notdef +!01 U+0001 .notdef +!02 U+0002 .notdef +!03 U+0003 .notdef +!04 U+0004 .notdef +!05 U+0005 .notdef +!06 U+0006 .notdef +!07 U+0007 .notdef +!08 U+0008 .notdef +!09 U+0009 .notdef +!0A U+000A .notdef +!0B U+000B .notdef +!0C U+000C .notdef +!0D U+000D .notdef +!0E U+000E .notdef +!0F U+000F .notdef +!10 U+0010 .notdef +!11 U+0011 .notdef +!12 U+0012 .notdef +!13 U+0013 .notdef +!14 U+0014 .notdef +!15 U+0015 .notdef +!16 U+0016 .notdef +!17 U+0017 .notdef +!18 U+0018 .notdef +!19 U+0019 .notdef +!1A U+001A .notdef +!1B U+001B .notdef +!1C U+001C .notdef +!1D U+001D .notdef +!1E U+001E .notdef +!1F U+001F .notdef +!20 U+0020 space +!21 U+0021 exclam +!22 U+0022 quotedbl +!23 U+0023 numbersign +!24 U+0024 dollar +!25 U+0025 percent +!26 U+0026 ampersand +!27 U+0027 quotesingle +!28 U+0028 parenleft +!29 U+0029 parenright +!2A U+002A asterisk +!2B U+002B plus +!2C U+002C comma +!2D U+002D hyphen +!2E U+002E period +!2F U+002F slash +!30 U+0030 zero +!31 U+0031 one +!32 U+0032 two +!33 U+0033 three +!34 U+0034 four +!35 U+0035 five +!36 U+0036 six +!37 U+0037 seven +!38 U+0038 eight +!39 U+0039 nine +!3A U+003A colon +!3B U+003B semicolon +!3C U+003C less +!3D U+003D equal +!3E U+003E greater +!3F U+003F question +!40 U+0040 at +!41 U+0041 A +!42 U+0042 B +!43 U+0043 C +!44 U+0044 D +!45 U+0045 E +!46 U+0046 F +!47 U+0047 G +!48 U+0048 H +!49 U+0049 I +!4A U+004A J +!4B U+004B K +!4C U+004C L +!4D U+004D M +!4E U+004E N +!4F U+004F O +!50 U+0050 P +!51 U+0051 Q +!52 U+0052 R +!53 U+0053 S +!54 U+0054 T +!55 U+0055 U +!56 U+0056 V +!57 U+0057 W +!58 U+0058 X +!59 U+0059 Y +!5A U+005A Z +!5B U+005B bracketleft +!5C U+005C backslash +!5D U+005D bracketright +!5E U+005E asciicircum +!5F U+005F underscore +!60 U+0060 grave +!61 U+0061 a +!62 U+0062 b +!63 U+0063 c +!64 U+0064 d +!65 U+0065 e +!66 U+0066 f +!67 U+0067 g +!68 U+0068 h +!69 U+0069 i +!6A U+006A j +!6B U+006B k +!6C U+006C l +!6D U+006D m +!6E U+006E n +!6F U+006F o +!70 U+0070 p +!71 U+0071 q +!72 U+0072 r +!73 U+0073 s +!74 U+0074 t +!75 U+0075 u +!76 U+0076 v +!77 U+0077 w +!78 U+0078 x +!79 U+0079 y +!7A U+007A z +!7B U+007B braceleft +!7C U+007C bar +!7D U+007D braceright +!7E U+007E asciitilde +!7F U+007F .notdef +!80 U+20AC Euro +!82 U+201A quotesinglbase +!83 U+0192 florin +!84 U+201E quotedblbase +!85 U+2026 ellipsis +!86 U+2020 dagger +!87 U+2021 daggerdbl +!88 U+02C6 circumflex +!89 U+2030 perthousand +!8B U+2039 guilsinglleft +!91 U+2018 quoteleft +!92 U+2019 quoteright +!93 U+201C quotedblleft +!94 U+201D quotedblright +!95 U+2022 bullet +!96 U+2013 endash +!97 U+2014 emdash +!98 U+02DC tilde +!99 U+2122 trademark +!9B U+203A guilsinglright +!A0 U+00A0 space +!A1 U+00A1 exclamdown +!A2 U+00A2 cent +!A3 U+00A3 sterling +!A4 U+20AA afii57636 +!A5 U+00A5 yen +!A6 U+00A6 brokenbar +!A7 U+00A7 section +!A8 U+00A8 dieresis +!A9 U+00A9 copyright +!AA U+00D7 multiply +!AB U+00AB guillemotleft +!AC U+00AC logicalnot +!AD U+00AD sfthyphen +!AE U+00AE registered +!AF U+00AF macron +!B0 U+00B0 degree +!B1 U+00B1 plusminus +!B2 U+00B2 twosuperior +!B3 U+00B3 threesuperior +!B4 U+00B4 acute +!B5 U+00B5 mu +!B6 U+00B6 paragraph +!B7 U+00B7 middot +!B8 U+00B8 cedilla +!B9 U+00B9 onesuperior +!BA U+00F7 divide +!BB U+00BB guillemotright +!BC U+00BC onequarter +!BD U+00BD onehalf +!BE U+00BE threequarters +!BF U+00BF questiondown +!C0 U+05B0 afii57799 +!C1 U+05B1 afii57801 +!C2 U+05B2 afii57800 +!C3 U+05B3 afii57802 +!C4 U+05B4 afii57793 +!C5 U+05B5 afii57794 +!C6 U+05B6 afii57795 +!C7 U+05B7 afii57798 +!C8 U+05B8 afii57797 +!C9 U+05B9 afii57806 +!CB U+05BB afii57796 +!CC U+05BC afii57807 +!CD U+05BD afii57839 +!CE U+05BE afii57645 +!CF U+05BF afii57841 +!D0 U+05C0 afii57842 +!D1 U+05C1 afii57804 +!D2 U+05C2 afii57803 +!D3 U+05C3 afii57658 +!D4 U+05F0 afii57716 +!D5 U+05F1 afii57717 +!D6 U+05F2 afii57718 +!D7 U+05F3 gereshhebrew +!D8 U+05F4 gershayimhebrew +!E0 U+05D0 afii57664 +!E1 U+05D1 afii57665 +!E2 U+05D2 afii57666 +!E3 U+05D3 afii57667 +!E4 U+05D4 afii57668 +!E5 U+05D5 afii57669 +!E6 U+05D6 afii57670 +!E7 U+05D7 afii57671 +!E8 U+05D8 afii57672 +!E9 U+05D9 afii57673 +!EA U+05DA afii57674 +!EB U+05DB afii57675 +!EC U+05DC afii57676 +!ED U+05DD afii57677 +!EE U+05DE afii57678 +!EF U+05DF afii57679 +!F0 U+05E0 afii57680 +!F1 U+05E1 afii57681 +!F2 U+05E2 afii57682 +!F3 U+05E3 afii57683 +!F4 U+05E4 afii57684 +!F5 U+05E5 afii57685 +!F6 U+05E6 afii57686 +!F7 U+05E7 afii57687 +!F8 U+05E8 afii57688 +!F9 U+05E9 afii57689 +!FA U+05EA afii57690 +!FD U+200E afii299 +!FE U+200F afii300 diff --git a/src/bb-library/makefont/cp1257.map b/src/bb-library/makefont/cp1257.map new file mode 100644 index 000000000..2f2ecfa21 --- /dev/null +++ b/src/bb-library/makefont/cp1257.map @@ -0,0 +1,244 @@ +!00 U+0000 .notdef +!01 U+0001 .notdef +!02 U+0002 .notdef +!03 U+0003 .notdef +!04 U+0004 .notdef +!05 U+0005 .notdef +!06 U+0006 .notdef +!07 U+0007 .notdef +!08 U+0008 .notdef +!09 U+0009 .notdef +!0A U+000A .notdef +!0B U+000B .notdef +!0C U+000C .notdef +!0D U+000D .notdef +!0E U+000E .notdef +!0F U+000F .notdef +!10 U+0010 .notdef +!11 U+0011 .notdef +!12 U+0012 .notdef +!13 U+0013 .notdef +!14 U+0014 .notdef +!15 U+0015 .notdef +!16 U+0016 .notdef +!17 U+0017 .notdef +!18 U+0018 .notdef +!19 U+0019 .notdef +!1A U+001A .notdef +!1B U+001B .notdef +!1C U+001C .notdef +!1D U+001D .notdef +!1E U+001E .notdef +!1F U+001F .notdef +!20 U+0020 space +!21 U+0021 exclam +!22 U+0022 quotedbl +!23 U+0023 numbersign +!24 U+0024 dollar +!25 U+0025 percent +!26 U+0026 ampersand +!27 U+0027 quotesingle +!28 U+0028 parenleft +!29 U+0029 parenright +!2A U+002A asterisk +!2B U+002B plus +!2C U+002C comma +!2D U+002D hyphen +!2E U+002E period +!2F U+002F slash +!30 U+0030 zero +!31 U+0031 one +!32 U+0032 two +!33 U+0033 three +!34 U+0034 four +!35 U+0035 five +!36 U+0036 six +!37 U+0037 seven +!38 U+0038 eight +!39 U+0039 nine +!3A U+003A colon +!3B U+003B semicolon +!3C U+003C less +!3D U+003D equal +!3E U+003E greater +!3F U+003F question +!40 U+0040 at +!41 U+0041 A +!42 U+0042 B +!43 U+0043 C +!44 U+0044 D +!45 U+0045 E +!46 U+0046 F +!47 U+0047 G +!48 U+0048 H +!49 U+0049 I +!4A U+004A J +!4B U+004B K +!4C U+004C L +!4D U+004D M +!4E U+004E N +!4F U+004F O +!50 U+0050 P +!51 U+0051 Q +!52 U+0052 R +!53 U+0053 S +!54 U+0054 T +!55 U+0055 U +!56 U+0056 V +!57 U+0057 W +!58 U+0058 X +!59 U+0059 Y +!5A U+005A Z +!5B U+005B bracketleft +!5C U+005C backslash +!5D U+005D bracketright +!5E U+005E asciicircum +!5F U+005F underscore +!60 U+0060 grave +!61 U+0061 a +!62 U+0062 b +!63 U+0063 c +!64 U+0064 d +!65 U+0065 e +!66 U+0066 f +!67 U+0067 g +!68 U+0068 h +!69 U+0069 i +!6A U+006A j +!6B U+006B k +!6C U+006C l +!6D U+006D m +!6E U+006E n +!6F U+006F o +!70 U+0070 p +!71 U+0071 q +!72 U+0072 r +!73 U+0073 s +!74 U+0074 t +!75 U+0075 u +!76 U+0076 v +!77 U+0077 w +!78 U+0078 x +!79 U+0079 y +!7A U+007A z +!7B U+007B braceleft +!7C U+007C bar +!7D U+007D braceright +!7E U+007E asciitilde +!7F U+007F .notdef +!80 U+20AC Euro +!82 U+201A quotesinglbase +!84 U+201E quotedblbase +!85 U+2026 ellipsis +!86 U+2020 dagger +!87 U+2021 daggerdbl +!89 U+2030 perthousand +!8B U+2039 guilsinglleft +!8D U+00A8 dieresis +!8E U+02C7 caron +!8F U+00B8 cedilla +!91 U+2018 quoteleft +!92 U+2019 quoteright +!93 U+201C quotedblleft +!94 U+201D quotedblright +!95 U+2022 bullet +!96 U+2013 endash +!97 U+2014 emdash +!99 U+2122 trademark +!9B U+203A guilsinglright +!9D U+00AF macron +!9E U+02DB ogonek +!A0 U+00A0 space +!A2 U+00A2 cent +!A3 U+00A3 sterling +!A4 U+00A4 currency +!A6 U+00A6 brokenbar +!A7 U+00A7 section +!A8 U+00D8 Oslash +!A9 U+00A9 copyright +!AA U+0156 Rcommaaccent +!AB U+00AB guillemotleft +!AC U+00AC logicalnot +!AD U+00AD hyphen +!AE U+00AE registered +!AF U+00C6 AE +!B0 U+00B0 degree +!B1 U+00B1 plusminus +!B2 U+00B2 twosuperior +!B3 U+00B3 threesuperior +!B4 U+00B4 acute +!B5 U+00B5 mu +!B6 U+00B6 paragraph +!B7 U+00B7 periodcentered +!B8 U+00F8 oslash +!B9 U+00B9 onesuperior +!BA U+0157 rcommaaccent +!BB U+00BB guillemotright +!BC U+00BC onequarter +!BD U+00BD onehalf +!BE U+00BE threequarters +!BF U+00E6 ae +!C0 U+0104 Aogonek +!C1 U+012E Iogonek +!C2 U+0100 Amacron +!C3 U+0106 Cacute +!C4 U+00C4 Adieresis +!C5 U+00C5 Aring +!C6 U+0118 Eogonek +!C7 U+0112 Emacron +!C8 U+010C Ccaron +!C9 U+00C9 Eacute +!CA U+0179 Zacute +!CB U+0116 Edotaccent +!CC U+0122 Gcommaaccent +!CD U+0136 Kcommaaccent +!CE U+012A Imacron +!CF U+013B Lcommaaccent +!D0 U+0160 Scaron +!D1 U+0143 Nacute +!D2 U+0145 Ncommaaccent +!D3 U+00D3 Oacute +!D4 U+014C Omacron +!D5 U+00D5 Otilde +!D6 U+00D6 Odieresis +!D7 U+00D7 multiply +!D8 U+0172 Uogonek +!D9 U+0141 Lslash +!DA U+015A Sacute +!DB U+016A Umacron +!DC U+00DC Udieresis +!DD U+017B Zdotaccent +!DE U+017D Zcaron +!DF U+00DF germandbls +!E0 U+0105 aogonek +!E1 U+012F iogonek +!E2 U+0101 amacron +!E3 U+0107 cacute +!E4 U+00E4 adieresis +!E5 U+00E5 aring +!E6 U+0119 eogonek +!E7 U+0113 emacron +!E8 U+010D ccaron +!E9 U+00E9 eacute +!EA U+017A zacute +!EB U+0117 edotaccent +!EC U+0123 gcommaaccent +!ED U+0137 kcommaaccent +!EE U+012B imacron +!EF U+013C lcommaaccent +!F0 U+0161 scaron +!F1 U+0144 nacute +!F2 U+0146 ncommaaccent +!F3 U+00F3 oacute +!F4 U+014D omacron +!F5 U+00F5 otilde +!F6 U+00F6 odieresis +!F7 U+00F7 divide +!F8 U+0173 uogonek +!F9 U+0142 lslash +!FA U+015B sacute +!FB U+016B umacron +!FC U+00FC udieresis +!FD U+017C zdotaccent +!FE U+017E zcaron +!FF U+02D9 dotaccent diff --git a/src/bb-library/makefont/cp1258.map b/src/bb-library/makefont/cp1258.map new file mode 100644 index 000000000..fed915f71 --- /dev/null +++ b/src/bb-library/makefont/cp1258.map @@ -0,0 +1,247 @@ +!00 U+0000 .notdef +!01 U+0001 .notdef +!02 U+0002 .notdef +!03 U+0003 .notdef +!04 U+0004 .notdef +!05 U+0005 .notdef +!06 U+0006 .notdef +!07 U+0007 .notdef +!08 U+0008 .notdef +!09 U+0009 .notdef +!0A U+000A .notdef +!0B U+000B .notdef +!0C U+000C .notdef +!0D U+000D .notdef +!0E U+000E .notdef +!0F U+000F .notdef +!10 U+0010 .notdef +!11 U+0011 .notdef +!12 U+0012 .notdef +!13 U+0013 .notdef +!14 U+0014 .notdef +!15 U+0015 .notdef +!16 U+0016 .notdef +!17 U+0017 .notdef +!18 U+0018 .notdef +!19 U+0019 .notdef +!1A U+001A .notdef +!1B U+001B .notdef +!1C U+001C .notdef +!1D U+001D .notdef +!1E U+001E .notdef +!1F U+001F .notdef +!20 U+0020 space +!21 U+0021 exclam +!22 U+0022 quotedbl +!23 U+0023 numbersign +!24 U+0024 dollar +!25 U+0025 percent +!26 U+0026 ampersand +!27 U+0027 quotesingle +!28 U+0028 parenleft +!29 U+0029 parenright +!2A U+002A asterisk +!2B U+002B plus +!2C U+002C comma +!2D U+002D hyphen +!2E U+002E period +!2F U+002F slash +!30 U+0030 zero +!31 U+0031 one +!32 U+0032 two +!33 U+0033 three +!34 U+0034 four +!35 U+0035 five +!36 U+0036 six +!37 U+0037 seven +!38 U+0038 eight +!39 U+0039 nine +!3A U+003A colon +!3B U+003B semicolon +!3C U+003C less +!3D U+003D equal +!3E U+003E greater +!3F U+003F question +!40 U+0040 at +!41 U+0041 A +!42 U+0042 B +!43 U+0043 C +!44 U+0044 D +!45 U+0045 E +!46 U+0046 F +!47 U+0047 G +!48 U+0048 H +!49 U+0049 I +!4A U+004A J +!4B U+004B K +!4C U+004C L +!4D U+004D M +!4E U+004E N +!4F U+004F O +!50 U+0050 P +!51 U+0051 Q +!52 U+0052 R +!53 U+0053 S +!54 U+0054 T +!55 U+0055 U +!56 U+0056 V +!57 U+0057 W +!58 U+0058 X +!59 U+0059 Y +!5A U+005A Z +!5B U+005B bracketleft +!5C U+005C backslash +!5D U+005D bracketright +!5E U+005E asciicircum +!5F U+005F underscore +!60 U+0060 grave +!61 U+0061 a +!62 U+0062 b +!63 U+0063 c +!64 U+0064 d +!65 U+0065 e +!66 U+0066 f +!67 U+0067 g +!68 U+0068 h +!69 U+0069 i +!6A U+006A j +!6B U+006B k +!6C U+006C l +!6D U+006D m +!6E U+006E n +!6F U+006F o +!70 U+0070 p +!71 U+0071 q +!72 U+0072 r +!73 U+0073 s +!74 U+0074 t +!75 U+0075 u +!76 U+0076 v +!77 U+0077 w +!78 U+0078 x +!79 U+0079 y +!7A U+007A z +!7B U+007B braceleft +!7C U+007C bar +!7D U+007D braceright +!7E U+007E asciitilde +!7F U+007F .notdef +!80 U+20AC Euro +!82 U+201A quotesinglbase +!83 U+0192 florin +!84 U+201E quotedblbase +!85 U+2026 ellipsis +!86 U+2020 dagger +!87 U+2021 daggerdbl +!88 U+02C6 circumflex +!89 U+2030 perthousand +!8B U+2039 guilsinglleft +!8C U+0152 OE +!91 U+2018 quoteleft +!92 U+2019 quoteright +!93 U+201C quotedblleft +!94 U+201D quotedblright +!95 U+2022 bullet +!96 U+2013 endash +!97 U+2014 emdash +!98 U+02DC tilde +!99 U+2122 trademark +!9B U+203A guilsinglright +!9C U+0153 oe +!9F U+0178 Ydieresis +!A0 U+00A0 space +!A1 U+00A1 exclamdown +!A2 U+00A2 cent +!A3 U+00A3 sterling +!A4 U+00A4 currency +!A5 U+00A5 yen +!A6 U+00A6 brokenbar +!A7 U+00A7 section +!A8 U+00A8 dieresis +!A9 U+00A9 copyright +!AA U+00AA ordfeminine +!AB U+00AB guillemotleft +!AC U+00AC logicalnot +!AD U+00AD hyphen +!AE U+00AE registered +!AF U+00AF macron +!B0 U+00B0 degree +!B1 U+00B1 plusminus +!B2 U+00B2 twosuperior +!B3 U+00B3 threesuperior +!B4 U+00B4 acute +!B5 U+00B5 mu +!B6 U+00B6 paragraph +!B7 U+00B7 periodcentered +!B8 U+00B8 cedilla +!B9 U+00B9 onesuperior +!BA U+00BA ordmasculine +!BB U+00BB guillemotright +!BC U+00BC onequarter +!BD U+00BD onehalf +!BE U+00BE threequarters +!BF U+00BF questiondown +!C0 U+00C0 Agrave +!C1 U+00C1 Aacute +!C2 U+00C2 Acircumflex +!C3 U+0102 Abreve +!C4 U+00C4 Adieresis +!C5 U+00C5 Aring +!C6 U+00C6 AE +!C7 U+00C7 Ccedilla +!C8 U+00C8 Egrave +!C9 U+00C9 Eacute +!CA U+00CA Ecircumflex +!CB U+00CB Edieresis +!CC U+0300 gravecomb +!CD U+00CD Iacute +!CE U+00CE Icircumflex +!CF U+00CF Idieresis +!D0 U+0110 Dcroat +!D1 U+00D1 Ntilde +!D2 U+0309 hookabovecomb +!D3 U+00D3 Oacute +!D4 U+00D4 Ocircumflex +!D5 U+01A0 Ohorn +!D6 U+00D6 Odieresis +!D7 U+00D7 multiply +!D8 U+00D8 Oslash +!D9 U+00D9 Ugrave +!DA U+00DA Uacute +!DB U+00DB Ucircumflex +!DC U+00DC Udieresis +!DD U+01AF Uhorn +!DE U+0303 tildecomb +!DF U+00DF germandbls +!E0 U+00E0 agrave +!E1 U+00E1 aacute +!E2 U+00E2 acircumflex +!E3 U+0103 abreve +!E4 U+00E4 adieresis +!E5 U+00E5 aring +!E6 U+00E6 ae +!E7 U+00E7 ccedilla +!E8 U+00E8 egrave +!E9 U+00E9 eacute +!EA U+00EA ecircumflex +!EB U+00EB edieresis +!EC U+0301 acutecomb +!ED U+00ED iacute +!EE U+00EE icircumflex +!EF U+00EF idieresis +!F0 U+0111 dcroat +!F1 U+00F1 ntilde +!F2 U+0323 dotbelowcomb +!F3 U+00F3 oacute +!F4 U+00F4 ocircumflex +!F5 U+01A1 ohorn +!F6 U+00F6 odieresis +!F7 U+00F7 divide +!F8 U+00F8 oslash +!F9 U+00F9 ugrave +!FA U+00FA uacute +!FB U+00FB ucircumflex +!FC U+00FC udieresis +!FD U+01B0 uhorn +!FE U+20AB dong +!FF U+00FF ydieresis diff --git a/src/bb-library/makefont/cp874.map b/src/bb-library/makefont/cp874.map new file mode 100644 index 000000000..1006e6b17 --- /dev/null +++ b/src/bb-library/makefont/cp874.map @@ -0,0 +1,225 @@ +!00 U+0000 .notdef +!01 U+0001 .notdef +!02 U+0002 .notdef +!03 U+0003 .notdef +!04 U+0004 .notdef +!05 U+0005 .notdef +!06 U+0006 .notdef +!07 U+0007 .notdef +!08 U+0008 .notdef +!09 U+0009 .notdef +!0A U+000A .notdef +!0B U+000B .notdef +!0C U+000C .notdef +!0D U+000D .notdef +!0E U+000E .notdef +!0F U+000F .notdef +!10 U+0010 .notdef +!11 U+0011 .notdef +!12 U+0012 .notdef +!13 U+0013 .notdef +!14 U+0014 .notdef +!15 U+0015 .notdef +!16 U+0016 .notdef +!17 U+0017 .notdef +!18 U+0018 .notdef +!19 U+0019 .notdef +!1A U+001A .notdef +!1B U+001B .notdef +!1C U+001C .notdef +!1D U+001D .notdef +!1E U+001E .notdef +!1F U+001F .notdef +!20 U+0020 space +!21 U+0021 exclam +!22 U+0022 quotedbl +!23 U+0023 numbersign +!24 U+0024 dollar +!25 U+0025 percent +!26 U+0026 ampersand +!27 U+0027 quotesingle +!28 U+0028 parenleft +!29 U+0029 parenright +!2A U+002A asterisk +!2B U+002B plus +!2C U+002C comma +!2D U+002D hyphen +!2E U+002E period +!2F U+002F slash +!30 U+0030 zero +!31 U+0031 one +!32 U+0032 two +!33 U+0033 three +!34 U+0034 four +!35 U+0035 five +!36 U+0036 six +!37 U+0037 seven +!38 U+0038 eight +!39 U+0039 nine +!3A U+003A colon +!3B U+003B semicolon +!3C U+003C less +!3D U+003D equal +!3E U+003E greater +!3F U+003F question +!40 U+0040 at +!41 U+0041 A +!42 U+0042 B +!43 U+0043 C +!44 U+0044 D +!45 U+0045 E +!46 U+0046 F +!47 U+0047 G +!48 U+0048 H +!49 U+0049 I +!4A U+004A J +!4B U+004B K +!4C U+004C L +!4D U+004D M +!4E U+004E N +!4F U+004F O +!50 U+0050 P +!51 U+0051 Q +!52 U+0052 R +!53 U+0053 S +!54 U+0054 T +!55 U+0055 U +!56 U+0056 V +!57 U+0057 W +!58 U+0058 X +!59 U+0059 Y +!5A U+005A Z +!5B U+005B bracketleft +!5C U+005C backslash +!5D U+005D bracketright +!5E U+005E asciicircum +!5F U+005F underscore +!60 U+0060 grave +!61 U+0061 a +!62 U+0062 b +!63 U+0063 c +!64 U+0064 d +!65 U+0065 e +!66 U+0066 f +!67 U+0067 g +!68 U+0068 h +!69 U+0069 i +!6A U+006A j +!6B U+006B k +!6C U+006C l +!6D U+006D m +!6E U+006E n +!6F U+006F o +!70 U+0070 p +!71 U+0071 q +!72 U+0072 r +!73 U+0073 s +!74 U+0074 t +!75 U+0075 u +!76 U+0076 v +!77 U+0077 w +!78 U+0078 x +!79 U+0079 y +!7A U+007A z +!7B U+007B braceleft +!7C U+007C bar +!7D U+007D braceright +!7E U+007E asciitilde +!7F U+007F .notdef +!80 U+20AC Euro +!85 U+2026 ellipsis +!91 U+2018 quoteleft +!92 U+2019 quoteright +!93 U+201C quotedblleft +!94 U+201D quotedblright +!95 U+2022 bullet +!96 U+2013 endash +!97 U+2014 emdash +!A0 U+00A0 space +!A1 U+0E01 kokaithai +!A2 U+0E02 khokhaithai +!A3 U+0E03 khokhuatthai +!A4 U+0E04 khokhwaithai +!A5 U+0E05 khokhonthai +!A6 U+0E06 khorakhangthai +!A7 U+0E07 ngonguthai +!A8 U+0E08 chochanthai +!A9 U+0E09 chochingthai +!AA U+0E0A chochangthai +!AB U+0E0B sosothai +!AC U+0E0C chochoethai +!AD U+0E0D yoyingthai +!AE U+0E0E dochadathai +!AF U+0E0F topatakthai +!B0 U+0E10 thothanthai +!B1 U+0E11 thonangmonthothai +!B2 U+0E12 thophuthaothai +!B3 U+0E13 nonenthai +!B4 U+0E14 dodekthai +!B5 U+0E15 totaothai +!B6 U+0E16 thothungthai +!B7 U+0E17 thothahanthai +!B8 U+0E18 thothongthai +!B9 U+0E19 nonuthai +!BA U+0E1A bobaimaithai +!BB U+0E1B poplathai +!BC U+0E1C phophungthai +!BD U+0E1D fofathai +!BE U+0E1E phophanthai +!BF U+0E1F fofanthai +!C0 U+0E20 phosamphaothai +!C1 U+0E21 momathai +!C2 U+0E22 yoyakthai +!C3 U+0E23 roruathai +!C4 U+0E24 ruthai +!C5 U+0E25 lolingthai +!C6 U+0E26 luthai +!C7 U+0E27 wowaenthai +!C8 U+0E28 sosalathai +!C9 U+0E29 sorusithai +!CA U+0E2A sosuathai +!CB U+0E2B hohipthai +!CC U+0E2C lochulathai +!CD U+0E2D oangthai +!CE U+0E2E honokhukthai +!CF U+0E2F paiyannoithai +!D0 U+0E30 saraathai +!D1 U+0E31 maihanakatthai +!D2 U+0E32 saraaathai +!D3 U+0E33 saraamthai +!D4 U+0E34 saraithai +!D5 U+0E35 saraiithai +!D6 U+0E36 sarauethai +!D7 U+0E37 saraueethai +!D8 U+0E38 sarauthai +!D9 U+0E39 sarauuthai +!DA U+0E3A phinthuthai +!DF U+0E3F bahtthai +!E0 U+0E40 saraethai +!E1 U+0E41 saraaethai +!E2 U+0E42 saraothai +!E3 U+0E43 saraaimaimuanthai +!E4 U+0E44 saraaimaimalaithai +!E5 U+0E45 lakkhangyaothai +!E6 U+0E46 maiyamokthai +!E7 U+0E47 maitaikhuthai +!E8 U+0E48 maiekthai +!E9 U+0E49 maithothai +!EA U+0E4A maitrithai +!EB U+0E4B maichattawathai +!EC U+0E4C thanthakhatthai +!ED U+0E4D nikhahitthai +!EE U+0E4E yamakkanthai +!EF U+0E4F fongmanthai +!F0 U+0E50 zerothai +!F1 U+0E51 onethai +!F2 U+0E52 twothai +!F3 U+0E53 threethai +!F4 U+0E54 fourthai +!F5 U+0E55 fivethai +!F6 U+0E56 sixthai +!F7 U+0E57 seventhai +!F8 U+0E58 eightthai +!F9 U+0E59 ninethai +!FA U+0E5A angkhankhuthai +!FB U+0E5B khomutthai diff --git a/src/bb-library/makefont/iso-8859-1.map b/src/bb-library/makefont/iso-8859-1.map new file mode 100644 index 000000000..61740a38f --- /dev/null +++ b/src/bb-library/makefont/iso-8859-1.map @@ -0,0 +1,256 @@ +!00 U+0000 .notdef +!01 U+0001 .notdef +!02 U+0002 .notdef +!03 U+0003 .notdef +!04 U+0004 .notdef +!05 U+0005 .notdef +!06 U+0006 .notdef +!07 U+0007 .notdef +!08 U+0008 .notdef +!09 U+0009 .notdef +!0A U+000A .notdef +!0B U+000B .notdef +!0C U+000C .notdef +!0D U+000D .notdef +!0E U+000E .notdef +!0F U+000F .notdef +!10 U+0010 .notdef +!11 U+0011 .notdef +!12 U+0012 .notdef +!13 U+0013 .notdef +!14 U+0014 .notdef +!15 U+0015 .notdef +!16 U+0016 .notdef +!17 U+0017 .notdef +!18 U+0018 .notdef +!19 U+0019 .notdef +!1A U+001A .notdef +!1B U+001B .notdef +!1C U+001C .notdef +!1D U+001D .notdef +!1E U+001E .notdef +!1F U+001F .notdef +!20 U+0020 space +!21 U+0021 exclam +!22 U+0022 quotedbl +!23 U+0023 numbersign +!24 U+0024 dollar +!25 U+0025 percent +!26 U+0026 ampersand +!27 U+0027 quotesingle +!28 U+0028 parenleft +!29 U+0029 parenright +!2A U+002A asterisk +!2B U+002B plus +!2C U+002C comma +!2D U+002D hyphen +!2E U+002E period +!2F U+002F slash +!30 U+0030 zero +!31 U+0031 one +!32 U+0032 two +!33 U+0033 three +!34 U+0034 four +!35 U+0035 five +!36 U+0036 six +!37 U+0037 seven +!38 U+0038 eight +!39 U+0039 nine +!3A U+003A colon +!3B U+003B semicolon +!3C U+003C less +!3D U+003D equal +!3E U+003E greater +!3F U+003F question +!40 U+0040 at +!41 U+0041 A +!42 U+0042 B +!43 U+0043 C +!44 U+0044 D +!45 U+0045 E +!46 U+0046 F +!47 U+0047 G +!48 U+0048 H +!49 U+0049 I +!4A U+004A J +!4B U+004B K +!4C U+004C L +!4D U+004D M +!4E U+004E N +!4F U+004F O +!50 U+0050 P +!51 U+0051 Q +!52 U+0052 R +!53 U+0053 S +!54 U+0054 T +!55 U+0055 U +!56 U+0056 V +!57 U+0057 W +!58 U+0058 X +!59 U+0059 Y +!5A U+005A Z +!5B U+005B bracketleft +!5C U+005C backslash +!5D U+005D bracketright +!5E U+005E asciicircum +!5F U+005F underscore +!60 U+0060 grave +!61 U+0061 a +!62 U+0062 b +!63 U+0063 c +!64 U+0064 d +!65 U+0065 e +!66 U+0066 f +!67 U+0067 g +!68 U+0068 h +!69 U+0069 i +!6A U+006A j +!6B U+006B k +!6C U+006C l +!6D U+006D m +!6E U+006E n +!6F U+006F o +!70 U+0070 p +!71 U+0071 q +!72 U+0072 r +!73 U+0073 s +!74 U+0074 t +!75 U+0075 u +!76 U+0076 v +!77 U+0077 w +!78 U+0078 x +!79 U+0079 y +!7A U+007A z +!7B U+007B braceleft +!7C U+007C bar +!7D U+007D braceright +!7E U+007E asciitilde +!7F U+007F .notdef +!80 U+0080 .notdef +!81 U+0081 .notdef +!82 U+0082 .notdef +!83 U+0083 .notdef +!84 U+0084 .notdef +!85 U+0085 .notdef +!86 U+0086 .notdef +!87 U+0087 .notdef +!88 U+0088 .notdef +!89 U+0089 .notdef +!8A U+008A .notdef +!8B U+008B .notdef +!8C U+008C .notdef +!8D U+008D .notdef +!8E U+008E .notdef +!8F U+008F .notdef +!90 U+0090 .notdef +!91 U+0091 .notdef +!92 U+0092 .notdef +!93 U+0093 .notdef +!94 U+0094 .notdef +!95 U+0095 .notdef +!96 U+0096 .notdef +!97 U+0097 .notdef +!98 U+0098 .notdef +!99 U+0099 .notdef +!9A U+009A .notdef +!9B U+009B .notdef +!9C U+009C .notdef +!9D U+009D .notdef +!9E U+009E .notdef +!9F U+009F .notdef +!A0 U+00A0 space +!A1 U+00A1 exclamdown +!A2 U+00A2 cent +!A3 U+00A3 sterling +!A4 U+00A4 currency +!A5 U+00A5 yen +!A6 U+00A6 brokenbar +!A7 U+00A7 section +!A8 U+00A8 dieresis +!A9 U+00A9 copyright +!AA U+00AA ordfeminine +!AB U+00AB guillemotleft +!AC U+00AC logicalnot +!AD U+00AD hyphen +!AE U+00AE registered +!AF U+00AF macron +!B0 U+00B0 degree +!B1 U+00B1 plusminus +!B2 U+00B2 twosuperior +!B3 U+00B3 threesuperior +!B4 U+00B4 acute +!B5 U+00B5 mu +!B6 U+00B6 paragraph +!B7 U+00B7 periodcentered +!B8 U+00B8 cedilla +!B9 U+00B9 onesuperior +!BA U+00BA ordmasculine +!BB U+00BB guillemotright +!BC U+00BC onequarter +!BD U+00BD onehalf +!BE U+00BE threequarters +!BF U+00BF questiondown +!C0 U+00C0 Agrave +!C1 U+00C1 Aacute +!C2 U+00C2 Acircumflex +!C3 U+00C3 Atilde +!C4 U+00C4 Adieresis +!C5 U+00C5 Aring +!C6 U+00C6 AE +!C7 U+00C7 Ccedilla +!C8 U+00C8 Egrave +!C9 U+00C9 Eacute +!CA U+00CA Ecircumflex +!CB U+00CB Edieresis +!CC U+00CC Igrave +!CD U+00CD Iacute +!CE U+00CE Icircumflex +!CF U+00CF Idieresis +!D0 U+00D0 Eth +!D1 U+00D1 Ntilde +!D2 U+00D2 Ograve +!D3 U+00D3 Oacute +!D4 U+00D4 Ocircumflex +!D5 U+00D5 Otilde +!D6 U+00D6 Odieresis +!D7 U+00D7 multiply +!D8 U+00D8 Oslash +!D9 U+00D9 Ugrave +!DA U+00DA Uacute +!DB U+00DB Ucircumflex +!DC U+00DC Udieresis +!DD U+00DD Yacute +!DE U+00DE Thorn +!DF U+00DF germandbls +!E0 U+00E0 agrave +!E1 U+00E1 aacute +!E2 U+00E2 acircumflex +!E3 U+00E3 atilde +!E4 U+00E4 adieresis +!E5 U+00E5 aring +!E6 U+00E6 ae +!E7 U+00E7 ccedilla +!E8 U+00E8 egrave +!E9 U+00E9 eacute +!EA U+00EA ecircumflex +!EB U+00EB edieresis +!EC U+00EC igrave +!ED U+00ED iacute +!EE U+00EE icircumflex +!EF U+00EF idieresis +!F0 U+00F0 eth +!F1 U+00F1 ntilde +!F2 U+00F2 ograve +!F3 U+00F3 oacute +!F4 U+00F4 ocircumflex +!F5 U+00F5 otilde +!F6 U+00F6 odieresis +!F7 U+00F7 divide +!F8 U+00F8 oslash +!F9 U+00F9 ugrave +!FA U+00FA uacute +!FB U+00FB ucircumflex +!FC U+00FC udieresis +!FD U+00FD yacute +!FE U+00FE thorn +!FF U+00FF ydieresis diff --git a/src/bb-library/makefont/iso-8859-11.map b/src/bb-library/makefont/iso-8859-11.map new file mode 100644 index 000000000..916881206 --- /dev/null +++ b/src/bb-library/makefont/iso-8859-11.map @@ -0,0 +1,248 @@ +!00 U+0000 .notdef +!01 U+0001 .notdef +!02 U+0002 .notdef +!03 U+0003 .notdef +!04 U+0004 .notdef +!05 U+0005 .notdef +!06 U+0006 .notdef +!07 U+0007 .notdef +!08 U+0008 .notdef +!09 U+0009 .notdef +!0A U+000A .notdef +!0B U+000B .notdef +!0C U+000C .notdef +!0D U+000D .notdef +!0E U+000E .notdef +!0F U+000F .notdef +!10 U+0010 .notdef +!11 U+0011 .notdef +!12 U+0012 .notdef +!13 U+0013 .notdef +!14 U+0014 .notdef +!15 U+0015 .notdef +!16 U+0016 .notdef +!17 U+0017 .notdef +!18 U+0018 .notdef +!19 U+0019 .notdef +!1A U+001A .notdef +!1B U+001B .notdef +!1C U+001C .notdef +!1D U+001D .notdef +!1E U+001E .notdef +!1F U+001F .notdef +!20 U+0020 space +!21 U+0021 exclam +!22 U+0022 quotedbl +!23 U+0023 numbersign +!24 U+0024 dollar +!25 U+0025 percent +!26 U+0026 ampersand +!27 U+0027 quotesingle +!28 U+0028 parenleft +!29 U+0029 parenright +!2A U+002A asterisk +!2B U+002B plus +!2C U+002C comma +!2D U+002D hyphen +!2E U+002E period +!2F U+002F slash +!30 U+0030 zero +!31 U+0031 one +!32 U+0032 two +!33 U+0033 three +!34 U+0034 four +!35 U+0035 five +!36 U+0036 six +!37 U+0037 seven +!38 U+0038 eight +!39 U+0039 nine +!3A U+003A colon +!3B U+003B semicolon +!3C U+003C less +!3D U+003D equal +!3E U+003E greater +!3F U+003F question +!40 U+0040 at +!41 U+0041 A +!42 U+0042 B +!43 U+0043 C +!44 U+0044 D +!45 U+0045 E +!46 U+0046 F +!47 U+0047 G +!48 U+0048 H +!49 U+0049 I +!4A U+004A J +!4B U+004B K +!4C U+004C L +!4D U+004D M +!4E U+004E N +!4F U+004F O +!50 U+0050 P +!51 U+0051 Q +!52 U+0052 R +!53 U+0053 S +!54 U+0054 T +!55 U+0055 U +!56 U+0056 V +!57 U+0057 W +!58 U+0058 X +!59 U+0059 Y +!5A U+005A Z +!5B U+005B bracketleft +!5C U+005C backslash +!5D U+005D bracketright +!5E U+005E asciicircum +!5F U+005F underscore +!60 U+0060 grave +!61 U+0061 a +!62 U+0062 b +!63 U+0063 c +!64 U+0064 d +!65 U+0065 e +!66 U+0066 f +!67 U+0067 g +!68 U+0068 h +!69 U+0069 i +!6A U+006A j +!6B U+006B k +!6C U+006C l +!6D U+006D m +!6E U+006E n +!6F U+006F o +!70 U+0070 p +!71 U+0071 q +!72 U+0072 r +!73 U+0073 s +!74 U+0074 t +!75 U+0075 u +!76 U+0076 v +!77 U+0077 w +!78 U+0078 x +!79 U+0079 y +!7A U+007A z +!7B U+007B braceleft +!7C U+007C bar +!7D U+007D braceright +!7E U+007E asciitilde +!7F U+007F .notdef +!80 U+0080 .notdef +!81 U+0081 .notdef +!82 U+0082 .notdef +!83 U+0083 .notdef +!84 U+0084 .notdef +!85 U+0085 .notdef +!86 U+0086 .notdef +!87 U+0087 .notdef +!88 U+0088 .notdef +!89 U+0089 .notdef +!8A U+008A .notdef +!8B U+008B .notdef +!8C U+008C .notdef +!8D U+008D .notdef +!8E U+008E .notdef +!8F U+008F .notdef +!90 U+0090 .notdef +!91 U+0091 .notdef +!92 U+0092 .notdef +!93 U+0093 .notdef +!94 U+0094 .notdef +!95 U+0095 .notdef +!96 U+0096 .notdef +!97 U+0097 .notdef +!98 U+0098 .notdef +!99 U+0099 .notdef +!9A U+009A .notdef +!9B U+009B .notdef +!9C U+009C .notdef +!9D U+009D .notdef +!9E U+009E .notdef +!9F U+009F .notdef +!A0 U+00A0 space +!A1 U+0E01 kokaithai +!A2 U+0E02 khokhaithai +!A3 U+0E03 khokhuatthai +!A4 U+0E04 khokhwaithai +!A5 U+0E05 khokhonthai +!A6 U+0E06 khorakhangthai +!A7 U+0E07 ngonguthai +!A8 U+0E08 chochanthai +!A9 U+0E09 chochingthai +!AA U+0E0A chochangthai +!AB U+0E0B sosothai +!AC U+0E0C chochoethai +!AD U+0E0D yoyingthai +!AE U+0E0E dochadathai +!AF U+0E0F topatakthai +!B0 U+0E10 thothanthai +!B1 U+0E11 thonangmonthothai +!B2 U+0E12 thophuthaothai +!B3 U+0E13 nonenthai +!B4 U+0E14 dodekthai +!B5 U+0E15 totaothai +!B6 U+0E16 thothungthai +!B7 U+0E17 thothahanthai +!B8 U+0E18 thothongthai +!B9 U+0E19 nonuthai +!BA U+0E1A bobaimaithai +!BB U+0E1B poplathai +!BC U+0E1C phophungthai +!BD U+0E1D fofathai +!BE U+0E1E phophanthai +!BF U+0E1F fofanthai +!C0 U+0E20 phosamphaothai +!C1 U+0E21 momathai +!C2 U+0E22 yoyakthai +!C3 U+0E23 roruathai +!C4 U+0E24 ruthai +!C5 U+0E25 lolingthai +!C6 U+0E26 luthai +!C7 U+0E27 wowaenthai +!C8 U+0E28 sosalathai +!C9 U+0E29 sorusithai +!CA U+0E2A sosuathai +!CB U+0E2B hohipthai +!CC U+0E2C lochulathai +!CD U+0E2D oangthai +!CE U+0E2E honokhukthai +!CF U+0E2F paiyannoithai +!D0 U+0E30 saraathai +!D1 U+0E31 maihanakatthai +!D2 U+0E32 saraaathai +!D3 U+0E33 saraamthai +!D4 U+0E34 saraithai +!D5 U+0E35 saraiithai +!D6 U+0E36 sarauethai +!D7 U+0E37 saraueethai +!D8 U+0E38 sarauthai +!D9 U+0E39 sarauuthai +!DA U+0E3A phinthuthai +!DF U+0E3F bahtthai +!E0 U+0E40 saraethai +!E1 U+0E41 saraaethai +!E2 U+0E42 saraothai +!E3 U+0E43 saraaimaimuanthai +!E4 U+0E44 saraaimaimalaithai +!E5 U+0E45 lakkhangyaothai +!E6 U+0E46 maiyamokthai +!E7 U+0E47 maitaikhuthai +!E8 U+0E48 maiekthai +!E9 U+0E49 maithothai +!EA U+0E4A maitrithai +!EB U+0E4B maichattawathai +!EC U+0E4C thanthakhatthai +!ED U+0E4D nikhahitthai +!EE U+0E4E yamakkanthai +!EF U+0E4F fongmanthai +!F0 U+0E50 zerothai +!F1 U+0E51 onethai +!F2 U+0E52 twothai +!F3 U+0E53 threethai +!F4 U+0E54 fourthai +!F5 U+0E55 fivethai +!F6 U+0E56 sixthai +!F7 U+0E57 seventhai +!F8 U+0E58 eightthai +!F9 U+0E59 ninethai +!FA U+0E5A angkhankhuthai +!FB U+0E5B khomutthai diff --git a/src/bb-library/makefont/iso-8859-15.map b/src/bb-library/makefont/iso-8859-15.map new file mode 100644 index 000000000..6c2b57127 --- /dev/null +++ b/src/bb-library/makefont/iso-8859-15.map @@ -0,0 +1,256 @@ +!00 U+0000 .notdef +!01 U+0001 .notdef +!02 U+0002 .notdef +!03 U+0003 .notdef +!04 U+0004 .notdef +!05 U+0005 .notdef +!06 U+0006 .notdef +!07 U+0007 .notdef +!08 U+0008 .notdef +!09 U+0009 .notdef +!0A U+000A .notdef +!0B U+000B .notdef +!0C U+000C .notdef +!0D U+000D .notdef +!0E U+000E .notdef +!0F U+000F .notdef +!10 U+0010 .notdef +!11 U+0011 .notdef +!12 U+0012 .notdef +!13 U+0013 .notdef +!14 U+0014 .notdef +!15 U+0015 .notdef +!16 U+0016 .notdef +!17 U+0017 .notdef +!18 U+0018 .notdef +!19 U+0019 .notdef +!1A U+001A .notdef +!1B U+001B .notdef +!1C U+001C .notdef +!1D U+001D .notdef +!1E U+001E .notdef +!1F U+001F .notdef +!20 U+0020 space +!21 U+0021 exclam +!22 U+0022 quotedbl +!23 U+0023 numbersign +!24 U+0024 dollar +!25 U+0025 percent +!26 U+0026 ampersand +!27 U+0027 quotesingle +!28 U+0028 parenleft +!29 U+0029 parenright +!2A U+002A asterisk +!2B U+002B plus +!2C U+002C comma +!2D U+002D hyphen +!2E U+002E period +!2F U+002F slash +!30 U+0030 zero +!31 U+0031 one +!32 U+0032 two +!33 U+0033 three +!34 U+0034 four +!35 U+0035 five +!36 U+0036 six +!37 U+0037 seven +!38 U+0038 eight +!39 U+0039 nine +!3A U+003A colon +!3B U+003B semicolon +!3C U+003C less +!3D U+003D equal +!3E U+003E greater +!3F U+003F question +!40 U+0040 at +!41 U+0041 A +!42 U+0042 B +!43 U+0043 C +!44 U+0044 D +!45 U+0045 E +!46 U+0046 F +!47 U+0047 G +!48 U+0048 H +!49 U+0049 I +!4A U+004A J +!4B U+004B K +!4C U+004C L +!4D U+004D M +!4E U+004E N +!4F U+004F O +!50 U+0050 P +!51 U+0051 Q +!52 U+0052 R +!53 U+0053 S +!54 U+0054 T +!55 U+0055 U +!56 U+0056 V +!57 U+0057 W +!58 U+0058 X +!59 U+0059 Y +!5A U+005A Z +!5B U+005B bracketleft +!5C U+005C backslash +!5D U+005D bracketright +!5E U+005E asciicircum +!5F U+005F underscore +!60 U+0060 grave +!61 U+0061 a +!62 U+0062 b +!63 U+0063 c +!64 U+0064 d +!65 U+0065 e +!66 U+0066 f +!67 U+0067 g +!68 U+0068 h +!69 U+0069 i +!6A U+006A j +!6B U+006B k +!6C U+006C l +!6D U+006D m +!6E U+006E n +!6F U+006F o +!70 U+0070 p +!71 U+0071 q +!72 U+0072 r +!73 U+0073 s +!74 U+0074 t +!75 U+0075 u +!76 U+0076 v +!77 U+0077 w +!78 U+0078 x +!79 U+0079 y +!7A U+007A z +!7B U+007B braceleft +!7C U+007C bar +!7D U+007D braceright +!7E U+007E asciitilde +!7F U+007F .notdef +!80 U+0080 .notdef +!81 U+0081 .notdef +!82 U+0082 .notdef +!83 U+0083 .notdef +!84 U+0084 .notdef +!85 U+0085 .notdef +!86 U+0086 .notdef +!87 U+0087 .notdef +!88 U+0088 .notdef +!89 U+0089 .notdef +!8A U+008A .notdef +!8B U+008B .notdef +!8C U+008C .notdef +!8D U+008D .notdef +!8E U+008E .notdef +!8F U+008F .notdef +!90 U+0090 .notdef +!91 U+0091 .notdef +!92 U+0092 .notdef +!93 U+0093 .notdef +!94 U+0094 .notdef +!95 U+0095 .notdef +!96 U+0096 .notdef +!97 U+0097 .notdef +!98 U+0098 .notdef +!99 U+0099 .notdef +!9A U+009A .notdef +!9B U+009B .notdef +!9C U+009C .notdef +!9D U+009D .notdef +!9E U+009E .notdef +!9F U+009F .notdef +!A0 U+00A0 space +!A1 U+00A1 exclamdown +!A2 U+00A2 cent +!A3 U+00A3 sterling +!A4 U+20AC Euro +!A5 U+00A5 yen +!A6 U+0160 Scaron +!A7 U+00A7 section +!A8 U+0161 scaron +!A9 U+00A9 copyright +!AA U+00AA ordfeminine +!AB U+00AB guillemotleft +!AC U+00AC logicalnot +!AD U+00AD hyphen +!AE U+00AE registered +!AF U+00AF macron +!B0 U+00B0 degree +!B1 U+00B1 plusminus +!B2 U+00B2 twosuperior +!B3 U+00B3 threesuperior +!B4 U+017D Zcaron +!B5 U+00B5 mu +!B6 U+00B6 paragraph +!B7 U+00B7 periodcentered +!B8 U+017E zcaron +!B9 U+00B9 onesuperior +!BA U+00BA ordmasculine +!BB U+00BB guillemotright +!BC U+0152 OE +!BD U+0153 oe +!BE U+0178 Ydieresis +!BF U+00BF questiondown +!C0 U+00C0 Agrave +!C1 U+00C1 Aacute +!C2 U+00C2 Acircumflex +!C3 U+00C3 Atilde +!C4 U+00C4 Adieresis +!C5 U+00C5 Aring +!C6 U+00C6 AE +!C7 U+00C7 Ccedilla +!C8 U+00C8 Egrave +!C9 U+00C9 Eacute +!CA U+00CA Ecircumflex +!CB U+00CB Edieresis +!CC U+00CC Igrave +!CD U+00CD Iacute +!CE U+00CE Icircumflex +!CF U+00CF Idieresis +!D0 U+00D0 Eth +!D1 U+00D1 Ntilde +!D2 U+00D2 Ograve +!D3 U+00D3 Oacute +!D4 U+00D4 Ocircumflex +!D5 U+00D5 Otilde +!D6 U+00D6 Odieresis +!D7 U+00D7 multiply +!D8 U+00D8 Oslash +!D9 U+00D9 Ugrave +!DA U+00DA Uacute +!DB U+00DB Ucircumflex +!DC U+00DC Udieresis +!DD U+00DD Yacute +!DE U+00DE Thorn +!DF U+00DF germandbls +!E0 U+00E0 agrave +!E1 U+00E1 aacute +!E2 U+00E2 acircumflex +!E3 U+00E3 atilde +!E4 U+00E4 adieresis +!E5 U+00E5 aring +!E6 U+00E6 ae +!E7 U+00E7 ccedilla +!E8 U+00E8 egrave +!E9 U+00E9 eacute +!EA U+00EA ecircumflex +!EB U+00EB edieresis +!EC U+00EC igrave +!ED U+00ED iacute +!EE U+00EE icircumflex +!EF U+00EF idieresis +!F0 U+00F0 eth +!F1 U+00F1 ntilde +!F2 U+00F2 ograve +!F3 U+00F3 oacute +!F4 U+00F4 ocircumflex +!F5 U+00F5 otilde +!F6 U+00F6 odieresis +!F7 U+00F7 divide +!F8 U+00F8 oslash +!F9 U+00F9 ugrave +!FA U+00FA uacute +!FB U+00FB ucircumflex +!FC U+00FC udieresis +!FD U+00FD yacute +!FE U+00FE thorn +!FF U+00FF ydieresis diff --git a/src/bb-library/makefont/iso-8859-16.map b/src/bb-library/makefont/iso-8859-16.map new file mode 100644 index 000000000..202c8fe59 --- /dev/null +++ b/src/bb-library/makefont/iso-8859-16.map @@ -0,0 +1,256 @@ +!00 U+0000 .notdef +!01 U+0001 .notdef +!02 U+0002 .notdef +!03 U+0003 .notdef +!04 U+0004 .notdef +!05 U+0005 .notdef +!06 U+0006 .notdef +!07 U+0007 .notdef +!08 U+0008 .notdef +!09 U+0009 .notdef +!0A U+000A .notdef +!0B U+000B .notdef +!0C U+000C .notdef +!0D U+000D .notdef +!0E U+000E .notdef +!0F U+000F .notdef +!10 U+0010 .notdef +!11 U+0011 .notdef +!12 U+0012 .notdef +!13 U+0013 .notdef +!14 U+0014 .notdef +!15 U+0015 .notdef +!16 U+0016 .notdef +!17 U+0017 .notdef +!18 U+0018 .notdef +!19 U+0019 .notdef +!1A U+001A .notdef +!1B U+001B .notdef +!1C U+001C .notdef +!1D U+001D .notdef +!1E U+001E .notdef +!1F U+001F .notdef +!20 U+0020 space +!21 U+0021 exclam +!22 U+0022 quotedbl +!23 U+0023 numbersign +!24 U+0024 dollar +!25 U+0025 percent +!26 U+0026 ampersand +!27 U+0027 quotesingle +!28 U+0028 parenleft +!29 U+0029 parenright +!2A U+002A asterisk +!2B U+002B plus +!2C U+002C comma +!2D U+002D hyphen +!2E U+002E period +!2F U+002F slash +!30 U+0030 zero +!31 U+0031 one +!32 U+0032 two +!33 U+0033 three +!34 U+0034 four +!35 U+0035 five +!36 U+0036 six +!37 U+0037 seven +!38 U+0038 eight +!39 U+0039 nine +!3A U+003A colon +!3B U+003B semicolon +!3C U+003C less +!3D U+003D equal +!3E U+003E greater +!3F U+003F question +!40 U+0040 at +!41 U+0041 A +!42 U+0042 B +!43 U+0043 C +!44 U+0044 D +!45 U+0045 E +!46 U+0046 F +!47 U+0047 G +!48 U+0048 H +!49 U+0049 I +!4A U+004A J +!4B U+004B K +!4C U+004C L +!4D U+004D M +!4E U+004E N +!4F U+004F O +!50 U+0050 P +!51 U+0051 Q +!52 U+0052 R +!53 U+0053 S +!54 U+0054 T +!55 U+0055 U +!56 U+0056 V +!57 U+0057 W +!58 U+0058 X +!59 U+0059 Y +!5A U+005A Z +!5B U+005B bracketleft +!5C U+005C backslash +!5D U+005D bracketright +!5E U+005E asciicircum +!5F U+005F underscore +!60 U+0060 grave +!61 U+0061 a +!62 U+0062 b +!63 U+0063 c +!64 U+0064 d +!65 U+0065 e +!66 U+0066 f +!67 U+0067 g +!68 U+0068 h +!69 U+0069 i +!6A U+006A j +!6B U+006B k +!6C U+006C l +!6D U+006D m +!6E U+006E n +!6F U+006F o +!70 U+0070 p +!71 U+0071 q +!72 U+0072 r +!73 U+0073 s +!74 U+0074 t +!75 U+0075 u +!76 U+0076 v +!77 U+0077 w +!78 U+0078 x +!79 U+0079 y +!7A U+007A z +!7B U+007B braceleft +!7C U+007C bar +!7D U+007D braceright +!7E U+007E asciitilde +!7F U+007F .notdef +!80 U+0080 .notdef +!81 U+0081 .notdef +!82 U+0082 .notdef +!83 U+0083 .notdef +!84 U+0084 .notdef +!85 U+0085 .notdef +!86 U+0086 .notdef +!87 U+0087 .notdef +!88 U+0088 .notdef +!89 U+0089 .notdef +!8A U+008A .notdef +!8B U+008B .notdef +!8C U+008C .notdef +!8D U+008D .notdef +!8E U+008E .notdef +!8F U+008F .notdef +!90 U+0090 .notdef +!91 U+0091 .notdef +!92 U+0092 .notdef +!93 U+0093 .notdef +!94 U+0094 .notdef +!95 U+0095 .notdef +!96 U+0096 .notdef +!97 U+0097 .notdef +!98 U+0098 .notdef +!99 U+0099 .notdef +!9A U+009A .notdef +!9B U+009B .notdef +!9C U+009C .notdef +!9D U+009D .notdef +!9E U+009E .notdef +!9F U+009F .notdef +!A0 U+00A0 space +!A1 U+0104 Aogonek +!A2 U+0105 aogonek +!A3 U+0141 Lslash +!A4 U+20AC Euro +!A5 U+201E quotedblbase +!A6 U+0160 Scaron +!A7 U+00A7 section +!A8 U+0161 scaron +!A9 U+00A9 copyright +!AA U+0218 Scommaaccent +!AB U+00AB guillemotleft +!AC U+0179 Zacute +!AD U+00AD hyphen +!AE U+017A zacute +!AF U+017B Zdotaccent +!B0 U+00B0 degree +!B1 U+00B1 plusminus +!B2 U+010C Ccaron +!B3 U+0142 lslash +!B4 U+017D Zcaron +!B5 U+201D quotedblright +!B6 U+00B6 paragraph +!B7 U+00B7 periodcentered +!B8 U+017E zcaron +!B9 U+010D ccaron +!BA U+0219 scommaaccent +!BB U+00BB guillemotright +!BC U+0152 OE +!BD U+0153 oe +!BE U+0178 Ydieresis +!BF U+017C zdotaccent +!C0 U+00C0 Agrave +!C1 U+00C1 Aacute +!C2 U+00C2 Acircumflex +!C3 U+0102 Abreve +!C4 U+00C4 Adieresis +!C5 U+0106 Cacute +!C6 U+00C6 AE +!C7 U+00C7 Ccedilla +!C8 U+00C8 Egrave +!C9 U+00C9 Eacute +!CA U+00CA Ecircumflex +!CB U+00CB Edieresis +!CC U+00CC Igrave +!CD U+00CD Iacute +!CE U+00CE Icircumflex +!CF U+00CF Idieresis +!D0 U+0110 Dcroat +!D1 U+0143 Nacute +!D2 U+00D2 Ograve +!D3 U+00D3 Oacute +!D4 U+00D4 Ocircumflex +!D5 U+0150 Ohungarumlaut +!D6 U+00D6 Odieresis +!D7 U+015A Sacute +!D8 U+0170 Uhungarumlaut +!D9 U+00D9 Ugrave +!DA U+00DA Uacute +!DB U+00DB Ucircumflex +!DC U+00DC Udieresis +!DD U+0118 Eogonek +!DE U+021A Tcommaaccent +!DF U+00DF germandbls +!E0 U+00E0 agrave +!E1 U+00E1 aacute +!E2 U+00E2 acircumflex +!E3 U+0103 abreve +!E4 U+00E4 adieresis +!E5 U+0107 cacute +!E6 U+00E6 ae +!E7 U+00E7 ccedilla +!E8 U+00E8 egrave +!E9 U+00E9 eacute +!EA U+00EA ecircumflex +!EB U+00EB edieresis +!EC U+00EC igrave +!ED U+00ED iacute +!EE U+00EE icircumflex +!EF U+00EF idieresis +!F0 U+0111 dcroat +!F1 U+0144 nacute +!F2 U+00F2 ograve +!F3 U+00F3 oacute +!F4 U+00F4 ocircumflex +!F5 U+0151 ohungarumlaut +!F6 U+00F6 odieresis +!F7 U+015B sacute +!F8 U+0171 uhungarumlaut +!F9 U+00F9 ugrave +!FA U+00FA uacute +!FB U+00FB ucircumflex +!FC U+00FC udieresis +!FD U+0119 eogonek +!FE U+021B tcommaaccent +!FF U+00FF ydieresis diff --git a/src/bb-library/makefont/iso-8859-2.map b/src/bb-library/makefont/iso-8859-2.map new file mode 100644 index 000000000..65ae09f95 --- /dev/null +++ b/src/bb-library/makefont/iso-8859-2.map @@ -0,0 +1,256 @@ +!00 U+0000 .notdef +!01 U+0001 .notdef +!02 U+0002 .notdef +!03 U+0003 .notdef +!04 U+0004 .notdef +!05 U+0005 .notdef +!06 U+0006 .notdef +!07 U+0007 .notdef +!08 U+0008 .notdef +!09 U+0009 .notdef +!0A U+000A .notdef +!0B U+000B .notdef +!0C U+000C .notdef +!0D U+000D .notdef +!0E U+000E .notdef +!0F U+000F .notdef +!10 U+0010 .notdef +!11 U+0011 .notdef +!12 U+0012 .notdef +!13 U+0013 .notdef +!14 U+0014 .notdef +!15 U+0015 .notdef +!16 U+0016 .notdef +!17 U+0017 .notdef +!18 U+0018 .notdef +!19 U+0019 .notdef +!1A U+001A .notdef +!1B U+001B .notdef +!1C U+001C .notdef +!1D U+001D .notdef +!1E U+001E .notdef +!1F U+001F .notdef +!20 U+0020 space +!21 U+0021 exclam +!22 U+0022 quotedbl +!23 U+0023 numbersign +!24 U+0024 dollar +!25 U+0025 percent +!26 U+0026 ampersand +!27 U+0027 quotesingle +!28 U+0028 parenleft +!29 U+0029 parenright +!2A U+002A asterisk +!2B U+002B plus +!2C U+002C comma +!2D U+002D hyphen +!2E U+002E period +!2F U+002F slash +!30 U+0030 zero +!31 U+0031 one +!32 U+0032 two +!33 U+0033 three +!34 U+0034 four +!35 U+0035 five +!36 U+0036 six +!37 U+0037 seven +!38 U+0038 eight +!39 U+0039 nine +!3A U+003A colon +!3B U+003B semicolon +!3C U+003C less +!3D U+003D equal +!3E U+003E greater +!3F U+003F question +!40 U+0040 at +!41 U+0041 A +!42 U+0042 B +!43 U+0043 C +!44 U+0044 D +!45 U+0045 E +!46 U+0046 F +!47 U+0047 G +!48 U+0048 H +!49 U+0049 I +!4A U+004A J +!4B U+004B K +!4C U+004C L +!4D U+004D M +!4E U+004E N +!4F U+004F O +!50 U+0050 P +!51 U+0051 Q +!52 U+0052 R +!53 U+0053 S +!54 U+0054 T +!55 U+0055 U +!56 U+0056 V +!57 U+0057 W +!58 U+0058 X +!59 U+0059 Y +!5A U+005A Z +!5B U+005B bracketleft +!5C U+005C backslash +!5D U+005D bracketright +!5E U+005E asciicircum +!5F U+005F underscore +!60 U+0060 grave +!61 U+0061 a +!62 U+0062 b +!63 U+0063 c +!64 U+0064 d +!65 U+0065 e +!66 U+0066 f +!67 U+0067 g +!68 U+0068 h +!69 U+0069 i +!6A U+006A j +!6B U+006B k +!6C U+006C l +!6D U+006D m +!6E U+006E n +!6F U+006F o +!70 U+0070 p +!71 U+0071 q +!72 U+0072 r +!73 U+0073 s +!74 U+0074 t +!75 U+0075 u +!76 U+0076 v +!77 U+0077 w +!78 U+0078 x +!79 U+0079 y +!7A U+007A z +!7B U+007B braceleft +!7C U+007C bar +!7D U+007D braceright +!7E U+007E asciitilde +!7F U+007F .notdef +!80 U+0080 .notdef +!81 U+0081 .notdef +!82 U+0082 .notdef +!83 U+0083 .notdef +!84 U+0084 .notdef +!85 U+0085 .notdef +!86 U+0086 .notdef +!87 U+0087 .notdef +!88 U+0088 .notdef +!89 U+0089 .notdef +!8A U+008A .notdef +!8B U+008B .notdef +!8C U+008C .notdef +!8D U+008D .notdef +!8E U+008E .notdef +!8F U+008F .notdef +!90 U+0090 .notdef +!91 U+0091 .notdef +!92 U+0092 .notdef +!93 U+0093 .notdef +!94 U+0094 .notdef +!95 U+0095 .notdef +!96 U+0096 .notdef +!97 U+0097 .notdef +!98 U+0098 .notdef +!99 U+0099 .notdef +!9A U+009A .notdef +!9B U+009B .notdef +!9C U+009C .notdef +!9D U+009D .notdef +!9E U+009E .notdef +!9F U+009F .notdef +!A0 U+00A0 space +!A1 U+0104 Aogonek +!A2 U+02D8 breve +!A3 U+0141 Lslash +!A4 U+00A4 currency +!A5 U+013D Lcaron +!A6 U+015A Sacute +!A7 U+00A7 section +!A8 U+00A8 dieresis +!A9 U+0160 Scaron +!AA U+015E Scedilla +!AB U+0164 Tcaron +!AC U+0179 Zacute +!AD U+00AD hyphen +!AE U+017D Zcaron +!AF U+017B Zdotaccent +!B0 U+00B0 degree +!B1 U+0105 aogonek +!B2 U+02DB ogonek +!B3 U+0142 lslash +!B4 U+00B4 acute +!B5 U+013E lcaron +!B6 U+015B sacute +!B7 U+02C7 caron +!B8 U+00B8 cedilla +!B9 U+0161 scaron +!BA U+015F scedilla +!BB U+0165 tcaron +!BC U+017A zacute +!BD U+02DD hungarumlaut +!BE U+017E zcaron +!BF U+017C zdotaccent +!C0 U+0154 Racute +!C1 U+00C1 Aacute +!C2 U+00C2 Acircumflex +!C3 U+0102 Abreve +!C4 U+00C4 Adieresis +!C5 U+0139 Lacute +!C6 U+0106 Cacute +!C7 U+00C7 Ccedilla +!C8 U+010C Ccaron +!C9 U+00C9 Eacute +!CA U+0118 Eogonek +!CB U+00CB Edieresis +!CC U+011A Ecaron +!CD U+00CD Iacute +!CE U+00CE Icircumflex +!CF U+010E Dcaron +!D0 U+0110 Dcroat +!D1 U+0143 Nacute +!D2 U+0147 Ncaron +!D3 U+00D3 Oacute +!D4 U+00D4 Ocircumflex +!D5 U+0150 Ohungarumlaut +!D6 U+00D6 Odieresis +!D7 U+00D7 multiply +!D8 U+0158 Rcaron +!D9 U+016E Uring +!DA U+00DA Uacute +!DB U+0170 Uhungarumlaut +!DC U+00DC Udieresis +!DD U+00DD Yacute +!DE U+0162 Tcommaaccent +!DF U+00DF germandbls +!E0 U+0155 racute +!E1 U+00E1 aacute +!E2 U+00E2 acircumflex +!E3 U+0103 abreve +!E4 U+00E4 adieresis +!E5 U+013A lacute +!E6 U+0107 cacute +!E7 U+00E7 ccedilla +!E8 U+010D ccaron +!E9 U+00E9 eacute +!EA U+0119 eogonek +!EB U+00EB edieresis +!EC U+011B ecaron +!ED U+00ED iacute +!EE U+00EE icircumflex +!EF U+010F dcaron +!F0 U+0111 dcroat +!F1 U+0144 nacute +!F2 U+0148 ncaron +!F3 U+00F3 oacute +!F4 U+00F4 ocircumflex +!F5 U+0151 ohungarumlaut +!F6 U+00F6 odieresis +!F7 U+00F7 divide +!F8 U+0159 rcaron +!F9 U+016F uring +!FA U+00FA uacute +!FB U+0171 uhungarumlaut +!FC U+00FC udieresis +!FD U+00FD yacute +!FE U+0163 tcommaaccent +!FF U+02D9 dotaccent diff --git a/src/bb-library/makefont/iso-8859-4.map b/src/bb-library/makefont/iso-8859-4.map new file mode 100644 index 000000000..a7d87bf3e --- /dev/null +++ b/src/bb-library/makefont/iso-8859-4.map @@ -0,0 +1,256 @@ +!00 U+0000 .notdef +!01 U+0001 .notdef +!02 U+0002 .notdef +!03 U+0003 .notdef +!04 U+0004 .notdef +!05 U+0005 .notdef +!06 U+0006 .notdef +!07 U+0007 .notdef +!08 U+0008 .notdef +!09 U+0009 .notdef +!0A U+000A .notdef +!0B U+000B .notdef +!0C U+000C .notdef +!0D U+000D .notdef +!0E U+000E .notdef +!0F U+000F .notdef +!10 U+0010 .notdef +!11 U+0011 .notdef +!12 U+0012 .notdef +!13 U+0013 .notdef +!14 U+0014 .notdef +!15 U+0015 .notdef +!16 U+0016 .notdef +!17 U+0017 .notdef +!18 U+0018 .notdef +!19 U+0019 .notdef +!1A U+001A .notdef +!1B U+001B .notdef +!1C U+001C .notdef +!1D U+001D .notdef +!1E U+001E .notdef +!1F U+001F .notdef +!20 U+0020 space +!21 U+0021 exclam +!22 U+0022 quotedbl +!23 U+0023 numbersign +!24 U+0024 dollar +!25 U+0025 percent +!26 U+0026 ampersand +!27 U+0027 quotesingle +!28 U+0028 parenleft +!29 U+0029 parenright +!2A U+002A asterisk +!2B U+002B plus +!2C U+002C comma +!2D U+002D hyphen +!2E U+002E period +!2F U+002F slash +!30 U+0030 zero +!31 U+0031 one +!32 U+0032 two +!33 U+0033 three +!34 U+0034 four +!35 U+0035 five +!36 U+0036 six +!37 U+0037 seven +!38 U+0038 eight +!39 U+0039 nine +!3A U+003A colon +!3B U+003B semicolon +!3C U+003C less +!3D U+003D equal +!3E U+003E greater +!3F U+003F question +!40 U+0040 at +!41 U+0041 A +!42 U+0042 B +!43 U+0043 C +!44 U+0044 D +!45 U+0045 E +!46 U+0046 F +!47 U+0047 G +!48 U+0048 H +!49 U+0049 I +!4A U+004A J +!4B U+004B K +!4C U+004C L +!4D U+004D M +!4E U+004E N +!4F U+004F O +!50 U+0050 P +!51 U+0051 Q +!52 U+0052 R +!53 U+0053 S +!54 U+0054 T +!55 U+0055 U +!56 U+0056 V +!57 U+0057 W +!58 U+0058 X +!59 U+0059 Y +!5A U+005A Z +!5B U+005B bracketleft +!5C U+005C backslash +!5D U+005D bracketright +!5E U+005E asciicircum +!5F U+005F underscore +!60 U+0060 grave +!61 U+0061 a +!62 U+0062 b +!63 U+0063 c +!64 U+0064 d +!65 U+0065 e +!66 U+0066 f +!67 U+0067 g +!68 U+0068 h +!69 U+0069 i +!6A U+006A j +!6B U+006B k +!6C U+006C l +!6D U+006D m +!6E U+006E n +!6F U+006F o +!70 U+0070 p +!71 U+0071 q +!72 U+0072 r +!73 U+0073 s +!74 U+0074 t +!75 U+0075 u +!76 U+0076 v +!77 U+0077 w +!78 U+0078 x +!79 U+0079 y +!7A U+007A z +!7B U+007B braceleft +!7C U+007C bar +!7D U+007D braceright +!7E U+007E asciitilde +!7F U+007F .notdef +!80 U+0080 .notdef +!81 U+0081 .notdef +!82 U+0082 .notdef +!83 U+0083 .notdef +!84 U+0084 .notdef +!85 U+0085 .notdef +!86 U+0086 .notdef +!87 U+0087 .notdef +!88 U+0088 .notdef +!89 U+0089 .notdef +!8A U+008A .notdef +!8B U+008B .notdef +!8C U+008C .notdef +!8D U+008D .notdef +!8E U+008E .notdef +!8F U+008F .notdef +!90 U+0090 .notdef +!91 U+0091 .notdef +!92 U+0092 .notdef +!93 U+0093 .notdef +!94 U+0094 .notdef +!95 U+0095 .notdef +!96 U+0096 .notdef +!97 U+0097 .notdef +!98 U+0098 .notdef +!99 U+0099 .notdef +!9A U+009A .notdef +!9B U+009B .notdef +!9C U+009C .notdef +!9D U+009D .notdef +!9E U+009E .notdef +!9F U+009F .notdef +!A0 U+00A0 space +!A1 U+0104 Aogonek +!A2 U+0138 kgreenlandic +!A3 U+0156 Rcommaaccent +!A4 U+00A4 currency +!A5 U+0128 Itilde +!A6 U+013B Lcommaaccent +!A7 U+00A7 section +!A8 U+00A8 dieresis +!A9 U+0160 Scaron +!AA U+0112 Emacron +!AB U+0122 Gcommaaccent +!AC U+0166 Tbar +!AD U+00AD hyphen +!AE U+017D Zcaron +!AF U+00AF macron +!B0 U+00B0 degree +!B1 U+0105 aogonek +!B2 U+02DB ogonek +!B3 U+0157 rcommaaccent +!B4 U+00B4 acute +!B5 U+0129 itilde +!B6 U+013C lcommaaccent +!B7 U+02C7 caron +!B8 U+00B8 cedilla +!B9 U+0161 scaron +!BA U+0113 emacron +!BB U+0123 gcommaaccent +!BC U+0167 tbar +!BD U+014A Eng +!BE U+017E zcaron +!BF U+014B eng +!C0 U+0100 Amacron +!C1 U+00C1 Aacute +!C2 U+00C2 Acircumflex +!C3 U+00C3 Atilde +!C4 U+00C4 Adieresis +!C5 U+00C5 Aring +!C6 U+00C6 AE +!C7 U+012E Iogonek +!C8 U+010C Ccaron +!C9 U+00C9 Eacute +!CA U+0118 Eogonek +!CB U+00CB Edieresis +!CC U+0116 Edotaccent +!CD U+00CD Iacute +!CE U+00CE Icircumflex +!CF U+012A Imacron +!D0 U+0110 Dcroat +!D1 U+0145 Ncommaaccent +!D2 U+014C Omacron +!D3 U+0136 Kcommaaccent +!D4 U+00D4 Ocircumflex +!D5 U+00D5 Otilde +!D6 U+00D6 Odieresis +!D7 U+00D7 multiply +!D8 U+00D8 Oslash +!D9 U+0172 Uogonek +!DA U+00DA Uacute +!DB U+00DB Ucircumflex +!DC U+00DC Udieresis +!DD U+0168 Utilde +!DE U+016A Umacron +!DF U+00DF germandbls +!E0 U+0101 amacron +!E1 U+00E1 aacute +!E2 U+00E2 acircumflex +!E3 U+00E3 atilde +!E4 U+00E4 adieresis +!E5 U+00E5 aring +!E6 U+00E6 ae +!E7 U+012F iogonek +!E8 U+010D ccaron +!E9 U+00E9 eacute +!EA U+0119 eogonek +!EB U+00EB edieresis +!EC U+0117 edotaccent +!ED U+00ED iacute +!EE U+00EE icircumflex +!EF U+012B imacron +!F0 U+0111 dcroat +!F1 U+0146 ncommaaccent +!F2 U+014D omacron +!F3 U+0137 kcommaaccent +!F4 U+00F4 ocircumflex +!F5 U+00F5 otilde +!F6 U+00F6 odieresis +!F7 U+00F7 divide +!F8 U+00F8 oslash +!F9 U+0173 uogonek +!FA U+00FA uacute +!FB U+00FB ucircumflex +!FC U+00FC udieresis +!FD U+0169 utilde +!FE U+016B umacron +!FF U+02D9 dotaccent diff --git a/src/bb-library/makefont/iso-8859-5.map b/src/bb-library/makefont/iso-8859-5.map new file mode 100644 index 000000000..f9cd4edcf --- /dev/null +++ b/src/bb-library/makefont/iso-8859-5.map @@ -0,0 +1,256 @@ +!00 U+0000 .notdef +!01 U+0001 .notdef +!02 U+0002 .notdef +!03 U+0003 .notdef +!04 U+0004 .notdef +!05 U+0005 .notdef +!06 U+0006 .notdef +!07 U+0007 .notdef +!08 U+0008 .notdef +!09 U+0009 .notdef +!0A U+000A .notdef +!0B U+000B .notdef +!0C U+000C .notdef +!0D U+000D .notdef +!0E U+000E .notdef +!0F U+000F .notdef +!10 U+0010 .notdef +!11 U+0011 .notdef +!12 U+0012 .notdef +!13 U+0013 .notdef +!14 U+0014 .notdef +!15 U+0015 .notdef +!16 U+0016 .notdef +!17 U+0017 .notdef +!18 U+0018 .notdef +!19 U+0019 .notdef +!1A U+001A .notdef +!1B U+001B .notdef +!1C U+001C .notdef +!1D U+001D .notdef +!1E U+001E .notdef +!1F U+001F .notdef +!20 U+0020 space +!21 U+0021 exclam +!22 U+0022 quotedbl +!23 U+0023 numbersign +!24 U+0024 dollar +!25 U+0025 percent +!26 U+0026 ampersand +!27 U+0027 quotesingle +!28 U+0028 parenleft +!29 U+0029 parenright +!2A U+002A asterisk +!2B U+002B plus +!2C U+002C comma +!2D U+002D hyphen +!2E U+002E period +!2F U+002F slash +!30 U+0030 zero +!31 U+0031 one +!32 U+0032 two +!33 U+0033 three +!34 U+0034 four +!35 U+0035 five +!36 U+0036 six +!37 U+0037 seven +!38 U+0038 eight +!39 U+0039 nine +!3A U+003A colon +!3B U+003B semicolon +!3C U+003C less +!3D U+003D equal +!3E U+003E greater +!3F U+003F question +!40 U+0040 at +!41 U+0041 A +!42 U+0042 B +!43 U+0043 C +!44 U+0044 D +!45 U+0045 E +!46 U+0046 F +!47 U+0047 G +!48 U+0048 H +!49 U+0049 I +!4A U+004A J +!4B U+004B K +!4C U+004C L +!4D U+004D M +!4E U+004E N +!4F U+004F O +!50 U+0050 P +!51 U+0051 Q +!52 U+0052 R +!53 U+0053 S +!54 U+0054 T +!55 U+0055 U +!56 U+0056 V +!57 U+0057 W +!58 U+0058 X +!59 U+0059 Y +!5A U+005A Z +!5B U+005B bracketleft +!5C U+005C backslash +!5D U+005D bracketright +!5E U+005E asciicircum +!5F U+005F underscore +!60 U+0060 grave +!61 U+0061 a +!62 U+0062 b +!63 U+0063 c +!64 U+0064 d +!65 U+0065 e +!66 U+0066 f +!67 U+0067 g +!68 U+0068 h +!69 U+0069 i +!6A U+006A j +!6B U+006B k +!6C U+006C l +!6D U+006D m +!6E U+006E n +!6F U+006F o +!70 U+0070 p +!71 U+0071 q +!72 U+0072 r +!73 U+0073 s +!74 U+0074 t +!75 U+0075 u +!76 U+0076 v +!77 U+0077 w +!78 U+0078 x +!79 U+0079 y +!7A U+007A z +!7B U+007B braceleft +!7C U+007C bar +!7D U+007D braceright +!7E U+007E asciitilde +!7F U+007F .notdef +!80 U+0080 .notdef +!81 U+0081 .notdef +!82 U+0082 .notdef +!83 U+0083 .notdef +!84 U+0084 .notdef +!85 U+0085 .notdef +!86 U+0086 .notdef +!87 U+0087 .notdef +!88 U+0088 .notdef +!89 U+0089 .notdef +!8A U+008A .notdef +!8B U+008B .notdef +!8C U+008C .notdef +!8D U+008D .notdef +!8E U+008E .notdef +!8F U+008F .notdef +!90 U+0090 .notdef +!91 U+0091 .notdef +!92 U+0092 .notdef +!93 U+0093 .notdef +!94 U+0094 .notdef +!95 U+0095 .notdef +!96 U+0096 .notdef +!97 U+0097 .notdef +!98 U+0098 .notdef +!99 U+0099 .notdef +!9A U+009A .notdef +!9B U+009B .notdef +!9C U+009C .notdef +!9D U+009D .notdef +!9E U+009E .notdef +!9F U+009F .notdef +!A0 U+00A0 space +!A1 U+0401 afii10023 +!A2 U+0402 afii10051 +!A3 U+0403 afii10052 +!A4 U+0404 afii10053 +!A5 U+0405 afii10054 +!A6 U+0406 afii10055 +!A7 U+0407 afii10056 +!A8 U+0408 afii10057 +!A9 U+0409 afii10058 +!AA U+040A afii10059 +!AB U+040B afii10060 +!AC U+040C afii10061 +!AD U+00AD hyphen +!AE U+040E afii10062 +!AF U+040F afii10145 +!B0 U+0410 afii10017 +!B1 U+0411 afii10018 +!B2 U+0412 afii10019 +!B3 U+0413 afii10020 +!B4 U+0414 afii10021 +!B5 U+0415 afii10022 +!B6 U+0416 afii10024 +!B7 U+0417 afii10025 +!B8 U+0418 afii10026 +!B9 U+0419 afii10027 +!BA U+041A afii10028 +!BB U+041B afii10029 +!BC U+041C afii10030 +!BD U+041D afii10031 +!BE U+041E afii10032 +!BF U+041F afii10033 +!C0 U+0420 afii10034 +!C1 U+0421 afii10035 +!C2 U+0422 afii10036 +!C3 U+0423 afii10037 +!C4 U+0424 afii10038 +!C5 U+0425 afii10039 +!C6 U+0426 afii10040 +!C7 U+0427 afii10041 +!C8 U+0428 afii10042 +!C9 U+0429 afii10043 +!CA U+042A afii10044 +!CB U+042B afii10045 +!CC U+042C afii10046 +!CD U+042D afii10047 +!CE U+042E afii10048 +!CF U+042F afii10049 +!D0 U+0430 afii10065 +!D1 U+0431 afii10066 +!D2 U+0432 afii10067 +!D3 U+0433 afii10068 +!D4 U+0434 afii10069 +!D5 U+0435 afii10070 +!D6 U+0436 afii10072 +!D7 U+0437 afii10073 +!D8 U+0438 afii10074 +!D9 U+0439 afii10075 +!DA U+043A afii10076 +!DB U+043B afii10077 +!DC U+043C afii10078 +!DD U+043D afii10079 +!DE U+043E afii10080 +!DF U+043F afii10081 +!E0 U+0440 afii10082 +!E1 U+0441 afii10083 +!E2 U+0442 afii10084 +!E3 U+0443 afii10085 +!E4 U+0444 afii10086 +!E5 U+0445 afii10087 +!E6 U+0446 afii10088 +!E7 U+0447 afii10089 +!E8 U+0448 afii10090 +!E9 U+0449 afii10091 +!EA U+044A afii10092 +!EB U+044B afii10093 +!EC U+044C afii10094 +!ED U+044D afii10095 +!EE U+044E afii10096 +!EF U+044F afii10097 +!F0 U+2116 afii61352 +!F1 U+0451 afii10071 +!F2 U+0452 afii10099 +!F3 U+0453 afii10100 +!F4 U+0454 afii10101 +!F5 U+0455 afii10102 +!F6 U+0456 afii10103 +!F7 U+0457 afii10104 +!F8 U+0458 afii10105 +!F9 U+0459 afii10106 +!FA U+045A afii10107 +!FB U+045B afii10108 +!FC U+045C afii10109 +!FD U+00A7 section +!FE U+045E afii10110 +!FF U+045F afii10193 diff --git a/src/bb-library/makefont/iso-8859-7.map b/src/bb-library/makefont/iso-8859-7.map new file mode 100644 index 000000000..e163796b1 --- /dev/null +++ b/src/bb-library/makefont/iso-8859-7.map @@ -0,0 +1,250 @@ +!00 U+0000 .notdef +!01 U+0001 .notdef +!02 U+0002 .notdef +!03 U+0003 .notdef +!04 U+0004 .notdef +!05 U+0005 .notdef +!06 U+0006 .notdef +!07 U+0007 .notdef +!08 U+0008 .notdef +!09 U+0009 .notdef +!0A U+000A .notdef +!0B U+000B .notdef +!0C U+000C .notdef +!0D U+000D .notdef +!0E U+000E .notdef +!0F U+000F .notdef +!10 U+0010 .notdef +!11 U+0011 .notdef +!12 U+0012 .notdef +!13 U+0013 .notdef +!14 U+0014 .notdef +!15 U+0015 .notdef +!16 U+0016 .notdef +!17 U+0017 .notdef +!18 U+0018 .notdef +!19 U+0019 .notdef +!1A U+001A .notdef +!1B U+001B .notdef +!1C U+001C .notdef +!1D U+001D .notdef +!1E U+001E .notdef +!1F U+001F .notdef +!20 U+0020 space +!21 U+0021 exclam +!22 U+0022 quotedbl +!23 U+0023 numbersign +!24 U+0024 dollar +!25 U+0025 percent +!26 U+0026 ampersand +!27 U+0027 quotesingle +!28 U+0028 parenleft +!29 U+0029 parenright +!2A U+002A asterisk +!2B U+002B plus +!2C U+002C comma +!2D U+002D hyphen +!2E U+002E period +!2F U+002F slash +!30 U+0030 zero +!31 U+0031 one +!32 U+0032 two +!33 U+0033 three +!34 U+0034 four +!35 U+0035 five +!36 U+0036 six +!37 U+0037 seven +!38 U+0038 eight +!39 U+0039 nine +!3A U+003A colon +!3B U+003B semicolon +!3C U+003C less +!3D U+003D equal +!3E U+003E greater +!3F U+003F question +!40 U+0040 at +!41 U+0041 A +!42 U+0042 B +!43 U+0043 C +!44 U+0044 D +!45 U+0045 E +!46 U+0046 F +!47 U+0047 G +!48 U+0048 H +!49 U+0049 I +!4A U+004A J +!4B U+004B K +!4C U+004C L +!4D U+004D M +!4E U+004E N +!4F U+004F O +!50 U+0050 P +!51 U+0051 Q +!52 U+0052 R +!53 U+0053 S +!54 U+0054 T +!55 U+0055 U +!56 U+0056 V +!57 U+0057 W +!58 U+0058 X +!59 U+0059 Y +!5A U+005A Z +!5B U+005B bracketleft +!5C U+005C backslash +!5D U+005D bracketright +!5E U+005E asciicircum +!5F U+005F underscore +!60 U+0060 grave +!61 U+0061 a +!62 U+0062 b +!63 U+0063 c +!64 U+0064 d +!65 U+0065 e +!66 U+0066 f +!67 U+0067 g +!68 U+0068 h +!69 U+0069 i +!6A U+006A j +!6B U+006B k +!6C U+006C l +!6D U+006D m +!6E U+006E n +!6F U+006F o +!70 U+0070 p +!71 U+0071 q +!72 U+0072 r +!73 U+0073 s +!74 U+0074 t +!75 U+0075 u +!76 U+0076 v +!77 U+0077 w +!78 U+0078 x +!79 U+0079 y +!7A U+007A z +!7B U+007B braceleft +!7C U+007C bar +!7D U+007D braceright +!7E U+007E asciitilde +!7F U+007F .notdef +!80 U+0080 .notdef +!81 U+0081 .notdef +!82 U+0082 .notdef +!83 U+0083 .notdef +!84 U+0084 .notdef +!85 U+0085 .notdef +!86 U+0086 .notdef +!87 U+0087 .notdef +!88 U+0088 .notdef +!89 U+0089 .notdef +!8A U+008A .notdef +!8B U+008B .notdef +!8C U+008C .notdef +!8D U+008D .notdef +!8E U+008E .notdef +!8F U+008F .notdef +!90 U+0090 .notdef +!91 U+0091 .notdef +!92 U+0092 .notdef +!93 U+0093 .notdef +!94 U+0094 .notdef +!95 U+0095 .notdef +!96 U+0096 .notdef +!97 U+0097 .notdef +!98 U+0098 .notdef +!99 U+0099 .notdef +!9A U+009A .notdef +!9B U+009B .notdef +!9C U+009C .notdef +!9D U+009D .notdef +!9E U+009E .notdef +!9F U+009F .notdef +!A0 U+00A0 space +!A1 U+2018 quoteleft +!A2 U+2019 quoteright +!A3 U+00A3 sterling +!A6 U+00A6 brokenbar +!A7 U+00A7 section +!A8 U+00A8 dieresis +!A9 U+00A9 copyright +!AB U+00AB guillemotleft +!AC U+00AC logicalnot +!AD U+00AD hyphen +!AF U+2015 afii00208 +!B0 U+00B0 degree +!B1 U+00B1 plusminus +!B2 U+00B2 twosuperior +!B3 U+00B3 threesuperior +!B4 U+0384 tonos +!B5 U+0385 dieresistonos +!B6 U+0386 Alphatonos +!B7 U+00B7 periodcentered +!B8 U+0388 Epsilontonos +!B9 U+0389 Etatonos +!BA U+038A Iotatonos +!BB U+00BB guillemotright +!BC U+038C Omicrontonos +!BD U+00BD onehalf +!BE U+038E Upsilontonos +!BF U+038F Omegatonos +!C0 U+0390 iotadieresistonos +!C1 U+0391 Alpha +!C2 U+0392 Beta +!C3 U+0393 Gamma +!C4 U+0394 Delta +!C5 U+0395 Epsilon +!C6 U+0396 Zeta +!C7 U+0397 Eta +!C8 U+0398 Theta +!C9 U+0399 Iota +!CA U+039A Kappa +!CB U+039B Lambda +!CC U+039C Mu +!CD U+039D Nu +!CE U+039E Xi +!CF U+039F Omicron +!D0 U+03A0 Pi +!D1 U+03A1 Rho +!D3 U+03A3 Sigma +!D4 U+03A4 Tau +!D5 U+03A5 Upsilon +!D6 U+03A6 Phi +!D7 U+03A7 Chi +!D8 U+03A8 Psi +!D9 U+03A9 Omega +!DA U+03AA Iotadieresis +!DB U+03AB Upsilondieresis +!DC U+03AC alphatonos +!DD U+03AD epsilontonos +!DE U+03AE etatonos +!DF U+03AF iotatonos +!E0 U+03B0 upsilondieresistonos +!E1 U+03B1 alpha +!E2 U+03B2 beta +!E3 U+03B3 gamma +!E4 U+03B4 delta +!E5 U+03B5 epsilon +!E6 U+03B6 zeta +!E7 U+03B7 eta +!E8 U+03B8 theta +!E9 U+03B9 iota +!EA U+03BA kappa +!EB U+03BB lambda +!EC U+03BC mu +!ED U+03BD nu +!EE U+03BE xi +!EF U+03BF omicron +!F0 U+03C0 pi +!F1 U+03C1 rho +!F2 U+03C2 sigma1 +!F3 U+03C3 sigma +!F4 U+03C4 tau +!F5 U+03C5 upsilon +!F6 U+03C6 phi +!F7 U+03C7 chi +!F8 U+03C8 psi +!F9 U+03C9 omega +!FA U+03CA iotadieresis +!FB U+03CB upsilondieresis +!FC U+03CC omicrontonos +!FD U+03CD upsilontonos +!FE U+03CE omegatonos diff --git a/src/bb-library/makefont/iso-8859-9.map b/src/bb-library/makefont/iso-8859-9.map new file mode 100644 index 000000000..48c123ae6 --- /dev/null +++ b/src/bb-library/makefont/iso-8859-9.map @@ -0,0 +1,256 @@ +!00 U+0000 .notdef +!01 U+0001 .notdef +!02 U+0002 .notdef +!03 U+0003 .notdef +!04 U+0004 .notdef +!05 U+0005 .notdef +!06 U+0006 .notdef +!07 U+0007 .notdef +!08 U+0008 .notdef +!09 U+0009 .notdef +!0A U+000A .notdef +!0B U+000B .notdef +!0C U+000C .notdef +!0D U+000D .notdef +!0E U+000E .notdef +!0F U+000F .notdef +!10 U+0010 .notdef +!11 U+0011 .notdef +!12 U+0012 .notdef +!13 U+0013 .notdef +!14 U+0014 .notdef +!15 U+0015 .notdef +!16 U+0016 .notdef +!17 U+0017 .notdef +!18 U+0018 .notdef +!19 U+0019 .notdef +!1A U+001A .notdef +!1B U+001B .notdef +!1C U+001C .notdef +!1D U+001D .notdef +!1E U+001E .notdef +!1F U+001F .notdef +!20 U+0020 space +!21 U+0021 exclam +!22 U+0022 quotedbl +!23 U+0023 numbersign +!24 U+0024 dollar +!25 U+0025 percent +!26 U+0026 ampersand +!27 U+0027 quotesingle +!28 U+0028 parenleft +!29 U+0029 parenright +!2A U+002A asterisk +!2B U+002B plus +!2C U+002C comma +!2D U+002D hyphen +!2E U+002E period +!2F U+002F slash +!30 U+0030 zero +!31 U+0031 one +!32 U+0032 two +!33 U+0033 three +!34 U+0034 four +!35 U+0035 five +!36 U+0036 six +!37 U+0037 seven +!38 U+0038 eight +!39 U+0039 nine +!3A U+003A colon +!3B U+003B semicolon +!3C U+003C less +!3D U+003D equal +!3E U+003E greater +!3F U+003F question +!40 U+0040 at +!41 U+0041 A +!42 U+0042 B +!43 U+0043 C +!44 U+0044 D +!45 U+0045 E +!46 U+0046 F +!47 U+0047 G +!48 U+0048 H +!49 U+0049 I +!4A U+004A J +!4B U+004B K +!4C U+004C L +!4D U+004D M +!4E U+004E N +!4F U+004F O +!50 U+0050 P +!51 U+0051 Q +!52 U+0052 R +!53 U+0053 S +!54 U+0054 T +!55 U+0055 U +!56 U+0056 V +!57 U+0057 W +!58 U+0058 X +!59 U+0059 Y +!5A U+005A Z +!5B U+005B bracketleft +!5C U+005C backslash +!5D U+005D bracketright +!5E U+005E asciicircum +!5F U+005F underscore +!60 U+0060 grave +!61 U+0061 a +!62 U+0062 b +!63 U+0063 c +!64 U+0064 d +!65 U+0065 e +!66 U+0066 f +!67 U+0067 g +!68 U+0068 h +!69 U+0069 i +!6A U+006A j +!6B U+006B k +!6C U+006C l +!6D U+006D m +!6E U+006E n +!6F U+006F o +!70 U+0070 p +!71 U+0071 q +!72 U+0072 r +!73 U+0073 s +!74 U+0074 t +!75 U+0075 u +!76 U+0076 v +!77 U+0077 w +!78 U+0078 x +!79 U+0079 y +!7A U+007A z +!7B U+007B braceleft +!7C U+007C bar +!7D U+007D braceright +!7E U+007E asciitilde +!7F U+007F .notdef +!80 U+0080 .notdef +!81 U+0081 .notdef +!82 U+0082 .notdef +!83 U+0083 .notdef +!84 U+0084 .notdef +!85 U+0085 .notdef +!86 U+0086 .notdef +!87 U+0087 .notdef +!88 U+0088 .notdef +!89 U+0089 .notdef +!8A U+008A .notdef +!8B U+008B .notdef +!8C U+008C .notdef +!8D U+008D .notdef +!8E U+008E .notdef +!8F U+008F .notdef +!90 U+0090 .notdef +!91 U+0091 .notdef +!92 U+0092 .notdef +!93 U+0093 .notdef +!94 U+0094 .notdef +!95 U+0095 .notdef +!96 U+0096 .notdef +!97 U+0097 .notdef +!98 U+0098 .notdef +!99 U+0099 .notdef +!9A U+009A .notdef +!9B U+009B .notdef +!9C U+009C .notdef +!9D U+009D .notdef +!9E U+009E .notdef +!9F U+009F .notdef +!A0 U+00A0 space +!A1 U+00A1 exclamdown +!A2 U+00A2 cent +!A3 U+00A3 sterling +!A4 U+00A4 currency +!A5 U+00A5 yen +!A6 U+00A6 brokenbar +!A7 U+00A7 section +!A8 U+00A8 dieresis +!A9 U+00A9 copyright +!AA U+00AA ordfeminine +!AB U+00AB guillemotleft +!AC U+00AC logicalnot +!AD U+00AD hyphen +!AE U+00AE registered +!AF U+00AF macron +!B0 U+00B0 degree +!B1 U+00B1 plusminus +!B2 U+00B2 twosuperior +!B3 U+00B3 threesuperior +!B4 U+00B4 acute +!B5 U+00B5 mu +!B6 U+00B6 paragraph +!B7 U+00B7 periodcentered +!B8 U+00B8 cedilla +!B9 U+00B9 onesuperior +!BA U+00BA ordmasculine +!BB U+00BB guillemotright +!BC U+00BC onequarter +!BD U+00BD onehalf +!BE U+00BE threequarters +!BF U+00BF questiondown +!C0 U+00C0 Agrave +!C1 U+00C1 Aacute +!C2 U+00C2 Acircumflex +!C3 U+00C3 Atilde +!C4 U+00C4 Adieresis +!C5 U+00C5 Aring +!C6 U+00C6 AE +!C7 U+00C7 Ccedilla +!C8 U+00C8 Egrave +!C9 U+00C9 Eacute +!CA U+00CA Ecircumflex +!CB U+00CB Edieresis +!CC U+00CC Igrave +!CD U+00CD Iacute +!CE U+00CE Icircumflex +!CF U+00CF Idieresis +!D0 U+011E Gbreve +!D1 U+00D1 Ntilde +!D2 U+00D2 Ograve +!D3 U+00D3 Oacute +!D4 U+00D4 Ocircumflex +!D5 U+00D5 Otilde +!D6 U+00D6 Odieresis +!D7 U+00D7 multiply +!D8 U+00D8 Oslash +!D9 U+00D9 Ugrave +!DA U+00DA Uacute +!DB U+00DB Ucircumflex +!DC U+00DC Udieresis +!DD U+0130 Idotaccent +!DE U+015E Scedilla +!DF U+00DF germandbls +!E0 U+00E0 agrave +!E1 U+00E1 aacute +!E2 U+00E2 acircumflex +!E3 U+00E3 atilde +!E4 U+00E4 adieresis +!E5 U+00E5 aring +!E6 U+00E6 ae +!E7 U+00E7 ccedilla +!E8 U+00E8 egrave +!E9 U+00E9 eacute +!EA U+00EA ecircumflex +!EB U+00EB edieresis +!EC U+00EC igrave +!ED U+00ED iacute +!EE U+00EE icircumflex +!EF U+00EF idieresis +!F0 U+011F gbreve +!F1 U+00F1 ntilde +!F2 U+00F2 ograve +!F3 U+00F3 oacute +!F4 U+00F4 ocircumflex +!F5 U+00F5 otilde +!F6 U+00F6 odieresis +!F7 U+00F7 divide +!F8 U+00F8 oslash +!F9 U+00F9 ugrave +!FA U+00FA uacute +!FB U+00FB ucircumflex +!FC U+00FC udieresis +!FD U+0131 dotlessi +!FE U+015F scedilla +!FF U+00FF ydieresis diff --git a/src/bb-library/makefont/koi8-r.map b/src/bb-library/makefont/koi8-r.map new file mode 100644 index 000000000..6ad5d05d0 --- /dev/null +++ b/src/bb-library/makefont/koi8-r.map @@ -0,0 +1,256 @@ +!00 U+0000 .notdef +!01 U+0001 .notdef +!02 U+0002 .notdef +!03 U+0003 .notdef +!04 U+0004 .notdef +!05 U+0005 .notdef +!06 U+0006 .notdef +!07 U+0007 .notdef +!08 U+0008 .notdef +!09 U+0009 .notdef +!0A U+000A .notdef +!0B U+000B .notdef +!0C U+000C .notdef +!0D U+000D .notdef +!0E U+000E .notdef +!0F U+000F .notdef +!10 U+0010 .notdef +!11 U+0011 .notdef +!12 U+0012 .notdef +!13 U+0013 .notdef +!14 U+0014 .notdef +!15 U+0015 .notdef +!16 U+0016 .notdef +!17 U+0017 .notdef +!18 U+0018 .notdef +!19 U+0019 .notdef +!1A U+001A .notdef +!1B U+001B .notdef +!1C U+001C .notdef +!1D U+001D .notdef +!1E U+001E .notdef +!1F U+001F .notdef +!20 U+0020 space +!21 U+0021 exclam +!22 U+0022 quotedbl +!23 U+0023 numbersign +!24 U+0024 dollar +!25 U+0025 percent +!26 U+0026 ampersand +!27 U+0027 quotesingle +!28 U+0028 parenleft +!29 U+0029 parenright +!2A U+002A asterisk +!2B U+002B plus +!2C U+002C comma +!2D U+002D hyphen +!2E U+002E period +!2F U+002F slash +!30 U+0030 zero +!31 U+0031 one +!32 U+0032 two +!33 U+0033 three +!34 U+0034 four +!35 U+0035 five +!36 U+0036 six +!37 U+0037 seven +!38 U+0038 eight +!39 U+0039 nine +!3A U+003A colon +!3B U+003B semicolon +!3C U+003C less +!3D U+003D equal +!3E U+003E greater +!3F U+003F question +!40 U+0040 at +!41 U+0041 A +!42 U+0042 B +!43 U+0043 C +!44 U+0044 D +!45 U+0045 E +!46 U+0046 F +!47 U+0047 G +!48 U+0048 H +!49 U+0049 I +!4A U+004A J +!4B U+004B K +!4C U+004C L +!4D U+004D M +!4E U+004E N +!4F U+004F O +!50 U+0050 P +!51 U+0051 Q +!52 U+0052 R +!53 U+0053 S +!54 U+0054 T +!55 U+0055 U +!56 U+0056 V +!57 U+0057 W +!58 U+0058 X +!59 U+0059 Y +!5A U+005A Z +!5B U+005B bracketleft +!5C U+005C backslash +!5D U+005D bracketright +!5E U+005E asciicircum +!5F U+005F underscore +!60 U+0060 grave +!61 U+0061 a +!62 U+0062 b +!63 U+0063 c +!64 U+0064 d +!65 U+0065 e +!66 U+0066 f +!67 U+0067 g +!68 U+0068 h +!69 U+0069 i +!6A U+006A j +!6B U+006B k +!6C U+006C l +!6D U+006D m +!6E U+006E n +!6F U+006F o +!70 U+0070 p +!71 U+0071 q +!72 U+0072 r +!73 U+0073 s +!74 U+0074 t +!75 U+0075 u +!76 U+0076 v +!77 U+0077 w +!78 U+0078 x +!79 U+0079 y +!7A U+007A z +!7B U+007B braceleft +!7C U+007C bar +!7D U+007D braceright +!7E U+007E asciitilde +!7F U+007F .notdef +!80 U+2500 SF100000 +!81 U+2502 SF110000 +!82 U+250C SF010000 +!83 U+2510 SF030000 +!84 U+2514 SF020000 +!85 U+2518 SF040000 +!86 U+251C SF080000 +!87 U+2524 SF090000 +!88 U+252C SF060000 +!89 U+2534 SF070000 +!8A U+253C SF050000 +!8B U+2580 upblock +!8C U+2584 dnblock +!8D U+2588 block +!8E U+258C lfblock +!8F U+2590 rtblock +!90 U+2591 ltshade +!91 U+2592 shade +!92 U+2593 dkshade +!93 U+2320 integraltp +!94 U+25A0 filledbox +!95 U+2219 periodcentered +!96 U+221A radical +!97 U+2248 approxequal +!98 U+2264 lessequal +!99 U+2265 greaterequal +!9A U+00A0 space +!9B U+2321 integralbt +!9C U+00B0 degree +!9D U+00B2 twosuperior +!9E U+00B7 periodcentered +!9F U+00F7 divide +!A0 U+2550 SF430000 +!A1 U+2551 SF240000 +!A2 U+2552 SF510000 +!A3 U+0451 afii10071 +!A4 U+2553 SF520000 +!A5 U+2554 SF390000 +!A6 U+2555 SF220000 +!A7 U+2556 SF210000 +!A8 U+2557 SF250000 +!A9 U+2558 SF500000 +!AA U+2559 SF490000 +!AB U+255A SF380000 +!AC U+255B SF280000 +!AD U+255C SF270000 +!AE U+255D SF260000 +!AF U+255E SF360000 +!B0 U+255F SF370000 +!B1 U+2560 SF420000 +!B2 U+2561 SF190000 +!B3 U+0401 afii10023 +!B4 U+2562 SF200000 +!B5 U+2563 SF230000 +!B6 U+2564 SF470000 +!B7 U+2565 SF480000 +!B8 U+2566 SF410000 +!B9 U+2567 SF450000 +!BA U+2568 SF460000 +!BB U+2569 SF400000 +!BC U+256A SF540000 +!BD U+256B SF530000 +!BE U+256C SF440000 +!BF U+00A9 copyright +!C0 U+044E afii10096 +!C1 U+0430 afii10065 +!C2 U+0431 afii10066 +!C3 U+0446 afii10088 +!C4 U+0434 afii10069 +!C5 U+0435 afii10070 +!C6 U+0444 afii10086 +!C7 U+0433 afii10068 +!C8 U+0445 afii10087 +!C9 U+0438 afii10074 +!CA U+0439 afii10075 +!CB U+043A afii10076 +!CC U+043B afii10077 +!CD U+043C afii10078 +!CE U+043D afii10079 +!CF U+043E afii10080 +!D0 U+043F afii10081 +!D1 U+044F afii10097 +!D2 U+0440 afii10082 +!D3 U+0441 afii10083 +!D4 U+0442 afii10084 +!D5 U+0443 afii10085 +!D6 U+0436 afii10072 +!D7 U+0432 afii10067 +!D8 U+044C afii10094 +!D9 U+044B afii10093 +!DA U+0437 afii10073 +!DB U+0448 afii10090 +!DC U+044D afii10095 +!DD U+0449 afii10091 +!DE U+0447 afii10089 +!DF U+044A afii10092 +!E0 U+042E afii10048 +!E1 U+0410 afii10017 +!E2 U+0411 afii10018 +!E3 U+0426 afii10040 +!E4 U+0414 afii10021 +!E5 U+0415 afii10022 +!E6 U+0424 afii10038 +!E7 U+0413 afii10020 +!E8 U+0425 afii10039 +!E9 U+0418 afii10026 +!EA U+0419 afii10027 +!EB U+041A afii10028 +!EC U+041B afii10029 +!ED U+041C afii10030 +!EE U+041D afii10031 +!EF U+041E afii10032 +!F0 U+041F afii10033 +!F1 U+042F afii10049 +!F2 U+0420 afii10034 +!F3 U+0421 afii10035 +!F4 U+0422 afii10036 +!F5 U+0423 afii10037 +!F6 U+0416 afii10024 +!F7 U+0412 afii10019 +!F8 U+042C afii10046 +!F9 U+042B afii10045 +!FA U+0417 afii10025 +!FB U+0428 afii10042 +!FC U+042D afii10047 +!FD U+0429 afii10043 +!FE U+0427 afii10041 +!FF U+042A afii10044 diff --git a/src/bb-library/makefont/koi8-u.map b/src/bb-library/makefont/koi8-u.map new file mode 100644 index 000000000..40a7e4fd7 --- /dev/null +++ b/src/bb-library/makefont/koi8-u.map @@ -0,0 +1,256 @@ +!00 U+0000 .notdef +!01 U+0001 .notdef +!02 U+0002 .notdef +!03 U+0003 .notdef +!04 U+0004 .notdef +!05 U+0005 .notdef +!06 U+0006 .notdef +!07 U+0007 .notdef +!08 U+0008 .notdef +!09 U+0009 .notdef +!0A U+000A .notdef +!0B U+000B .notdef +!0C U+000C .notdef +!0D U+000D .notdef +!0E U+000E .notdef +!0F U+000F .notdef +!10 U+0010 .notdef +!11 U+0011 .notdef +!12 U+0012 .notdef +!13 U+0013 .notdef +!14 U+0014 .notdef +!15 U+0015 .notdef +!16 U+0016 .notdef +!17 U+0017 .notdef +!18 U+0018 .notdef +!19 U+0019 .notdef +!1A U+001A .notdef +!1B U+001B .notdef +!1C U+001C .notdef +!1D U+001D .notdef +!1E U+001E .notdef +!1F U+001F .notdef +!20 U+0020 space +!21 U+0021 exclam +!22 U+0022 quotedbl +!23 U+0023 numbersign +!24 U+0024 dollar +!25 U+0025 percent +!26 U+0026 ampersand +!27 U+0027 quotesingle +!28 U+0028 parenleft +!29 U+0029 parenright +!2A U+002A asterisk +!2B U+002B plus +!2C U+002C comma +!2D U+002D hyphen +!2E U+002E period +!2F U+002F slash +!30 U+0030 zero +!31 U+0031 one +!32 U+0032 two +!33 U+0033 three +!34 U+0034 four +!35 U+0035 five +!36 U+0036 six +!37 U+0037 seven +!38 U+0038 eight +!39 U+0039 nine +!3A U+003A colon +!3B U+003B semicolon +!3C U+003C less +!3D U+003D equal +!3E U+003E greater +!3F U+003F question +!40 U+0040 at +!41 U+0041 A +!42 U+0042 B +!43 U+0043 C +!44 U+0044 D +!45 U+0045 E +!46 U+0046 F +!47 U+0047 G +!48 U+0048 H +!49 U+0049 I +!4A U+004A J +!4B U+004B K +!4C U+004C L +!4D U+004D M +!4E U+004E N +!4F U+004F O +!50 U+0050 P +!51 U+0051 Q +!52 U+0052 R +!53 U+0053 S +!54 U+0054 T +!55 U+0055 U +!56 U+0056 V +!57 U+0057 W +!58 U+0058 X +!59 U+0059 Y +!5A U+005A Z +!5B U+005B bracketleft +!5C U+005C backslash +!5D U+005D bracketright +!5E U+005E asciicircum +!5F U+005F underscore +!60 U+0060 grave +!61 U+0061 a +!62 U+0062 b +!63 U+0063 c +!64 U+0064 d +!65 U+0065 e +!66 U+0066 f +!67 U+0067 g +!68 U+0068 h +!69 U+0069 i +!6A U+006A j +!6B U+006B k +!6C U+006C l +!6D U+006D m +!6E U+006E n +!6F U+006F o +!70 U+0070 p +!71 U+0071 q +!72 U+0072 r +!73 U+0073 s +!74 U+0074 t +!75 U+0075 u +!76 U+0076 v +!77 U+0077 w +!78 U+0078 x +!79 U+0079 y +!7A U+007A z +!7B U+007B braceleft +!7C U+007C bar +!7D U+007D braceright +!7E U+007E asciitilde +!7F U+007F .notdef +!80 U+2500 SF100000 +!81 U+2502 SF110000 +!82 U+250C SF010000 +!83 U+2510 SF030000 +!84 U+2514 SF020000 +!85 U+2518 SF040000 +!86 U+251C SF080000 +!87 U+2524 SF090000 +!88 U+252C SF060000 +!89 U+2534 SF070000 +!8A U+253C SF050000 +!8B U+2580 upblock +!8C U+2584 dnblock +!8D U+2588 block +!8E U+258C lfblock +!8F U+2590 rtblock +!90 U+2591 ltshade +!91 U+2592 shade +!92 U+2593 dkshade +!93 U+2320 integraltp +!94 U+25A0 filledbox +!95 U+2022 bullet +!96 U+221A radical +!97 U+2248 approxequal +!98 U+2264 lessequal +!99 U+2265 greaterequal +!9A U+00A0 space +!9B U+2321 integralbt +!9C U+00B0 degree +!9D U+00B2 twosuperior +!9E U+00B7 periodcentered +!9F U+00F7 divide +!A0 U+2550 SF430000 +!A1 U+2551 SF240000 +!A2 U+2552 SF510000 +!A3 U+0451 afii10071 +!A4 U+0454 afii10101 +!A5 U+2554 SF390000 +!A6 U+0456 afii10103 +!A7 U+0457 afii10104 +!A8 U+2557 SF250000 +!A9 U+2558 SF500000 +!AA U+2559 SF490000 +!AB U+255A SF380000 +!AC U+255B SF280000 +!AD U+0491 afii10098 +!AE U+255D SF260000 +!AF U+255E SF360000 +!B0 U+255F SF370000 +!B1 U+2560 SF420000 +!B2 U+2561 SF190000 +!B3 U+0401 afii10023 +!B4 U+0404 afii10053 +!B5 U+2563 SF230000 +!B6 U+0406 afii10055 +!B7 U+0407 afii10056 +!B8 U+2566 SF410000 +!B9 U+2567 SF450000 +!BA U+2568 SF460000 +!BB U+2569 SF400000 +!BC U+256A SF540000 +!BD U+0490 afii10050 +!BE U+256C SF440000 +!BF U+00A9 copyright +!C0 U+044E afii10096 +!C1 U+0430 afii10065 +!C2 U+0431 afii10066 +!C3 U+0446 afii10088 +!C4 U+0434 afii10069 +!C5 U+0435 afii10070 +!C6 U+0444 afii10086 +!C7 U+0433 afii10068 +!C8 U+0445 afii10087 +!C9 U+0438 afii10074 +!CA U+0439 afii10075 +!CB U+043A afii10076 +!CC U+043B afii10077 +!CD U+043C afii10078 +!CE U+043D afii10079 +!CF U+043E afii10080 +!D0 U+043F afii10081 +!D1 U+044F afii10097 +!D2 U+0440 afii10082 +!D3 U+0441 afii10083 +!D4 U+0442 afii10084 +!D5 U+0443 afii10085 +!D6 U+0436 afii10072 +!D7 U+0432 afii10067 +!D8 U+044C afii10094 +!D9 U+044B afii10093 +!DA U+0437 afii10073 +!DB U+0448 afii10090 +!DC U+044D afii10095 +!DD U+0449 afii10091 +!DE U+0447 afii10089 +!DF U+044A afii10092 +!E0 U+042E afii10048 +!E1 U+0410 afii10017 +!E2 U+0411 afii10018 +!E3 U+0426 afii10040 +!E4 U+0414 afii10021 +!E5 U+0415 afii10022 +!E6 U+0424 afii10038 +!E7 U+0413 afii10020 +!E8 U+0425 afii10039 +!E9 U+0418 afii10026 +!EA U+0419 afii10027 +!EB U+041A afii10028 +!EC U+041B afii10029 +!ED U+041C afii10030 +!EE U+041D afii10031 +!EF U+041E afii10032 +!F0 U+041F afii10033 +!F1 U+042F afii10049 +!F2 U+0420 afii10034 +!F3 U+0421 afii10035 +!F4 U+0422 afii10036 +!F5 U+0423 afii10037 +!F6 U+0416 afii10024 +!F7 U+0412 afii10019 +!F8 U+042C afii10046 +!F9 U+042B afii10045 +!FA U+0417 afii10025 +!FB U+0428 afii10042 +!FC U+042D afii10047 +!FD U+0429 afii10043 +!FE U+0427 afii10041 +!FF U+042A afii10044 diff --git a/src/bb-library/makefont/makefont.php b/src/bb-library/makefont/makefont.php new file mode 100644 index 000000000..2c147ac16 --- /dev/null +++ b/src/bb-library/makefont/makefont.php @@ -0,0 +1,447 @@ +$severity: "; + echo "$txt
"; + } +} + +function Notice($txt) +{ + Message($txt, 'Notice'); +} + +function Warning($txt) +{ + Message($txt, 'Warning'); +} + +function Error($txt) +{ + Message($txt, 'Error'); + exit; +} + +function LoadMap($enc) +{ + $file = dirname(__FILE__).'/'.strtolower($enc).'.map'; + $a = file($file); + if(empty($a)) + Error('Encoding not found: '.$enc); + $map = array_fill(0, 256, array('uv'=>-1, 'name'=>'.notdef')); + foreach($a as $line) + { + $e = explode(' ', rtrim($line)); + $c = hexdec(substr($e[0],1)); + $uv = hexdec(substr($e[1],2)); + $name = $e[2]; + $map[$c] = array('uv'=>$uv, 'name'=>$name); + } + return $map; +} + +function GetInfoFromTrueType($file, $embed, $subset, $map) +{ + // Return information from a TrueType font + try + { + $ttf = new TTFParser($file); + $ttf->Parse(); + } + catch(Exception $e) + { + Error($e->getMessage()); + } + if($embed) + { + if(!$ttf->embeddable) + Error('Font license does not allow embedding'); + if($subset) + { + $chars = array(); + foreach($map as $v) + { + if($v['name']!='.notdef') + $chars[] = $v['uv']; + } + $ttf->Subset($chars); + $info['Data'] = $ttf->Build(); + } + else + $info['Data'] = file_get_contents($file); + $info['OriginalSize'] = strlen($info['Data']); + } + $k = 1000/$ttf->unitsPerEm; + $info['FontName'] = $ttf->postScriptName; + $info['Bold'] = $ttf->bold; + $info['ItalicAngle'] = $ttf->italicAngle; + $info['IsFixedPitch'] = $ttf->isFixedPitch; + $info['Ascender'] = round($k*$ttf->typoAscender); + $info['Descender'] = round($k*$ttf->typoDescender); + $info['UnderlineThickness'] = round($k*$ttf->underlineThickness); + $info['UnderlinePosition'] = round($k*$ttf->underlinePosition); + $info['FontBBox'] = array(round($k*$ttf->xMin), round($k*$ttf->yMin), round($k*$ttf->xMax), round($k*$ttf->yMax)); + $info['CapHeight'] = round($k*$ttf->capHeight); + $info['MissingWidth'] = round($k*$ttf->glyphs[0]['w']); + $widths = array_fill(0, 256, $info['MissingWidth']); + foreach($map as $c=>$v) + { + if($v['name']!='.notdef') + { + if(isset($ttf->chars[$v['uv']])) + { + $id = $ttf->chars[$v['uv']]; + $w = $ttf->glyphs[$id]['w']; + $widths[$c] = round($k*$w); + } + else + Warning('Character '.$v['name'].' is missing'); + } + } + $info['Widths'] = $widths; + return $info; +} + +function GetInfoFromType1($file, $embed, $map) +{ + // Return information from a Type1 font + if($embed) + { + $f = fopen($file, 'rb'); + if(!$f) + Error('Can\'t open font file'); + // Read first segment + $a = unpack('Cmarker/Ctype/Vsize', fread($f,6)); + if($a['marker']!=128) + Error('Font file is not a valid binary Type1'); + $size1 = $a['size']; + $data = fread($f, $size1); + // Read second segment + $a = unpack('Cmarker/Ctype/Vsize', fread($f,6)); + if($a['marker']!=128) + Error('Font file is not a valid binary Type1'); + $size2 = $a['size']; + $data .= fread($f, $size2); + fclose($f); + $info['Data'] = $data; + $info['Size1'] = $size1; + $info['Size2'] = $size2; + } + + $afm = substr($file, 0, -3).'afm'; + if(!file_exists($afm)) + Error('AFM font file not found: '.$afm); + $a = file($afm); + if(empty($a)) + Error('AFM file empty or not readable'); + foreach($a as $line) + { + $e = explode(' ', rtrim($line)); + if(count($e)<2) + continue; + $entry = $e[0]; + if($entry=='C') + { + $w = $e[4]; + $name = $e[7]; + $cw[$name] = $w; + } + elseif($entry=='FontName') + $info['FontName'] = $e[1]; + elseif($entry=='Weight') + $info['Weight'] = $e[1]; + elseif($entry=='ItalicAngle') + $info['ItalicAngle'] = (int)$e[1]; + elseif($entry=='Ascender') + $info['Ascender'] = (int)$e[1]; + elseif($entry=='Descender') + $info['Descender'] = (int)$e[1]; + elseif($entry=='UnderlineThickness') + $info['UnderlineThickness'] = (int)$e[1]; + elseif($entry=='UnderlinePosition') + $info['UnderlinePosition'] = (int)$e[1]; + elseif($entry=='IsFixedPitch') + $info['IsFixedPitch'] = ($e[1]=='true'); + elseif($entry=='FontBBox') + $info['FontBBox'] = array((int)$e[1], (int)$e[2], (int)$e[3], (int)$e[4]); + elseif($entry=='CapHeight') + $info['CapHeight'] = (int)$e[1]; + elseif($entry=='StdVW') + $info['StdVW'] = (int)$e[1]; + } + + if(!isset($info['FontName'])) + Error('FontName missing in AFM file'); + if(!isset($info['Ascender'])) + $info['Ascender'] = $info['FontBBox'][3]; + if(!isset($info['Descender'])) + $info['Descender'] = $info['FontBBox'][1]; + $info['Bold'] = isset($info['Weight']) && preg_match('/bold|black/i', $info['Weight']); + if(isset($cw['.notdef'])) + $info['MissingWidth'] = $cw['.notdef']; + else + $info['MissingWidth'] = 0; + $widths = array_fill(0, 256, $info['MissingWidth']); + foreach($map as $c=>$v) + { + if($v['name']!='.notdef') + { + if(isset($cw[$v['name']])) + $widths[$c] = $cw[$v['name']]; + else + Warning('Character '.$v['name'].' is missing'); + } + } + $info['Widths'] = $widths; + return $info; +} + +function MakeFontDescriptor($info) +{ + // Ascent + $fd = "array('Ascent'=>".$info['Ascender']; + // Descent + $fd .= ",'Descent'=>".$info['Descender']; + // CapHeight + if(!empty($info['CapHeight'])) + $fd .= ",'CapHeight'=>".$info['CapHeight']; + else + $fd .= ",'CapHeight'=>".$info['Ascender']; + // Flags + $flags = 0; + if($info['IsFixedPitch']) + $flags += 1<<0; + $flags += 1<<5; + if($info['ItalicAngle']!=0) + $flags += 1<<6; + $fd .= ",'Flags'=>".$flags; + // FontBBox + $fbb = $info['FontBBox']; + $fd .= ",'FontBBox'=>'[".$fbb[0].' '.$fbb[1].' '.$fbb[2].' '.$fbb[3]."]'"; + // ItalicAngle + $fd .= ",'ItalicAngle'=>".$info['ItalicAngle']; + // StemV + if(isset($info['StdVW'])) + $stemv = $info['StdVW']; + elseif($info['Bold']) + $stemv = 120; + else + $stemv = 70; + $fd .= ",'StemV'=>".$stemv; + // MissingWidth + $fd .= ",'MissingWidth'=>".$info['MissingWidth'].')'; + return $fd; +} + +function MakeWidthArray($widths) +{ + $s = "array(\n\t"; + for($c=0;$c<=255;$c++) + { + if(chr($c)=="'") + $s .= "'\\''"; + elseif(chr($c)=="\\") + $s .= "'\\\\'"; + elseif($c>=32 && $c<=126) + $s .= "'".chr($c)."'"; + else + $s .= "chr($c)"; + $s .= '=>'.$widths[$c]; + if($c<255) + $s .= ','; + if(($c+1)%22==0) + $s .= "\n\t"; + } + $s .= ')'; + return $s; +} + +function MakeFontEncoding($map) +{ + // Build differences from reference encoding + $ref = LoadMap('cp1252'); + $s = ''; + $last = 0; + for($c=32;$c<=255;$c++) + { + if($map[$c]['name']!=$ref[$c]['name']) + { + if($c!=$last+1) + $s .= $c.' '; + $last = $c; + $s .= '/'.$map[$c]['name'].' '; + } + } + return rtrim($s); +} + +function MakeUnicodeArray($map) +{ + // Build mapping to Unicode values + $ranges = array(); + foreach($map as $c=>$v) + { + $uv = $v['uv']; + if($uv!=-1) + { + if(isset($range)) + { + if($c==$range[1]+1 && $uv==$range[3]+1) + { + $range[1]++; + $range[3]++; + } + else + { + $ranges[] = $range; + $range = array($c, $c, $uv, $uv); + } + } + else + $range = array($c, $c, $uv, $uv); + } + } + $ranges[] = $range; + + foreach($ranges as $range) + { + if(isset($s)) + $s .= ','; + else + $s = 'array('; + $s .= $range[0].'=>'; + $nb = $range[1]-$range[0]+1; + if($nb>1) + $s .= 'array('.$range[2].','.$nb.')'; + else + $s .= $range[2]; + } + $s .= ')'; + return $s; +} + +function SaveToFile($file, $s, $mode) +{ + $f = fopen($file, 'w'.$mode); + if(!$f) + Error('Can\'t write to file '.$file); + fwrite($f, $s); + fclose($f); +} + +function MakeDefinitionFile($file, $type, $enc, $embed, $subset, $map, $info) +{ + $s = "\n"; + SaveToFile($file, $s, 't'); +} + +function MakeFont($fontfile, $enc='cp1252', $embed=true, $subset=true) +{ + // Generate a font definition file + if(!file_exists($fontfile)) + Error('Font file not found: '.$fontfile); + $ext = strtolower(substr($fontfile,-3)); + if($ext=='ttf' || $ext=='otf') + $type = 'TrueType'; + elseif($ext=='pfb') + $type = 'Type1'; + else + Error('Unrecognized font file extension: '.$ext); + + $map = LoadMap($enc); + + if($type=='TrueType') + $info = GetInfoFromTrueType($fontfile, $embed, $subset, $map); + else + $info = GetInfoFromType1($fontfile, $embed, $map); + + $basename = substr(basename($fontfile), 0, -4); + if($embed) + { + if(function_exists('gzcompress')) + { + $file = $basename.'.z'; + SaveToFile($file, gzcompress($info['Data']), 'b'); + $info['File'] = $file; + Message('Font file compressed: '.$file); + } + else + { + $info['File'] = basename($fontfile); + $subset = false; + Notice('Font file could not be compressed (zlib extension not available)'); + } + } + + MakeDefinitionFile($basename.'.php', $type, $enc, $embed, $subset, $map, $info); + Message('Font definition file generated: '.$basename.'.php'); +} + +if(PHP_SAPI=='cli') +{ + // Command-line interface + ini_set('log_errors', '0'); + if($argc==1) + die("Usage: php makefont.php fontfile [encoding] [embed] [subset]\n"); + $fontfile = $argv[1]; + if($argc>=3) + $enc = $argv[2]; + else + $enc = 'cp1252'; + if($argc>=4) + $embed = ($argv[3]=='true' || $argv[3]=='1'); + else + $embed = true; + if($argc>=5) + $subset = ($argv[4]=='true' || $argv[4]=='1'); + else + $subset = true; + MakeFont($fontfile, $enc, $embed, $subset); +} +?> diff --git a/src/bb-library/makefont/ttfparser.php b/src/bb-library/makefont/ttfparser.php new file mode 100644 index 000000000..56c46a4f6 --- /dev/null +++ b/src/bb-library/makefont/ttfparser.php @@ -0,0 +1,723 @@ +f = fopen($file, 'rb'); + if(!$this->f) + $this->Error('Can\'t open file: '.$file); + } + + function __destruct() + { + if(is_resource($this->f)) + fclose($this->f); + } + + function Parse() + { + $this->ParseOffsetTable(); + $this->ParseHead(); + $this->ParseHhea(); + $this->ParseMaxp(); + $this->ParseHmtx(); + $this->ParseLoca(); + $this->ParseGlyf(); + $this->ParseCmap(); + $this->ParseName(); + $this->ParseOS2(); + $this->ParsePost(); + } + + function ParseOffsetTable() + { + $version = $this->Read(4); + if($version=='OTTO') + $this->Error('OpenType fonts based on PostScript outlines are not supported'); + if($version!="\x00\x01\x00\x00") + $this->Error('Unrecognized file format'); + $numTables = $this->ReadUShort(); + $this->Skip(3*2); // searchRange, entrySelector, rangeShift + $this->tables = array(); + for($i=0;$i<$numTables;$i++) + { + $tag = $this->Read(4); + $checkSum = $this->Read(4); + $offset = $this->ReadULong(); + $length = $this->ReadULong(4); + $this->tables[$tag] = array('offset'=>$offset, 'length'=>$length, 'checkSum'=>$checkSum); + } + } + + function ParseHead() + { + $this->Seek('head'); + $this->Skip(3*4); // version, fontRevision, checkSumAdjustment + $magicNumber = $this->ReadULong(); + if($magicNumber!=0x5F0F3CF5) + $this->Error('Incorrect magic number'); + $this->Skip(2); // flags + $this->unitsPerEm = $this->ReadUShort(); + $this->Skip(2*8); // created, modified + $this->xMin = $this->ReadShort(); + $this->yMin = $this->ReadShort(); + $this->xMax = $this->ReadShort(); + $this->yMax = $this->ReadShort(); + $this->Skip(3*2); // macStyle, lowestRecPPEM, fontDirectionHint + $this->indexToLocFormat = $this->ReadShort(); + } + + function ParseHhea() + { + $this->Seek('hhea'); + $this->Skip(4+15*2); + $this->numberOfHMetrics = $this->ReadUShort(); + } + + function ParseMaxp() + { + $this->Seek('maxp'); + $this->Skip(4); + $this->numGlyphs = $this->ReadUShort(); + } + + function ParseHmtx() + { + $this->Seek('hmtx'); + $this->glyphs = array(); + for($i=0;$i<$this->numberOfHMetrics;$i++) + { + $advanceWidth = $this->ReadUShort(); + $lsb = $this->ReadShort(); + $this->glyphs[$i] = array('w'=>$advanceWidth, 'lsb'=>$lsb); + } + for($i=$this->numberOfHMetrics;$i<$this->numGlyphs;$i++) + { + $lsb = $this->ReadShort(); + $this->glyphs[$i] = array('w'=>$advanceWidth, 'lsb'=>$lsb); + } + } + + function ParseLoca() + { + $this->Seek('loca'); + $offsets = array(); + if($this->indexToLocFormat==0) + { + // Short format + for($i=0;$i<=$this->numGlyphs;$i++) + $offsets[] = 2*$this->ReadUShort(); + } + else + { + // Long format + for($i=0;$i<=$this->numGlyphs;$i++) + $offsets[] = $this->ReadULong(); + } + for($i=0;$i<$this->numGlyphs;$i++) + { + $this->glyphs[$i]['offset'] = $offsets[$i]; + $this->glyphs[$i]['length'] = $offsets[$i+1] - $offsets[$i]; + } + } + + function ParseGlyf() + { + $tableOffset = $this->tables['glyf']['offset']; + foreach($this->glyphs as &$glyph) + { + if($glyph['length']>0) + { + fseek($this->f, $tableOffset+$glyph['offset'], SEEK_SET); + if($this->ReadShort()<0) + { + // Composite glyph + $this->Skip(4*2); // xMin, yMin, xMax, yMax + $offset = 5*2; + $a = array(); + do + { + $flags = $this->ReadUShort(); + $index = $this->ReadUShort(); + $a[$offset+2] = $index; + if($flags & 1) // ARG_1_AND_2_ARE_WORDS + $skip = 2*2; + else + $skip = 2; + if($flags & 8) // WE_HAVE_A_SCALE + $skip += 2; + elseif($flags & 64) // WE_HAVE_AN_X_AND_Y_SCALE + $skip += 2*2; + elseif($flags & 128) // WE_HAVE_A_TWO_BY_TWO + $skip += 4*2; + $this->Skip($skip); + $offset += 2*2 + $skip; + } + while($flags & 32); // MORE_COMPONENTS + $glyph['components'] = $a; + } + } + } + } + + function ParseCmap() + { + $this->Seek('cmap'); + $this->Skip(2); // version + $numTables = $this->ReadUShort(); + $offset31 = 0; + for($i=0;$i<$numTables;$i++) + { + $platformID = $this->ReadUShort(); + $encodingID = $this->ReadUShort(); + $offset = $this->ReadULong(); + if($platformID==3 && $encodingID==1) + $offset31 = $offset; + } + if($offset31==0) + $this->Error('No Unicode encoding found'); + + $startCount = array(); + $endCount = array(); + $idDelta = array(); + $idRangeOffset = array(); + $this->chars = array(); + fseek($this->f, $this->tables['cmap']['offset']+$offset31, SEEK_SET); + $format = $this->ReadUShort(); + if($format!=4) + $this->Error('Unexpected subtable format: '.$format); + $this->Skip(2*2); // length, language + $segCount = $this->ReadUShort()/2; + $this->Skip(3*2); // searchRange, entrySelector, rangeShift + for($i=0;$i<$segCount;$i++) + $endCount[$i] = $this->ReadUShort(); + $this->Skip(2); // reservedPad + for($i=0;$i<$segCount;$i++) + $startCount[$i] = $this->ReadUShort(); + for($i=0;$i<$segCount;$i++) + $idDelta[$i] = $this->ReadShort(); + $offset = ftell($this->f); + for($i=0;$i<$segCount;$i++) + $idRangeOffset[$i] = $this->ReadUShort(); + + for($i=0;$i<$segCount;$i++) + { + $c1 = $startCount[$i]; + $c2 = $endCount[$i]; + $d = $idDelta[$i]; + $ro = $idRangeOffset[$i]; + if($ro>0) + fseek($this->f, $offset+2*$i+$ro, SEEK_SET); + for($c=$c1;$c<=$c2;$c++) + { + if($c==0xFFFF) + break; + if($ro>0) + { + $gid = $this->ReadUShort(); + if($gid>0) + $gid += $d; + } + else + $gid = $c+$d; + if($gid>=65536) + $gid -= 65536; + if($gid>0) + $this->chars[$c] = $gid; + } + } + } + + function ParseName() + { + $this->Seek('name'); + $tableOffset = $this->tables['name']['offset']; + $this->postScriptName = ''; + $this->Skip(2); // format + $count = $this->ReadUShort(); + $stringOffset = $this->ReadUShort(); + for($i=0;$i<$count;$i++) + { + $this->Skip(3*2); // platformID, encodingID, languageID + $nameID = $this->ReadUShort(); + $length = $this->ReadUShort(); + $offset = $this->ReadUShort(); + if($nameID==6) + { + // PostScript name + fseek($this->f, $tableOffset+$stringOffset+$offset, SEEK_SET); + $s = $this->Read($length); + $s = str_replace(chr(0), '', $s); + $s = preg_replace('|[ \[\](){}<>/%]|', '', $s); + $this->postScriptName = $s; + break; + } + } + if($this->postScriptName=='') + $this->Error('PostScript name not found'); + } + + function ParseOS2() + { + $this->Seek('OS/2'); + $version = $this->ReadUShort(); + $this->Skip(3*2); // xAvgCharWidth, usWeightClass, usWidthClass + $fsType = $this->ReadUShort(); + $this->embeddable = ($fsType!=2) && ($fsType & 0x200)==0; + $this->Skip(11*2+10+4*4+4); + $fsSelection = $this->ReadUShort(); + $this->bold = ($fsSelection & 32)!=0; + $this->Skip(2*2); // usFirstCharIndex, usLastCharIndex + $this->typoAscender = $this->ReadShort(); + $this->typoDescender = $this->ReadShort(); + if($version>=2) + { + $this->Skip(3*2+2*4+2); + $this->capHeight = $this->ReadShort(); + } + else + $this->capHeight = 0; + } + + function ParsePost() + { + $this->Seek('post'); + $version = $this->ReadULong(); + $this->italicAngle = $this->ReadShort(); + $this->Skip(2); // Skip decimal part + $this->underlinePosition = $this->ReadShort(); + $this->underlineThickness = $this->ReadShort(); + $this->isFixedPitch = ($this->ReadULong()!=0); + if($version==0x20000) + { + // Extract glyph names + $this->Skip(4*4); // min/max usage + $this->Skip(2); // numberOfGlyphs + $glyphNameIndex = array(); + $names = array(); + $numNames = 0; + for($i=0;$i<$this->numGlyphs;$i++) + { + $index = $this->ReadUShort(); + $glyphNameIndex[] = $index; + if($index>=258 && $index-257>$numNames) + $numNames = $index-257; + } + for($i=0;$i<$numNames;$i++) + { + $len = ord($this->Read(1)); + $names[] = $this->Read($len); + } + foreach($glyphNameIndex as $i=>$index) + { + if($index>=258) + $this->glyphs[$i]['name'] = $names[$index-258]; + else + $this->glyphs[$i]['name'] = $index; + } + $this->glyphNames = true; + } + else + $this->glyphNames = false; + } + + function Subset($chars) + { +/* $chars = array_keys($this->chars); + $this->subsettedChars = $chars; + $this->subsettedGlyphs = array(); + for($i=0;$i<$this->numGlyphs;$i++) + { + $this->subsettedGlyphs[] = $i; + $this->glyphs[$i]['ssid'] = $i; + }*/ + + $this->AddGlyph(0); + $this->subsettedChars = array(); + foreach($chars as $char) + { + if(isset($this->chars[$char])) + { + $this->subsettedChars[] = $char; + $this->AddGlyph($this->chars[$char]); + } + } + } + + function AddGlyph($id) + { + if(!isset($this->glyphs[$id]['ssid'])) + { + $this->glyphs[$id]['ssid'] = count($this->subsettedGlyphs); + $this->subsettedGlyphs[] = $id; + if(isset($this->glyphs[$id]['components'])) + { + foreach($this->glyphs[$id]['components'] as $cid) + $this->AddGlyph($cid); + } + } + } + + function Build() + { + $this->BuildCmap(); + $this->BuildHhea(); + $this->BuildHmtx(); + $this->BuildLoca(); + $this->BuildGlyf(); + $this->BuildMaxp(); + $this->BuildPost(); + return $this->BuildFont(); + } + + function BuildCmap() + { + if(!isset($this->subsettedChars)) + return; + + // Divide charset in contiguous segments + $chars = $this->subsettedChars; + sort($chars); + $segments = array(); + $segment = array($chars[0], $chars[0]); + for($i=1;$i$segment[1]+1) + { + $segments[] = $segment; + $segment = array($chars[$i], $chars[$i]); + } + else + $segment[1]++; + } + $segments[] = $segment; + $segments[] = array(0xFFFF, 0xFFFF); + $segCount = count($segments); + + // Build a Format 4 subtable + $startCount = array(); + $endCount = array(); + $idDelta = array(); + $idRangeOffset = array(); + $glyphIdArray = ''; + for($i=0;$i<$segCount;$i++) + { + list($start, $end) = $segments[$i]; + $startCount[] = $start; + $endCount[] = $end; + if($start!=$end) + { + // Segment with multiple chars + $idDelta[] = 0; + $idRangeOffset[] = strlen($glyphIdArray) + ($segCount-$i)*2; + for($c=$start;$c<=$end;$c++) + { + $ssid = $this->glyphs[$this->chars[$c]]['ssid']; + $glyphIdArray .= pack('n', $ssid); + } + } + else + { + // Segment with a single char + if($start<0xFFFF) + $ssid = $this->glyphs[$this->chars[$start]]['ssid']; + else + $ssid = 0; + $idDelta[] = $ssid - $start; + $idRangeOffset[] = 0; + } + } + $entrySelector = 0; + $n = $segCount; + while($n!=1) + { + $n = $n>>1; + $entrySelector++; + } + $searchRange = (1<<$entrySelector)*2; + $rangeShift = 2*$segCount - $searchRange; + $cmap = pack('nnnn', 2*$segCount, $searchRange, $entrySelector, $rangeShift); + foreach($endCount as $val) + $cmap .= pack('n', $val); + $cmap .= pack('n', 0); // reservedPad + foreach($startCount as $val) + $cmap .= pack('n', $val); + foreach($idDelta as $val) + $cmap .= pack('n', $val); + foreach($idRangeOffset as $val) + $cmap .= pack('n', $val); + $cmap .= $glyphIdArray; + + $data = pack('nn', 0, 1); // version, numTables + $data .= pack('nnN', 3, 1, 12); // platformID, encodingID, offset + $data .= pack('nnn', 4, 6+strlen($cmap), 0); // format, length, language + $data .= $cmap; + $this->SetTable('cmap', $data); + } + + function BuildHhea() + { + $this->LoadTable('hhea'); + $numberOfHMetrics = count($this->subsettedGlyphs); + $data = substr_replace($this->tables['hhea']['data'], pack('n',$numberOfHMetrics), 4+15*2, 2); + $this->SetTable('hhea', $data); + } + + function BuildHmtx() + { + $data = ''; + foreach($this->subsettedGlyphs as $id) + { + $glyph = $this->glyphs[$id]; + $data .= pack('nn', $glyph['w'], $glyph['lsb']); + } + $this->SetTable('hmtx', $data); + } + + function BuildLoca() + { + $data = ''; + $offset = 0; + foreach($this->subsettedGlyphs as $id) + { + if($this->indexToLocFormat==0) + $data .= pack('n', $offset/2); + else + $data .= pack('N', $offset); + $offset += $this->glyphs[$id]['length']; + } + if($this->indexToLocFormat==0) + $data .= pack('n', $offset/2); + else + $data .= pack('N', $offset); + $this->SetTable('loca', $data); + } + + function BuildGlyf() + { + $tableOffset = $this->tables['glyf']['offset']; + $data = ''; + foreach($this->subsettedGlyphs as $id) + { + $glyph = $this->glyphs[$id]; + fseek($this->f, $tableOffset+$glyph['offset'], SEEK_SET); + $glyph_data = $this->Read($glyph['length']); + if(isset($glyph['components'])) + { + // Composite glyph + foreach($glyph['components'] as $offset=>$cid) + { + $ssid = $this->glyphs[$cid]['ssid']; + $glyph_data = substr_replace($glyph_data, pack('n',$ssid), $offset, 2); + } + } + $data .= $glyph_data; + } + $this->SetTable('glyf', $data); + } + + function BuildMaxp() + { + $this->LoadTable('maxp'); + $numGlyphs = count($this->subsettedGlyphs); + $data = substr_replace($this->tables['maxp']['data'], pack('n',$numGlyphs), 4, 2); + $this->SetTable('maxp', $data); + } + + function BuildPost() + { + $this->Seek('post'); + if($this->glyphNames) + { + // Version 2.0 + $numberOfGlyphs = count($this->subsettedGlyphs); + $numNames = 0; + $names = ''; + $data = $this->Read(2*4+2*2+5*4); + $data .= pack('n', $numberOfGlyphs); + foreach($this->subsettedGlyphs as $id) + { + $name = $this->glyphs[$id]['name']; + if(is_string($name)) + { + $data .= pack('n', 258+$numNames); + $names .= chr(strlen($name)).$name; + $numNames++; + } + else + $data .= pack('n', $name); + } + $data .= $names; + } + else + { + // Version 3.0 + $this->Skip(4); + $data = "\x00\x03\x00\x00"; + $data .= $this->Read(4+2*2+5*4); + } + $this->SetTable('post', $data); + } + + function BuildFont() + { + $tags = array(); + foreach(array('cmap', 'cvt ', 'fpgm', 'glyf', 'head', 'hhea', 'hmtx', 'loca', 'maxp', 'name', 'post', 'prep') as $tag) + { + if(isset($this->tables[$tag])) + $tags[] = $tag; + } + $numTables = count($tags); + $offset = 12 + 16*$numTables; + foreach($tags as $tag) + { + if(!isset($this->tables[$tag]['data'])) + $this->LoadTable($tag); + $this->tables[$tag]['offset'] = $offset; + $offset += strlen($this->tables[$tag]['data']); + } +// $this->tables['head']['data'] = substr_replace($this->tables['head']['data'], "\x00\x00\x00\x00", 8, 4); + + // Build offset table + $entrySelector = 0; + $n = $numTables; + while($n!=1) + { + $n = $n>>1; + $entrySelector++; + } + $searchRange = 16*(1<<$entrySelector); + $rangeShift = 16*$numTables - $searchRange; + $offsetTable = pack('nnnnnn', 1, 0, $numTables, $searchRange, $entrySelector, $rangeShift); + foreach($tags as $tag) + { + $table = $this->tables[$tag]; + $offsetTable .= $tag.$table['checkSum'].pack('NN', $table['offset'], $table['length']); + } + + // Compute checkSumAdjustment (0xB1B0AFBA - font checkSum) + $s = $this->CheckSum($offsetTable); + foreach($tags as $tag) + $s .= $this->tables[$tag]['checkSum']; + $a = unpack('n2', $this->CheckSum($s)); + $high = 0xB1B0 + ($a[1]^0xFFFF); + $low = 0xAFBA + ($a[2]^0xFFFF) + 1; + $checkSumAdjustment = pack('nn', $high+($low>>16), $low); + $this->tables['head']['data'] = substr_replace($this->tables['head']['data'], $checkSumAdjustment, 8, 4); + + $font = $offsetTable; + foreach($tags as $tag) + $font .= $this->tables[$tag]['data']; + + return $font; + } + + function LoadTable($tag) + { + $this->Seek($tag); + $length = $this->tables[$tag]['length']; + $n = $length % 4; + if($n>0) + $length += 4 - $n; + $this->tables[$tag]['data'] = $this->Read($length); + } + + function SetTable($tag, $data) + { + $length = strlen($data); + $n = $length % 4; + if($n>0) + $data = str_pad($data, $length+4-$n, "\x00"); + $this->tables[$tag]['data'] = $data; + $this->tables[$tag]['length'] = $length; + $this->tables[$tag]['checkSum'] = $this->CheckSum($data); + } + + function Seek($tag) + { + if(!isset($this->tables[$tag])) + $this->Error('Table not found: '.$tag); + fseek($this->f, $this->tables[$tag]['offset'], SEEK_SET); + } + + function Skip($n) + { + fseek($this->f, $n, SEEK_CUR); + } + + function Read($n) + { + return $n>0 ? fread($this->f, $n) : ''; + } + + function ReadUShort() + { + $a = unpack('nn', fread($this->f,2)); + return $a['n']; + } + + function ReadShort() + { + $a = unpack('nn', fread($this->f,2)); + $v = $a['n']; + if($v>=0x8000) + $v -= 65536; + return $v; + } + + function ReadULong() + { + $a = unpack('NN', fread($this->f,4)); + return $a['N']; + } + + function CheckSum($s) + { + $n = strlen($s); + $high = 0; + $low = 0; + for($i=0;$i<$n;$i+=4) + { + $high += (ord($s[$i])<<8) + ord($s[$i+1]); + $low += (ord($s[$i+2])<<8) + ord($s[$i+3]); + } + return pack('nn', $high+($low>>16), $low); + } + + function Error($msg) + { + throw new Exception($msg); + } +} +?> diff --git a/src/bb-library/tutorial/20k_c1.txt b/src/bb-library/tutorial/20k_c1.txt new file mode 100644 index 000000000..6d5b29542 --- /dev/null +++ b/src/bb-library/tutorial/20k_c1.txt @@ -0,0 +1,10 @@ +The year 1866 was marked by a bizarre development, an unexplained and downright inexplicable phenomenon that surely no one has forgotten. Without getting into those rumors that upset civilians in the seaports and deranged the public mind even far inland, it must be said that professional seamen were especially alarmed. Traders, shipowners, captains of vessels, skippers, and master mariners from Europe and America, naval officers from every country, and at their heels the various national governments on these two continents, were all extremely disturbed by the business. +In essence, over a period of time several ships had encountered "an enormous thing" at sea, a long spindle-shaped object, sometimes giving off a phosphorescent glow, infinitely bigger and faster than any whale. +The relevant data on this apparition, as recorded in various logbooks, agreed pretty closely as to the structure of the object or creature in question, its unprecedented speed of movement, its startling locomotive power, and the unique vitality with which it seemed to be gifted. If it was a cetacean, it exceeded in bulk any whale previously classified by science. No naturalist, neither Cuvier nor Lacépède, neither Professor Dumeril nor Professor de Quatrefages, would have accepted the existence of such a monster sight unseen -- specifically, unseen by their own scientific eyes. +Striking an average of observations taken at different times -- rejecting those timid estimates that gave the object a length of 200 feet, and ignoring those exaggerated views that saw it as a mile wide and three long--you could still assert that this phenomenal creature greatly exceeded the dimensions of anything then known to ichthyologists, if it existed at all. +Now then, it did exist, this was an undeniable fact; and since the human mind dotes on objects of wonder, you can understand the worldwide excitement caused by this unearthly apparition. As for relegating it to the realm of fiction, that charge had to be dropped. +In essence, on July 20, 1866, the steamer Governor Higginson, from the Calcutta & Burnach Steam Navigation Co., encountered this moving mass five miles off the eastern shores of Australia. Captain Baker at first thought he was in the presence of an unknown reef; he was even about to fix its exact position when two waterspouts shot out of this inexplicable object and sprang hissing into the air some 150 feet. So, unless this reef was subject to the intermittent eruptions of a geyser, the Governor Higginson had fair and honest dealings with some aquatic mammal, until then unknown, that could spurt from its blowholes waterspouts mixed with air and steam. +Similar events were likewise observed in Pacific seas, on July 23 of the same year, by the Christopher Columbus from the West India & Pacific Steam Navigation Co. Consequently, this extraordinary cetacean could transfer itself from one locality to another with startling swiftness, since within an interval of just three days, the Governor Higginson and the Christopher Columbus had observed it at two positions on the charts separated by a distance of more than 700 nautical leagues. +Fifteen days later and 2,000 leagues farther, the Helvetia from the Compagnie Nationale and the Shannon from the Royal Mail line, running on opposite tacks in that part of the Atlantic lying between the United States and Europe, respectively signaled each other that the monster had been sighted in latitude 42 degrees 15' north and longitude 60 degrees 35' west of the meridian of Greenwich. From their simultaneous observations, they were able to estimate the mammal's minimum length at more than 350 English feet; this was because both the Shannon and the Helvetia were of smaller dimensions, although each measured 100 meters stem to stern. Now then, the biggest whales, those rorqual whales that frequent the waterways of the Aleutian Islands, have never exceeded a length of 56 meters--if they reach even that. +One after another, reports arrived that would profoundly affect public opinion: new observations taken by the transatlantic liner Pereire, the Inman line's Etna running afoul of the monster, an official report drawn up by officers on the French frigate Normandy, dead-earnest reckonings obtained by the general staff of Commodore Fitz-James aboard the Lord Clyde. In lighthearted countries, people joked about this phenomenon, but such serious, practical countries as England, America, and Germany were deeply concerned. +In every big city the monster was the latest rage; they sang about it in the coffee houses, they ridiculed it in the newspapers, they dramatized it in the theaters. The tabloids found it a fine opportunity for hatching all sorts of hoaxes. In those newspapers short of copy, you saw the reappearance of every gigantic imaginary creature, from "Moby Dick," that dreadful white whale from the High Arctic regions, to the stupendous kraken whose tentacles could entwine a 500-ton craft and drag it into the ocean depths. They even reprinted reports from ancient times: the views of Aristotle and Pliny accepting the existence of such monsters, then the Norwegian stories of Bishop Pontoppidan, the narratives of Paul Egede, and finally the reports of Captain Harrington -- whose good faith is above suspicion--in which he claims he saw, while aboard the Castilian in 1857, one of those enormous serpents that, until then, had frequented only the seas of France's old extremist newspaper, The Constitutionalist. diff --git a/src/bb-library/tutorial/20k_c2.txt b/src/bb-library/tutorial/20k_c2.txt new file mode 100644 index 000000000..7b5c56514 --- /dev/null +++ b/src/bb-library/tutorial/20k_c2.txt @@ -0,0 +1,23 @@ +During the period in which these developments were occurring, I had returned from a scientific undertaking organized to explore the Nebraska badlands in the United States. In my capacity as Assistant Professor at the Paris Museum of Natural History, I had been attached to this expedition by the French government. After spending six months in Nebraska, I arrived in New York laden with valuable collections near the end of March. My departure for France was set for early May. In the meantime, then, I was busy classifying my mineralogical, botanical, and zoological treasures when that incident took place with the Scotia. +I was perfectly abreast of this question, which was the big news of the day, and how could I not have been? I had read and reread every American and European newspaper without being any farther along. This mystery puzzled me. Finding it impossible to form any views, I drifted from one extreme to the other. Something was out there, that much was certain, and any doubting Thomas was invited to place his finger on the Scotia's wound. +When I arrived in New York, the question was at the boiling point. The hypothesis of a drifting islet or an elusive reef, put forward by people not quite in their right minds, was completely eliminated. And indeed, unless this reef had an engine in its belly, how could it move about with such prodigious speed? +Also discredited was the idea of a floating hull or some other enormous wreckage, and again because of this speed of movement. +So only two possible solutions to the question were left, creating two very distinct groups of supporters: on one side, those favoring a monster of colossal strength; on the other, those favoring an "underwater boat" of tremendous motor power. +Now then, although the latter hypothesis was completely admissible, it couldn't stand up to inquiries conducted in both the New World and the Old. That a private individual had such a mechanism at his disposal was less than probable. Where and when had he built it, and how could he have built it in secret? +Only some government could own such an engine of destruction, and in these disaster-filled times, when men tax their ingenuity to build increasingly powerful aggressive weapons, it was possible that, unknown to the rest of the world, some nation could have been testing such a fearsome machine. The Chassepot rifle led to the torpedo, and the torpedo has led to this underwater battering ram, which in turn will lead to the world putting its foot down. At least I hope it will. +But this hypothesis of a war machine collapsed in the face of formal denials from the various governments. Since the public interest was at stake and transoceanic travel was suffering, the sincerity of these governments could not be doubted. Besides, how could the assembly of this underwater boat have escaped public notice? Keeping a secret under such circumstances would be difficult enough for an individual, and certainly impossible for a nation whose every move is under constant surveillance by rival powers. +So, after inquiries conducted in England, France, Russia, Prussia, Spain, Italy, America, and even Turkey, the hypothesis of an underwater Monitor was ultimately rejected. +After I arrived in New York, several people did me the honor of consulting me on the phenomenon in question. In France I had published a two-volume work, in quarto, entitled The Mysteries of the Great Ocean Depths. Well received in scholarly circles, this book had established me as a specialist in this pretty obscure field of natural history. My views were in demand. As long as I could deny the reality of the business, I confined myself to a flat "no comment." But soon, pinned to the wall, I had to explain myself straight out. And in this vein, "the honorable Pierre Aronnax, Professor at the Paris Museum," was summoned by The New York Herald to formulate his views no matter what. +I complied. Since I could no longer hold my tongue, I let it wag. I discussed the question in its every aspect, both political and scientific, and this is an excerpt from the well-padded article I published in the issue of April 30. + +"Therefore," I wrote, "after examining these different hypotheses one by one, we are forced, every other supposition having been refuted, to accept the existence of an extremely powerful marine animal. +"The deepest parts of the ocean are totally unknown to us. No soundings have been able to reach them. What goes on in those distant depths? What creatures inhabit, or could inhabit, those regions twelve or fifteen miles beneath the surface of the water? What is the constitution of these animals? It's almost beyond conjecture. +"However, the solution to this problem submitted to me can take the form of a choice between two alternatives. +"Either we know every variety of creature populating our planet, or we do not. +"If we do not know every one of them, if nature still keeps ichthyological secrets from us, nothing is more admissible than to accept the existence of fish or cetaceans of new species or even new genera, animals with a basically 'cast-iron' constitution that inhabit strata beyond the reach of our soundings, and which some development or other, an urge or a whim if you prefer, can bring to the upper level of the ocean for long intervals. +"If, on the other hand, we do know every living species, we must look for the animal in question among those marine creatures already cataloged, and in this event I would be inclined to accept the existence of a giant narwhale. +"The common narwhale, or sea unicorn, often reaches a length of sixty feet. Increase its dimensions fivefold or even tenfold, then give this cetacean a strength in proportion to its size while enlarging its offensive weapons, and you have the animal we're looking for. It would have the proportions determined by the officers of the Shannon, the instrument needed to perforate the Scotia, and the power to pierce a steamer's hull. +"In essence, the narwhale is armed with a sort of ivory sword, or lance, as certain naturalists have expressed it. It's a king-sized tooth as hard as steel. Some of these teeth have been found buried in the bodies of baleen whales, which the narwhale attacks with invariable success. Others have been wrenched, not without difficulty, from the undersides of vessels that narwhales have pierced clean through, as a gimlet pierces a wine barrel. The museum at the Faculty of Medicine in Paris owns one of these tusks with a length of 2.25 meters and a width at its base of forty-eight centimeters! +"All right then! Imagine this weapon to be ten times stronger and the animal ten times more powerful, launch it at a speed of twenty miles per hour, multiply its mass times its velocity, and you get just the collision we need to cause the specified catastrophe. +"So, until information becomes more abundant, I plump for a sea unicorn of colossal dimensions, no longer armed with a mere lance but with an actual spur, like ironclad frigates or those warships called 'rams,' whose mass and motor power it would possess simultaneously. +"This inexplicable phenomenon is thus explained away--unless it's something else entirely, which, despite everything that has been sighted, studied, explored and experienced, is still possible!" diff --git a/src/bb-library/tutorial/calligra.php b/src/bb-library/tutorial/calligra.php new file mode 100644 index 000000000..a9cfdb384 --- /dev/null +++ b/src/bb-library/tutorial/calligra.php @@ -0,0 +1,25 @@ +899,'Descent'=>-234,'CapHeight'=>899,'Flags'=>32,'FontBBox'=>'[-173 -234 1328 899]','ItalicAngle'=>0,'StemV'=>70,'MissingWidth'=>800); +$up = -200; +$ut = 20; +$cw = array( + chr(0)=>800,chr(1)=>800,chr(2)=>800,chr(3)=>800,chr(4)=>800,chr(5)=>800,chr(6)=>800,chr(7)=>800,chr(8)=>800,chr(9)=>800,chr(10)=>800,chr(11)=>800,chr(12)=>800,chr(13)=>800,chr(14)=>800,chr(15)=>800,chr(16)=>800,chr(17)=>800,chr(18)=>800,chr(19)=>800,chr(20)=>800,chr(21)=>800, + chr(22)=>800,chr(23)=>800,chr(24)=>800,chr(25)=>800,chr(26)=>800,chr(27)=>800,chr(28)=>800,chr(29)=>800,chr(30)=>800,chr(31)=>800,' '=>282,'!'=>324,'"'=>405,'#'=>584,'$'=>632,'%'=>980,'&'=>776,'\''=>259,'('=>299,')'=>299,'*'=>377,'+'=>600, + ','=>259,'-'=>432,'.'=>254,'/'=>597,'0'=>529,'1'=>298,'2'=>451,'3'=>359,'4'=>525,'5'=>423,'6'=>464,'7'=>417,'8'=>457,'9'=>479,':'=>275,';'=>282,'<'=>600,'='=>600,'>'=>600,'?'=>501,'@'=>800,'A'=>743, + 'B'=>636,'C'=>598,'D'=>712,'E'=>608,'F'=>562,'G'=>680,'H'=>756,'I'=>308,'J'=>314,'K'=>676,'L'=>552,'M'=>1041,'N'=>817,'O'=>729,'P'=>569,'Q'=>698,'R'=>674,'S'=>618,'T'=>673,'U'=>805,'V'=>753,'W'=>1238, + 'X'=>716,'Y'=>754,'Z'=>599,'['=>315,'\\'=>463,']'=>315,'^'=>600,'_'=>547,'`'=>278,'a'=>581,'b'=>564,'c'=>440,'d'=>571,'e'=>450,'f'=>347,'g'=>628,'h'=>611,'i'=>283,'j'=>283,'k'=>560,'l'=>252,'m'=>976, + 'n'=>595,'o'=>508,'p'=>549,'q'=>540,'r'=>395,'s'=>441,'t'=>307,'u'=>614,'v'=>556,'w'=>915,'x'=>559,'y'=>597,'z'=>452,'{'=>315,'|'=>222,'}'=>315,'~'=>600,chr(127)=>800,chr(128)=>800,chr(129)=>800,chr(130)=>0,chr(131)=>0, + chr(132)=>0,chr(133)=>780,chr(134)=>0,chr(135)=>0,chr(136)=>278,chr(137)=>0,chr(138)=>0,chr(139)=>0,chr(140)=>1064,chr(141)=>800,chr(142)=>0,chr(143)=>800,chr(144)=>800,chr(145)=>259,chr(146)=>259,chr(147)=>470,chr(148)=>470,chr(149)=>500,chr(150)=>300,chr(151)=>600,chr(152)=>278,chr(153)=>990, + chr(154)=>0,chr(155)=>0,chr(156)=>790,chr(157)=>800,chr(158)=>800,chr(159)=>754,chr(160)=>282,chr(161)=>324,chr(162)=>450,chr(163)=>640,chr(164)=>518,chr(165)=>603,chr(166)=>0,chr(167)=>519,chr(168)=>254,chr(169)=>800,chr(170)=>349,chr(171)=>0,chr(172)=>0,chr(173)=>432,chr(174)=>800,chr(175)=>278, + chr(176)=>0,chr(177)=>0,chr(178)=>0,chr(179)=>0,chr(180)=>278,chr(181)=>614,chr(182)=>0,chr(183)=>254,chr(184)=>278,chr(185)=>0,chr(186)=>305,chr(187)=>0,chr(188)=>0,chr(189)=>0,chr(190)=>0,chr(191)=>501,chr(192)=>743,chr(193)=>743,chr(194)=>743,chr(195)=>743,chr(196)=>743,chr(197)=>743, + chr(198)=>1060,chr(199)=>598,chr(200)=>608,chr(201)=>608,chr(202)=>608,chr(203)=>608,chr(204)=>308,chr(205)=>308,chr(206)=>308,chr(207)=>308,chr(208)=>0,chr(209)=>817,chr(210)=>729,chr(211)=>729,chr(212)=>729,chr(213)=>729,chr(214)=>729,chr(215)=>0,chr(216)=>729,chr(217)=>805,chr(218)=>805,chr(219)=>805, + chr(220)=>805,chr(221)=>0,chr(222)=>0,chr(223)=>688,chr(224)=>581,chr(225)=>581,chr(226)=>581,chr(227)=>581,chr(228)=>581,chr(229)=>581,chr(230)=>792,chr(231)=>440,chr(232)=>450,chr(233)=>450,chr(234)=>450,chr(235)=>450,chr(236)=>283,chr(237)=>283,chr(238)=>283,chr(239)=>283,chr(240)=>0,chr(241)=>595, + chr(242)=>508,chr(243)=>508,chr(244)=>508,chr(245)=>508,chr(246)=>508,chr(247)=>0,chr(248)=>508,chr(249)=>614,chr(250)=>614,chr(251)=>614,chr(252)=>614,chr(253)=>0,chr(254)=>0,chr(255)=>597); +$enc = 'cp1252'; +$uv = array(0=>array(0,128),128=>8364,130=>8218,131=>402,132=>8222,133=>8230,134=>array(8224,2),136=>710,137=>8240,138=>352,139=>8249,140=>338,142=>381,145=>array(8216,2),147=>array(8220,2),149=>8226,150=>array(8211,2),152=>732,153=>8482,154=>353,155=>8250,156=>339,158=>382,159=>376,160=>array(160,96)); +$file = 'calligra.z'; +$originalsize = 33948; +$subsetted = true; +?> diff --git a/src/bb-library/tutorial/calligra.ttf b/src/bb-library/tutorial/calligra.ttf new file mode 100644 index 000000000..9713c468c Binary files /dev/null and b/src/bb-library/tutorial/calligra.ttf differ diff --git a/src/bb-library/tutorial/calligra.z b/src/bb-library/tutorial/calligra.z new file mode 100644 index 000000000..8a14e9ced Binary files /dev/null and b/src/bb-library/tutorial/calligra.z differ diff --git a/src/bb-library/tutorial/countries.txt b/src/bb-library/tutorial/countries.txt new file mode 100644 index 000000000..5a48a42e7 --- /dev/null +++ b/src/bb-library/tutorial/countries.txt @@ -0,0 +1,15 @@ +Austria;Vienna;83859;8075 +Belgium;Brussels;30518;10192 +Denmark;Copenhagen;43094;5295 +Finland;Helsinki;304529;5147 +France;Paris;543965;58728 +Germany;Berlin;357022;82057 +Greece;Athens;131625;10511 +Ireland;Dublin;70723;3694 +Italy;Roma;301316;57563 +Luxembourg;Luxembourg;2586;424 +Netherlands;Amsterdam;41526;15654 +Portugal;Lisbon;91906;9957 +Spain;Madrid;504790;39348 +Sweden;Stockholm;410934;8839 +United Kingdom;London;243820;58862 diff --git a/src/bb-library/tutorial/index.htm b/src/bb-library/tutorial/index.htm new file mode 100644 index 000000000..d1f8fb6c1 --- /dev/null +++ b/src/bb-library/tutorial/index.htm @@ -0,0 +1,20 @@ + + + + +Tutorials + + + +

Tutorials

+ + + diff --git a/src/bb-library/tutorial/logo.png b/src/bb-library/tutorial/logo.png new file mode 100644 index 000000000..284a0071c Binary files /dev/null and b/src/bb-library/tutorial/logo.png differ diff --git a/src/bb-library/tutorial/makefont.php b/src/bb-library/tutorial/makefont.php new file mode 100644 index 000000000..7a092010c --- /dev/null +++ b/src/bb-library/tutorial/makefont.php @@ -0,0 +1,6 @@ + diff --git a/src/bb-library/tutorial/tuto1.htm b/src/bb-library/tutorial/tuto1.htm new file mode 100644 index 000000000..0b95c9360 --- /dev/null +++ b/src/bb-library/tutorial/tuto1.htm @@ -0,0 +1,76 @@ + + + + +Minimal example + + + +

Minimal example

+Let's start with the classic example: +
+
<?php
+require('fpdf.php');
+
+$pdf = new FPDF();
+$pdf->AddPage();
+$pdf->SetFont('Arial','B',16);
+$pdf->Cell(40,10,'Hello World!');
+$pdf->Output();
+?>
+
+

[Demo]

+After including the library file, we create an FPDF object. +The constructor is used here with the default values: pages are in A4 portrait and +the unit of measure is millimeter. It could have been specified explicitly with: +
+
$pdf = new FPDF('P','mm','A4');
+
+
+It's possible to use landscape (L), other page sizes (such as Letter and +Legal) and units (pt, cm, in). +
+
+There's no page at the moment, so we have to add one with AddPage(). The origin +is at the upper-left corner and the current position is by default set at 1 cm from the +borders; the margins can be changed with SetMargins(). +
+
+Before we can print text, it's mandatory to select a font with SetFont(). +We choose Arial bold 16: +
+
$pdf->SetFont('Arial','B',16);
+
+
+We could have specified italics with I, underlined with U or a regular font with an empty string +(or any combination). Note that the font size is given in points, not millimeters (or another user +unit); it's the only exception. The other standard fonts are Times, Courier, Symbol and ZapfDingbats. +
+
+We can now print a cell with Cell(). A cell is a rectangular area, possibly framed, +which contains a line of text. It is output at the current position. We specify its dimensions, +its text (centered or aligned), if borders should be drawn, and where the current position +moves after it (to the right, below or to the beginning of the next line). To add a frame, we would do this: +
+
$pdf->Cell(40,10,'Hello World !',1);
+
+
+To add a new cell next to it with centered text and go to the next line, we would do: +
+
$pdf->Cell(60,10,'Powered by FPDF.',0,1,'C');
+
+
+Remark: the line break can also be done with Ln(). This method additionnaly allows to specify +the height of the break. +
+
+Finally, the document is closed and sent to the browser with Output(). We could have saved +it to a file by passing the appropriate parameters. +
+
+Caution: in case when the PDF is sent to the browser, nothing else must be output by the +script, neither before nor after (no HTML, not even a space or a carriage return). If you send something +before, you will get the error message: "Some data has already been output, can't send PDF file". If you +send something after, the document might not display. + + diff --git a/src/bb-library/tutorial/tuto1.php b/src/bb-library/tutorial/tuto1.php new file mode 100644 index 000000000..3ab55a106 --- /dev/null +++ b/src/bb-library/tutorial/tuto1.php @@ -0,0 +1,9 @@ +AddPage(); +$pdf->SetFont('Arial','B',16); +$pdf->Cell(40,10,'Hello World!'); +$pdf->Output(); +?> diff --git a/src/bb-library/tutorial/tuto2.htm b/src/bb-library/tutorial/tuto2.htm new file mode 100644 index 000000000..c402cf44b --- /dev/null +++ b/src/bb-library/tutorial/tuto2.htm @@ -0,0 +1,80 @@ + + + + +Header, footer, page break and image + + + +

Header, footer, page break and image

+Here's a two page example with header, footer and logo: +
+
<?php
+require('fpdf.php');
+
+class PDF extends FPDF
+{
+// Page header
+function Header()
+{
+    // Logo
+    $this->Image('logo.png',10,6,30);
+    // Arial bold 15
+    $this->SetFont('Arial','B',15);
+    // Move to the right
+    $this->Cell(80);
+    // Title
+    $this->Cell(30,10,'Title',1,0,'C');
+    // Line break
+    $this->Ln(20);
+}
+
+// Page footer
+function Footer()
+{
+    // Position at 1.5 cm from bottom
+    $this->SetY(-15);
+    // Arial italic 8
+    $this->SetFont('Arial','I',8);
+    // Page number
+    $this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
+}
+}
+
+// Instanciation of inherited class
+$pdf = new PDF();
+$pdf->AliasNbPages();
+$pdf->AddPage();
+$pdf->SetFont('Times','',12);
+for($i=1;$i<=40;$i++)
+    $pdf->Cell(0,10,'Printing line number '.$i,0,1);
+$pdf->Output();
+?>
+
+

[Demo]

+This example makes use of the Header() and Footer() methods to process page headers and +footers. They are called automatically. They already exist in the FPDF class but do nothing, +therefore we have to extend the class and override them. +
+
+The logo is printed with the Image() method by specifying its upper-left corner and +its width. The height is calculated automatically to respect the image proportions. +
+
+To print the page number, a null value is passed as the cell width. It means that the cell +should extend up to the right margin of the page; this is handy to center text. The current page +number is returned by the PageNo() method; as for the total number of pages, it's obtained +via the special value {nb} which is substituted when the document is finished +(provided you first called AliasNbPages()). +
+Note the use of the SetY() method which allows to set position at an absolute location in +the page, starting from the top or the bottom. +
+
+Another interesting feature is used here: the automatic page breaking. As soon as a cell would +cross a limit in the page (at 2 centimeters from the bottom by default), a break is issued +and the font restored. Although the header and footer select their own font (Arial), the body +continues with Times. This mechanism of automatic restoration also applies to colors and line +width. The limit which triggers page breaks can be set with SetAutoPageBreak(). + + diff --git a/src/bb-library/tutorial/tuto2.php b/src/bb-library/tutorial/tuto2.php new file mode 100644 index 000000000..6a1b4f863 --- /dev/null +++ b/src/bb-library/tutorial/tuto2.php @@ -0,0 +1,41 @@ +Image('logo.png',10,6,30); + // Arial bold 15 + $this->SetFont('Arial','B',15); + // Move to the right + $this->Cell(80); + // Title + $this->Cell(30,10,'Title',1,0,'C'); + // Line break + $this->Ln(20); +} + +// Page footer +function Footer() +{ + // Position at 1.5 cm from bottom + $this->SetY(-15); + // Arial italic 8 + $this->SetFont('Arial','I',8); + // Page number + $this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C'); +} +} + +// Instanciation of inherited class +$pdf = new PDF(); +$pdf->AliasNbPages(); +$pdf->AddPage(); +$pdf->SetFont('Times','',12); +for($i=1;$i<=40;$i++) + $pdf->Cell(0,10,'Printing line number '.$i,0,1); +$pdf->Output(); +?> diff --git a/src/bb-library/tutorial/tuto3.htm b/src/bb-library/tutorial/tuto3.htm new file mode 100644 index 000000000..5d8363f51 --- /dev/null +++ b/src/bb-library/tutorial/tuto3.htm @@ -0,0 +1,115 @@ + + + + +Line breaks and colors + + + +

Line breaks and colors

+Let's continue with an example which prints justified paragraphs. It also illustrates the use +of colors. +
+
<?php
+require('fpdf.php');
+
+class PDF extends FPDF
+{
+function Header()
+{
+    global $title;
+
+    // Arial bold 15
+    $this->SetFont('Arial','B',15);
+    // Calculate width of title and position
+    $w = $this->GetStringWidth($title)+6;
+    $this->SetX((210-$w)/2);
+    // Colors of frame, background and text
+    $this->SetDrawColor(0,80,180);
+    $this->SetFillColor(230,230,0);
+    $this->SetTextColor(220,50,50);
+    // Thickness of frame (1 mm)
+    $this->SetLineWidth(1);
+    // Title
+    $this->Cell($w,9,$title,1,1,'C',true);
+    // Line break
+    $this->Ln(10);
+}
+
+function Footer()
+{
+    // Position at 1.5 cm from bottom
+    $this->SetY(-15);
+    // Arial italic 8
+    $this->SetFont('Arial','I',8);
+    // Text color in gray
+    $this->SetTextColor(128);
+    // Page number
+    $this->Cell(0,10,'Page '.$this->PageNo(),0,0,'C');
+}
+
+function ChapterTitle($num, $label)
+{
+    // Arial 12
+    $this->SetFont('Arial','',12);
+    // Background color
+    $this->SetFillColor(200,220,255);
+    // Title
+    $this->Cell(0,6,"Chapter $num : $label",0,1,'L',true);
+    // Line break
+    $this->Ln(4);
+}
+
+function ChapterBody($file)
+{
+    // Read text file
+    $txt = file_get_contents($file);
+    // Times 12
+    $this->SetFont('Times','',12);
+    // Output justified text
+    $this->MultiCell(0,5,$txt);
+    // Line break
+    $this->Ln();
+    // Mention in italics
+    $this->SetFont('','I');
+    $this->Cell(0,5,'(end of excerpt)');
+}
+
+function PrintChapter($num, $title, $file)
+{
+    $this->AddPage();
+    $this->ChapterTitle($num,$title);
+    $this->ChapterBody($file);
+}
+}
+
+$pdf = new PDF();
+$title = '20000 Leagues Under the Seas';
+$pdf->SetTitle($title);
+$pdf->SetAuthor('Jules Verne');
+$pdf->PrintChapter(1,'A RUNAWAY REEF','20k_c1.txt');
+$pdf->PrintChapter(2,'THE PROS AND CONS','20k_c2.txt');
+$pdf->Output();
+?>
+
+

[Demo]

+The GetStringWidth() method allows to determine the length of a string in the current font, +which is used here to calculate the position and the width of the frame surrounding the title. +Then colors are set (via SetDrawColor(), SetFillColor() and SetTextColor()) and the +thickness of the line is set to 1 mm (instead of 0.2 by default) with SetLineWidth(). Finally, +we output the cell (the last parameter true indicates that the background must +be filled). +
+
+The method used to print the paragraphs is MultiCell(). Each time a line reaches the +right extremity of the cell or a carriage return character is met, a line break is issued +and a new cell automatically created under the current one. Text is justified by default. +
+
+Two document properties are defined: the title (SetTitle()) and the author (SetAuthor()). +There are several ways to view them in Adobe Reader. The first one is to open the file directly with +the reader, go to the File menu and choose the Properties option. The second one, also available from +the plug-in, is to right-click and select Document Properties. The third method is to type the Ctrl+D +key combination. + + diff --git a/src/bb-library/tutorial/tuto3.php b/src/bb-library/tutorial/tuto3.php new file mode 100644 index 000000000..3316ddb0c --- /dev/null +++ b/src/bb-library/tutorial/tuto3.php @@ -0,0 +1,81 @@ +SetFont('Arial','B',15); + // Calculate width of title and position + $w = $this->GetStringWidth($title)+6; + $this->SetX((210-$w)/2); + // Colors of frame, background and text + $this->SetDrawColor(0,80,180); + $this->SetFillColor(230,230,0); + $this->SetTextColor(220,50,50); + // Thickness of frame (1 mm) + $this->SetLineWidth(1); + // Title + $this->Cell($w,9,$title,1,1,'C',true); + // Line break + $this->Ln(10); +} + +function Footer() +{ + // Position at 1.5 cm from bottom + $this->SetY(-15); + // Arial italic 8 + $this->SetFont('Arial','I',8); + // Text color in gray + $this->SetTextColor(128); + // Page number + $this->Cell(0,10,'Page '.$this->PageNo(),0,0,'C'); +} + +function ChapterTitle($num, $label) +{ + // Arial 12 + $this->SetFont('Arial','',12); + // Background color + $this->SetFillColor(200,220,255); + // Title + $this->Cell(0,6,"Chapter $num : $label",0,1,'L',true); + // Line break + $this->Ln(4); +} + +function ChapterBody($file) +{ + // Read text file + $txt = file_get_contents($file); + // Times 12 + $this->SetFont('Times','',12); + // Output justified text + $this->MultiCell(0,5,$txt); + // Line break + $this->Ln(); + // Mention in italics + $this->SetFont('','I'); + $this->Cell(0,5,'(end of excerpt)'); +} + +function PrintChapter($num, $title, $file) +{ + $this->AddPage(); + $this->ChapterTitle($num,$title); + $this->ChapterBody($file); +} +} + +$pdf = new PDF(); +$title = '20000 Leagues Under the Seas'; +$pdf->SetTitle($title); +$pdf->SetAuthor('Jules Verne'); +$pdf->PrintChapter(1,'A RUNAWAY REEF','20k_c1.txt'); +$pdf->PrintChapter(2,'THE PROS AND CONS','20k_c2.txt'); +$pdf->Output(); +?> diff --git a/src/bb-library/tutorial/tuto4.htm b/src/bb-library/tutorial/tuto4.htm new file mode 100644 index 000000000..05ccde266 --- /dev/null +++ b/src/bb-library/tutorial/tuto4.htm @@ -0,0 +1,132 @@ + + + + +Multi-columns + + + +

Multi-columns

+This example is a variant of the previous one showing how to lay the text across multiple +columns. +
+
<?php
+require('fpdf.php');
+
+class PDF extends FPDF
+{
+protected $col = 0; // Current column
+protected $y0;      // Ordinate of column start
+
+function Header()
+{
+    // Page header
+    global $title;
+
+    $this->SetFont('Arial','B',15);
+    $w = $this->GetStringWidth($title)+6;
+    $this->SetX((210-$w)/2);
+    $this->SetDrawColor(0,80,180);
+    $this->SetFillColor(230,230,0);
+    $this->SetTextColor(220,50,50);
+    $this->SetLineWidth(1);
+    $this->Cell($w,9,$title,1,1,'C',true);
+    $this->Ln(10);
+    // Save ordinate
+    $this->y0 = $this->GetY();
+}
+
+function Footer()
+{
+    // Page footer
+    $this->SetY(-15);
+    $this->SetFont('Arial','I',8);
+    $this->SetTextColor(128);
+    $this->Cell(0,10,'Page '.$this->PageNo(),0,0,'C');
+}
+
+function SetCol($col)
+{
+    // Set position at a given column
+    $this->col = $col;
+    $x = 10+$col*65;
+    $this->SetLeftMargin($x);
+    $this->SetX($x);
+}
+
+function AcceptPageBreak()
+{
+    // Method accepting or not automatic page break
+    if($this->col<2)
+    {
+        // Go to next column
+        $this->SetCol($this->col+1);
+        // Set ordinate to top
+        $this->SetY($this->y0);
+        // Keep on page
+        return false;
+    }
+    else
+    {
+        // Go back to first column
+        $this->SetCol(0);
+        // Page break
+        return true;
+    }
+}
+
+function ChapterTitle($num, $label)
+{
+    // Title
+    $this->SetFont('Arial','',12);
+    $this->SetFillColor(200,220,255);
+    $this->Cell(0,6,"Chapter $num : $label",0,1,'L',true);
+    $this->Ln(4);
+    // Save ordinate
+    $this->y0 = $this->GetY();
+}
+
+function ChapterBody($file)
+{
+    // Read text file
+    $txt = file_get_contents($file);
+    // Font
+    $this->SetFont('Times','',12);
+    // Output text in a 6 cm width column
+    $this->MultiCell(60,5,$txt);
+    $this->Ln();
+    // Mention
+    $this->SetFont('','I');
+    $this->Cell(0,5,'(end of excerpt)');
+    // Go back to first column
+    $this->SetCol(0);
+}
+
+function PrintChapter($num, $title, $file)
+{
+    // Add chapter
+    $this->AddPage();
+    $this->ChapterTitle($num,$title);
+    $this->ChapterBody($file);
+}
+}
+
+$pdf = new PDF();
+$title = '20000 Leagues Under the Seas';
+$pdf->SetTitle($title);
+$pdf->SetAuthor('Jules Verne');
+$pdf->PrintChapter(1,'A RUNAWAY REEF','20k_c1.txt');
+$pdf->PrintChapter(2,'THE PROS AND CONS','20k_c2.txt');
+$pdf->Output();
+?>
+
+

[Demo]

+The key method used is AcceptPageBreak(). It allows to accept or not an automatic page +break. By refusing it and altering the margin and current position, the desired column layout +is achieved. +
+For the rest, not many changes; two properties have been added to the class to save the current +column number and the position where columns begin, and the MultiCell() call specifies a +6 centimeter width. + + diff --git a/src/bb-library/tutorial/tuto4.php b/src/bb-library/tutorial/tuto4.php new file mode 100644 index 000000000..c39b42c92 --- /dev/null +++ b/src/bb-library/tutorial/tuto4.php @@ -0,0 +1,109 @@ +SetFont('Arial','B',15); + $w = $this->GetStringWidth($title)+6; + $this->SetX((210-$w)/2); + $this->SetDrawColor(0,80,180); + $this->SetFillColor(230,230,0); + $this->SetTextColor(220,50,50); + $this->SetLineWidth(1); + $this->Cell($w,9,$title,1,1,'C',true); + $this->Ln(10); + // Save ordinate + $this->y0 = $this->GetY(); +} + +function Footer() +{ + // Page footer + $this->SetY(-15); + $this->SetFont('Arial','I',8); + $this->SetTextColor(128); + $this->Cell(0,10,'Page '.$this->PageNo(),0,0,'C'); +} + +function SetCol($col) +{ + // Set position at a given column + $this->col = $col; + $x = 10+$col*65; + $this->SetLeftMargin($x); + $this->SetX($x); +} + +function AcceptPageBreak() +{ + // Method accepting or not automatic page break + if($this->col<2) + { + // Go to next column + $this->SetCol($this->col+1); + // Set ordinate to top + $this->SetY($this->y0); + // Keep on page + return false; + } + else + { + // Go back to first column + $this->SetCol(0); + // Page break + return true; + } +} + +function ChapterTitle($num, $label) +{ + // Title + $this->SetFont('Arial','',12); + $this->SetFillColor(200,220,255); + $this->Cell(0,6,"Chapter $num : $label",0,1,'L',true); + $this->Ln(4); + // Save ordinate + $this->y0 = $this->GetY(); +} + +function ChapterBody($file) +{ + // Read text file + $txt = file_get_contents($file); + // Font + $this->SetFont('Times','',12); + // Output text in a 6 cm width column + $this->MultiCell(60,5,$txt); + $this->Ln(); + // Mention + $this->SetFont('','I'); + $this->Cell(0,5,'(end of excerpt)'); + // Go back to first column + $this->SetCol(0); +} + +function PrintChapter($num, $title, $file) +{ + // Add chapter + $this->AddPage(); + $this->ChapterTitle($num,$title); + $this->ChapterBody($file); +} +} + +$pdf = new PDF(); +$title = '20000 Leagues Under the Seas'; +$pdf->SetTitle($title); +$pdf->SetAuthor('Jules Verne'); +$pdf->PrintChapter(1,'A RUNAWAY REEF','20k_c1.txt'); +$pdf->PrintChapter(2,'THE PROS AND CONS','20k_c2.txt'); +$pdf->Output(); +?> diff --git a/src/bb-library/tutorial/tuto5.htm b/src/bb-library/tutorial/tuto5.htm new file mode 100644 index 000000000..f90102bde --- /dev/null +++ b/src/bb-library/tutorial/tuto5.htm @@ -0,0 +1,134 @@ + + + + +Tables + + + +

Tables

+This tutorial shows different ways to make tables. +
+
<?php
+require('fpdf.php');
+
+class PDF extends FPDF
+{
+// Load data
+function LoadData($file)
+{
+    // Read file lines
+    $lines = file($file);
+    $data = array();
+    foreach($lines as $line)
+        $data[] = explode(';',trim($line));
+    return $data;
+}
+
+// Simple table
+function BasicTable($header, $data)
+{
+    // Header
+    foreach($header as $col)
+        $this->Cell(40,7,$col,1);
+    $this->Ln();
+    // Data
+    foreach($data as $row)
+    {
+        foreach($row as $col)
+            $this->Cell(40,6,$col,1);
+        $this->Ln();
+    }
+}
+
+// Better table
+function ImprovedTable($header, $data)
+{
+    // Column widths
+    $w = array(40, 35, 40, 45);
+    // Header
+    for($i=0;$i<count($header);$i++)
+        $this->Cell($w[$i],7,$header[$i],1,0,'C');
+    $this->Ln();
+    // Data
+    foreach($data as $row)
+    {
+        $this->Cell($w[0],6,$row[0],'LR');
+        $this->Cell($w[1],6,$row[1],'LR');
+        $this->Cell($w[2],6,number_format($row[2]),'LR',0,'R');
+        $this->Cell($w[3],6,number_format($row[3]),'LR',0,'R');
+        $this->Ln();
+    }
+    // Closing line
+    $this->Cell(array_sum($w),0,'','T');
+}
+
+// Colored table
+function FancyTable($header, $data)
+{
+    // Colors, line width and bold font
+    $this->SetFillColor(255,0,0);
+    $this->SetTextColor(255);
+    $this->SetDrawColor(128,0,0);
+    $this->SetLineWidth(.3);
+    $this->SetFont('','B');
+    // Header
+    $w = array(40, 35, 40, 45);
+    for($i=0;$i<count($header);$i++)
+        $this->Cell($w[$i],7,$header[$i],1,0,'C',true);
+    $this->Ln();
+    // Color and font restoration
+    $this->SetFillColor(224,235,255);
+    $this->SetTextColor(0);
+    $this->SetFont('');
+    // Data
+    $fill = false;
+    foreach($data as $row)
+    {
+        $this->Cell($w[0],6,$row[0],'LR',0,'L',$fill);
+        $this->Cell($w[1],6,$row[1],'LR',0,'L',$fill);
+        $this->Cell($w[2],6,number_format($row[2]),'LR',0,'R',$fill);
+        $this->Cell($w[3],6,number_format($row[3]),'LR',0,'R',$fill);
+        $this->Ln();
+        $fill = !$fill;
+    }
+    // Closing line
+    $this->Cell(array_sum($w),0,'','T');
+}
+}
+
+$pdf = new PDF();
+// Column headings
+$header = array('Country', 'Capital', 'Area (sq km)', 'Pop. (thousands)');
+// Data loading
+$data = $pdf->LoadData('countries.txt');
+$pdf->SetFont('Arial','',14);
+$pdf->AddPage();
+$pdf->BasicTable($header,$data);
+$pdf->AddPage();
+$pdf->ImprovedTable($header,$data);
+$pdf->AddPage();
+$pdf->FancyTable($header,$data);
+$pdf->Output();
+?>
+
+

[Demo]

+A table being just a collection of cells, it's natural to build one from them. The first +example is achieved in the most basic way possible: simple framed cells, all of the same size +and left aligned. The result is rudimentary but very quick to obtain. +
+
+The second table brings some improvements: each column has its own width, headings are centered, +and numbers right aligned. Moreover, horizontal lines have been removed. This is done by means +of the border parameter of the Cell() method, which specifies which sides of the +cell must be drawn. Here we want the left (L) and right (R) ones. It remains +the problem of the horizontal line to finish the table. There are two possibilities: either +check for the last line in the loop, in which case we use LRB for the border +parameter; or, as done here, add the line once the loop is over. +
+
+The third table is similar to the second one but uses colors. Fill, text and line colors are +simply specified. Alternate coloring for rows is obtained by using alternatively transparent +and filled cells. + + diff --git a/src/bb-library/tutorial/tuto5.php b/src/bb-library/tutorial/tuto5.php new file mode 100644 index 000000000..252b70f2e --- /dev/null +++ b/src/bb-library/tutorial/tuto5.php @@ -0,0 +1,102 @@ +Cell(40,7,$col,1); + $this->Ln(); + // Data + foreach($data as $row) + { + foreach($row as $col) + $this->Cell(40,6,$col,1); + $this->Ln(); + } +} + +// Better table +function ImprovedTable($header, $data) +{ + // Column widths + $w = array(40, 35, 40, 45); + // Header + for($i=0;$iCell($w[$i],7,$header[$i],1,0,'C'); + $this->Ln(); + // Data + foreach($data as $row) + { + $this->Cell($w[0],6,$row[0],'LR'); + $this->Cell($w[1],6,$row[1],'LR'); + $this->Cell($w[2],6,number_format($row[2]),'LR',0,'R'); + $this->Cell($w[3],6,number_format($row[3]),'LR',0,'R'); + $this->Ln(); + } + // Closing line + $this->Cell(array_sum($w),0,'','T'); +} + +// Colored table +function FancyTable($header, $data) +{ + // Colors, line width and bold font + $this->SetFillColor(255,0,0); + $this->SetTextColor(255); + $this->SetDrawColor(128,0,0); + $this->SetLineWidth(.3); + $this->SetFont('','B'); + // Header + $w = array(40, 35, 40, 45); + for($i=0;$iCell($w[$i],7,$header[$i],1,0,'C',true); + $this->Ln(); + // Color and font restoration + $this->SetFillColor(224,235,255); + $this->SetTextColor(0); + $this->SetFont(''); + // Data + $fill = false; + foreach($data as $row) + { + $this->Cell($w[0],6,$row[0],'LR',0,'L',$fill); + $this->Cell($w[1],6,$row[1],'LR',0,'L',$fill); + $this->Cell($w[2],6,number_format($row[2]),'LR',0,'R',$fill); + $this->Cell($w[3],6,number_format($row[3]),'LR',0,'R',$fill); + $this->Ln(); + $fill = !$fill; + } + // Closing line + $this->Cell(array_sum($w),0,'','T'); +} +} + +$pdf = new PDF(); +// Column headings +$header = array('Country', 'Capital', 'Area (sq km)', 'Pop. (thousands)'); +// Data loading +$data = $pdf->LoadData('countries.txt'); +$pdf->SetFont('Arial','',14); +$pdf->AddPage(); +$pdf->BasicTable($header,$data); +$pdf->AddPage(); +$pdf->ImprovedTable($header,$data); +$pdf->AddPage(); +$pdf->FancyTable($header,$data); +$pdf->Output(); +?> diff --git a/src/bb-library/tutorial/tuto6.htm b/src/bb-library/tutorial/tuto6.htm new file mode 100644 index 000000000..602a119e2 --- /dev/null +++ b/src/bb-library/tutorial/tuto6.htm @@ -0,0 +1,154 @@ + + + + +Links and flowing text + + + +

Links and flowing text

+This tutorial explains how to insert links (internal and external) and shows a new text writing +mode. It also contains a basic HTML parser. +
+
<?php
+require('fpdf.php');
+
+class PDF extends FPDF
+{
+protected $B = 0;
+protected $I = 0;
+protected $U = 0;
+protected $HREF = '';
+
+function WriteHTML($html)
+{
+    // HTML parser
+    $html = str_replace("\n",' ',$html);
+    $a = preg_split('/<(.*)>/U',$html,-1,PREG_SPLIT_DELIM_CAPTURE);
+    foreach($a as $i=>$e)
+    {
+        if($i%2==0)
+        {
+            // Text
+            if($this->HREF)
+                $this->PutLink($this->HREF,$e);
+            else
+                $this->Write(5,$e);
+        }
+        else
+        {
+            // Tag
+            if($e[0]=='/')
+                $this->CloseTag(strtoupper(substr($e,1)));
+            else
+            {
+                // Extract attributes
+                $a2 = explode(' ',$e);
+                $tag = strtoupper(array_shift($a2));
+                $attr = array();
+                foreach($a2 as $v)
+                {
+                    if(preg_match('/([^=]*)=["\']?([^"\']*)/',$v,$a3))
+                        $attr[strtoupper($a3[1])] = $a3[2];
+                }
+                $this->OpenTag($tag,$attr);
+            }
+        }
+    }
+}
+
+function OpenTag($tag, $attr)
+{
+    // Opening tag
+    if($tag=='B' || $tag=='I' || $tag=='U')
+        $this->SetStyle($tag,true);
+    if($tag=='A')
+        $this->HREF = $attr['HREF'];
+    if($tag=='BR')
+        $this->Ln(5);
+}
+
+function CloseTag($tag)
+{
+    // Closing tag
+    if($tag=='B' || $tag=='I' || $tag=='U')
+        $this->SetStyle($tag,false);
+    if($tag=='A')
+        $this->HREF = '';
+}
+
+function SetStyle($tag, $enable)
+{
+    // Modify style and select corresponding font
+    $this->$tag += ($enable ? 1 : -1);
+    $style = '';
+    foreach(array('B', 'I', 'U') as $s)
+    {
+        if($this->$s>0)
+            $style .= $s;
+    }
+    $this->SetFont('',$style);
+}
+
+function PutLink($URL, $txt)
+{
+    // Put a hyperlink
+    $this->SetTextColor(0,0,255);
+    $this->SetStyle('U',true);
+    $this->Write(5,$txt,$URL);
+    $this->SetStyle('U',false);
+    $this->SetTextColor(0);
+}
+}
+
+$html = 'You can now easily print text mixing different styles: <b>bold</b>, <i>italic</i>,
+<u>underlined</u>, or <b><i><u>all at once</u></i></b>!<br><br>You can also insert links on
+text, such as <a href="http://www.fpdf.org">www.fpdf.org</a>, or on an image: click on the logo.';
+
+$pdf = new PDF();
+// First page
+$pdf->AddPage();
+$pdf->SetFont('Arial','',20);
+$pdf->Write(5,"To find out what's new in this tutorial, click ");
+$pdf->SetFont('','U');
+$link = $pdf->AddLink();
+$pdf->Write(5,'here',$link);
+$pdf->SetFont('');
+// Second page
+$pdf->AddPage();
+$pdf->SetLink($link);
+$pdf->Image('logo.png',10,12,30,0,'','http://www.fpdf.org');
+$pdf->SetLeftMargin(45);
+$pdf->SetFontSize(14);
+$pdf->WriteHTML($html);
+$pdf->Output();
+?>
+
+

[Demo]

+The new method to print text is Write(). It's very close to MultiCell(); the differences are: +
    +
  • The end of line is at the right margin and the next line begins at the left one
  • +
  • The current position moves at the end of the text
  • +
+So it allows to write a chunk of text, alter the font style, then continue from the exact +place we left it. On the other hand, you cannot justify it. +
+
+The method is used on the first page to put a link pointing to the second one. The beginning of +the sentence is written in regular style, then we switch to underline and finish it. The link +is created with AddLink(), which returns a link identifier. The identifier is +passed as third parameter of Write(). Once the second page is created, we use SetLink() to +make the link point to the beginning of the current page. +
+
+Then we put an image with an external link on it. An external link is just a URL. It's passed as +last parameter of Image(). +
+
+Finally, the left margin is moved after the image with SetLeftMargin() and some text in +HTML format is output. A very simple HTML parser is used for this, based on regular expressions. +Recognized tags are <b>, <i>, <u>, <a> and <br>; the others are +ignored. The parser also makes use of the Write() method. An external link is put the same way as +an internal one (third parameter of Write()). Note that Cell() also allows to put links. + + diff --git a/src/bb-library/tutorial/tuto6.php b/src/bb-library/tutorial/tuto6.php new file mode 100644 index 000000000..427e4d34a --- /dev/null +++ b/src/bb-library/tutorial/tuto6.php @@ -0,0 +1,113 @@ +/U',$html,-1,PREG_SPLIT_DELIM_CAPTURE); + foreach($a as $i=>$e) + { + if($i%2==0) + { + // Text + if($this->HREF) + $this->PutLink($this->HREF,$e); + else + $this->Write(5,$e); + } + else + { + // Tag + if($e[0]=='/') + $this->CloseTag(strtoupper(substr($e,1))); + else + { + // Extract attributes + $a2 = explode(' ',$e); + $tag = strtoupper(array_shift($a2)); + $attr = array(); + foreach($a2 as $v) + { + if(preg_match('/([^=]*)=["\']?([^"\']*)/',$v,$a3)) + $attr[strtoupper($a3[1])] = $a3[2]; + } + $this->OpenTag($tag,$attr); + } + } + } +} + +function OpenTag($tag, $attr) +{ + // Opening tag + if($tag=='B' || $tag=='I' || $tag=='U') + $this->SetStyle($tag,true); + if($tag=='A') + $this->HREF = $attr['HREF']; + if($tag=='BR') + $this->Ln(5); +} + +function CloseTag($tag) +{ + // Closing tag + if($tag=='B' || $tag=='I' || $tag=='U') + $this->SetStyle($tag,false); + if($tag=='A') + $this->HREF = ''; +} + +function SetStyle($tag, $enable) +{ + // Modify style and select corresponding font + $this->$tag += ($enable ? 1 : -1); + $style = ''; + foreach(array('B', 'I', 'U') as $s) + { + if($this->$s>0) + $style .= $s; + } + $this->SetFont('',$style); +} + +function PutLink($URL, $txt) +{ + // Put a hyperlink + $this->SetTextColor(0,0,255); + $this->SetStyle('U',true); + $this->Write(5,$txt,$URL); + $this->SetStyle('U',false); + $this->SetTextColor(0); +} +} + +$html = 'You can now easily print text mixing different styles: bold, italic, +underlined, or all at once!

You can also insert links on +text, such as www.fpdf.org, or on an image: click on the logo.'; + +$pdf = new PDF(); +// First page +$pdf->AddPage(); +$pdf->SetFont('Arial','',20); +$pdf->Write(5,"To find out what's new in this tutorial, click "); +$pdf->SetFont('','U'); +$link = $pdf->AddLink(); +$pdf->Write(5,'here',$link); +$pdf->SetFont(''); +// Second page +$pdf->AddPage(); +$pdf->SetLink($link); +$pdf->Image('logo.png',10,12,30,0,'','http://www.fpdf.org'); +$pdf->SetLeftMargin(45); +$pdf->SetFontSize(14); +$pdf->WriteHTML($html); +$pdf->Output(); +?> diff --git a/src/bb-library/tutorial/tuto7.htm b/src/bb-library/tutorial/tuto7.htm new file mode 100644 index 000000000..146a952b6 --- /dev/null +++ b/src/bb-library/tutorial/tuto7.htm @@ -0,0 +1,187 @@ + + + + +Adding new fonts and encodings + + + +

Adding new fonts and encodings

+This tutorial explains how to use TrueType, OpenType and Type1 fonts so that you are not limited to the +standard fonts anymore. The other benefit is that you can choose the text encoding, which allows you to +use other languages than the Western ones (the standard fonts support only cp1252 aka windows-1252). +
+
+For OpenType, only the format based on TrueType is supported (not the one based on Type1).
+For Type1, you will need the corresponding AFM file (it is usually provided with the font). +
+
+Adding a new font requires two steps: +
    +
  • Generation of the font definition file
  • +
  • Declaration of the font in the script
  • +
+ +

Generation of the font definition file

+The first step consists in generating a PHP file containing all the information needed by FPDF; +in addition, the font file is compressed. To do this, a helper script is provided in the makefont +directory of the package: makefont.php. It contains the following function: +
+
+MakeFont(string fontfile [, string enc [, boolean embed [, boolean subset]]]) +
+
fontfile
+
+

Path to the .ttf, .otf or .pfb file.

+
+
enc
+
+

Name of the encoding to use. Default value: cp1252.

+
+
embed
+
+

Whether to embed the font or not. Default value: true.

+
+
subset
+
+

Whether to subset the font or not. Default value: true.

+
+
+The first parameter is the name of the font file. The extension must be either .ttf, .otf or .pfb and +determines the font type. If your Type1 font is in ASCII format (.pfa), you can convert it to binary +(.pfb) with the help of t1utils. +
+
+For Type1 fonts, the corresponding .afm file must be present in the same directory. +
+
+The encoding defines the association between a code (from 0 to 255) and a character. The first 128 are +always the same and correspond to ASCII; the following are variable. Encodings are stored in .map +files. The available ones are: +
    +
  • cp1250 (Central Europe)
  • +
  • cp1251 (Cyrillic)
  • +
  • cp1252 (Western Europe)
  • +
  • cp1253 (Greek)
  • +
  • cp1254 (Turkish)
  • +
  • cp1255 (Hebrew)
  • +
  • cp1257 (Baltic)
  • +
  • cp1258 (Vietnamese)
  • +
  • cp874 (Thai)
  • +
  • ISO-8859-1 (Western Europe)
  • +
  • ISO-8859-2 (Central Europe)
  • +
  • ISO-8859-4 (Baltic)
  • +
  • ISO-8859-5 (Cyrillic)
  • +
  • ISO-8859-7 (Greek)
  • +
  • ISO-8859-9 (Turkish)
  • +
  • ISO-8859-11 (Thai)
  • +
  • ISO-8859-15 (Western Europe)
  • +
  • ISO-8859-16 (Central Europe)
  • +
  • KOI8-R (Russian)
  • +
  • KOI8-U (Ukrainian)
  • +
+Of course, the font must contain the characters corresponding to the selected encoding. +
+
+The third parameter indicates whether the font should be embedded in the PDF or not. When a font is +not embedded, it is searched in the system. The advantage is that the PDF file is smaller; on the +other hand, if it is not available, then a substitution font is used. So you should ensure that the +needed font is installed on the client systems. Embedding is the recommended option to guarantee a +correct rendering. +
+
+The last parameter indicates whether subsetting should be used, that is to say, whether only +the characters from the selected encoding should be kept in the embedded font. As a result, +the size of the PDF file can be greatly reduced, especially if the original font was big. +
+
+After you have called the function (create a new file for this and include makefont.php), a .php file +is created, with the same name as the font file. You may rename it if you wish. If the case of embedding, +the font file is compressed and gives a second file with .z as extension (except if the compression +function is not available, it requires Zlib). You may rename it too, but in this case you have to change +the variable $file in the .php file accordingly. +
+
+Example: +
+
<?php
+require('makefont/makefont.php');
+
+MakeFont('C:\\Windows\\Fonts\\comic.ttf','cp1252');
+?>
+
+which gives the files comic.php and comic.z. +
+
+Then copy the generated files to the font directory. If the font file could not be compressed, copy +it directly instead of the .z version. +
+
+Another way to call MakeFont() is through the command line: +
+
+php makefont\makefont.php C:\Windows\Fonts\comic.ttf cp1252 +
+
+Finally, for TrueType and OpenType fonts, you can also generate the files +online instead of doing it manually. + +

Declaration of the font in the script

+The second step is simple. You just need to call the AddFont() method: +
+
$pdf->AddFont('Comic','','comic.php');
+
+
+And the font is now available (in regular and underlined styles), usable like the others. If we +had worked with Comic Sans MS Bold (comicbd.ttf), we would have written: +
+
$pdf->AddFont('Comic','B','comicbd.php');
+
+
+ +

Example

+Let's now see a complete example. We will use the font Calligrapher. +The first step is the generation of the font files: +
+
<?php
+require('makefont/makefont.php');
+
+MakeFont('calligra.ttf','cp1252');
+?>
+
+The script gives the following report: +
+
+Warning: character Euro is missing
+Warning: character zcaron is missing
+Font file compressed: calligra.z
+Font definition file generated: calligra.php
+
+The euro character is not present in the font (it's too old). Another character is missing too. +
+
+Alternatively we could have used the command line: +
+
+php makefont\makefont.php calligra.ttf cp1252 +
+
+or used the online generator. +
+
+We can now copy the two generated files to the font directory and write the script: +
+
<?php
+require('fpdf.php');
+
+$pdf = new FPDF();
+$pdf->AddFont('Calligrapher','','calligra.php');
+$pdf->AddPage();
+$pdf->SetFont('Calligrapher','',35);
+$pdf->Write(10,'Enjoy new fonts with FPDF!');
+$pdf->Output();
+?>
+
+

[Demo]

+ + diff --git a/src/bb-library/tutorial/tuto7.php b/src/bb-library/tutorial/tuto7.php new file mode 100644 index 000000000..a7acb47f4 --- /dev/null +++ b/src/bb-library/tutorial/tuto7.php @@ -0,0 +1,11 @@ +AddFont('Calligrapher','','calligra.php'); +$pdf->AddPage(); +$pdf->SetFont('Calligrapher','',35); +$pdf->Cell(0,10,'Enjoy new fonts with FPDF!'); +$pdf->Output(); +?> diff --git a/src/bb-load.php b/src/bb-load.php index f17b77547..bfd1eab55 100644 --- a/src/bb-load.php +++ b/src/bb-load.php @@ -89,7 +89,7 @@ if((isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST']) || (php_sapi_name() = if(file_exists($predictConfigPath)) { $configPath = $predictConfigPath; } -} + // check if config is available if(!file_exists($configPath) || 0 == filesize( $configPath )) { diff --git a/src/bb-modules/Theme/Service.php b/src/bb-modules/Theme/Service.php index dac5bc9f4..dd4085cee 100644 --- a/src/bb-modules/Theme/Service.php +++ b/src/bb-modules/Theme/Service.php @@ -277,7 +277,6 @@ class Service implements InjectionAwareInterface if ($handle = opendir($path)) { while (false !== ($file = readdir($handle))) { if (is_dir($path . DIRECTORY_SEPARATOR . $file) && $file[0] != '.') { - try { if (!$client && strpos($file, 'admin') !== false) { $list[] = $this->_loadTheme($file); @@ -383,4 +382,4 @@ class Service implements InjectionAwareInterface return $config; } -} \ No newline at end of file +} diff --git a/src/bb-vendor/autoload.php b/src/bb-vendor/autoload.php new file mode 100644 index 000000000..04abfc33f --- /dev/null +++ b/src/bb-vendor/autoload.php @@ -0,0 +1,7 @@ + $vendorDir . '/ralouphie/getallheaders/src/getallheaders.php', + '320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php', + '0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php', + 'c964ee0ededf28c96ebd9db5099ef910' => $vendorDir . '/guzzlehttp/promises/src/functions_include.php', + 'a0edc8309cc5e1d60e3047b5df6b7052' => $vendorDir . '/guzzlehttp/psr7/src/functions_include.php', + '6124b4c8570aa390c21fafd04a26c69f' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/deep_copy.php', + '37a3dc5111fe8f707ab4c132ef1dbc62' => $vendorDir . '/guzzlehttp/guzzle/src/functions_include.php', + 'e40631d46120a9c38ea139981f8dab26' => $vendorDir . '/ircmaxell/password-compat/lib/password.php', + '04c6c5c2f7095ccf6c481d3e53e1776f' => $vendorDir . '/mustangostang/spyc/Spyc.php', +); diff --git a/src/bb-vendor/composer/autoload_namespaces.php b/src/bb-vendor/composer/autoload_namespaces.php new file mode 100644 index 000000000..0d3dcabcb --- /dev/null +++ b/src/bb-vendor/composer/autoload_namespaces.php @@ -0,0 +1,18 @@ + array($vendorDir . '/twig/extensions/lib'), + 'Twig_' => array($vendorDir . '/twig/twig/lib'), + 'Pimple' => array($vendorDir . '/pimple/pimple/src'), + 'Michelf' => array($vendorDir . '/michelf/php-markdown'), + 'JsonSerializable' => array($vendorDir . '/geoip2/geoip2/compat'), + 'Guzzle\\Tests' => array($vendorDir . '/guzzle/guzzle/tests'), + 'Guzzle' => array($vendorDir . '/guzzle/guzzle/src'), + 'GeoIp2' => array($vendorDir . '/geoip2/geoip2/src'), + '' => array($baseDir . '/bb-library'), +); diff --git a/src/bb-vendor/composer/autoload_psr4.php b/src/bb-vendor/composer/autoload_psr4.php new file mode 100644 index 000000000..db2aa42c7 --- /dev/null +++ b/src/bb-vendor/composer/autoload_psr4.php @@ -0,0 +1,28 @@ + array($vendorDir . '/setasign/fpdi/src'), + 'Twig\\Extensions\\' => array($vendorDir . '/twig/extensions/src'), + 'Twig\\' => array($vendorDir . '/twig/twig/src'), + 'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'), + 'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'), + 'Symfony\\Component\\EventDispatcher\\' => array($vendorDir . '/symfony/event-dispatcher'), + 'Stripe\\' => array($vendorDir . '/stripe/stripe-php/lib'), + 'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'), + 'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src'), + 'Psr\\Http\\Client\\' => array($vendorDir . '/psr/http-client/src'), + 'Psr\\Container\\' => array($vendorDir . '/psr/container/src'), + 'PHPMailer\\PHPMailer\\' => array($vendorDir . '/phpmailer/phpmailer/src'), + 'Mpdf\\' => array($vendorDir . '/mpdf/mpdf/src'), + 'MaxMind\\Db\\' => array($vendorDir . '/maxmind-db/reader/src/MaxMind/Db'), + 'GuzzleHttp\\Psr7\\' => array($vendorDir . '/guzzlehttp/psr7/src'), + 'GuzzleHttp\\Promise\\' => array($vendorDir . '/guzzlehttp/promises/src'), + 'GuzzleHttp\\' => array($vendorDir . '/guzzlehttp/guzzle/src'), + 'DeepCopy\\' => array($vendorDir . '/myclabs/deep-copy/src/DeepCopy'), + 'Box\\Mod\\' => array($baseDir . '/bb-modules'), +); diff --git a/src/bb-vendor/composer/autoload_real.php b/src/bb-vendor/composer/autoload_real.php new file mode 100644 index 000000000..737bedb54 --- /dev/null +++ b/src/bb-vendor/composer/autoload_real.php @@ -0,0 +1,73 @@ += 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded()); + if ($useStaticLoader) { + require_once __DIR__ . '/autoload_static.php'; + + call_user_func(\Composer\Autoload\ComposerStaticInitd025dea45a31447fa4961b5fce4f57c3::getInitializer($loader)); + } else { + $map = require __DIR__ . '/autoload_namespaces.php'; + foreach ($map as $namespace => $path) { + $loader->set($namespace, $path); + } + + $map = require __DIR__ . '/autoload_psr4.php'; + foreach ($map as $namespace => $path) { + $loader->setPsr4($namespace, $path); + } + + $classMap = require __DIR__ . '/autoload_classmap.php'; + if ($classMap) { + $loader->addClassMap($classMap); + } + } + + $loader->register(true); + + if ($useStaticLoader) { + $includeFiles = Composer\Autoload\ComposerStaticInitd025dea45a31447fa4961b5fce4f57c3::$files; + } else { + $includeFiles = require __DIR__ . '/autoload_files.php'; + } + foreach ($includeFiles as $fileIdentifier => $file) { + composerRequired025dea45a31447fa4961b5fce4f57c3($fileIdentifier, $file); + } + + return $loader; + } +} + +function composerRequired025dea45a31447fa4961b5fce4f57c3($fileIdentifier, $file) +{ + if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { + require $file; + + $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; + } +} diff --git a/src/bb-vendor/composer/autoload_static.php b/src/bb-vendor/composer/autoload_static.php new file mode 100644 index 000000000..af13c348f --- /dev/null +++ b/src/bb-vendor/composer/autoload_static.php @@ -0,0 +1,210 @@ + __DIR__ . '/..' . '/ralouphie/getallheaders/src/getallheaders.php', + '320cde22f66dd4f5d3fd621d3e88b98f' => __DIR__ . '/..' . '/symfony/polyfill-ctype/bootstrap.php', + '0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php', + 'c964ee0ededf28c96ebd9db5099ef910' => __DIR__ . '/..' . '/guzzlehttp/promises/src/functions_include.php', + 'a0edc8309cc5e1d60e3047b5df6b7052' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/functions_include.php', + '6124b4c8570aa390c21fafd04a26c69f' => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy/deep_copy.php', + '37a3dc5111fe8f707ab4c132ef1dbc62' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/functions_include.php', + 'e40631d46120a9c38ea139981f8dab26' => __DIR__ . '/..' . '/ircmaxell/password-compat/lib/password.php', + '04c6c5c2f7095ccf6c481d3e53e1776f' => __DIR__ . '/..' . '/mustangostang/spyc/Spyc.php', + ); + + public static $prefixLengthsPsr4 = array ( + 's' => + array ( + 'setasign\\Fpdi\\' => 14, + ), + 'T' => + array ( + 'Twig\\Extensions\\' => 16, + 'Twig\\' => 5, + ), + 'S' => + array ( + 'Symfony\\Polyfill\\Mbstring\\' => 26, + 'Symfony\\Polyfill\\Ctype\\' => 23, + 'Symfony\\Component\\EventDispatcher\\' => 34, + 'Stripe\\' => 7, + ), + 'P' => + array ( + 'Psr\\Log\\' => 8, + 'Psr\\Http\\Message\\' => 17, + 'Psr\\Http\\Client\\' => 16, + 'Psr\\Container\\' => 14, + 'PHPMailer\\PHPMailer\\' => 20, + ), + 'M' => + array ( + 'Mpdf\\' => 5, + 'MaxMind\\Db\\' => 11, + ), + 'G' => + array ( + 'GuzzleHttp\\Psr7\\' => 16, + 'GuzzleHttp\\Promise\\' => 19, + 'GuzzleHttp\\' => 11, + ), + 'D' => + array ( + 'DeepCopy\\' => 9, + ), + 'B' => + array ( + 'Box\\Mod\\' => 8, + ), + ); + + public static $prefixDirsPsr4 = array ( + 'setasign\\Fpdi\\' => + array ( + 0 => __DIR__ . '/..' . '/setasign/fpdi/src', + ), + 'Twig\\Extensions\\' => + array ( + 0 => __DIR__ . '/..' . '/twig/extensions/src', + ), + 'Twig\\' => + array ( + 0 => __DIR__ . '/..' . '/twig/twig/src', + ), + 'Symfony\\Polyfill\\Mbstring\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring', + ), + 'Symfony\\Polyfill\\Ctype\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-ctype', + ), + 'Symfony\\Component\\EventDispatcher\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/event-dispatcher', + ), + 'Stripe\\' => + array ( + 0 => __DIR__ . '/..' . '/stripe/stripe-php/lib', + ), + 'Psr\\Log\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/log/Psr/Log', + ), + 'Psr\\Http\\Message\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/http-message/src', + ), + 'Psr\\Http\\Client\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/http-client/src', + ), + 'Psr\\Container\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/container/src', + ), + 'PHPMailer\\PHPMailer\\' => + array ( + 0 => __DIR__ . '/..' . '/phpmailer/phpmailer/src', + ), + 'Mpdf\\' => + array ( + 0 => __DIR__ . '/..' . '/mpdf/mpdf/src', + ), + 'MaxMind\\Db\\' => + array ( + 0 => __DIR__ . '/..' . '/maxmind-db/reader/src/MaxMind/Db', + ), + 'GuzzleHttp\\Psr7\\' => + array ( + 0 => __DIR__ . '/..' . '/guzzlehttp/psr7/src', + ), + 'GuzzleHttp\\Promise\\' => + array ( + 0 => __DIR__ . '/..' . '/guzzlehttp/promises/src', + ), + 'GuzzleHttp\\' => + array ( + 0 => __DIR__ . '/..' . '/guzzlehttp/guzzle/src', + ), + 'DeepCopy\\' => + array ( + 0 => __DIR__ . '/..' . '/myclabs/deep-copy/src/DeepCopy', + ), + 'Box\\Mod\\' => + array ( + 0 => __DIR__ . '/../..' . '/bb-modules', + ), + ); + + public static $prefixesPsr0 = array ( + 'T' => + array ( + 'Twig_Extensions_' => + array ( + 0 => __DIR__ . '/..' . '/twig/extensions/lib', + ), + 'Twig_' => + array ( + 0 => __DIR__ . '/..' . '/twig/twig/lib', + ), + ), + 'P' => + array ( + 'Pimple' => + array ( + 0 => __DIR__ . '/..' . '/pimple/pimple/src', + ), + ), + 'M' => + array ( + 'Michelf' => + array ( + 0 => __DIR__ . '/..' . '/michelf/php-markdown', + ), + ), + 'J' => + array ( + 'JsonSerializable' => + array ( + 0 => __DIR__ . '/..' . '/geoip2/geoip2/compat', + ), + ), + 'G' => + array ( + 'Guzzle\\Tests' => + array ( + 0 => __DIR__ . '/..' . '/guzzle/guzzle/tests', + ), + 'Guzzle' => + array ( + 0 => __DIR__ . '/..' . '/guzzle/guzzle/src', + ), + 'GeoIp2' => + array ( + 0 => __DIR__ . '/..' . '/geoip2/geoip2/src', + ), + ), + ); + + public static $fallbackDirsPsr0 = array ( + 0 => __DIR__ . '/../..' . '/bb-library', + ); + + public static function getInitializer(ClassLoader $loader) + { + return \Closure::bind(function () use ($loader) { + $loader->prefixLengthsPsr4 = ComposerStaticInitd025dea45a31447fa4961b5fce4f57c3::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInitd025dea45a31447fa4961b5fce4f57c3::$prefixDirsPsr4; + $loader->prefixesPsr0 = ComposerStaticInitd025dea45a31447fa4961b5fce4f57c3::$prefixesPsr0; + $loader->fallbackDirsPsr0 = ComposerStaticInitd025dea45a31447fa4961b5fce4f57c3::$fallbackDirsPsr0; + + }, null, ClassLoader::class); + } +} diff --git a/src/bb-vendor/composer/installed.json b/src/bb-vendor/composer/installed.json new file mode 100644 index 000000000..9f6aca72e --- /dev/null +++ b/src/bb-vendor/composer/installed.json @@ -0,0 +1,1604 @@ +[ + { + "name": "geoip2/geoip2", + "version": "v2.1.0", + "version_normalized": "2.1.0.0", + "source": { + "type": "git", + "url": "https://github.com/maxmind/GeoIP2-php.git", + "reference": "64f226209342c4a2f54b82ba3f0707db944f7d70" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/maxmind/GeoIP2-php/zipball/64f226209342c4a2f54b82ba3f0707db944f7d70", + "reference": "64f226209342c4a2f54b82ba3f0707db944f7d70", + "shasum": "" + }, + "require": { + "guzzle/guzzle": "3.*", + "maxmind-db/reader": "~1.0", + "php": ">=5.3.1" + }, + "require-dev": { + "phpunit/phpunit": "4.2.*", + "satooshi/php-coveralls": "dev-master" + }, + "time": "2014-10-29T17:11:44+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-0": { + "GeoIp2": "src/", + "JsonSerializable": "compat/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "Gregory J. Oschwald", + "email": "goschwald@maxmind.com", + "homepage": "http://www.maxmind.com/" + } + ], + "description": "MaxMind GeoIP2 PHP API", + "homepage": "https://github.com/maxmind/GeoIP2-php", + "keywords": [ + "IP", + "geoip", + "geoip2", + "geolocation", + "maxmind" + ] + }, + { + "name": "guzzle/guzzle", + "version": "v3.9.3", + "version_normalized": "3.9.3.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/guzzle3.git", + "reference": "0645b70d953bc1c067bbc8d5bc53194706b628d9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/guzzle3/zipball/0645b70d953bc1c067bbc8d5bc53194706b628d9", + "reference": "0645b70d953bc1c067bbc8d5bc53194706b628d9", + "shasum": "" + }, + "require": { + "ext-curl": "*", + "php": ">=5.3.3", + "symfony/event-dispatcher": "~2.1" + }, + "replace": { + "guzzle/batch": "self.version", + "guzzle/cache": "self.version", + "guzzle/common": "self.version", + "guzzle/http": "self.version", + "guzzle/inflection": "self.version", + "guzzle/iterator": "self.version", + "guzzle/log": "self.version", + "guzzle/parser": "self.version", + "guzzle/plugin": "self.version", + "guzzle/plugin-async": "self.version", + "guzzle/plugin-backoff": "self.version", + "guzzle/plugin-cache": "self.version", + "guzzle/plugin-cookie": "self.version", + "guzzle/plugin-curlauth": "self.version", + "guzzle/plugin-error-response": "self.version", + "guzzle/plugin-history": "self.version", + "guzzle/plugin-log": "self.version", + "guzzle/plugin-md5": "self.version", + "guzzle/plugin-mock": "self.version", + "guzzle/plugin-oauth": "self.version", + "guzzle/service": "self.version", + "guzzle/stream": "self.version" + }, + "require-dev": { + "doctrine/cache": "~1.3", + "monolog/monolog": "~1.0", + "phpunit/phpunit": "3.7.*", + "psr/log": "~1.0", + "symfony/class-loader": "~2.1", + "zendframework/zend-cache": "2.*,<2.3", + "zendframework/zend-log": "2.*,<2.3" + }, + "suggest": { + "guzzlehttp/guzzle": "Guzzle 5 has moved to a new package name. The package you have installed, Guzzle 3, is deprecated." + }, + "time": "2015-03-18T18:23:50+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.9-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-0": { + "Guzzle": "src/", + "Guzzle\\Tests": "tests/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Guzzle Community", + "homepage": "https://github.com/guzzle/guzzle/contributors" + } + ], + "description": "PHP HTTP client. This library is deprecated in favor of https://packagist.org/packages/guzzlehttp/guzzle", + "homepage": "http://guzzlephp.org/", + "keywords": [ + "client", + "curl", + "framework", + "http", + "http client", + "rest", + "web service" + ], + "abandoned": "guzzlehttp/guzzle" + }, + { + "name": "guzzlehttp/guzzle", + "version": "7.0.1", + "version_normalized": "7.0.1.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/guzzle.git", + "reference": "2d9d3c186a6637a43193e66b097c50e4451eaab2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/2d9d3c186a6637a43193e66b097c50e4451eaab2", + "reference": "2d9d3c186a6637a43193e66b097c50e4451eaab2", + "shasum": "" + }, + "require": { + "ext-json": "*", + "guzzlehttp/promises": "^1.0", + "guzzlehttp/psr7": "^1.6.1", + "php": "^7.2.5", + "psr/http-client": "^1.0" + }, + "provide": { + "psr/http-client-implementation": "1.0" + }, + "require-dev": { + "ergebnis/composer-normalize": "^2.0", + "ext-curl": "*", + "php-http/client-integration-tests": "dev-phpunit8", + "phpunit/phpunit": "^8.5.5", + "psr/log": "^1.1" + }, + "suggest": { + "ext-curl": "Required for CURL handler support", + "ext-intl": "Required for Internationalized Domain Name (IDN) support", + "psr/log": "Required for using the Log middleware" + }, + "time": "2020-06-27T10:33:25+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "7.0-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "GuzzleHttp\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://sagikazarmark.hu" + } + ], + "description": "Guzzle is a PHP HTTP client library", + "homepage": "http://guzzlephp.org/", + "keywords": [ + "client", + "curl", + "framework", + "http", + "http client", + "psr-18", + "psr-7", + "rest", + "web service" + ] + }, + { + "name": "guzzlehttp/promises", + "version": "v1.3.1", + "version_normalized": "1.3.1.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/promises.git", + "reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/promises/zipball/a59da6cf61d80060647ff4d3eb2c03a2bc694646", + "reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646", + "shasum": "" + }, + "require": { + "php": ">=5.5.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.0" + }, + "time": "2016-12-20T10:07:11+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.4-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "description": "Guzzle promises library", + "keywords": [ + "promise" + ] + }, + { + "name": "guzzlehttp/psr7", + "version": "1.6.1", + "version_normalized": "1.6.1.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/psr7.git", + "reference": "239400de7a173fe9901b9ac7c06497751f00727a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/239400de7a173fe9901b9ac7c06497751f00727a", + "reference": "239400de7a173fe9901b9ac7c06497751f00727a", + "shasum": "" + }, + "require": { + "php": ">=5.4.0", + "psr/http-message": "~1.0", + "ralouphie/getallheaders": "^2.0.5 || ^3.0.0" + }, + "provide": { + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "ext-zlib": "*", + "phpunit/phpunit": "~4.8.36 || ^5.7.27 || ^6.5.8" + }, + "suggest": { + "zendframework/zend-httphandlerrunner": "Emit PSR-7 responses" + }, + "time": "2019-07-01T23:21:34+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.6-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Schultze", + "homepage": "https://github.com/Tobion" + } + ], + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "http", + "message", + "psr-7", + "request", + "response", + "stream", + "uri", + "url" + ] + }, + { + "name": "ircmaxell/password-compat", + "version": "v1.0.4", + "version_normalized": "1.0.4.0", + "source": { + "type": "git", + "url": "https://github.com/ircmaxell/password_compat.git", + "reference": "5c5cde8822a69545767f7c7f3058cb15ff84614c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ircmaxell/password_compat/zipball/5c5cde8822a69545767f7c7f3058cb15ff84614c", + "reference": "5c5cde8822a69545767f7c7f3058cb15ff84614c", + "shasum": "" + }, + "require-dev": { + "phpunit/phpunit": "4.*" + }, + "time": "2014-11-20T16:49:30+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "lib/password.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Anthony Ferrara", + "email": "ircmaxell@php.net", + "homepage": "http://blog.ircmaxell.com" + } + ], + "description": "A compatibility library for the proposed simplified password hashing algorithm: https://wiki.php.net/rfc/password_hash", + "homepage": "https://github.com/ircmaxell/password_compat", + "keywords": [ + "hashing", + "password" + ] + }, + { + "name": "maxmind-db/reader", + "version": "v1.7.0", + "version_normalized": "1.7.0.0", + "source": { + "type": "git", + "url": "https://github.com/maxmind/MaxMind-DB-Reader-php.git", + "reference": "942553da239f12051275f9c666538b5dd09e2908" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/maxmind/MaxMind-DB-Reader-php/zipball/942553da239f12051275f9c666538b5dd09e2908", + "reference": "942553da239f12051275f9c666538b5dd09e2908", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "conflict": { + "ext-maxminddb": "<1.7.0,>=2.0.0" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "2.*", + "php-coveralls/php-coveralls": "^2.1", + "phpunit/phpcov": ">=6.0.0", + "phpunit/phpunit": ">=8.0.0,<10.0.0", + "squizlabs/php_codesniffer": "3.*" + }, + "suggest": { + "ext-bcmath": "bcmath or gmp is required for decoding larger integers with the pure PHP decoder", + "ext-gmp": "bcmath or gmp is required for decoding larger integers with the pure PHP decoder", + "ext-maxminddb": "A C-based database decoder that provides significantly faster lookups" + }, + "time": "2020-08-07T22:10:05+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "MaxMind\\Db\\": "src/MaxMind/Db" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "Gregory J. Oschwald", + "email": "goschwald@maxmind.com", + "homepage": "https://www.maxmind.com/" + } + ], + "description": "MaxMind DB Reader API", + "homepage": "https://github.com/maxmind/MaxMind-DB-Reader-php", + "keywords": [ + "database", + "geoip", + "geoip2", + "geolocation", + "maxmind" + ] + }, + { + "name": "michelf/php-markdown", + "version": "1.7.0", + "version_normalized": "1.7.0.0", + "source": { + "type": "git", + "url": "https://github.com/michelf/php-markdown.git", + "reference": "1f51cc520948f66cd2af8cbc45a5ee175e774220" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/michelf/php-markdown/zipball/1f51cc520948f66cd2af8cbc45a5ee175e774220", + "reference": "1f51cc520948f66cd2af8cbc45a5ee175e774220", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "time": "2016-10-29T18:58:20+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-lib": "1.4.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-0": { + "Michelf": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Michel Fortin", + "email": "michel.fortin@michelf.ca", + "homepage": "https://michelf.ca/", + "role": "Developer" + }, + { + "name": "John Gruber", + "homepage": "https://daringfireball.net/" + } + ], + "description": "PHP Markdown", + "homepage": "https://michelf.ca/projects/php-markdown/", + "keywords": [ + "markdown" + ] + }, + { + "name": "mpdf/mpdf", + "version": "v8.0.4", + "version_normalized": "8.0.4.0", + "source": { + "type": "git", + "url": "https://github.com/mpdf/mpdf.git", + "reference": "d3147a0d790b6d11936fd9c73fa31a7ed45e3f6f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/mpdf/mpdf/zipball/d3147a0d790b6d11936fd9c73fa31a7ed45e3f6f", + "reference": "d3147a0d790b6d11936fd9c73fa31a7ed45e3f6f", + "shasum": "" + }, + "require": { + "ext-gd": "*", + "ext-mbstring": "*", + "myclabs/deep-copy": "^1.7", + "paragonie/random_compat": "^1.4|^2.0|9.99.99", + "php": "^5.6 || ~7.0.0 || ~7.1.0 || ~7.2.0 || ~7.3.0 || ~7.4.0", + "psr/log": "^1.0", + "setasign/fpdi": "^2.1" + }, + "require-dev": { + "mockery/mockery": "^0.9.5", + "mpdf/qrcode": "^1.0.0", + "phpunit/phpunit": "^5.0", + "squizlabs/php_codesniffer": "^3.5.0", + "tracy/tracy": "^2.4" + }, + "suggest": { + "ext-bcmath": "Needed for generation of some types of barcodes", + "ext-xml": "Needed mainly for SVG manipulation", + "ext-zlib": "Needed for compression of embedded resources, such as fonts" + }, + "time": "2019-11-28T09:39:33+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-development": "7.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Mpdf\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "GPL-2.0-only" + ], + "authors": [ + { + "name": "Matěj Humpál", + "role": "Developer, maintainer" + }, + { + "name": "Ian Back", + "role": "Developer (retired)" + } + ], + "description": "PHP library generating PDF files from UTF-8 encoded HTML", + "homepage": "https://mpdf.github.io", + "keywords": [ + "pdf", + "php", + "utf-8" + ] + }, + { + "name": "mustangostang/spyc", + "version": "0.5.1", + "version_normalized": "0.5.1.0", + "source": { + "type": "git", + "url": "https://github.com/mustangostang/spyc.git", + "reference": "dc4785b4d7227fd9905e086d499fb8abfadf9977" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/mustangostang/spyc/zipball/dc4785b4d7227fd9905e086d499fb8abfadf9977", + "reference": "dc4785b4d7227fd9905e086d499fb8abfadf9977", + "shasum": "" + }, + "require": { + "php": ">=5.3.1" + }, + "time": "2013-02-21T10:52:01+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "0.5.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "Spyc.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT License" + ], + "authors": [ + { + "name": "mustangostang", + "email": "vlad.andersen@gmail.com" + } + ], + "description": "A simple YAML loader/dumper class for PHP", + "homepage": "https://github.com/mustangostang/spyc/", + "keywords": [ + "spyc", + "yaml", + "yml" + ] + }, + { + "name": "myclabs/deep-copy", + "version": "1.10.1", + "version_normalized": "1.10.1.0", + "source": { + "type": "git", + "url": "https://github.com/myclabs/DeepCopy.git", + "reference": "969b211f9a51aa1f6c01d1d2aef56d3bd91598e5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/969b211f9a51aa1f6c01d1d2aef56d3bd91598e5", + "reference": "969b211f9a51aa1f6c01d1d2aef56d3bd91598e5", + "shasum": "" + }, + "require": { + "php": "^7.1 || ^8.0" + }, + "replace": { + "myclabs/deep-copy": "self.version" + }, + "require-dev": { + "doctrine/collections": "^1.0", + "doctrine/common": "^2.6", + "phpunit/phpunit": "^7.1" + }, + "time": "2020-06-29T13:22:24+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "DeepCopy\\": "src/DeepCopy/" + }, + "files": [ + "src/DeepCopy/deep_copy.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Create deep copies (clones) of your objects", + "keywords": [ + "clone", + "copy", + "duplicate", + "object", + "object graph" + ], + "funding": [ + { + "url": "https://tidelift.com/funding/github/packagist/myclabs/deep-copy", + "type": "tidelift" + } + ] + }, + { + "name": "paragonie/random_compat", + "version": "v9.99.99", + "version_normalized": "9.99.99.0", + "source": { + "type": "git", + "url": "https://github.com/paragonie/random_compat.git", + "reference": "84b4dfb120c6f9b4ff7b3685f9b8f1aa365a0c95" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/paragonie/random_compat/zipball/84b4dfb120c6f9b4ff7b3685f9b8f1aa365a0c95", + "reference": "84b4dfb120c6f9b4ff7b3685f9b8f1aa365a0c95", + "shasum": "" + }, + "require": { + "php": "^7" + }, + "require-dev": { + "phpunit/phpunit": "4.*|5.*", + "vimeo/psalm": "^1" + }, + "suggest": { + "ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes." + }, + "time": "2018-07-02T15:55:56+00:00", + "type": "library", + "installation-source": "dist", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Paragon Initiative Enterprises", + "email": "security@paragonie.com", + "homepage": "https://paragonie.com" + } + ], + "description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7", + "keywords": [ + "csprng", + "polyfill", + "pseudorandom", + "random" + ] + }, + { + "name": "phpmailer/phpmailer", + "version": "v6.1.6", + "version_normalized": "6.1.6.0", + "source": { + "type": "git", + "url": "https://github.com/PHPMailer/PHPMailer.git", + "reference": "c2796cb1cb99d7717290b48c4e6f32cb6c60b7b3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/c2796cb1cb99d7717290b48c4e6f32cb6c60b7b3", + "reference": "c2796cb1cb99d7717290b48c4e6f32cb6c60b7b3", + "shasum": "" + }, + "require": { + "ext-ctype": "*", + "ext-filter": "*", + "php": ">=5.5.0" + }, + "require-dev": { + "doctrine/annotations": "^1.2", + "friendsofphp/php-cs-fixer": "^2.2", + "phpunit/phpunit": "^4.8 || ^5.7" + }, + "suggest": { + "ext-mbstring": "Needed to send email in multibyte encoding charset", + "hayageek/oauth2-yahoo": "Needed for Yahoo XOAUTH2 authentication", + "league/oauth2-google": "Needed for Google XOAUTH2 authentication", + "psr/log": "For optional PSR-3 debug logging", + "stevenmaguire/oauth2-microsoft": "Needed for Microsoft XOAUTH2 authentication", + "symfony/polyfill-mbstring": "To support UTF-8 if the Mbstring PHP extension is not enabled (^1.2)" + }, + "time": "2020-05-27T12:24:03+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "PHPMailer\\PHPMailer\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-2.1-only" + ], + "authors": [ + { + "name": "Marcus Bointon", + "email": "phpmailer@synchromedia.co.uk" + }, + { + "name": "Jim Jagielski", + "email": "jimjag@gmail.com" + }, + { + "name": "Andy Prevost", + "email": "codeworxtech@users.sourceforge.net" + }, + { + "name": "Brent R. Matzelle" + } + ], + "description": "PHPMailer is a full-featured email creation and transfer class for PHP", + "funding": [ + { + "url": "https://github.com/synchro", + "type": "github" + } + ] + }, + { + "name": "pimple/pimple", + "version": "v3.3.0", + "version_normalized": "3.3.0.0", + "source": { + "type": "git", + "url": "https://github.com/silexphp/Pimple.git", + "reference": "e55d12f9d6a0e7f9c85992b73df1267f46279930" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/silexphp/Pimple/zipball/e55d12f9d6a0e7f9c85992b73df1267f46279930", + "reference": "e55d12f9d6a0e7f9c85992b73df1267f46279930", + "shasum": "" + }, + "require": { + "php": "^7.2.5", + "psr/container": "^1.0" + }, + "require-dev": { + "symfony/phpunit-bridge": "^3.4|^4.4|^5.0" + }, + "time": "2020-03-03T09:12:48+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.3.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-0": { + "Pimple": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + } + ], + "description": "Pimple, a simple Dependency Injection Container", + "homepage": "https://pimple.symfony.com", + "keywords": [ + "container", + "dependency injection" + ] + }, + { + "name": "psr/container", + "version": "1.0.0", + "version_normalized": "1.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/container.git", + "reference": "b7ce3b176482dbbc1245ebf52b181af44c2cf55f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/container/zipball/b7ce3b176482dbbc1245ebf52b181af44c2cf55f", + "reference": "b7ce3b176482dbbc1245ebf52b181af44c2cf55f", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "time": "2017-02-14T16:28:37+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Container\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common Container Interface (PHP FIG PSR-11)", + "homepage": "https://github.com/php-fig/container", + "keywords": [ + "PSR-11", + "container", + "container-interface", + "container-interop", + "psr" + ] + }, + { + "name": "psr/http-client", + "version": "1.0.1", + "version_normalized": "1.0.1.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-client.git", + "reference": "2dfb5f6c5eff0e91e20e913f8c5452ed95b86621" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-client/zipball/2dfb5f6c5eff0e91e20e913f8c5452ed95b86621", + "reference": "2dfb5f6c5eff0e91e20e913f8c5452ed95b86621", + "shasum": "" + }, + "require": { + "php": "^7.0 || ^8.0", + "psr/http-message": "^1.0" + }, + "time": "2020-06-29T06:28:15+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Http\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP clients", + "homepage": "https://github.com/php-fig/http-client", + "keywords": [ + "http", + "http-client", + "psr", + "psr-18" + ] + }, + { + "name": "psr/http-message", + "version": "1.0.1", + "version_normalized": "1.0.1.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "time": "2016-08-06T14:39:51+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ] + }, + { + "name": "psr/log", + "version": "1.1.3", + "version_normalized": "1.1.3.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "0f73288fd15629204f9d42b7055f72dacbe811fc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/0f73288fd15629204f9d42b7055f72dacbe811fc", + "reference": "0f73288fd15629204f9d42b7055f72dacbe811fc", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "time": "2020-03-23T09:12:05+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Log\\": "Psr/Log/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", + "keywords": [ + "log", + "psr", + "psr-3" + ] + }, + { + "name": "ralouphie/getallheaders", + "version": "3.0.3", + "version_normalized": "3.0.3.0", + "source": { + "type": "git", + "url": "https://github.com/ralouphie/getallheaders.git", + "reference": "120b605dfeb996808c31b6477290a714d356e822" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822", + "reference": "120b605dfeb996808c31b6477290a714d356e822", + "shasum": "" + }, + "require": { + "php": ">=5.6" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^2.1", + "phpunit/phpunit": "^5 || ^6.5" + }, + "time": "2019-03-08T08:55:37+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "src/getallheaders.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "description": "A polyfill for getallheaders." + }, + { + "name": "setasign/fpdi", + "version": "v2.3.4", + "version_normalized": "2.3.4.0", + "source": { + "type": "git", + "url": "https://github.com/Setasign/FPDI.git", + "reference": "2b5fb811c04f937ef257ef3f798cebeded33c136" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Setasign/FPDI/zipball/2b5fb811c04f937ef257ef3f798cebeded33c136", + "reference": "2b5fb811c04f937ef257ef3f798cebeded33c136", + "shasum": "" + }, + "require": { + "ext-zlib": "*", + "php": "^5.6 || ^7.0" + }, + "conflict": { + "setasign/tfpdf": "<1.31" + }, + "require-dev": { + "phpunit/phpunit": "~5.7", + "setasign/fpdf": "~1.8", + "setasign/tfpdf": "1.31", + "squizlabs/php_codesniffer": "^3.5", + "tecnickcom/tcpdf": "~6.2" + }, + "suggest": { + "setasign/fpdf": "FPDI will extend this class but as it is also possible to use TCPDF or tFPDF as an alternative. There's no fixed dependency configured." + }, + "time": "2020-08-27T06:55:47+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "setasign\\Fpdi\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jan Slabon", + "email": "jan.slabon@setasign.com", + "homepage": "https://www.setasign.com" + }, + { + "name": "Maximilian Kresse", + "email": "maximilian.kresse@setasign.com", + "homepage": "https://www.setasign.com" + } + ], + "description": "FPDI is a collection of PHP classes facilitating developers to read pages from existing PDF documents and use them as templates in FPDF. Because it is also possible to use FPDI with TCPDF, there are no fixed dependencies defined. Please see suggestions for packages which evaluates the dependencies automatically.", + "homepage": "https://www.setasign.com/fpdi", + "keywords": [ + "fpdf", + "fpdi", + "pdf" + ], + "funding": [ + { + "url": "https://tidelift.com/funding/github/packagist/setasign/fpdi", + "type": "tidelift" + } + ] + }, + { + "name": "stripe/stripe-php", + "version": "v2.1.1", + "version_normalized": "2.1.1.0", + "source": { + "type": "git", + "url": "https://github.com/stripe/stripe-php.git", + "reference": "9d468f2faa25b2b5447c033bf70aaded6139dd6b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/stripe/stripe-php/zipball/9d468f2faa25b2b5447c033bf70aaded6139dd6b", + "reference": "9d468f2faa25b2b5447c033bf70aaded6139dd6b", + "shasum": "" + }, + "require": { + "ext-curl": "*", + "ext-json": "*", + "ext-mbstring": "*", + "php": ">=5.3.3" + }, + "require-dev": { + "phpunit/phpunit": "~4.0", + "satooshi/php-coveralls": "~0.6.1", + "squizlabs/php_codesniffer": "~2.0" + }, + "time": "2015-03-02T05:44:40+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Stripe\\": "lib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Stripe and contributors", + "homepage": "https://github.com/stripe/stripe-php/contributors" + } + ], + "description": "Stripe PHP Library", + "homepage": "https://stripe.com/", + "keywords": [ + "api", + "payment processing", + "stripe" + ] + }, + { + "name": "symfony/event-dispatcher", + "version": "v2.8.52", + "version_normalized": "2.8.52.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher.git", + "reference": "a77e974a5fecb4398833b0709210e3d5e334ffb0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/a77e974a5fecb4398833b0709210e3d5e334ffb0", + "reference": "a77e974a5fecb4398833b0709210e3d5e334ffb0", + "shasum": "" + }, + "require": { + "php": ">=5.3.9" + }, + "require-dev": { + "psr/log": "~1.0", + "symfony/config": "^2.0.5|~3.0.0", + "symfony/dependency-injection": "~2.6|~3.0.0", + "symfony/expression-language": "~2.6|~3.0.0", + "symfony/stopwatch": "~2.3|~3.0.0" + }, + "suggest": { + "symfony/dependency-injection": "", + "symfony/http-kernel": "" + }, + "time": "2018-11-21T14:20:20+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.8-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\EventDispatcher\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony EventDispatcher Component", + "homepage": "https://symfony.com" + }, + { + "name": "symfony/polyfill-ctype", + "version": "v1.18.1", + "version_normalized": "1.18.1.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-ctype.git", + "reference": "1c302646f6efc070cd46856e600e5e0684d6b454" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/1c302646f6efc070cd46856e600e5e0684d6b454", + "reference": "1c302646f6efc070cd46856e600e5e0684d6b454", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "suggest": { + "ext-ctype": "For best performance" + }, + "time": "2020-07-14T12:35:20+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.18-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Ctype\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Gert de Pagter", + "email": "BackEndTea@gmail.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for ctype functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "ctype", + "polyfill", + "portable" + ], + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ] + }, + { + "name": "symfony/polyfill-mbstring", + "version": "v1.18.1", + "version_normalized": "1.18.1.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-mbstring.git", + "reference": "a6977d63bf9a0ad4c65cd352709e230876f9904a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/a6977d63bf9a0ad4c65cd352709e230876f9904a", + "reference": "a6977d63bf9a0ad4c65cd352709e230876f9904a", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "time": "2020-07-14T12:35:20+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.18-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Mbstring\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for the Mbstring extension", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "mbstring", + "polyfill", + "portable", + "shim" + ], + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ] + }, + { + "name": "twig/extensions", + "version": "v1.5.4", + "version_normalized": "1.5.4.0", + "source": { + "type": "git", + "url": "https://github.com/twigphp/Twig-extensions.git", + "reference": "57873c8b0c1be51caa47df2cdb824490beb16202" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/twigphp/Twig-extensions/zipball/57873c8b0c1be51caa47df2cdb824490beb16202", + "reference": "57873c8b0c1be51caa47df2cdb824490beb16202", + "shasum": "" + }, + "require": { + "twig/twig": "^1.27|^2.0" + }, + "require-dev": { + "symfony/phpunit-bridge": "^3.4", + "symfony/translation": "^2.7|^3.4" + }, + "suggest": { + "symfony/translation": "Allow the time_diff output to be translated" + }, + "time": "2018-12-05T18:34:18+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.5-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-0": { + "Twig_Extensions_": "lib/" + }, + "psr-4": { + "Twig\\Extensions\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + } + ], + "description": "Common additional features for Twig that do not directly belong in core", + "keywords": [ + "i18n", + "text" + ] + }, + { + "name": "twig/twig", + "version": "v2.13.0", + "version_normalized": "2.13.0.0", + "source": { + "type": "git", + "url": "https://github.com/twigphp/Twig.git", + "reference": "46a612ba1bbf6ee1c58acabacd868212ff8a2911" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/twigphp/Twig/zipball/46a612ba1bbf6ee1c58acabacd868212ff8a2911", + "reference": "46a612ba1bbf6ee1c58acabacd868212ff8a2911", + "shasum": "" + }, + "require": { + "php": ">=7.1.3", + "symfony/polyfill-ctype": "^1.8", + "symfony/polyfill-mbstring": "^1.3" + }, + "require-dev": { + "psr/container": "^1.0", + "symfony/phpunit-bridge": "^4.4.9|^5.0.9" + }, + "time": "2020-07-05T13:08:05+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.13-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-0": { + "Twig_": "lib/" + }, + "psr-4": { + "Twig\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Twig Team", + "role": "Contributors" + }, + { + "name": "Armin Ronacher", + "email": "armin.ronacher@active-4.com", + "role": "Project Founder" + } + ], + "description": "Twig, the flexible, fast, and secure template language for PHP", + "homepage": "https://twig.symfony.com", + "keywords": [ + "templating" + ], + "funding": [ + { + "url": "https://certification.symfony.com/", + "type": "custom" + }, + { + "url": "https://live.symfony.com/", + "type": "custom" + }, + { + "url": "https://symfony.com/cloud/", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/twig/twig", + "type": "tidelift" + } + ] + } +] diff --git a/src/bb-vendor/geoip2/geoip2/.gitignore b/src/bb-vendor/geoip2/geoip2/.gitignore new file mode 100644 index 000000000..678ddeb67 --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/.gitignore @@ -0,0 +1,14 @@ +_site +.gh-pages +.idea +GeoLite2-City.mmdb +apigen.phar +box.phar +build +composer.lock +composer.phar +phpunit.xml +geoip2-php.sublime-* +vendor/ +*.sw? +*.old diff --git a/src/bb-vendor/geoip2/geoip2/.gitmodules b/src/bb-vendor/geoip2/geoip2/.gitmodules new file mode 100644 index 000000000..820339f2e --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/.gitmodules @@ -0,0 +1,3 @@ +[submodule "maxmind-db"] + path = maxmind-db + url = git://github.com/maxmind/MaxMind-DB.git diff --git a/src/bb-vendor/geoip2/geoip2/.travis.yml b/src/bb-vendor/geoip2/geoip2/.travis.yml new file mode 100644 index 000000000..ea133d9bf --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/.travis.yml @@ -0,0 +1,29 @@ +language: php + +php: + - 5.3 + - 5.4 + - 5.5 + - 5.6 + - hhvm + +before_install: + - composer self-update + - composer install --dev -n --prefer-source + - if [ "5.5" == $TRAVIS_PHP_VERSION ]; then pyrus install pear/PHP_CodeSniffer; fi + - phpenv rehash + +script: + - mkdir -p build/logs + - if [ "5.5" == $TRAVIS_PHP_VERSION ]; then phpcs --standard=PSR2 src/; fi + - phpunit -c phpunit.xml.dist + +after_script: + - php vendor/bin/coveralls + +notifications: + email: + recipients: + - dev@maxmind.com + on_success: change + on_failure: always diff --git a/src/bb-vendor/geoip2/geoip2/CHANGELOG.md b/src/bb-vendor/geoip2/geoip2/CHANGELOG.md new file mode 100644 index 000000000..4bf29fd42 --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/CHANGELOG.md @@ -0,0 +1,133 @@ +CHANGELOG +========= + +2.1.0 (2014-10-29) +------------------ + +* Update ApiGen dependency to version that isn't broken on case sensitive + file systems. +* Added support for the GeoIP2 Anonymous IP database. The + `GeoIP2\Database\Reader` class now has an `anonymousIp` method which returns + a `GeoIP2\Model\AnonymousIp` object. +* Boolean attributes like those in the `GeoIP2\Record\Traits` class now return + `false` instead of `null` when they were not true. + +2.0.0 (2014-09-22) +------------------ + +* First production release. + +0.9.0 (2014-09-15) +------------------ + +* IMPORTANT: The deprecated `omni()` and `cityIspOrg()` methods have been + removed from `GeoIp2\WebService\Client`. + +0.8.1 (2014-09-12) +------------------ + +* The check added to the `GeoIP2\Database\Reader` lookup methods in 0.8.0 did + not work with the GeoIP2 City Database Subset by Continent with World + Countries. This has been fixed. Fixes GitHub issue #23. + +0.8.0 (2014-09-10) +------------------ + +* The `GeoIp2\Database\Reader` lookup methods (e.g., `city()`, `isp()`) now + throw a `BadMethodCallException` if they are used with a database that + does not match the method. In particular, doing a `city()` lookup on a + GeoIP2 Country database will result in an exception, and vice versa. +* A `metadata()` method has been added to the `GeoIP2\Database\Reader` class. + This returns a `MaxMind\Db\Reader\Metadata` class with information about the + database. +* The name attribute was missing from the RepresentedCountry class. + +0.7.0 (2014-07-22) +------------------ + +* The web service client API has been updated for the v2.1 release of the web + service. In particular, the `cityIspOrg` and `omni` methods on + `GeoIp2\WebService\Client` should be considered deprecated. The `city` + method now provides all of the data formerly provided by `cityIspOrg`, and + the `omni` method has been replaced by the `insights` method. +* Support was added for GeoIP2 Connection Type, Domain and ISP databases. + + +0.6.3 (2014-05-12) +------------------ + +* With the previous Phar builds, some users received `phar error: invalid url + or non-existent phar` errors. The correct alias is now used for the Phar, + and this should no longer be an issue. + +0.6.2 (2014-05-08) +------------------ + +* The Phar build was broken with Guzzle 3.9.0+. This has been fixed. + +0.6.1 (2014-05-01) +------------------ + +* This API now officially supports HHVM. +* The `maxmind-db/reader` dependency was updated to a version that does not + require BC Math. +* The Composer compatibility autoload rules are now targeted more narrowly. +* A `box.json` file is included to build a Phar package. + +0.6.0 (2014-02-19) +------------------ + +* This API is now licensed under the Apache License, Version 2.0. +* Model and record classes now implement `JsonSerializable`. +* `isset` now works with model and record classes. + +0.5.0 (2013-10-21) +------------------ + +* Renamed $languages constructor parameters to $locales for both the Client + and Reader classes. +* Documentation and code clean-up (Ben Morel). +* Added the interface `GeoIp2\ProviderInterface`, which is implemented by both + `\GeoIp2\Database\Reader` and `\GeoIp2\WebService\Client`. + +0.4.0 (2013-07-16) +------------------ + +* This is the first release with the GeoIP2 database reader. Please see the + `README.md` file and the `\GeoIp2\Database\Reader` class. +* The general exception classes were replaced with specific exception classes + representing particular types of errors, such as an authentication error. + +0.3.0 (2013-07-12) +------------------ + +* In namespaces and class names, "GeoIP2" was renamed to "GeoIp2" to improve + consistency. + +0.2.1 (2013-06-10) +------------------ + +* First official beta release. +* Documentation updates and corrections. + +0.2.0 (2013-05-29) +------------------ + +* `GenericException` was renamed to `GeoIP2Exception`. +* We now support more languages. The new languages are de, es, fr, and pt-BR. +* The REST API now returns a record with data about your account. There is + a new `GeoIP\Records\MaxMind` class for this data. +* The `continentCode` attribute on `Continent` was renamed to `code`. +* Documentation updates. + +0.1.1 (2013-05-14) +------------------ + +* Updated Guzzle version requirement. +* Fixed Composer example in README.md. + + +0.1.0 (2013-05-13) +------------------ + +* Initial release. diff --git a/src/bb-vendor/geoip2/geoip2/README.md b/src/bb-vendor/geoip2/geoip2/README.md new file mode 100644 index 000000000..ff90f2d70 --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/README.md @@ -0,0 +1,328 @@ +# GeoIP2 PHP API # + +## Description ## + +This package provides an API for the GeoIP2 [web services] +(http://dev.maxmind.com/geoip/geoip2/web-services) and [databases] +(http://dev.maxmind.com/geoip/geoip2/downloadable). The API also works with +the free [GeoLite2 databases](http://dev.maxmind.com/geoip/geoip2/geolite2/). + +## Install via Composer ## + +We recommend installing this package with [Composer](http://getcomposer.org/). + +### Download Composer ### + +To download Composer, run in the root directory of your project: + +```bash +curl -sS https://getcomposer.org/installer | php +``` + +You should now have the file `composer.phar` in your project directory. + +### Install Dependencies ### + +Run in your project root: + +``` +php composer.phar require geoip2/geoip2:~2.0 +``` + +You should now have the files `composer.json` and `composer.lock` as well as +the directory `vendor` in your project directory. If you use a version control +system, `composer.json` should be added to it. + +### Require Autoloader ### + +After installing the dependencies, you need to require the Composer autoloader +from your code: + +```php +require 'vendor/autoload.php'; +``` + +## Install via Phar ## + +Although we strongly recommend using Composer, we also provide a +[phar archive](http://php.net/manual/en/book.phar.php) containing all of the +dependencies for GeoIP2. Our latest phar archive is available on +[our releases page](https://github.com/maxmind/GeoIP2-php/releases). + +To use the archive, just require it from your script: + +```php +require 'geoip2.phar'; +``` + +## Optional C Extension ## + +The [MaxMind DB API](https://github.com/maxmind/MaxMind-DB-Reader-php) +includes an optional C extension that you may install to dramatically increase +the performance of lookups in GeoIP2 or GeoLite2 databases. To install, please +follow the instructions included with that API. + +The extension has no effect on web-service lookups. + +## Database Reader ## + +### Usage ### + +To use this API, you must create a new `\GeoIp2\Database\Reader` object with +the path to the database file as the first argument to the constructor. You +may then call the method corresponding to the database you are using. + +If the lookup succeeds, the method call will return a model class for the +record in the database. This model in turn contains multiple container +classes for the different parts of the data such as the city in which the +IP address is located. + +If the record is not found, a `\GeoIp2\Exception\AddressNotFoundException` +is thrown. If the database is invalid or corrupt, a +`\MaxMind\Db\InvalidDatabaseException` will be thrown. + +See the API documentation for more details. + +### City Example ### + +```php +city('128.101.101.101'); + +print($record->country->isoCode . "\n"); // 'US' +print($record->country->name . "\n"); // 'United States' +print($record->country->names['zh-CN'] . "\n"); // '美国' + +print($record->mostSpecificSubdivision->name . "\n"); // 'Minnesota' +print($record->mostSpecificSubdivision->isoCode . "\n"); // 'MN' + +print($record->city->name . "\n"); // 'Minneapolis' + +print($record->postal->code . "\n"); // '55455' + +print($record->location->latitude . "\n"); // 44.9733 +print($record->location->longitude . "\n"); // -93.2323 + +``` + +### Anonymoous-IP Example ### + +```php +anonymousIp('128.101.101.101'); + +if ($record->isAnonymous) { print "anon\n"; } +print($record->ipAddress . "\n"); // '128.101.101.101' + +``` + +### Connection-Type Example ### + +```php +connectionType('128.101.101.101'); + +print($record->connectionType . "\n"); // 'Corporate' +print($record->ipAddress . "\n"); // '128.101.101.101' + +``` + +### Domain Example ### + +```php +domain('128.101.101.101'); + +print($record->domain . "\n"); // 'umn.edu' +print($record->ipAddress . "\n"); // '128.101.101.101' + +``` + +### ISP Example ### + +```php +isp('128.101.101.101'); + +print($record->autonomousSystemNumber . "\n"); // 217 +print($record->autonomousSystemOrganization . "\n"); // 'University of Minnesota' +print($record->isp . "\n"); // 'University of Minnesota' +print($record->organization . "\n"); // 'University of Minnesota' + +print($record->ipAddress . "\n"); // '128.101.101.101' + +``` + +## Web Service Client ## + +### Usage ### + +To use this API, you must create a new `\GeoIp2\WebService\Client` +object with your `$userId` and `$licenseKey`, then you call the method +corresponding to a specific end point, passing it the IP address you want to +look up. + +If the request succeeds, the method call will return a model class for the end +point you called. This model in turn contains multiple record classes, each of +which represents part of the data returned by the web service. + +If there is an error, a structured exception is thrown. + +See the API documentation for more details. + +### Example ### + +```php +city('128.101.101.101'); + +print($record->country->isoCode . "\n"); // 'US' +print($record->country->name . "\n"); // 'United States' +print($record->country->names['zh-CN'] . "\n"); // '美国' + +print($record->mostSpecificSubdivision->name . "\n"); // 'Minnesota' +print($record->mostSpecificSubdivision->isoCode . "\n"); // 'MN' + +print($record->city->name . "\n"); // 'Minneapolis' + +print($record->postal->code . "\n"); // '55455' + +print($record->location->latitude . "\n"); // 44.9733 +print($record->location->longitude . "\n"); // -93.2323 + +``` + +### What data is returned? ### + +While many of the end points return the same basic records, the attributes +which can be populated vary between end points. In addition, while an end +point may offer a particular piece of data, MaxMind does not always have every +piece of data for any given IP address. + +Because of these factors, it is possible for any end point to return a record +where some or all of the attributes are unpopulated. + +See the +[GeoIP2 Precision web service docs](http://dev.maxmind.com/geoip/geoip2/web-services) +for details on what data each end point may return. + +The only piece of data which is always returned is the `ipAddress` +attribute in the `GeoIp2\Record\Traits` record. + +## Integration with GeoNames ## + +[GeoNames](http://www.geonames.org/) offers web services and downloadable +databases with data on geographical features around the world, including +populated places. They offer both free and paid premium data. Each +feature is unique identified by a `geonameId`, which is an integer. + +Many of the records returned by the GeoIP2 web services and databases +include a `geonameId` property. This is the ID of a geographical feature +(city, region, country, etc.) in the GeoNames database. + +Some of the data that MaxMind provides is also sourced from GeoNames. We +source things like place names, ISO codes, and other similar data from +the GeoNames premium data set. + +## Reporting data problems ## + +If the problem you find is that an IP address is incorrectly mapped, +please +[submit your correction to MaxMind](http://www.maxmind.com/en/correction). + +If you find some other sort of mistake, like an incorrect spelling, +please check the [GeoNames site](http://www.geonames.org/) first. Once +you've searched for a place and found it on the GeoNames map view, there +are a number of links you can use to correct data ("move", "edit", +"alternate names", etc.). Once the correction is part of the GeoNames +data set, it will be automatically incorporated into future MaxMind +releases. + +If you are a paying MaxMind customer and you're not sure where to submit +a correction, please +[contact MaxMind support](http://www.maxmind.com/en/support) for help. + +## Other Support ## + +Please report all issues with this code using the +[GitHub issue tracker](https://github.com/maxmind/GeoIP2-php/issues). + +If you are having an issue with a MaxMind service that is not specific +to the client API, please see +[our support page](http://www.maxmind.com/en/support). + +## Requirements ## + +This code requires PHP 5.3 or greater. Older versions of PHP are not +supported. + +This library works and is tested with HHVM. + +This library also relies on the [Guzzle HTTP client](http://guzzlephp.org/) +and the [MaxMind DB Reader](https://github.com/maxmind/MaxMind-DB-Reader-php). + +If you are using PHP 5.3 with an autoloader besides Composer, you must load +`JsonSerializable.php` in the `compat` directory. + +## Contributing ## + +Patches and pull requests are encouraged. All code should follow the +PSR-2 style guidelines. Please include unit tests whenever possible. + +## Versioning ## + +The GeoIP2 PHP API uses [Semantic Versioning](http://semver.org/). + +## Copyright and License ## + +This software is Copyright (c) 2014 by MaxMind, Inc. + +This is free software, licensed under the Apache License, Version 2.0. + diff --git a/src/bb-vendor/geoip2/geoip2/bin/benchmark.php b/src/bb-vendor/geoip2/geoip2/bin/benchmark.php new file mode 100755 index 000000000..1458ab6b6 --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/bin/benchmark.php @@ -0,0 +1,26 @@ +#!/usr/bin/env php + +city($ip); + } catch (AddressNotFoundException $e) { + } + if ($i % 1000 == 0) { + print($i . ' ' . $ip . "\n"); + } +} +$endTime = microtime(true); + +$duration = $endTime - $startTime; +print('Requests per second: ' . $count / $duration . "\n"); diff --git a/src/bb-vendor/geoip2/geoip2/box.json b/src/bb-vendor/geoip2/geoip2/box.json new file mode 100644 index 000000000..459a60ddd --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/box.json @@ -0,0 +1,36 @@ +{ + "alias": "geoip2.phar", + "main": "phar-stub.php", + "output": "geoip2.phar", + "compactors": [ + "Herrera\\Box\\Compactor\\Composer", + "Herrera\\Box\\Compactor\\Json", + "Herrera\\Box\\Compactor\\Php" + ], + "files": [ + "LICENSE" + ], + "finder": [ + { + "name": [ + "LICENSE", + "LICENSE.*", + "*.php", + "*.pem", + "*.pem.md5" + ], + "exclude": [ + "phpunit", + "satooshi", + "Tests", + "tests", + "yaml" + ], + "in": "vendor" + } + ], + + "directories": ["compat", "src/"], + "git-version": "git-version", + "stub": true +} diff --git a/src/bb-vendor/geoip2/geoip2/compat/JsonSerializable.php b/src/bb-vendor/geoip2/geoip2/compat/JsonSerializable.php new file mode 100644 index 000000000..a27632ff4 --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/compat/JsonSerializable.php @@ -0,0 +1,13 @@ +=5.3.1" + }, + "require-dev": { + "phpunit/phpunit": "4.2.*", + "satooshi/php-coveralls": "dev-master" + }, + "autoload": { + "psr-0": { + "GeoIp2": "src/", + "JsonSerializable": "compat/" + } + } +} diff --git a/src/bb-vendor/geoip2/geoip2/dev-bin/release.sh b/src/bb-vendor/geoip2/geoip2/dev-bin/release.sh new file mode 100755 index 000000000..97ffbcde0 --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/dev-bin/release.sh @@ -0,0 +1,105 @@ +#!/bin/bash + +set -e + +TAG=$1 + +if [ -z $TAG ]; then + echo "Please specify a tag" + exit 1 +fi + +if [ -f geoip2.phar ]; then + rm geoip2.phar +fi + +if [ -n "$(git status --porcelain)" ]; then + echo ". is not clean." >&2 + exit 1 +fi + +if [ -d vendor ]; then + rm -fr vendor +fi + +php composer.phar self-update +php composer.phar update --no-dev + +if [ ! -f box.phar ]; then + wget -O box.phar "https://github.com/kherge-archive/Box/releases/download/2.4.4/box-2.4.4.phar" +fi + +php box.phar build + +php composer.phar update + +./vendor/bin/phpunit + +if [ ! -d .gh-pages ]; then + echo "Checking out gh-pages in .gh-pages" + git clone -b gh-pages git@git.maxmind.com:GeoIP2-php .gh-pages + pushd .gh-pages +else + echo "Updating .gh-pages" + pushd .gh-pages + git pull +fi + +if [ -n "$(git status --porcelain)" ]; then + echo ".gh-pages is not clean" >&2 + exit 1 +fi + +# We no longer have apigen as a dependency in Composer as releases are +# sporadically deleted upstream and compatibility is often broken on patch +# releases. +if [ ! -f apigen.phar ]; then + wget -O apigen.phar "https://github.com/apigen/apigen/releases/download/v4.0.0-RC3/apigen-4.0.0-RC3.phar" +fi + + +cat < apigen.neon +destination: doc/$TAG + +source: + - ../src + +title: "GeoIP2 PHP API $TAG" +EOF + +php apigen.phar generate + + +PAGE=index.md +cat < $PAGE +--- +layout: default +title: MaxMind GeoIP2 PHP API +language: php +version: $TAG +--- + +EOF + +cat ../README.md >> $PAGE + +git add doc/ +git commit -m "Updated for $TAG" -a + +read -e -p "Push to origin? " SHOULD_PUSH + +if [ "$SHOULD_PUSH" != "y" ]; then + echo "Aborting" + exit 1 +fi + +# If we don't push directly to github, the page doesn't get built for some +# reason. +git push git@github.com:maxmind/GeoIP2-php.git +git push + +popd + +git tag -a $TAG +git push +git push --tags diff --git a/src/bb-vendor/geoip2/geoip2/phar-stub.php b/src/bb-vendor/geoip2/geoip2/phar-stub.php new file mode 100644 index 000000000..05b4e74cc --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/phar-stub.php @@ -0,0 +1,17 @@ + + + + + + ./tests/GeoIp2/Test/ + + + + + + ./src/GeoIp2/ + + + + + + + + diff --git a/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Database/Reader.php b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Database/Reader.php new file mode 100644 index 000000000..ffad3035c --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Database/Reader.php @@ -0,0 +1,229 @@ +dbReader = new DbReader($filename); + $this->locales = $locales; + } + + /** + * This method returns a GeoIP2 City model. + * + * @param string $ipAddress IPv4 or IPv6 address as a string. + * + * @return \GeoIp2\Model\City + * + * @throws \GeoIp2\Exception\AddressNotFoundException if the address is + * not in the database. + * @throws \MaxMind\Db\Reader\InvalidDatabaseException if the database + * is corrupt or invalid + */ + public function city($ipAddress) + { + return $this->modelFor('City', 'City', $ipAddress); + } + + /** + * This method returns a GeoIP2 Country model. + * + * @param string $ipAddress IPv4 or IPv6 address as a string. + * + * @return \GeoIp2\Model\Country + * + * @throws \GeoIp2\Exception\AddressNotFoundException if the address is + * not in the database. + * @throws \MaxMind\Db\Reader\InvalidDatabaseException if the database + * is corrupt or invalid + */ + public function country($ipAddress) + { + return $this->modelFor('Country', 'Country', $ipAddress); + } + + /** + * This method returns a GeoIP2 Anonymous IP model. + * + * @param string $ipAddress IPv4 or IPv6 address as a string. + * + * @return \GeoIp2\Model\AnonymousIp + * + * @throws \GeoIp2\Exception\AddressNotFoundException if the address is + * not in the database. + * @throws \MaxMind\Db\Reader\InvalidDatabaseException if the database + * is corrupt or invalid + */ + public function anonymousIp($ipAddress) + { + return $this->flatModelFor( + 'AnonymousIp', + 'GeoIP2-Anonymous-IP', + $ipAddress + ); + } + + /** + * This method returns a GeoIP2 Connection Type model. + * + * @param string $ipAddress IPv4 or IPv6 address as a string. + * + * @return \GeoIp2\Model\ConnectionType + * + * @throws \GeoIp2\Exception\AddressNotFoundException if the address is + * not in the database. + * @throws \MaxMind\Db\Reader\InvalidDatabaseException if the database + * is corrupt or invalid + */ + public function connectionType($ipAddress) + { + return $this->flatModelFor( + 'ConnectionType', + 'GeoIP2-Connection-Type', + $ipAddress + ); + } + + /** + * This method returns a GeoIP2 Domain model. + * + * @param string $ipAddress IPv4 or IPv6 address as a string. + * + * @return \GeoIp2\Model\Domain + * + * @throws \GeoIp2\Exception\AddressNotFoundException if the address is + * not in the database. + * @throws \MaxMind\Db\Reader\InvalidDatabaseException if the database + * is corrupt or invalid + */ + public function domain($ipAddress) + { + return $this->flatModelFor( + 'Domain', + 'GeoIP2-Domain', + $ipAddress + ); + } + + /** + * This method returns a GeoIP2 ISP model. + * + * @param string $ipAddress IPv4 or IPv6 address as a string. + * + * @return \GeoIp2\Model\Isp + * + * @throws \GeoIp2\Exception\AddressNotFoundException if the address is + * not in the database. + * @throws \MaxMind\Db\Reader\InvalidDatabaseException if the database + * is corrupt or invalid + */ + public function isp($ipAddress) + { + return $this->flatModelFor( + 'Isp', + 'GeoIP2-ISP', + $ipAddress + ); + } + + private function modelFor($class, $type, $ipAddress) + { + $record = $this->getRecord($class, $type, $ipAddress); + + $record['traits']['ip_address'] = $ipAddress; + $class = "GeoIp2\\Model\\" . $class; + + return new $class($record, $this->locales); + } + + private function flatModelFor($class, $type, $ipAddress) + { + $record = $this->getRecord($class, $type, $ipAddress); + + $record['ip_address'] = $ipAddress; + $class = "GeoIp2\\Model\\" . $class; + + return new $class($record); + } + + private function getRecord($class, $type, $ipAddress) + { + if (strpos($this->metadata()->databaseType, $type) === false) { + $method = lcfirst($class); + throw new \BadMethodCallException( + "The $method method cannot be used to open a " + . $this->metadata()->databaseType . " database" + ); + } + $record = $this->dbReader->get($ipAddress); + if ($record === null) { + throw new AddressNotFoundException( + "The address $ipAddress is not in the database." + ); + } + return $record; + } + + /** + * @throws \InvalidArgumentException if arguments are passed to the method. + * @throws \BadMethodCallException if the database has been closed. + * @return \MaxMind\Db\Reader\Metadata object for the database. + */ + public function metadata() + { + return $this->dbReader->metadata(); + } + + /** + * Closes the GeoIP2 database and returns the resources to the system. + */ + public function close() + { + $this->dbReader->close(); + } +} diff --git a/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Exception/AddressNotFoundException.php b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Exception/AddressNotFoundException.php new file mode 100644 index 000000000..d5483388b --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Exception/AddressNotFoundException.php @@ -0,0 +1,10 @@ +uri = $uri; + parent::__construct($message, $httpStatus, $previous); + } +} diff --git a/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Exception/InvalidRequestException.php b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Exception/InvalidRequestException.php new file mode 100644 index 000000000..6712d73e9 --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Exception/InvalidRequestException.php @@ -0,0 +1,26 @@ +error = $error; + parent::__construct($message, $httpStatus, $uri, $previous); + } +} diff --git a/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Exception/OutOfQueriesException.php b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Exception/OutOfQueriesException.php new file mode 100644 index 000000000..87a6ade41 --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Exception/OutOfQueriesException.php @@ -0,0 +1,10 @@ +raw = $raw; + } + + /** + * @ignore + */ + protected function get($field) + { + if (isset($this->raw[$field])) { + return $this->raw[$field]; + } else { + if (preg_match('/^is_/', $field)) { + return false; + } else { + return null; + } + } + } + + /** + * @ignore + */ + public function __get($attr) + { + if ($attr != "instance" && property_exists($this, $attr)) { + return $this->$attr; + } + + throw new \RuntimeException("Unknown attribute: $attr"); + } + + /** + * @ignore + */ + public function __isset($attr) + { + return $attr != "instance" && isset($this->$attr); + } + + public function jsonSerialize() + { + return $this->raw; + } +} diff --git a/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Model/AnonymousIp.php b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Model/AnonymousIp.php new file mode 100644 index 000000000..fb6cbd11b --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Model/AnonymousIp.php @@ -0,0 +1,50 @@ +isAnonymous = $this->get('is_anonymous'); + $this->isAnonymousVpn = $this->get('is_anonymous_vpn'); + $this->isHostingProvider = $this->get('is_hosting_provider'); + $this->isPublicProxy = $this->get('is_public_proxy'); + $this->isTorExitNode = $this->get('is_tor_exit_node'); + $this->ipAddress = $this->get('ip_address'); + } +} diff --git a/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Model/City.php b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Model/City.php new file mode 100644 index 000000000..adb61c89e --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Model/City.php @@ -0,0 +1,119 @@ +city = new \GeoIp2\Record\City($this->get('city'), $locales); + $this->location = new \GeoIp2\Record\Location($this->get('location')); + $this->postal = new \GeoIp2\Record\Postal($this->get('postal')); + + $this->createSubdivisions($raw, $locales); + } + + private function createSubdivisions($raw, $locales) + { + if (!isset($raw['subdivisions'])) { + return; + } + + foreach ($raw['subdivisions'] as $sub) { + array_push( + $this->subdivisions, + new \GeoIp2\Record\Subdivision($sub, $locales) + ); + } + } + + /** + * @ignore + */ + public function __get($attr) + { + if ($attr == 'mostSpecificSubdivision') { + return $this->$attr(); + } else { + return parent::__get($attr); + } + } + + private function mostSpecificSubdivision() + { + return empty($this->subdivisions) ? + new \GeoIp2\Record\Subdivision(array(), $this->locales) : + end($this->subdivisions); + } +} diff --git a/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Model/ConnectionType.php b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Model/ConnectionType.php new file mode 100644 index 000000000..ffc617868 --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Model/ConnectionType.php @@ -0,0 +1,31 @@ +connectionType = $this->get('connection_type'); + $this->ipAddress = $this->get('ip_address'); + } +} diff --git a/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Model/Country.php b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Model/Country.php new file mode 100644 index 000000000..5d8e130ce --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Model/Country.php @@ -0,0 +1,73 @@ +continent = new \GeoIp2\Record\Continent( + $this->get('continent'), + $locales + ); + $this->country = new \GeoIp2\Record\Country( + $this->get('country'), + $locales + ); + $this->maxmind = new \GeoIp2\Record\MaxMind($this->get('maxmind')); + $this->registeredCountry = new \GeoIp2\Record\Country( + $this->get('registered_country'), + $locales + ); + $this->representedCountry = new \GeoIp2\Record\RepresentedCountry( + $this->get('represented_country'), + $locales + ); + $this->traits = new \GeoIp2\Record\Traits($this->get('traits')); + + $this->locales = $locales; + } +} diff --git a/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Model/Domain.php b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Model/Domain.php new file mode 100644 index 000000000..cd55b044f --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Model/Domain.php @@ -0,0 +1,31 @@ +domain = $this->get('domain'); + $this->ipAddress = $this->get('ip_address'); + } +} diff --git a/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Model/Insights.php b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Model/Insights.php new file mode 100644 index 000000000..a738a997a --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Model/Insights.php @@ -0,0 +1,56 @@ +autonomousSystemNumber = $this->get('autonomous_system_number'); + $this->autonomousSystemOrganization = + $this->get('autonomous_system_organization'); + $this->isp = $this->get('isp'); + $this->organization = $this->get('organization'); + + $this->ipAddress = $this->get('ip_address'); + } +} diff --git a/src/bb-vendor/geoip2/geoip2/src/GeoIp2/ProviderInterface.php b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/ProviderInterface.php new file mode 100644 index 000000000..6c3992f55 --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/ProviderInterface.php @@ -0,0 +1,20 @@ +locales = $locales; + parent::__construct($record); + } + + /** + * @ignore + */ + public function __get($attr) + { + if ($attr == 'name') { + return $this->name(); + } else { + return parent::__get($attr); + } + } + + private function name() + { + foreach ($this->locales as $locale) { + if (isset($this->names[$locale])) { + return $this->names[$locale]; + } + } + } +} diff --git a/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Record/AbstractRecord.php b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Record/AbstractRecord.php new file mode 100644 index 000000000..42f0887e1 --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Record/AbstractRecord.php @@ -0,0 +1,58 @@ +record = isset($record) ? $record : array(); + } + + /** + * @ignore + */ + public function __get($attr) + { + // XXX - kind of ugly but greatly reduces boilerplate code + $key = $this->attributeToKey($attr); + + if ($this->__isset($attr)) { + return $this->record[$key]; + } elseif ($this->validAttribute($attr)) { + if (preg_match('/^is_/', $key)) { + return false; + } else { + return null; + } + } else { + throw new \RuntimeException("Unknown attribute: $attr"); + } + } + + public function __isset($attr) + { + return $this->validAttribute($attr) && + isset($this->record[$this->attributeToKey($attr)]); + } + + private function attributeToKey($attr) + { + return strtolower(preg_replace('/([A-Z])/', '_\1', $attr)); + } + + private function validAttribute($attr) + { + return in_array($attr, $this->validAttributes); + } + + public function jsonSerialize() + { + return $this->record; + } +} diff --git a/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Record/City.php b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Record/City.php new file mode 100644 index 000000000..31c2b6416 --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Record/City.php @@ -0,0 +1,29 @@ +military + * but this could expand to include other types in the future. + */ +class RepresentedCountry extends Country +{ + protected $validAttributes = array( + 'confidence', + 'geonameId', + 'isoCode', + 'names', + 'type' + ); +} diff --git a/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Record/Subdivision.php b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Record/Subdivision.php new file mode 100644 index 000000000..61758ddb8 --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/Record/Subdivision.php @@ -0,0 +1,42 @@ +The user type associated with the IP + * address. This can be one of the following values:

+ *
    + *
  • business + *
  • cafe + *
  • cellular + *
  • college + *
  • content_delivery_network + *
  • dialup + *
  • government + *
  • hosting + *
  • library + *
  • military + *
  • residential + *
  • router + *
  • school + *
  • search_engine_spider + *
  • traveler + *
+ *

+ * This attribute is only available from the Insights web service end + * point. + *

+ */ +class Traits extends AbstractRecord +{ + /** + * @ignore + */ + protected $validAttributes = array( + 'autonomousSystemNumber', + 'autonomousSystemOrganization', + 'domain', + 'isAnonymousProxy', + 'isSatelliteProvider', + 'isp', + 'ipAddress', + 'organization', + 'userType' + ); +} diff --git a/src/bb-vendor/geoip2/geoip2/src/GeoIp2/WebService/Client.php b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/WebService/Client.php new file mode 100644 index 000000000..45db4ae88 --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/src/GeoIp2/WebService/Client.php @@ -0,0 +1,326 @@ +userId = $userId; + $this->licenseKey = $licenseKey; + $this->locales = $locales; + $this->host = $host; + // To enable unit testing + $this->guzzleClient = $guzzleClient; + } + + /** + * This method calls the GeoIP2 Precision: City endpoint. + * + * @param string $ipAddress IPv4 or IPv6 address as a string. If no + * address is provided, the address that the web service is called + * from will be used. + * + * @return \GeoIp2\Model\City + * + * @throws \GeoIp2\Exception\AddressNotFoundException if the address you + * provided is not in our database (e.g., a private address). + * @throws \GeoIp2\Exception\AuthenticationException if there is a problem + * with the user ID or license key that you provided. + * @throws \GeoIp2\Exception\OutOfQueriesException if your account is out + * of queries. + * @throws \GeoIp2\Exception\InvalidRequestException} if your request was + * received by the web service but is invalid for some other reason. + * This may indicate an issue with this API. Please report the error to + * MaxMind. + * @throws \GeoIp2\Exception\HttpException if an unexpected HTTP error + * code or message was returned. This could indicate a problem with the + * connection between your server and the web service or that the web + * service returned an invalid document or 500 error code. + * @throws \GeoIp2\Exception\GeoIp2Exception This serves as the parent + * class to the above exceptions. It will be thrown directly if a 200 + * status code is returned but the body is invalid. + */ + public function city($ipAddress = 'me') + { + return $this->responseFor('city', 'City', $ipAddress); + } + + /** + * This method calls the GeoIP2 Precision: Country endpoint. + * + * @param string $ipAddress IPv4 or IPv6 address as a string. If no + * address is provided, the address that the web service is called + * from will be used. + * + * @return \GeoIp2\Model\Country + * + * @throws \GeoIp2\Exception\AddressNotFoundException if the address you + * provided is not in our database (e.g., a private address). + * @throws \GeoIp2\Exception\AuthenticationException if there is a problem + * with the user ID or license key that you provided. + * @throws \GeoIp2\Exception\OutOfQueriesException if your account is out + * of queries. + * @throws \GeoIp2\Exception\InvalidRequestException} if your request was + * received by the web service but is invalid for some other reason. + * This may indicate an issue with this API. Please report the error to + * MaxMind. + * @throws \GeoIp2\Exception\HttpException if an unexpected HTTP error + * code or message was returned. This could indicate a problem with the + * connection between your server and the web service or that the web + * service returned an invalid document or 500 error code. + * @throws \GeoIp2\Exception\GeoIp2Exception This serves as the parent + * class to the above exceptions. It will be thrown directly if a 200 + * status code is returned but the body is invalid. + */ + public function country($ipAddress = 'me') + { + return $this->responseFor('country', 'Country', $ipAddress); + } + + /** + * This method calls the GeoIP2 Precision: Insights endpoint. + * + * @param string $ipAddress IPv4 or IPv6 address as a string. If no + * address is provided, the address that the web service is called + * from will be used. + * + * @return \GeoIp2\Model\Insights + * + * @throws \GeoIp2\Exception\AddressNotFoundException if the address you + * provided is not in our database (e.g., a private address). + * @throws \GeoIp2\Exception\AuthenticationException if there is a problem + * with the user ID or license key that you provided. + * @throws \GeoIp2\Exception\OutOfQueriesException if your account is out + * of queries. + * @throws \GeoIp2\Exception\InvalidRequestException} if your request was + * received by the web service but is invalid for some other reason. + * This may indicate an issue with this API. Please report the error to + * MaxMind. + * @throws \GeoIp2\Exception\HttpException if an unexpected HTTP error + * code or message was returned. This could indicate a problem with the + * connection between your server and the web service or that the web + * service returned an invalid document or 500 error code. + * @throws \GeoIp2\Exception\GeoIp2Exception This serves as the parent + * class to the above exceptions. It will be thrown directly if a 200 + * status code is returned but the body is invalid. + */ + public function insights($ipAddress = 'me') + { + return $this->responseFor('insights', 'Insights', $ipAddress); + } + + private function responseFor($endpoint, $class, $ipAddress) + { + $uri = implode('/', array($this->baseUri(), $endpoint, $ipAddress)); + + $client = $this->guzzleClient ? + $this->guzzleClient : new GuzzleClient(); + $request = $client->get($uri, array('Accept' => 'application/json')); + $request->setAuth($this->userId, $this->licenseKey); + $this->setUserAgent($request); + + try { + $response = $request->send(); + } catch (ClientErrorResponseException $e) { + $this->handle4xx($e->getResponse(), $uri); + } catch (ServerErrorResponseException $e) { + $this->handle5xx($e->getResponse(), $uri); + } + + if ($response && $response->isSuccessful()) { + $body = $this->handleSuccess($response, $uri); + $class = "GeoIp2\\Model\\" . $class; + return new $class($body, $this->locales); + } else { + $this->handleNon200($response, $uri); + } + } + + private function handleSuccess($response, $uri) + { + if ($response->getContentLength() == 0) { + throw new GeoIp2Exception( + "Received a 200 response for $uri but did not " . + "receive a HTTP body." + ); + } + + try { + return $response->json(); + } catch (RuntimeException $e) { + throw new GeoIp2Exception( + "Received a 200 response for $uri but could not decode " . + "the response as JSON: " . $e->getMessage() + ); + + } + } + + private function handle4xx($response, $uri) + { + $status = $response->getStatusCode(); + + if ($response->getContentLength() > 0) { + if (strstr($response->getContentType(), 'json')) { + try { + $body = $response->json(); + if (!isset($body['code']) || !isset($body['error'])) { + throw new GeoIp2Exception( + 'Response contains JSON but it does not specify ' . + 'code or error keys: ' . $response->getBody() + ); + } + } catch (RuntimeException $e) { + throw new HttpException( + "Received a $status error for $uri but it did not " . + "include the expected JSON body: " . + $e->getMessage(), + $status, + $uri + ); + } + } else { + throw new HttpException( + "Received a $status error for $uri with the " . + "following body: " . $response->getBody(), + $status, + $uri + ); + } + } else { + throw new HttpException( + "Received a $status error for $uri with no body", + $status, + $uri + ); + } + $this->handleWebServiceError( + $body['error'], + $body['code'], + $status, + $uri + ); + } + + private function handleWebServiceError($message, $code, $status, $uri) + { + switch ($code) { + case 'IP_ADDRESS_NOT_FOUND': + case 'IP_ADDRESS_RESERVED': + throw new AddressNotFoundException($message); + case 'AUTHORIZATION_INVALID': + case 'LICENSE_KEY_REQUIRED': + case 'USER_ID_REQUIRED': + throw new AuthenticationException($message); + case 'OUT_OF_QUERIES': + throw new OutOfQueriesException($message); + default: + throw new InvalidRequestException( + $message, + $code, + $status, + $uri + ); + } + } + + private function handle5xx($response, $uri) + { + $status = $response->getStatusCode(); + + throw new HttpException( + "Received a server error ($status) for $uri", + $status, + $uri + ); + } + + private function handleNon200($response, $uri) + { + $status = $response->getStatusCode(); + + throw new HttpException( + "Received a very surprising HTTP status " . + "($status) for $uri", + $status, + $uri + ); + } + + private function setUserAgent($request) + { + $userAgent = $request->getHeader('User-Agent'); + $userAgent = "GeoIP2 PHP API ($userAgent)"; + $request->setHeader('User-Agent', $userAgent); + } + + private function baseUri() + { + return 'https://' . $this->host . '/geoip/v2.1'; + } +} diff --git a/src/bb-vendor/geoip2/geoip2/tests/GeoIp2/Test/Database/ReaderTest.php b/src/bb-vendor/geoip2/geoip2/tests/GeoIp2/Test/Database/ReaderTest.php new file mode 100644 index 000000000..ef00e742e --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/tests/GeoIp2/Test/Database/ReaderTest.php @@ -0,0 +1,154 @@ +$method('81.2.69.160'); + $this->assertEquals('United Kingdom', $record->country->name); + } + $reader->close(); + } + + public function testLocaleList() + { + + foreach (array('City', 'Country') as $type) { + $reader = new Reader( + "maxmind-db/test-data/GeoIP2-$type-Test.mmdb", + array('xx', 'ru', 'pt-BR', 'es', 'en') + ); + $method = lcfirst($type); + + $record = $reader->$method('81.2.69.160'); + $this->assertEquals('Великобритания', $record->country->name); + } + $reader->close(); + } + + public function testHasIpAddress() + { + foreach (array('City', 'Country') as $type) { + $reader = new Reader("maxmind-db/test-data/GeoIP2-$type-Test.mmdb"); + $method = lcfirst($type); + $record = $reader->$method('81.2.69.160'); + $this->assertEquals('81.2.69.160', $record->traits->ipAddress); + } + $reader->close(); + } + + /** + * @expectedException GeoIp2\Exception\AddressNotFoundException + * @expectedExceptionMessage The address 10.10.10.10 is not in the database. + */ + public function testUnknownAddress() + { + $reader = new Reader('maxmind-db/test-data/GeoIP2-City-Test.mmdb'); + $reader->city('10.10.10.10'); + $reader->close(); + } + + /** + * @expectedException BadMethodCallException + * @expectedExceptionMessage The country method cannot be used to open a GeoIP2-City database + */ + public function testIncorrectDatabase() + { + $reader = new Reader('maxmind-db/test-data/GeoIP2-City-Test.mmdb'); + $reader->country('10.10.10.10'); + $reader->close(); + } + + /** + * @expectedException BadMethodCallException + * @expectedExceptionMessage The domain method cannot be used to open a GeoIP2-City database + */ + public function testIncorrectDatabaseFlat() + { + $reader = new Reader('maxmind-db/test-data/GeoIP2-City-Test.mmdb'); + $reader->domain('10.10.10.10'); + $reader->close(); + } + + /** + * @expectedException InvalidArgumentException + * @expectedExceptionMessage is not a valid IP address + */ + public function testInvalidAddress() + { + $reader = new Reader('maxmind-db/test-data/GeoIP2-City-Test.mmdb'); + $reader->city('invalid'); + $reader->close(); + } + + public function testAnonymousIp() + { + $reader = new Reader('maxmind-db/test-data/GeoIP2-Anonymous-IP-Test.mmdb'); + $ipAddress = '1.2.0.1'; + + $record = $reader->anonymousIp($ipAddress); + $this->assertSame(true, $record->isAnonymous); + $this->assertSame(true, $record->isAnonymousVpn); + $this->assertSame(false, $record->isHostingProvider); + $this->assertSame(false, $record->isPublicProxy); + $this->assertSame(false, $record->isTorExitNode); + $this->assertEquals($ipAddress, $record->ipAddress); + $reader->close(); + } + + public function testConnectionType() + { + $reader = new Reader('maxmind-db/test-data/GeoIP2-Connection-Type-Test.mmdb'); + $ipAddress = '1.0.1.0'; + + $record = $reader->connectionType($ipAddress); + $this->assertEquals('Cable/DSL', $record->connectionType); + $this->assertEquals($ipAddress, $record->ipAddress); + $reader->close(); + } + + public function testDomain() + { + $reader = new Reader('maxmind-db/test-data/GeoIP2-Domain-Test.mmdb'); + + $ipAddress = '1.2.0.0'; + $record = $reader->domain($ipAddress); + $this->assertEquals('maxmind.com', $record->domain); + $this->assertEquals($ipAddress, $record->ipAddress); + $reader->close(); + } + + public function testIsp() + { + $reader = new Reader('maxmind-db/test-data/GeoIP2-ISP-Test.mmdb'); + + $ipAddress = '1.128.0.0'; + $record = $reader->isp($ipAddress); + $this->assertEquals(1221, $record->autonomousSystemNumber); + $this->assertEquals( + 'Telstra Pty Ltd', + $record->autonomousSystemOrganization + ); + + $this->assertEquals('Telstra Internet', $record->isp); + $this->assertEquals('Telstra Internet', $record->organization); + + $this->assertEquals($ipAddress, $record->ipAddress); + $reader->close(); + } + + public function testMetadata() + { + $reader = new Reader('maxmind-db/test-data/GeoIP2-City-Test.mmdb'); + $this->assertEquals('GeoIP2-City', $reader->metadata()->databaseType); + + $reader->close(); + } +} diff --git a/src/bb-vendor/geoip2/geoip2/tests/GeoIp2/Test/Model/CountryTest.php b/src/bb-vendor/geoip2/geoip2/tests/GeoIp2/Test/Model/CountryTest.php new file mode 100644 index 000000000..ccfc96a77 --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/tests/GeoIp2/Test/Model/CountryTest.php @@ -0,0 +1,226 @@ + array( + 'code' => 'NA', + 'geoname_id' => 42, + 'names' => array('en' => 'North America'), + ), + 'country' => array( + 'geoname_id' => 1, + 'iso_code' => 'US', + 'names' => array('en' => 'United States of America'), + ), + 'registered_country' => array( + 'geoname_id' => 2, + 'iso_code' => 'CA', + 'names' => array('en' => 'Canada'), + ), + 'traits' => array( + 'ip_address' => '1.2.3.4', + ), + ); + + private $model; + + public function setUp() + { + $this->model = new Country($this->raw, array('en')); + } + + public function testObjects() + { + $this->assertInstanceOf( + 'GeoIp2\Model\Country', + $this->model, + 'minimal GeoIp2::Model::Country object' + ); + $this->assertInstanceOf( + 'GeoIp2\Record\Continent', + $this->model->continent + ); + $this->assertInstanceOf( + 'GeoIp2\Record\Country', + $this->model->country + ); + $this->assertInstanceOf( + 'GeoIp2\Record\Country', + $this->model->registeredCountry + ); + $this->assertInstanceOf( + 'GeoIp2\Record\RepresentedCountry', + $this->model->representedCountry + ); + $this->assertInstanceOf( + 'GeoIp2\Record\Traits', + $this->model->traits + ); + } + + public function testValues() + { + + $this->assertEquals( + 42, + $this->model->continent->geonameId, + 'continent geoname_id is 42' + ); + + $this->assertEquals( + 'NA', + $this->model->continent->code, + 'continent code is NA' + ); + + $this->assertEquals( + array('en' => 'North America'), + $this->model->continent->names, + 'continent names' + ); + + $this->assertEquals( + 'North America', + $this->model->continent->name, + 'continent name is North America' + ); + + $this->assertEquals( + 1, + $this->model->country->geonameId, + 'country geoname_id is 1' + ); + + $this->assertEquals( + 'US', + $this->model->country->isoCode, + 'country iso_code is US' + ); + + $this->assertEquals( + array('en' => 'United States of America'), + $this->model->country->names, + 'country name' + ); + + $this->assertEquals( + $this->model->country->name, + 'United States of America', + 'country name is United States of America' + ); + + $this->assertEquals( + null, + $this->model->country->confidence, + 'country confidence is undef' + ); + + $this->assertEquals( + 2, + $this->model->registeredCountry->geonameId, + 'registered_country geoname_id is 2' + ); + + $this->assertEquals( + 'CA', + $this->model->registeredCountry->isoCode, + 'registered_country iso_code is CA' + ); + + $this->assertEquals( + array('en' => 'Canada'), + $this->model->registeredCountry->names, + 'registered_country names' + ); + + $this->assertEquals( + 'Canada', + $this->model->registeredCountry->name, + 'registered_country name is Canada' + ); + + foreach (array('isAnonymousProxy', 'isSatelliteProvider') as $meth) { + $this->assertEquals( + 0, + $this->model->traits->$meth, + "traits $meth returns 0 by default" + ); + } + + $this->assertEquals( + $this->raw, + $this->model->raw, + 'raw method returns raw input' + ); + } + + public function testJsonSerialize() + { + $this->assertEquals( + $this->raw, + $this->model->jsonSerialize(), + 'jsonSerialize returns initial array' + ); + + $this->assertEquals( + $this->raw['country'], + $this->model->country->jsonSerialize(), + 'jsonSerialize returns initial array for the record' + ); + + if (version_compare(PHP_VERSION, '5.4.0', '<')) { + $this->markTestSkipped('Requires PHP 5.4+.'); + } + + $this->assertEquals( + json_encode($this->raw), + json_encode($this->model), + 'json_encode can be called on the model object directly' + ); + + $this->assertEquals( + json_encode($this->raw['country']), + json_encode($this->model->country), + 'json_encode can be called on the record object directly' + ); + } + + public function testIsSet() + { + $this->assertTrue(isset($this->model->traits), 'traits is set'); + $this->assertFalse(isset($this->model->unknown), 'unknown is not set'); + + $this->assertTrue( + isset($this->model->traits->ipAddress), + 'ip_address is set' + ); + $this->assertFalse( + isset($this->model->traits->unknown), + 'unknown trait is not set' + ); + } + + /** + * @expectedException RuntimeException + * @expectedExceptionMessage Unknown attribute + */ + public function testUnknownRecord() + { + $this->model->unknownRecord; + } + + /** + * @expectedException RuntimeException + * @expectedExceptionMessage Unknown attribute + */ + public function testUnknownTrait() + { + $this->model->traits->unknown; + } +} diff --git a/src/bb-vendor/geoip2/geoip2/tests/GeoIp2/Test/Model/InsightsTest.php b/src/bb-vendor/geoip2/geoip2/tests/GeoIp2/Test/Model/InsightsTest.php new file mode 100644 index 000000000..e4c7a3465 --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/tests/GeoIp2/Test/Model/InsightsTest.php @@ -0,0 +1,260 @@ + array( + 'confidence' => 76, + 'geoname_id' => 9876, + 'names' => array('en' => 'Minneapolis'), + ), + 'continent' => array( + 'code' => 'NA', + 'geoname_id' => 42, + 'names' => array('en' => 'North America'), + ), + 'country' => array( + 'confidence' => 99, + 'geoname_id' => 1, + 'iso_code' => 'US', + 'names' => array('en' => 'United States of America'), + ), + 'location' => array( + 'accuracy_radius' => 1500, + 'latitude' => 44.98, + 'longitude' => 93.2636, + 'metro_code' => 765, + 'postal_code' => '55401', + 'postal_confidence' => 33, + 'time_zone' => 'America/Chicago', + ), + 'maxmind' => array( + 'queries_remaining' => 22, + ), + 'registered_country' => array( + 'geoname_id' => 2, + 'iso_code' => 'CA', + 'names' => array('en' => 'Canada'), + ), + 'represented_country' => array( + 'geoname_id' => 3, + 'iso_code' => 'GB', + 'names' => array('en' => 'United Kingdom'), + ), + 'subdivisions' => array( + array( + 'confidence' => 88, + 'geoname_id' => 574635, + 'iso_code' => 'MN', + 'names' => array('en' => 'Minnesota'), + ) + ), + 'traits' => array( + 'autonomous_system_number' => 1234, + 'autonomous_system_organization' => 'AS Organization', + 'domain' => 'example.com', + 'ip_address' => '1.2.3.4', + 'is_satellite_provider' => true, + 'isp' => 'Comcast', + 'organization' => 'Blorg', + 'user_type' => 'college', + ), + ); + + $model = new Insights($raw, array('en')); + + $this->assertInstanceOf( + 'GeoIp2\Model\Insights', + $model, + 'GeoIp2\Model\Insights object' + ); + + $this->assertInstanceOf( + 'GeoIp2\Record\City', + $model->city, + '$model->city' + ); + + $this->assertInstanceOf( + 'GeoIp2\Record\Continent', + $model->continent, + '$model->continent' + ); + + $this->assertInstanceOf( + 'GeoIp2\Record\Country', + $model->country, + '$model->country' + ); + + $this->assertInstanceOf( + 'GeoIp2\Record\Location', + $model->location, + '$model->location' + ); + + $this->assertInstanceOf( + 'GeoIp2\Record\Country', + $model->registeredCountry, + '$model->registeredCountry' + ); + + $this->assertInstanceOf( + 'GeoIp2\Record\RepresentedCountry', + $model->representedCountry, + '$model->representedCountry' + ); + + $subdivisions = $model->subdivisions; + foreach ($subdivisions as $subdiv) { + $this->assertInstanceOf('GeoIp2\Record\Subdivision', $subdiv); + } + + $this->assertInstanceOf( + 'GeoIp2\Record\Subdivision', + $model->mostSpecificSubdivision, + '$model->mostSpecificSubdivision' + ); + + $this->assertInstanceOf( + 'GeoIp2\Record\Traits', + $model->traits, + '$model->traits' + ); + + $this->assertSame( + true, + $model->traits->isSatelliteProvider, + '$model->traits->isSatelliteProvider is true' + ); + + $this->assertSame( + false, + $model->traits->isAnonymousProxy, + '$model->traits->isAnonymousProxy is false' + ); + + $this->assertEquals( + 22, + $model->maxmind->queriesRemaining, + 'queriesRemaining is correct' + ); + + $this->assertEquals( + $raw, + $model->raw, + 'raw method returns raw input' + ); + } + + public function testEmptyObjects() + { + $raw = array('traits' => array('ip_address' => '5.6.7.8')); + + $model = new Insights($raw, array('en')); + + $this->assertInstanceOf( + 'GeoIp2\Model\Insights', + $model, + 'GeoIp2\Model\Insights object with no data except traits.ipAddress' + ); + + $this->assertInstanceOf( + 'GeoIp2\Record\City', + $model->city, + '$model->city' + ); + + $this->assertInstanceOf( + 'GeoIp2\Record\Continent', + $model->continent, + '$model->continent' + ); + + $this->assertInstanceOf( + 'GeoIp2\Record\Country', + $model->country, + '$model->country' + ); + + $this->assertInstanceOf( + 'GeoIp2\Record\Location', + $model->location, + '$model->location' + ); + + $this->assertInstanceOf( + 'GeoIp2\Record\Country', + $model->registeredCountry, + '$model->registeredCountry' + ); + + $this->assertInstanceOf( + 'GeoIp2\Record\RepresentedCountry', + $model->representedCountry, + '$model->representedCountry' + ); + + $this->assertCount( + 0, + $model->subdivisions, + '$model->subdivisions returns an empty list' + ); + + $this->assertInstanceOf( + 'GeoIp2\Record\Subdivision', + $model->mostSpecificSubdivision, + '$model->mostSpecificSubdivision' + ); + + $this->assertInstanceOf( + 'GeoIp2\Record\Traits', + $model->traits, + '$model->traits' + ); + + $this->assertEquals( + $raw, + $model->raw, + 'raw method returns raw input with no added empty values' + ); + } + + + public function testUnknown() + { + $raw = array( + 'new_top_level' => array('foo' => 42), + 'city' => array( + 'confidence' => 76, + 'geoname_id_id' => 9876, + 'names' => array('en' => 'Minneapolis'), + 'population' => 50, + ), + 'traits' => array('ip_address' => '5.6.7.8') + ); + + // checking whether there are exceptions with unknown keys + $model = new Insights($raw, array('en')); + + $this->assertInstanceOf( + 'GeoIp2\Model\Insights', + $model, + 'no exception when Insights model gets raw data with unknown keys' + ); + + $this->assertEquals( + $raw, + $model->raw, + 'raw method returns raw input' + ); + } +} diff --git a/src/bb-vendor/geoip2/geoip2/tests/GeoIp2/Test/Model/NameTest.php b/src/bb-vendor/geoip2/geoip2/tests/GeoIp2/Test/Model/NameTest.php new file mode 100644 index 000000000..78fe7c656 --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/tests/GeoIp2/Test/Model/NameTest.php @@ -0,0 +1,82 @@ + array( + 'code' => 'NA', + 'geoname_id' => 42, + 'names' => array( + 'en' => 'North America', + 'zh-CN' => '北美洲', + ), + ), + 'country' => array( + 'geoname_id' => 1, + 'iso_code' => 'US', + 'names' => array( + 'en' => 'United States of America', + 'ru' => 'объединяет государства', + 'zh-CN' => '美国', + ), + ), + 'traits' => array( + 'ip_address' => '1.2.3.4', + ), + ); + + public function testFallback() + { + $model = new Country($this->raw, array('ru', 'zh-CN', 'en')); + + $this->assertEquals( + '北美洲', + $model->continent->name, + 'continent name is in Chinese (no Russian available)' + ); + + $this->assertEquals( + 'объединяет государства', + $model->country->name, + 'country name is in Russian' + ); + } + + public function testTwoFallbacks() + { + $model = new Country($this->raw, array('ru', 'ja')); + + $this->assertEquals( + null, + $model->continent->name, + 'continent name is undef (no Russian or Japanese available)' + ); + + $this->assertEquals( + 'объединяет государства', + $model->country->name, + 'country name is in Russian' + ); + } + + public function testNoFallbacks() + { + $model = new Country($this->raw, array('ja')); + + $this->assertEquals( + null, + $model->continent->name, + 'continent name is undef (no Japanese available) ' + ); + + $this->assertEquals( + null, + $model->country->name, + 'country name is undef (no Japanese available) ' + ); + } +} diff --git a/src/bb-vendor/geoip2/geoip2/tests/GeoIp2/Test/WebService/ClientTest.php b/src/bb-vendor/geoip2/geoip2/tests/GeoIp2/Test/WebService/ClientTest.php new file mode 100644 index 000000000..9270da85b --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/tests/GeoIp2/Test/WebService/ClientTest.php @@ -0,0 +1,502 @@ + array( + 'code' => 'NA', + 'geoname_id' => 42, + 'names' => array('en' => 'North America'), + ), + 'country' => array( + 'geoname_id' => 1, + 'iso_code' => 'US', + 'names' => array('en' => 'United States of America'), + ), + 'maxmind' => array('queries_remaining' => 11), + 'traits' => array( + 'ip_address' => '1.2.3.4', + ), + ); + + + private function getResponse($ip) + { + $responses = array( + '1.2.3.4' => $this->response( + 'country', + 200, + $this->country + ), + 'me' => $this->response( + 'country', + 200, + $this->country + ), + '1.2.3.5' => $this->response('country', 200), + '2.2.3.5' => $this->response('country', 200, 'bad body'), + '1.2.3.6' => $this->response( + 'error', + 400, + array( + 'code' => 'IP_ADDRESS_INVALID', + 'error' => 'The value "1.2.3" is not a valid ip address' + ) + ), + '1.2.3.7' => $this->response( + 'error', + 400 + ), + '1.2.3.8' => $this->response( + 'error', + 400, + array('weird' => 42) + ), + '1.2.3.9' => $this->response( + 'error', + 400, + null, + 'bad body' + ), + '1.2.3.10' => $this->response( + null, + 500 + ), + '1.2.3.11' => $this->response( + null, + 300 + ), + '1.2.3.12' => $this->response( + 'error', + 406, + 'Cannot satisfy your Accept-Charset requirements', + null, + 'text/plain' + ), + '1.2.3.13' => $this->response( + 'error', + 404, + array( + 'code' => 'IP_ADDRESS_NOT_FOUND', + 'error' => 'The address "1.2.3.13" is not in our database.' + ) + ), + '1.2.3.14' => $this->response( + 'error', + 400, + array( + 'code' => 'IP_ADDRESS_RESERVED', + 'error' => 'The address "1.2.3.14" is a private address.' + ) + ), + '1.2.3.15' => $this->response( + 'error', + 401, + array( + 'code' => 'AUTHORIZATION_INVALID', + 'error' => 'A user ID and license key are required to use this service' + ) + ), + '1.2.3.16' => $this->response( + 'error', + 401, + array( + 'code' => 'LICENSE_KEY_REQUIRED', + 'error' => 'A license key is required to use this service' + ) + ), + '1.2.3.17' => $this->response( + 'error', + 401, + array( + 'code' => 'USER_ID_REQUIRED', + 'error' => 'A user ID is required to use this service' + ) + ), + '1.2.3.18' => $this->response( + 'error', + 402, + array( + 'code' => 'OUT_OF_QUERIES', + 'error' => 'The license key you have provided is out of queries.' + ) + ), + ); + return $responses[$ip]; + } + + public function testCountry() + { + $country = $this->client($this->getResponse('1.2.3.4')) + ->country('1.2.3.4'); + + $this->assertInstanceOf('GeoIp2\Model\Country', $country); + + $this->assertEquals( + 42, + $country->continent->geonameId, + 'continent geoname_id is 42' + ); + + $this->assertEquals( + 'NA', + $country->continent->code, + 'continent code is NA' + ); + + $this->assertEquals( + array('en' => 'North America'), + $country->continent->names, + 'continent names' + ); + + $this->assertEquals( + 'North America', + $country->continent->name, + 'continent name is North America' + ); + + $this->assertEquals( + 1, + $country->country->geonameId, + 'country geoname_id is 1' + ); + + $this->assertEquals( + 'US', + $country->country->isoCode, + 'country iso_code is US' + ); + + $this->assertEquals( + array('en' => 'United States of America'), + $country->country->names, + 'country names' + ); + + $this->assertEquals( + 'United States of America', + $country->country->name, + 'country name is United States of America' + ); + + $this->assertEquals( + 11, + $country->maxmind->queriesRemaining, + 'queriesRemaining is correct' + ); + + } + + + public function testInsights() + { + + $record = $this->client($this->getResponse('1.2.3.4')) + ->insights('1.2.3.4'); + + $this->assertInstanceOf('GeoIp2\Model\Insights', $record); + + $this->assertEquals( + 42, + $record->continent->geonameId, + 'continent geoname_id is 42' + ); + } + + public function testCity() + { + $city = $this->client($this->getResponse('1.2.3.4')) + ->city('1.2.3.4'); + + $this->assertInstanceOf('GeoIp2\Model\City', $city); + } + + public function testMe() + { + $client = $this->client($this->getResponse('me')); + + $this->assertInstanceOf( + 'GeoIp2\Model\City', + $client->city('me'), + 'can set ip parameter to me' + ); + } + + /** + * @expectedException GeoIp2\Exception\GeoIp2Exception + * @expectedExceptionMessage Received a 200 response for https://geoip.maxmind.com/geoip/v2.1/country/1.2.3.5 but did not receive a HTTP body. + */ + public function testNoBodyException() + { + $client = $this->client($this->getResponse('1.2.3.5')); + + $client->country('1.2.3.5'); + } + + /** + * @expectedException GeoIp2\Exception\GeoIp2Exception + * @expectedExceptionMessage Received a 200 response for https://geoip.maxmind.com/geoip/v2.1/country/2.2.3.5 but could not decode the response as JSON: + */ + public function testBadBodyException() + { + $client = $this->client($this->getResponse('2.2.3.5')); + + $client->country('2.2.3.5'); + } + + + /** + * @expectedException GeoIp2\Exception\InvalidRequestException + * @expectedExceptionCode 400 + * @expectedExceptionMessage The value "1.2.3" is not a valid ip address + */ + public function testInvalidIPException() + { + $client = $this->client($this->getResponse('1.2.3.6')); + + $client->country('1.2.3.6'); + } + + /** + * @expectedException GeoIp2\Exception\HttpException + * @expectedExceptionCode 400 + * @expectedExceptionMessage with no body + */ + public function testNoErrorBodyIPException() + { + $client = $this->client($this->getResponse('1.2.3.7')); + + $client->country('1.2.3.7'); + } + + /** + * @expectedException GeoIp2\Exception\GeoIp2Exception + * @expectedExceptionMessage Response contains JSON but it does not specify code or error keys + */ + public function testWeirdErrorBodyIPException() + { + $client = $this->client($this->getResponse('1.2.3.8')); + + $client->country('1.2.3.8'); + + } + + /** + * @expectedException GeoIp2\Exception\HttpException + * @expectedExceptionCode 400 + * @expectedExceptionMessage did not include the expected JSON body + */ + public function testInvalidErrorBodyIPException() + { + $client = $this->client($this->getResponse('1.2.3.9')); + + $client->country('1.2.3.9'); + + } + + /** + * @expectedException GeoIp2\Exception\HttpException + * @expectedExceptionCode 500 + * @expectedExceptionMessage Received a server error (500) + */ + public function test500PException() + { + $client = $this->client($this->getResponse('1.2.3.10')); + + $client->country('1.2.3.10'); + + } + + /** + * @expectedException GeoIp2\Exception\HttpException + * @expectedExceptionCode 300 + * @expectedExceptionMessage Received a very surprising HTTP status (300) + */ + public function test3xxException() + { + $client = $this->client($this->getResponse('1.2.3.11')); + + $client->country('1.2.3.11'); + + } + + /** + * @expectedException GeoIp2\Exception\HttpException + * @expectedExceptionCode 406 + * @expectedExceptionMessage Received a 406 error for https://geoip.maxmind.com/geoip/v2.1/country/1.2.3.12 with the following body: Cannot satisfy your Accept-Charset requirements + */ + public function test406Exception() + { + $client = $this->client($this->getResponse('1.2.3.12')); + $client->country('1.2.3.12'); + } + + /** + * @expectedException GeoIp2\Exception\AddressNotFoundException + * @expectedExceptionMessage The address "1.2.3.13" is not in our database. + */ + public function testAddressNotFoundException() + { + $client = $this->client($this->getResponse('1.2.3.13')); + + $client->country('1.2.3.13'); + } + + /** + * @expectedException GeoIp2\Exception\AddressNotFoundException + * @expectedExceptionMessage The address "1.2.3.14" is a private address. + */ + public function testAddressReservedException() + { + $client = $this->client($this->getResponse('1.2.3.14')); + + $client->country('1.2.3.14'); + } + + /** + * @expectedException GeoIp2\Exception\AuthenticationException + * @expectedExceptionMessage A user ID and license key are required to use this service + */ + public function testAuthorizationException() + { + $client = $this->client($this->getResponse('1.2.3.15')); + + $client->country('1.2.3.15'); + } + + /** + * @expectedException GeoIp2\Exception\AuthenticationException + * @expectedExceptionMessage A license key is required to use this service + */ + public function testMissingLicenseKeyException() + { + $client = $this->client($this->getResponse('1.2.3.16')); + + $client->country('1.2.3.16'); + } + + /** + * @expectedException GeoIp2\Exception\AuthenticationException + * @expectedExceptionMessage A user ID is required to use this service + */ + public function testMissingUserIdException() + { + $client = $this->client($this->getResponse('1.2.3.17')); + + $client->country('1.2.3.17'); + } + + /** + * @expectedException GeoIp2\Exception\OutOfQueriesException + * @expectedExceptionMessage The license key you have provided is out of queries. + */ + public function testOutOfQueriesException() + { + $client = $this->client($this->getResponse('1.2.3.18')); + + $client->country('1.2.3.18'); + } + + public function testParams() + { + $plugin = new MockPlugin(); + $plugin->addResponse($this->getResponse('1.2.3.4')); + $guzzleClient = new GuzzleClient(); + $guzzleClient->addSubscriber($plugin); + + $client = new Client( + 42, + 'abcdef123456', + array('en'), + 'geoip.maxmind.com', + $guzzleClient + ); + $client->country('1.2.3.4'); + + $all_requests = $plugin->getReceivedRequests(); + $request = $all_requests[0]; + + $this->assertEquals( + 'https://geoip.maxmind.com/geoip/v2.1/country/1.2.3.4', + $request->getUrl(), + 'got expected URI for Country request' + ); + $this->assertEquals( + 'GET', + $request->getMethod(), + 'request is a GET' + ); + + $this->assertEquals( + 'application/json', + $request->getHeader('Accept'), + 'request sets Accept header to application/json' + ); + + $this->assertStringMatchesFormat( + 'GeoIP2 PHP API (Guzzle%s)', + $request->getHeader('User-Agent') . '', + 'request sets Accept header to application/json' + ); + } + + + private function client($response, $locales = array('en')) + { + $plugin = new MockPlugin(); + $plugin->addResponse($response); + $guzzleClient = new GuzzleClient(); + $guzzleClient->addSubscriber($plugin); + + $client = new Client( + 42, + 'abcdef123456', + $locales, + 'geoip.maxmind.com', + $guzzleClient + ); + + return $client; + } + + private function response( + $endpoint, + $status, + $body = null, + $bad = null, + $contentType = null + ) { + $headers = array(); + if ($contentType) { + $headers['Content-Type'] = $contentType; + } elseif ($status == 200 || ($status >= 400 && $status < 500)) { + $headers['Content-Type'] = 'application/vnd.maxmind.com-' + . $endpoint . '+json; charset=UTF-8; version=1.0;'; + } + + if ($bad) { + $body = '{ invalid: }'; + } elseif (is_array($body)) { + $body = json_encode($body); + } + + $headers['Content-Length'] = strlen($body); + + return new Response($status, $headers, $body); + } + + public function testTest() + { + $this->assertEquals(1, 1); + } +} diff --git a/src/bb-vendor/geoip2/geoip2/tests/bootstrap.php b/src/bb-vendor/geoip2/geoip2/tests/bootstrap.php new file mode 100644 index 000000000..719da964c --- /dev/null +++ b/src/bb-vendor/geoip2/geoip2/tests/bootstrap.php @@ -0,0 +1,7 @@ +add('GeoIp2\Test', __DIR__); diff --git a/src/bb-vendor/guzzle/guzzle/.gitignore b/src/bb-vendor/guzzle/guzzle/.gitignore new file mode 100644 index 000000000..893035d5b --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/.gitignore @@ -0,0 +1,27 @@ +# Ingore common cruft +.DS_STORE +coverage +.idea + +# Ignore binary files +guzzle.phar +guzzle-min.phar + +# Ignore potentially sensitive phpunit file +phpunit.xml + +# Ignore composer generated files +composer.phar +composer.lock +composer-test.lock +vendor/ + +# Ignore build files +build/ +phing/build.properties + +# Ignore subsplit working directory +.subsplit + +docs/_build +docs/*.pyc diff --git a/src/bb-vendor/guzzle/guzzle/.travis.yml b/src/bb-vendor/guzzle/guzzle/.travis.yml new file mode 100644 index 000000000..209e05cd6 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/.travis.yml @@ -0,0 +1,17 @@ +language: php + +php: + - 5.3 + - 5.4 + - 5.5 + - 5.6 + - hhvm + +before_script: + - curl --version + - pecl install uri_template-beta || echo "pecl uri_template not available" + - composer self-update + - composer install --no-interaction --prefer-source --dev + - ~/.nvm/nvm.sh install v0.6.14 + +script: composer test diff --git a/src/bb-vendor/guzzle/guzzle/CHANGELOG.md b/src/bb-vendor/guzzle/guzzle/CHANGELOG.md new file mode 100644 index 000000000..f0dc5444a --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/CHANGELOG.md @@ -0,0 +1,751 @@ +# CHANGELOG + +## 3.9.3 - 2015-03-18 + +* Ensuring Content-Length is not stripped from a request when it is `0`. +* Added more information to stream wrapper exceptions. +* Message parser will no longer throw warnings for malformed messages. +* Giving a valid cache TTL when max-age is 0. + +## 3.9.2 - 2014-09-10 + +* Retrying "Connection died, retrying a fresh connect" curl errors. +* Automatically extracting the cacert from the phar in client constructor. +* Added EntityBody support for OPTIONS requests. + +## 3.9.1 - 2014-05-07 + +* Added a fix to ReadLimitEntityBody to ensure it doesn't infinitely loop. +* Added a fix to the stream checksum function so that when the first read + returns a falsey value, it still continues to consume the stream until EOF. + +## 3.9.0 - 2014-04-23 + +* `null`, `false`, and `"_guzzle_blank_"` all now serialize as an empty value + with no trailing "=". See dc1d824277. +* No longer performing an MD5 check on the cacert each time the phar is used, + but rather copying the cacert to the temp directory. +* `"0"` can now be added as a URL path +* Deleting cookies that are set to empty +* If-Modified-Since is no longer unnecessarily added to the CachePlugin +* Cookie path matching now follows RFC 6265 s5.1.4 +* Updated service descriptions are now added to a service client's composite + factory. +* MockPlugin now throws an exception if the queue is empty. +* Properly parsing URLs that start with "http" but are not absolute +* Added the ability to configure the curl_multi_select timeout setting +* OAuth parameters are now sorted using lexicographical byte value ordering +* Fixing invalid usage of an out of range PHP feature in the ErrorResponsePlugin + +## 3.8.1 -2014-01-28 + +* Bug: Always using GET requests when redirecting from a 303 response +* Bug: CURLOPT_SSL_VERIFYHOST is now correctly set to false when setting `$certificateAuthority` to false in + `Guzzle\Http\ClientInterface::setSslVerification()` +* Bug: RedirectPlugin now uses strict RFC 3986 compliance when combining a base URL with a relative URL +* Bug: The body of a request can now be set to `"0"` +* Sending PHP stream requests no longer forces `HTTP/1.0` +* Adding more information to ExceptionCollection exceptions so that users have more context, including a stack trace of + each sub-exception +* Updated the `$ref` attribute in service descriptions to merge over any existing parameters of a schema (rather than + clobbering everything). +* Merging URLs will now use the query string object from the relative URL (thus allowing custom query aggregators) +* Query strings are now parsed in a way that they do no convert empty keys with no value to have a dangling `=`. + For example `foo&bar=baz` is now correctly parsed and recognized as `foo&bar=baz` rather than `foo=&bar=baz`. +* Now properly escaping the regular expression delimiter when matching Cookie domains. +* Network access is now disabled when loading XML documents + +## 3.8.0 - 2013-12-05 + +* Added the ability to define a POST name for a file +* JSON response parsing now properly walks additionalProperties +* cURL error code 18 is now retried automatically in the BackoffPlugin +* Fixed a cURL error when URLs contain fragments +* Fixed an issue in the BackoffPlugin retry event where it was trying to access all exceptions as if they were + CurlExceptions +* CURLOPT_PROGRESS function fix for PHP 5.5 (69fcc1e) +* Added the ability for Guzzle to work with older versions of cURL that do not support `CURLOPT_TIMEOUT_MS` +* Fixed a bug that was encountered when parsing empty header parameters +* UriTemplate now has a `setRegex()` method to match the docs +* The `debug` request parameter now checks if it is truthy rather than if it exists +* Setting the `debug` request parameter to true shows verbose cURL output instead of using the LogPlugin +* Added the ability to combine URLs using strict RFC 3986 compliance +* Command objects can now return the validation errors encountered by the command +* Various fixes to cache revalidation (#437 and 29797e5) +* Various fixes to the AsyncPlugin +* Cleaned up build scripts + +## 3.7.4 - 2013-10-02 + +* Bug fix: 0 is now an allowed value in a description parameter that has a default value (#430) +* Bug fix: SchemaFormatter now returns an integer when formatting to a Unix timestamp + (see https://github.com/aws/aws-sdk-php/issues/147) +* Bug fix: Cleaned up and fixed URL dot segment removal to properly resolve internal dots +* Minimum PHP version is now properly specified as 5.3.3 (up from 5.3.2) (#420) +* Updated the bundled cacert.pem (#419) +* OauthPlugin now supports adding authentication to headers or query string (#425) + +## 3.7.3 - 2013-09-08 + +* Added the ability to get the exception associated with a request/command when using `MultiTransferException` and + `CommandTransferException`. +* Setting `additionalParameters` of a response to false is now honored when parsing responses with a service description +* Schemas are only injected into response models when explicitly configured. +* No longer guessing Content-Type based on the path of a request. Content-Type is now only guessed based on the path of + an EntityBody. +* Bug fix: ChunkedIterator can now properly chunk a \Traversable as well as an \Iterator. +* Bug fix: FilterIterator now relies on `\Iterator` instead of `\Traversable`. +* Bug fix: Gracefully handling malformed responses in RequestMediator::writeResponseBody() +* Bug fix: Replaced call to canCache with canCacheRequest in the CallbackCanCacheStrategy of the CachePlugin +* Bug fix: Visiting XML attributes first before visting XML children when serializing requests +* Bug fix: Properly parsing headers that contain commas contained in quotes +* Bug fix: mimetype guessing based on a filename is now case-insensitive + +## 3.7.2 - 2013-08-02 + +* Bug fix: Properly URL encoding paths when using the PHP-only version of the UriTemplate expander + See https://github.com/guzzle/guzzle/issues/371 +* Bug fix: Cookie domains are now matched correctly according to RFC 6265 + See https://github.com/guzzle/guzzle/issues/377 +* Bug fix: GET parameters are now used when calculating an OAuth signature +* Bug fix: Fixed an issue with cache revalidation where the If-None-Match header was being double quoted +* `Guzzle\Common\AbstractHasDispatcher::dispatch()` now returns the event that was dispatched +* `Guzzle\Http\QueryString::factory()` now guesses the most appropriate query aggregator to used based on the input. + See https://github.com/guzzle/guzzle/issues/379 +* Added a way to add custom domain objects to service description parsing using the `operation.parse_class` event. See + https://github.com/guzzle/guzzle/pull/380 +* cURL multi cleanup and optimizations + +## 3.7.1 - 2013-07-05 + +* Bug fix: Setting default options on a client now works +* Bug fix: Setting options on HEAD requests now works. See #352 +* Bug fix: Moving stream factory before send event to before building the stream. See #353 +* Bug fix: Cookies no longer match on IP addresses per RFC 6265 +* Bug fix: Correctly parsing header parameters that are in `<>` and quotes +* Added `cert` and `ssl_key` as request options +* `Host` header can now diverge from the host part of a URL if the header is set manually +* `Guzzle\Service\Command\LocationVisitor\Request\XmlVisitor` was rewritten to change from using SimpleXML to XMLWriter +* OAuth parameters are only added via the plugin if they aren't already set +* Exceptions are now thrown when a URL cannot be parsed +* Returning `false` if `Guzzle\Http\EntityBody::getContentMd5()` fails +* Not setting a `Content-MD5` on a command if calculating the Content-MD5 fails via the CommandContentMd5Plugin + +## 3.7.0 - 2013-06-10 + +* See UPGRADING.md for more information on how to upgrade. +* Requests now support the ability to specify an array of $options when creating a request to more easily modify a + request. You can pass a 'request.options' configuration setting to a client to apply default request options to + every request created by a client (e.g. default query string variables, headers, curl options, etc). +* Added a static facade class that allows you to use Guzzle with static methods and mount the class to `\Guzzle`. + See `Guzzle\Http\StaticClient::mount`. +* Added `command.request_options` to `Guzzle\Service\Command\AbstractCommand` to pass request options to requests + created by a command (e.g. custom headers, query string variables, timeout settings, etc). +* Stream size in `Guzzle\Stream\PhpStreamRequestFactory` will now be set if Content-Length is returned in the + headers of a response +* Added `Guzzle\Common\Collection::setPath($path, $value)` to set a value into an array using a nested key + (e.g. `$collection->setPath('foo/baz/bar', 'test'); echo $collection['foo']['bar']['bar'];`) +* ServiceBuilders now support storing and retrieving arbitrary data +* CachePlugin can now purge all resources for a given URI +* CachePlugin can automatically purge matching cached items when a non-idempotent request is sent to a resource +* CachePlugin now uses the Vary header to determine if a resource is a cache hit +* `Guzzle\Http\Message\Response` now implements `\Serializable` +* Added `Guzzle\Cache\CacheAdapterFactory::fromCache()` to more easily create cache adapters +* `Guzzle\Service\ClientInterface::execute()` now accepts an array, single command, or Traversable +* Fixed a bug in `Guzzle\Http\Message\Header\Link::addLink()` +* Better handling of calculating the size of a stream in `Guzzle\Stream\Stream` using fstat() and caching the size +* `Guzzle\Common\Exception\ExceptionCollection` now creates a more readable exception message +* Fixing BC break: Added back the MonologLogAdapter implementation rather than extending from PsrLog so that older + Symfony users can still use the old version of Monolog. +* Fixing BC break: Added the implementation back in for `Guzzle\Http\Message\AbstractMessage::getTokenizedHeader()`. + Now triggering an E_USER_DEPRECATED warning when used. Use `$message->getHeader()->parseParams()`. +* Several performance improvements to `Guzzle\Common\Collection` +* Added an `$options` argument to the end of the following methods of `Guzzle\Http\ClientInterface`: + createRequest, head, delete, put, patch, post, options, prepareRequest +* Added an `$options` argument to the end of `Guzzle\Http\Message\Request\RequestFactoryInterface::createRequest()` +* Added an `applyOptions()` method to `Guzzle\Http\Message\Request\RequestFactoryInterface` +* Changed `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $body = null)` to + `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $options = array())`. You can still pass in a + resource, string, or EntityBody into the $options parameter to specify the download location of the response. +* Changed `Guzzle\Common\Collection::__construct($data)` to no longer accepts a null value for `$data` but a + default `array()` +* Added `Guzzle\Stream\StreamInterface::isRepeatable` +* Removed `Guzzle\Http\ClientInterface::setDefaultHeaders(). Use + $client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. or + $client->getConfig()->setPath('request.options/headers', array('header_name' => 'value'))`. +* Removed `Guzzle\Http\ClientInterface::getDefaultHeaders(). Use $client->getConfig()->getPath('request.options/headers')`. +* Removed `Guzzle\Http\ClientInterface::expandTemplate()` +* Removed `Guzzle\Http\ClientInterface::setRequestFactory()` +* Removed `Guzzle\Http\ClientInterface::getCurlMulti()` +* Removed `Guzzle\Http\Message\RequestInterface::canCache` +* Removed `Guzzle\Http\Message\RequestInterface::setIsRedirect` +* Removed `Guzzle\Http\Message\RequestInterface::isRedirect` +* Made `Guzzle\Http\Client::expandTemplate` and `getUriTemplate` protected methods. +* You can now enable E_USER_DEPRECATED warnings to see if you are using a deprecated method by setting + `Guzzle\Common\Version::$emitWarnings` to true. +* Marked `Guzzle\Http\Message\Request::isResponseBodyRepeatable()` as deprecated. Use + `$request->getResponseBody()->isRepeatable()` instead. +* Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use + `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +* Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use + `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +* Marked `Guzzle\Http\Message\Request::setIsRedirect()` as deprecated. Use the HistoryPlugin instead. +* Marked `Guzzle\Http\Message\Request::isRedirect()` as deprecated. Use the HistoryPlugin instead. +* Marked `Guzzle\Cache\CacheAdapterFactory::factory()` as deprecated +* Marked 'command.headers', 'command.response_body' and 'command.on_complete' as deprecated for AbstractCommand. + These will work through Guzzle 4.0 +* Marked 'request.params' for `Guzzle\Http\Client` as deprecated. Use [request.options][params]. +* Marked `Guzzle\Service\Client::enableMagicMethods()` as deprecated. Magic methods can no longer be disabled on a Guzzle\Service\Client. +* Marked `Guzzle\Service\Client::getDefaultHeaders()` as deprecated. Use $client->getConfig()->getPath('request.options/headers')`. +* Marked `Guzzle\Service\Client::setDefaultHeaders()` as deprecated. Use $client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. +* Marked `Guzzle\Parser\Url\UrlParser` as deprecated. Just use PHP's `parse_url()` and percent encode your UTF-8. +* Marked `Guzzle\Common\Collection::inject()` as deprecated. +* Marked `Guzzle\Plugin\CurlAuth\CurlAuthPlugin` as deprecated. Use `$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest');` +* CacheKeyProviderInterface and DefaultCacheKeyProvider are no longer used. All of this logic is handled in a + CacheStorageInterface. These two objects and interface will be removed in a future version. +* Always setting X-cache headers on cached responses +* Default cache TTLs are now handled by the CacheStorageInterface of a CachePlugin +* `CacheStorageInterface::cache($key, Response $response, $ttl = null)` has changed to `cache(RequestInterface + $request, Response $response);` +* `CacheStorageInterface::fetch($key)` has changed to `fetch(RequestInterface $request);` +* `CacheStorageInterface::delete($key)` has changed to `delete(RequestInterface $request);` +* Added `CacheStorageInterface::purge($url)` +* `DefaultRevalidation::__construct(CacheKeyProviderInterface $cacheKey, CacheStorageInterface $cache, CachePlugin + $plugin)` has changed to `DefaultRevalidation::__construct(CacheStorageInterface $cache, + CanCacheStrategyInterface $canCache = null)` +* Added `RevalidationInterface::shouldRevalidate(RequestInterface $request, Response $response)` + +## 3.6.0 - 2013-05-29 + +* ServiceDescription now implements ToArrayInterface +* Added command.hidden_params to blacklist certain headers from being treated as additionalParameters +* Guzzle can now correctly parse incomplete URLs +* Mixed casing of headers are now forced to be a single consistent casing across all values for that header. +* Messages internally use a HeaderCollection object to delegate handling case-insensitive header resolution +* Removed the whole changedHeader() function system of messages because all header changes now go through addHeader(). +* Specific header implementations can be created for complex headers. When a message creates a header, it uses a + HeaderFactory which can map specific headers to specific header classes. There is now a Link header and + CacheControl header implementation. +* Removed from interface: Guzzle\Http\ClientInterface::setUriTemplate +* Removed from interface: Guzzle\Http\ClientInterface::setCurlMulti() +* Removed Guzzle\Http\Message\Request::receivedRequestHeader() and implemented this functionality in + Guzzle\Http\Curl\RequestMediator +* Removed the optional $asString parameter from MessageInterface::getHeader(). Just cast the header to a string. +* Removed the optional $tryChunkedTransfer option from Guzzle\Http\Message\EntityEnclosingRequestInterface +* Removed the $asObjects argument from Guzzle\Http\Message\MessageInterface::getHeaders() +* Removed Guzzle\Parser\ParserRegister::get(). Use getParser() +* Removed Guzzle\Parser\ParserRegister::set(). Use registerParser(). +* All response header helper functions return a string rather than mixing Header objects and strings inconsistently +* Removed cURL blacklist support. This is no longer necessary now that Expect, Accept, etc are managed by Guzzle + directly via interfaces +* Removed the injecting of a request object onto a response object. The methods to get and set a request still exist + but are a no-op until removed. +* Most classes that used to require a ``Guzzle\Service\Command\CommandInterface` typehint now request a + `Guzzle\Service\Command\ArrayCommandInterface`. +* Added `Guzzle\Http\Message\RequestInterface::startResponse()` to the RequestInterface to handle injecting a response + on a request while the request is still being transferred +* The ability to case-insensitively search for header values +* Guzzle\Http\Message\Header::hasExactHeader +* Guzzle\Http\Message\Header::raw. Use getAll() +* Deprecated cache control specific methods on Guzzle\Http\Message\AbstractMessage. Use the CacheControl header object + instead. +* `Guzzle\Service\Command\CommandInterface` now extends from ToArrayInterface and ArrayAccess +* Added the ability to cast Model objects to a string to view debug information. + +## 3.5.0 - 2013-05-13 + +* Bug: Fixed a regression so that request responses are parsed only once per oncomplete event rather than multiple times +* Bug: Better cleanup of one-time events accross the board (when an event is meant to fire once, it will now remove + itself from the EventDispatcher) +* Bug: `Guzzle\Log\MessageFormatter` now properly writes "total_time" and "connect_time" values +* Bug: Cloning an EntityEnclosingRequest now clones the EntityBody too +* Bug: Fixed an undefined index error when parsing nested JSON responses with a sentAs parameter that reference a + non-existent key +* Bug: All __call() method arguments are now required (helps with mocking frameworks) +* Deprecating Response::getRequest() and now using a shallow clone of a request object to remove a circular reference + to help with refcount based garbage collection of resources created by sending a request +* Deprecating ZF1 cache and log adapters. These will be removed in the next major version. +* Deprecating `Response::getPreviousResponse()` (method signature still exists, but it'sdeprecated). Use the + HistoryPlugin for a history. +* Added a `responseBody` alias for the `response_body` location +* Refactored internals to no longer rely on Response::getRequest() +* HistoryPlugin can now be cast to a string +* HistoryPlugin now logs transactions rather than requests and responses to more accurately keep track of the requests + and responses that are sent over the wire +* Added `getEffectiveUrl()` and `getRedirectCount()` to Response objects + +## 3.4.3 - 2013-04-30 + +* Bug fix: Fixing bug introduced in 3.4.2 where redirect responses are duplicated on the final redirected response +* Added a check to re-extract the temp cacert bundle from the phar before sending each request + +## 3.4.2 - 2013-04-29 + +* Bug fix: Stream objects now work correctly with "a" and "a+" modes +* Bug fix: Removing `Transfer-Encoding: chunked` header when a Content-Length is present +* Bug fix: AsyncPlugin no longer forces HEAD requests +* Bug fix: DateTime timezones are now properly handled when using the service description schema formatter +* Bug fix: CachePlugin now properly handles stale-if-error directives when a request to the origin server fails +* Setting a response on a request will write to the custom request body from the response body if one is specified +* LogPlugin now writes to php://output when STDERR is undefined +* Added the ability to set multiple POST files for the same key in a single call +* application/x-www-form-urlencoded POSTs now use the utf-8 charset by default +* Added the ability to queue CurlExceptions to the MockPlugin +* Cleaned up how manual responses are queued on requests (removed "queued_response" and now using request.before_send) +* Configuration loading now allows remote files + +## 3.4.1 - 2013-04-16 + +* Large refactoring to how CurlMulti handles work. There is now a proxy that sits in front of a pool of CurlMulti + handles. This greatly simplifies the implementation, fixes a couple bugs, and provides a small performance boost. +* Exceptions are now properly grouped when sending requests in parallel +* Redirects are now properly aggregated when a multi transaction fails +* Redirects now set the response on the original object even in the event of a failure +* Bug fix: Model names are now properly set even when using $refs +* Added support for PHP 5.5's CurlFile to prevent warnings with the deprecated @ syntax +* Added support for oauth_callback in OAuth signatures +* Added support for oauth_verifier in OAuth signatures +* Added support to attempt to retrieve a command first literally, then ucfirst, the with inflection + +## 3.4.0 - 2013-04-11 + +* Bug fix: URLs are now resolved correctly based on http://tools.ietf.org/html/rfc3986#section-5.2. #289 +* Bug fix: Absolute URLs with a path in a service description will now properly override the base URL. #289 +* Bug fix: Parsing a query string with a single PHP array value will now result in an array. #263 +* Bug fix: Better normalization of the User-Agent header to prevent duplicate headers. #264. +* Bug fix: Added `number` type to service descriptions. +* Bug fix: empty parameters are removed from an OAuth signature +* Bug fix: Revalidating a cache entry prefers the Last-Modified over the Date header +* Bug fix: Fixed "array to string" error when validating a union of types in a service description +* Bug fix: Removed code that attempted to determine the size of a stream when data is written to the stream +* Bug fix: Not including an `oauth_token` if the value is null in the OauthPlugin. +* Bug fix: Now correctly aggregating successful requests and failed requests in CurlMulti when a redirect occurs. +* The new default CURLOPT_TIMEOUT setting has been increased to 150 seconds so that Guzzle works on poor connections. +* Added a feature to EntityEnclosingRequest::setBody() that will automatically set the Content-Type of the request if + the Content-Type can be determined based on the entity body or the path of the request. +* Added the ability to overwrite configuration settings in a client when grabbing a throwaway client from a builder. +* Added support for a PSR-3 LogAdapter. +* Added a `command.after_prepare` event +* Added `oauth_callback` parameter to the OauthPlugin +* Added the ability to create a custom stream class when using a stream factory +* Added a CachingEntityBody decorator +* Added support for `additionalParameters` in service descriptions to define how custom parameters are serialized. +* The bundled SSL certificate is now provided in the phar file and extracted when running Guzzle from a phar. +* You can now send any EntityEnclosingRequest with POST fields or POST files and cURL will handle creating bodies +* POST requests using a custom entity body are now treated exactly like PUT requests but with a custom cURL method. This + means that the redirect behavior of POST requests with custom bodies will not be the same as POST requests that use + POST fields or files (the latter is only used when emulating a form POST in the browser). +* Lots of cleanup to CurlHandle::factory and RequestFactory::createRequest + +## 3.3.1 - 2013-03-10 + +* Added the ability to create PHP streaming responses from HTTP requests +* Bug fix: Running any filters when parsing response headers with service descriptions +* Bug fix: OauthPlugin fixes to allow for multi-dimensional array signing, and sorting parameters before signing +* Bug fix: Removed the adding of default empty arrays and false Booleans to responses in order to be consistent across + response location visitors. +* Bug fix: Removed the possibility of creating configuration files with circular dependencies +* RequestFactory::create() now uses the key of a POST file when setting the POST file name +* Added xmlAllowEmpty to serialize an XML body even if no XML specific parameters are set + +## 3.3.0 - 2013-03-03 + +* A large number of performance optimizations have been made +* Bug fix: Added 'wb' as a valid write mode for streams +* Bug fix: `Guzzle\Http\Message\Response::json()` now allows scalar values to be returned +* Bug fix: Fixed bug in `Guzzle\Http\Message\Response` where wrapping quotes were stripped from `getEtag()` +* BC: Removed `Guzzle\Http\Utils` class +* BC: Setting a service description on a client will no longer modify the client's command factories. +* BC: Emitting IO events from a RequestMediator is now a parameter that must be set in a request's curl options using + the 'emit_io' key. This was previously set under a request's parameters using 'curl.emit_io' +* BC: `Guzzle\Stream\Stream::getWrapper()` and `Guzzle\Stream\Stream::getSteamType()` are no longer converted to + lowercase +* Operation parameter objects are now lazy loaded internally +* Added ErrorResponsePlugin that can throw errors for responses defined in service description operations' errorResponses +* Added support for instantiating responseType=class responseClass classes. Classes must implement + `Guzzle\Service\Command\ResponseClassInterface` +* Added support for additionalProperties for top-level parameters in responseType=model responseClasses. These + additional properties also support locations and can be used to parse JSON responses where the outermost part of the + JSON is an array +* Added support for nested renaming of JSON models (rename sentAs to name) +* CachePlugin + * Added support for stale-if-error so that the CachePlugin can now serve stale content from the cache on error + * Debug headers can now added to cached response in the CachePlugin + +## 3.2.0 - 2013-02-14 + +* CurlMulti is no longer reused globally. A new multi object is created per-client. This helps to isolate clients. +* URLs with no path no longer contain a "/" by default +* Guzzle\Http\QueryString does no longer manages the leading "?". This is now handled in Guzzle\Http\Url. +* BadResponseException no longer includes the full request and response message +* Adding setData() to Guzzle\Service\Description\ServiceDescriptionInterface +* Adding getResponseBody() to Guzzle\Http\Message\RequestInterface +* Various updates to classes to use ServiceDescriptionInterface type hints rather than ServiceDescription +* Header values can now be normalized into distinct values when multiple headers are combined with a comma separated list +* xmlEncoding can now be customized for the XML declaration of a XML service description operation +* Guzzle\Http\QueryString now uses Guzzle\Http\QueryAggregator\QueryAggregatorInterface objects to add custom value + aggregation and no longer uses callbacks +* The URL encoding implementation of Guzzle\Http\QueryString can now be customized +* Bug fix: Filters were not always invoked for array service description parameters +* Bug fix: Redirects now use a target response body rather than a temporary response body +* Bug fix: The default exponential backoff BackoffPlugin was not giving when the request threshold was exceeded +* Bug fix: Guzzle now takes the first found value when grabbing Cache-Control directives + +## 3.1.2 - 2013-01-27 + +* Refactored how operation responses are parsed. Visitors now include a before() method responsible for parsing the + response body. For example, the XmlVisitor now parses the XML response into an array in the before() method. +* Fixed an issue where cURL would not automatically decompress responses when the Accept-Encoding header was sent +* CURLOPT_SSL_VERIFYHOST is never set to 1 because it is deprecated (see 5e0ff2ef20f839e19d1eeb298f90ba3598784444) +* Fixed a bug where redirect responses were not chained correctly using getPreviousResponse() +* Setting default headers on a client after setting the user-agent will not erase the user-agent setting + +## 3.1.1 - 2013-01-20 + +* Adding wildcard support to Guzzle\Common\Collection::getPath() +* Adding alias support to ServiceBuilder configs +* Adding Guzzle\Service\Resource\CompositeResourceIteratorFactory and cleaning up factory interface + +## 3.1.0 - 2013-01-12 + +* BC: CurlException now extends from RequestException rather than BadResponseException +* BC: Renamed Guzzle\Plugin\Cache\CanCacheStrategyInterface::canCache() to canCacheRequest() and added CanCacheResponse() +* Added getData to ServiceDescriptionInterface +* Added context array to RequestInterface::setState() +* Bug: Removing hard dependency on the BackoffPlugin from Guzzle\Http +* Bug: Adding required content-type when JSON request visitor adds JSON to a command +* Bug: Fixing the serialization of a service description with custom data +* Made it easier to deal with exceptions thrown when transferring commands or requests in parallel by providing + an array of successful and failed responses +* Moved getPath from Guzzle\Service\Resource\Model to Guzzle\Common\Collection +* Added Guzzle\Http\IoEmittingEntityBody +* Moved command filtration from validators to location visitors +* Added `extends` attributes to service description parameters +* Added getModels to ServiceDescriptionInterface + +## 3.0.7 - 2012-12-19 + +* Fixing phar detection when forcing a cacert to system if null or true +* Allowing filename to be passed to `Guzzle\Http\Message\Request::setResponseBody()` +* Cleaning up `Guzzle\Common\Collection::inject` method +* Adding a response_body location to service descriptions + +## 3.0.6 - 2012-12-09 + +* CurlMulti performance improvements +* Adding setErrorResponses() to Operation +* composer.json tweaks + +## 3.0.5 - 2012-11-18 + +* Bug: Fixing an infinite recursion bug caused from revalidating with the CachePlugin +* Bug: Response body can now be a string containing "0" +* Bug: Using Guzzle inside of a phar uses system by default but now allows for a custom cacert +* Bug: QueryString::fromString now properly parses query string parameters that contain equal signs +* Added support for XML attributes in service description responses +* DefaultRequestSerializer now supports array URI parameter values for URI template expansion +* Added better mimetype guessing to requests and post files + +## 3.0.4 - 2012-11-11 + +* Bug: Fixed a bug when adding multiple cookies to a request to use the correct glue value +* Bug: Cookies can now be added that have a name, domain, or value set to "0" +* Bug: Using the system cacert bundle when using the Phar +* Added json and xml methods to Response to make it easier to parse JSON and XML response data into data structures +* Enhanced cookie jar de-duplication +* Added the ability to enable strict cookie jars that throw exceptions when invalid cookies are added +* Added setStream to StreamInterface to actually make it possible to implement custom rewind behavior for entity bodies +* Added the ability to create any sort of hash for a stream rather than just an MD5 hash + +## 3.0.3 - 2012-11-04 + +* Implementing redirects in PHP rather than cURL +* Added PECL URI template extension and using as default parser if available +* Bug: Fixed Content-Length parsing of Response factory +* Adding rewind() method to entity bodies and streams. Allows for custom rewinding of non-repeatable streams. +* Adding ToArrayInterface throughout library +* Fixing OauthPlugin to create unique nonce values per request + +## 3.0.2 - 2012-10-25 + +* Magic methods are enabled by default on clients +* Magic methods return the result of a command +* Service clients no longer require a base_url option in the factory +* Bug: Fixed an issue with URI templates where null template variables were being expanded + +## 3.0.1 - 2012-10-22 + +* Models can now be used like regular collection objects by calling filter, map, etc +* Models no longer require a Parameter structure or initial data in the constructor +* Added a custom AppendIterator to get around a PHP bug with the `\AppendIterator` + +## 3.0.0 - 2012-10-15 + +* Rewrote service description format to be based on Swagger + * Now based on JSON schema + * Added nested input structures and nested response models + * Support for JSON and XML input and output models + * Renamed `commands` to `operations` + * Removed dot class notation + * Removed custom types +* Broke the project into smaller top-level namespaces to be more component friendly +* Removed support for XML configs and descriptions. Use arrays or JSON files. +* Removed the Validation component and Inspector +* Moved all cookie code to Guzzle\Plugin\Cookie +* Magic methods on a Guzzle\Service\Client now return the command un-executed. +* Calling getResult() or getResponse() on a command will lazily execute the command if needed. +* Now shipping with cURL's CA certs and using it by default +* Added previousResponse() method to response objects +* No longer sending Accept and Accept-Encoding headers on every request +* Only sending an Expect header by default when a payload is greater than 1MB +* Added/moved client options: + * curl.blacklist to curl.option.blacklist + * Added ssl.certificate_authority +* Added a Guzzle\Iterator component +* Moved plugins from Guzzle\Http\Plugin to Guzzle\Plugin +* Added a more robust backoff retry strategy (replaced the ExponentialBackoffPlugin) +* Added a more robust caching plugin +* Added setBody to response objects +* Updating LogPlugin to use a more flexible MessageFormatter +* Added a completely revamped build process +* Cleaning up Collection class and removing default values from the get method +* Fixed ZF2 cache adapters + +## 2.8.8 - 2012-10-15 + +* Bug: Fixed a cookie issue that caused dot prefixed domains to not match where popular browsers did + +## 2.8.7 - 2012-09-30 + +* Bug: Fixed config file aliases for JSON includes +* Bug: Fixed cookie bug on a request object by using CookieParser to parse cookies on requests +* Bug: Removing the path to a file when sending a Content-Disposition header on a POST upload +* Bug: Hardening request and response parsing to account for missing parts +* Bug: Fixed PEAR packaging +* Bug: Fixed Request::getInfo +* Bug: Fixed cases where CURLM_CALL_MULTI_PERFORM return codes were causing curl transactions to fail +* Adding the ability for the namespace Iterator factory to look in multiple directories +* Added more getters/setters/removers from service descriptions +* Added the ability to remove POST fields from OAuth signatures +* OAuth plugin now supports 2-legged OAuth + +## 2.8.6 - 2012-09-05 + +* Added the ability to modify and build service descriptions +* Added the use of visitors to apply parameters to locations in service descriptions using the dynamic command +* Added a `json` parameter location +* Now allowing dot notation for classes in the CacheAdapterFactory +* Using the union of two arrays rather than an array_merge when extending service builder services and service params +* Ensuring that a service is a string before doing strpos() checks on it when substituting services for references + in service builder config files. +* Services defined in two different config files that include one another will by default replace the previously + defined service, but you can now create services that extend themselves and merge their settings over the previous +* The JsonLoader now supports aliasing filenames with different filenames. This allows you to alias something like + '_default' with a default JSON configuration file. + +## 2.8.5 - 2012-08-29 + +* Bug: Suppressed empty arrays from URI templates +* Bug: Added the missing $options argument from ServiceDescription::factory to enable caching +* Added support for HTTP responses that do not contain a reason phrase in the start-line +* AbstractCommand commands are now invokable +* Added a way to get the data used when signing an Oauth request before a request is sent + +## 2.8.4 - 2012-08-15 + +* Bug: Custom delay time calculations are no longer ignored in the ExponentialBackoffPlugin +* Added the ability to transfer entity bodies as a string rather than streamed. This gets around curl error 65. Set `body_as_string` in a request's curl options to enable. +* Added a StreamInterface, EntityBodyInterface, and added ftell() to Guzzle\Common\Stream +* Added an AbstractEntityBodyDecorator and a ReadLimitEntityBody decorator to transfer only a subset of a decorated stream +* Stream and EntityBody objects will now return the file position to the previous position after a read required operation (e.g. getContentMd5()) +* Added additional response status codes +* Removed SSL information from the default User-Agent header +* DELETE requests can now send an entity body +* Added an EventDispatcher to the ExponentialBackoffPlugin and added an ExponentialBackoffLogger to log backoff retries +* Added the ability of the MockPlugin to consume mocked request bodies +* LogPlugin now exposes request and response objects in the extras array + +## 2.8.3 - 2012-07-30 + +* Bug: Fixed a case where empty POST requests were sent as GET requests +* Bug: Fixed a bug in ExponentialBackoffPlugin that caused fatal errors when retrying an EntityEnclosingRequest that does not have a body +* Bug: Setting the response body of a request to null after completing a request, not when setting the state of a request to new +* Added multiple inheritance to service description commands +* Added an ApiCommandInterface and added ``getParamNames()`` and ``hasParam()`` +* Removed the default 2mb size cutoff from the Md5ValidatorPlugin so that it now defaults to validating everything +* Changed CurlMulti::perform to pass a smaller timeout to CurlMulti::executeHandles + +## 2.8.2 - 2012-07-24 + +* Bug: Query string values set to 0 are no longer dropped from the query string +* Bug: A Collection object is no longer created each time a call is made to ``Guzzle\Service\Command\AbstractCommand::getRequestHeaders()`` +* Bug: ``+`` is now treated as an encoded space when parsing query strings +* QueryString and Collection performance improvements +* Allowing dot notation for class paths in filters attribute of a service descriptions + +## 2.8.1 - 2012-07-16 + +* Loosening Event Dispatcher dependency +* POST redirects can now be customized using CURLOPT_POSTREDIR + +## 2.8.0 - 2012-07-15 + +* BC: Guzzle\Http\Query + * Query strings with empty variables will always show an equal sign unless the variable is set to QueryString::BLANK (e.g. ?acl= vs ?acl) + * Changed isEncodingValues() and isEncodingFields() to isUrlEncoding() + * Changed setEncodeValues(bool) and setEncodeFields(bool) to useUrlEncoding(bool) + * Changed the aggregation functions of QueryString to be static methods + * Can now use fromString() with querystrings that have a leading ? +* cURL configuration values can be specified in service descriptions using ``curl.`` prefixed parameters +* Content-Length is set to 0 before emitting the request.before_send event when sending an empty request body +* Cookies are no longer URL decoded by default +* Bug: URI template variables set to null are no longer expanded + +## 2.7.2 - 2012-07-02 + +* BC: Moving things to get ready for subtree splits. Moving Inflection into Common. Moving Guzzle\Http\Parser to Guzzle\Parser. +* BC: Removing Guzzle\Common\Batch\Batch::count() and replacing it with isEmpty() +* CachePlugin now allows for a custom request parameter function to check if a request can be cached +* Bug fix: CachePlugin now only caches GET and HEAD requests by default +* Bug fix: Using header glue when transferring headers over the wire +* Allowing deeply nested arrays for composite variables in URI templates +* Batch divisors can now return iterators or arrays + +## 2.7.1 - 2012-06-26 + +* Minor patch to update version number in UA string +* Updating build process + +## 2.7.0 - 2012-06-25 + +* BC: Inflection classes moved to Guzzle\Inflection. No longer static methods. Can now inject custom inflectors into classes. +* BC: Removed magic setX methods from commands +* BC: Magic methods mapped to service description commands are now inflected in the command factory rather than the client __call() method +* Verbose cURL options are no longer enabled by default. Set curl.debug to true on a client to enable. +* Bug: Now allowing colons in a response start-line (e.g. HTTP/1.1 503 Service Unavailable: Back-end server is at capacity) +* Guzzle\Service\Resource\ResourceIteratorApplyBatched now internally uses the Guzzle\Common\Batch namespace +* Added Guzzle\Service\Plugin namespace and a PluginCollectionPlugin +* Added the ability to set POST fields and files in a service description +* Guzzle\Http\EntityBody::factory() now accepts objects with a __toString() method +* Adding a command.before_prepare event to clients +* Added BatchClosureTransfer and BatchClosureDivisor +* BatchTransferException now includes references to the batch divisor and transfer strategies +* Fixed some tests so that they pass more reliably +* Added Guzzle\Common\Log\ArrayLogAdapter + +## 2.6.6 - 2012-06-10 + +* BC: Removing Guzzle\Http\Plugin\BatchQueuePlugin +* BC: Removing Guzzle\Service\Command\CommandSet +* Adding generic batching system (replaces the batch queue plugin and command set) +* Updating ZF cache and log adapters and now using ZF's composer repository +* Bug: Setting the name of each ApiParam when creating through an ApiCommand +* Adding result_type, result_doc, deprecated, and doc_url to service descriptions +* Bug: Changed the default cookie header casing back to 'Cookie' + +## 2.6.5 - 2012-06-03 + +* BC: Renaming Guzzle\Http\Message\RequestInterface::getResourceUri() to getResource() +* BC: Removing unused AUTH_BASIC and AUTH_DIGEST constants from +* BC: Guzzle\Http\Cookie is now used to manage Set-Cookie data, not Cookie data +* BC: Renaming methods in the CookieJarInterface +* Moving almost all cookie logic out of the CookiePlugin and into the Cookie or CookieJar implementations +* Making the default glue for HTTP headers ';' instead of ',' +* Adding a removeValue to Guzzle\Http\Message\Header +* Adding getCookies() to request interface. +* Making it easier to add event subscribers to HasDispatcherInterface classes. Can now directly call addSubscriber() + +## 2.6.4 - 2012-05-30 + +* BC: Cleaning up how POST files are stored in EntityEnclosingRequest objects. Adding PostFile class. +* BC: Moving ApiCommand specific functionality from the Inspector and on to the ApiCommand +* Bug: Fixing magic method command calls on clients +* Bug: Email constraint only validates strings +* Bug: Aggregate POST fields when POST files are present in curl handle +* Bug: Fixing default User-Agent header +* Bug: Only appending or prepending parameters in commands if they are specified +* Bug: Not requiring response reason phrases or status codes to match a predefined list of codes +* Allowing the use of dot notation for class namespaces when using instance_of constraint +* Added any_match validation constraint +* Added an AsyncPlugin +* Passing request object to the calculateWait method of the ExponentialBackoffPlugin +* Allowing the result of a command object to be changed +* Parsing location and type sub values when instantiating a service description rather than over and over at runtime + +## 2.6.3 - 2012-05-23 + +* [BC] Guzzle\Common\FromConfigInterface no longer requires any config options. +* [BC] Refactoring how POST files are stored on an EntityEnclosingRequest. They are now separate from POST fields. +* You can now use an array of data when creating PUT request bodies in the request factory. +* Removing the requirement that HTTPS requests needed a Cache-Control: public directive to be cacheable. +* [Http] Adding support for Content-Type in multipart POST uploads per upload +* [Http] Added support for uploading multiple files using the same name (foo[0], foo[1]) +* Adding more POST data operations for easier manipulation of POST data. +* You can now set empty POST fields. +* The body of a request is only shown on EntityEnclosingRequest objects that do not use POST files. +* Split the Guzzle\Service\Inspector::validateConfig method into two methods. One to initialize when a command is created, and one to validate. +* CS updates + +## 2.6.2 - 2012-05-19 + +* [Http] Better handling of nested scope requests in CurlMulti. Requests are now always prepares in the send() method rather than the addRequest() method. + +## 2.6.1 - 2012-05-19 + +* [BC] Removing 'path' support in service descriptions. Use 'uri'. +* [BC] Guzzle\Service\Inspector::parseDocBlock is now protected. Adding getApiParamsForClass() with cache. +* [BC] Removing Guzzle\Common\NullObject. Use https://github.com/mtdowling/NullObject if you need it. +* [BC] Removing Guzzle\Common\XmlElement. +* All commands, both dynamic and concrete, have ApiCommand objects. +* Adding a fix for CurlMulti so that if all of the connections encounter some sort of curl error, then the loop exits. +* Adding checks to EntityEnclosingRequest so that empty POST files and fields are ignored. +* Making the method signature of Guzzle\Service\Builder\ServiceBuilder::factory more flexible. + +## 2.6.0 - 2012-05-15 + +* [BC] Moving Guzzle\Service\Builder to Guzzle\Service\Builder\ServiceBuilder +* [BC] Executing a Command returns the result of the command rather than the command +* [BC] Moving all HTTP parsing logic to Guzzle\Http\Parsers. Allows for faster C implementations if needed. +* [BC] Changing the Guzzle\Http\Message\Response::setProtocol() method to accept a protocol and version in separate args. +* [BC] Moving ResourceIterator* to Guzzle\Service\Resource +* [BC] Completely refactored ResourceIterators to iterate over a cloned command object +* [BC] Moved Guzzle\Http\UriTemplate to Guzzle\Http\Parser\UriTemplate\UriTemplate +* [BC] Guzzle\Guzzle is now deprecated +* Moving Guzzle\Common\Guzzle::inject to Guzzle\Common\Collection::inject +* Adding Guzzle\Version class to give version information about Guzzle +* Adding Guzzle\Http\Utils class to provide getDefaultUserAgent() and getHttpDate() +* Adding Guzzle\Curl\CurlVersion to manage caching curl_version() data +* ServiceDescription and ServiceBuilder are now cacheable using similar configs +* Changing the format of XML and JSON service builder configs. Backwards compatible. +* Cleaned up Cookie parsing +* Trimming the default Guzzle User-Agent header +* Adding a setOnComplete() method to Commands that is called when a command completes +* Keeping track of requests that were mocked in the MockPlugin +* Fixed a caching bug in the CacheAdapterFactory +* Inspector objects can be injected into a Command object +* Refactoring a lot of code and tests to be case insensitive when dealing with headers +* Adding Guzzle\Http\Message\HeaderComparison for easy comparison of HTTP headers using a DSL +* Adding the ability to set global option overrides to service builder configs +* Adding the ability to include other service builder config files from within XML and JSON files +* Moving the parseQuery method out of Url and on to QueryString::fromString() as a static factory method. + +## 2.5.0 - 2012-05-08 + +* Major performance improvements +* [BC] Simplifying Guzzle\Common\Collection. Please check to see if you are using features that are now deprecated. +* [BC] Using a custom validation system that allows a flyweight implementation for much faster validation. No longer using Symfony2 Validation component. +* [BC] No longer supporting "{{ }}" for injecting into command or UriTemplates. Use "{}" +* Added the ability to passed parameters to all requests created by a client +* Added callback functionality to the ExponentialBackoffPlugin +* Using microtime in ExponentialBackoffPlugin to allow more granular backoff strategies. +* Rewinding request stream bodies when retrying requests +* Exception is thrown when JSON response body cannot be decoded +* Added configurable magic method calls to clients and commands. This is off by default. +* Fixed a defect that added a hash to every parsed URL part +* Fixed duplicate none generation for OauthPlugin. +* Emitting an event each time a client is generated by a ServiceBuilder +* Using an ApiParams object instead of a Collection for parameters of an ApiCommand +* cache.* request parameters should be renamed to params.cache.* +* Added the ability to set arbitrary curl options on requests (disable_wire, progress, etc). See CurlHandle. +* Added the ability to disable type validation of service descriptions +* ServiceDescriptions and ServiceBuilders are now Serializable diff --git a/src/bb-vendor/guzzle/guzzle/LICENSE b/src/bb-vendor/guzzle/guzzle/LICENSE new file mode 100644 index 000000000..d51aa6986 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2011 Michael Dowling, https://github.com/mtdowling + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/src/bb-vendor/guzzle/guzzle/README.md b/src/bb-vendor/guzzle/guzzle/README.md new file mode 100644 index 000000000..6be06bf47 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/README.md @@ -0,0 +1,57 @@ +Guzzle, PHP HTTP client and webservice framework +================================================ + +# This is an old version of Guzzle + +This repository is for Guzzle 3.x. Guzzle 5.x, the new version of Guzzle, has +been released and is available at +[https://github.com/guzzle/guzzle](https://github.com/guzzle/guzzle). The +documentation for Guzzle version 5+ can be found at +[http://guzzlephp.org](http://guzzlephp.org). + +Guzzle 3 is only maintained for bug and security fixes. Guzzle 3 will be EOL +at some point in late 2015. + +### About Guzzle 3 + +[![Composer Downloads](https://poser.pugx.org/guzzle/guzzle/d/total.png)](https://packagist.org/packages/guzzle/guzzle) + [![Build Status](https://secure.travis-ci.org/guzzle/guzzle3.png?branch=master)](http://travis-ci.org/guzzle/guzzle3) + +- Extremely powerful API provides all the power of cURL with a simple interface. +- Truly take advantage of HTTP/1.1 with persistent connections, connection pooling, and parallel requests. +- Service description DSL allows you build awesome web service clients faster. +- Symfony2 event-based plugin system allows you to completely modify the behavior of a request. + +Get answers with: [Documentation](http://guzzle3.readthedocs.org/en/latest/), [Forums](https://groups.google.com/forum/?hl=en#!forum/guzzle), IRC ([#guzzlephp](irc://irc.freenode.net/#guzzlephp) @ irc.freenode.net) + +### Installing via Composer + +The recommended way to install Guzzle is through [Composer](http://getcomposer.org). + +```bash +# Install Composer +curl -sS https://getcomposer.org/installer | php + +# Add Guzzle as a dependency +php composer.phar require guzzle/guzzle:~3.9 +``` + +After installing, you need to require Composer's autoloader: + +```php +require 'vendor/autoload.php'; +``` +## Known Issues + +1. Problem following a specific redirect: https://github.com/guzzle/guzzle/issues/385. + This has been fixed in Guzzle 4/5. +2. Root XML attributes not serialized in a service description: https://github.com/guzzle/guzzle3/issues/5. + This has been fixed in Guzzle 4/5. +3. Accept-Encoding not preserved when following redirect: https://github.com/guzzle/guzzle3/issues/9 + Fixed in Guzzle 4/5. +4. String "Array" Transmitted w/ PostFiles and Duplicate Aggregator: https://github.com/guzzle/guzzle3/issues/10 + Fixed in Guzzle 4/5. +5. Recursive model references with array items: https://github.com/guzzle/guzzle3/issues/13 + Fixed in Guzzle 4/5 +6. String "Array" Transmitted w/ PostFiles and Duplicate Aggregator: https://github.com/guzzle/guzzle3/issues/10 + Fixed in Guzzle 4/5. diff --git a/src/bb-vendor/guzzle/guzzle/UPGRADING.md b/src/bb-vendor/guzzle/guzzle/UPGRADING.md new file mode 100644 index 000000000..f58bf1171 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/UPGRADING.md @@ -0,0 +1,537 @@ +Guzzle Upgrade Guide +==================== + +3.6 to 3.7 +---------- + +### Deprecations + +- You can now enable E_USER_DEPRECATED warnings to see if you are using any deprecated methods.: + +```php +\Guzzle\Common\Version::$emitWarnings = true; +``` + +The following APIs and options have been marked as deprecated: + +- Marked `Guzzle\Http\Message\Request::isResponseBodyRepeatable()` as deprecated. Use `$request->getResponseBody()->isRepeatable()` instead. +- Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +- Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +- Marked `Guzzle\Http\Message\Request::setIsRedirect()` as deprecated. Use the HistoryPlugin instead. +- Marked `Guzzle\Http\Message\Request::isRedirect()` as deprecated. Use the HistoryPlugin instead. +- Marked `Guzzle\Cache\CacheAdapterFactory::factory()` as deprecated +- Marked `Guzzle\Service\Client::enableMagicMethods()` as deprecated. Magic methods can no longer be disabled on a Guzzle\Service\Client. +- Marked `Guzzle\Parser\Url\UrlParser` as deprecated. Just use PHP's `parse_url()` and percent encode your UTF-8. +- Marked `Guzzle\Common\Collection::inject()` as deprecated. +- Marked `Guzzle\Plugin\CurlAuth\CurlAuthPlugin` as deprecated. Use + `$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest|NTLM|Any'));` or + `$client->setDefaultOption('auth', array('user', 'pass', 'Basic|Digest|NTLM|Any'));` + +3.7 introduces `request.options` as a parameter for a client configuration and as an optional argument to all creational +request methods. When paired with a client's configuration settings, these options allow you to specify default settings +for various aspects of a request. Because these options make other previous configuration options redundant, several +configuration options and methods of a client and AbstractCommand have been deprecated. + +- Marked `Guzzle\Service\Client::getDefaultHeaders()` as deprecated. Use `$client->getDefaultOption('headers')`. +- Marked `Guzzle\Service\Client::setDefaultHeaders()` as deprecated. Use `$client->setDefaultOption('headers/{header_name}', 'value')`. +- Marked 'request.params' for `Guzzle\Http\Client` as deprecated. Use `$client->setDefaultOption('params/{param_name}', 'value')` +- Marked 'command.headers', 'command.response_body' and 'command.on_complete' as deprecated for AbstractCommand. These will work through Guzzle 4.0 + + $command = $client->getCommand('foo', array( + 'command.headers' => array('Test' => '123'), + 'command.response_body' => '/path/to/file' + )); + + // Should be changed to: + + $command = $client->getCommand('foo', array( + 'command.request_options' => array( + 'headers' => array('Test' => '123'), + 'save_as' => '/path/to/file' + ) + )); + +### Interface changes + +Additions and changes (you will need to update any implementations or subclasses you may have created): + +- Added an `$options` argument to the end of the following methods of `Guzzle\Http\ClientInterface`: + createRequest, head, delete, put, patch, post, options, prepareRequest +- Added an `$options` argument to the end of `Guzzle\Http\Message\Request\RequestFactoryInterface::createRequest()` +- Added an `applyOptions()` method to `Guzzle\Http\Message\Request\RequestFactoryInterface` +- Changed `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $body = null)` to + `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $options = array())`. You can still pass in a + resource, string, or EntityBody into the $options parameter to specify the download location of the response. +- Changed `Guzzle\Common\Collection::__construct($data)` to no longer accepts a null value for `$data` but a + default `array()` +- Added `Guzzle\Stream\StreamInterface::isRepeatable` +- Made `Guzzle\Http\Client::expandTemplate` and `getUriTemplate` protected methods. + +The following methods were removed from interfaces. All of these methods are still available in the concrete classes +that implement them, but you should update your code to use alternative methods: + +- Removed `Guzzle\Http\ClientInterface::setDefaultHeaders(). Use + `$client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. or + `$client->getConfig()->setPath('request.options/headers', array('header_name' => 'value'))` or + `$client->setDefaultOption('headers/{header_name}', 'value')`. or + `$client->setDefaultOption('headers', array('header_name' => 'value'))`. +- Removed `Guzzle\Http\ClientInterface::getDefaultHeaders(). Use `$client->getConfig()->getPath('request.options/headers')`. +- Removed `Guzzle\Http\ClientInterface::expandTemplate()`. This is an implementation detail. +- Removed `Guzzle\Http\ClientInterface::setRequestFactory()`. This is an implementation detail. +- Removed `Guzzle\Http\ClientInterface::getCurlMulti()`. This is a very specific implementation detail. +- Removed `Guzzle\Http\Message\RequestInterface::canCache`. Use the CachePlugin. +- Removed `Guzzle\Http\Message\RequestInterface::setIsRedirect`. Use the HistoryPlugin. +- Removed `Guzzle\Http\Message\RequestInterface::isRedirect`. Use the HistoryPlugin. + +### Cache plugin breaking changes + +- CacheKeyProviderInterface and DefaultCacheKeyProvider are no longer used. All of this logic is handled in a + CacheStorageInterface. These two objects and interface will be removed in a future version. +- Always setting X-cache headers on cached responses +- Default cache TTLs are now handled by the CacheStorageInterface of a CachePlugin +- `CacheStorageInterface::cache($key, Response $response, $ttl = null)` has changed to `cache(RequestInterface + $request, Response $response);` +- `CacheStorageInterface::fetch($key)` has changed to `fetch(RequestInterface $request);` +- `CacheStorageInterface::delete($key)` has changed to `delete(RequestInterface $request);` +- Added `CacheStorageInterface::purge($url)` +- `DefaultRevalidation::__construct(CacheKeyProviderInterface $cacheKey, CacheStorageInterface $cache, CachePlugin + $plugin)` has changed to `DefaultRevalidation::__construct(CacheStorageInterface $cache, + CanCacheStrategyInterface $canCache = null)` +- Added `RevalidationInterface::shouldRevalidate(RequestInterface $request, Response $response)` + +3.5 to 3.6 +---------- + +* Mixed casing of headers are now forced to be a single consistent casing across all values for that header. +* Messages internally use a HeaderCollection object to delegate handling case-insensitive header resolution +* Removed the whole changedHeader() function system of messages because all header changes now go through addHeader(). + For example, setHeader() first removes the header using unset on a HeaderCollection and then calls addHeader(). + Keeping the Host header and URL host in sync is now handled by overriding the addHeader method in Request. +* Specific header implementations can be created for complex headers. When a message creates a header, it uses a + HeaderFactory which can map specific headers to specific header classes. There is now a Link header and + CacheControl header implementation. +* Moved getLinks() from Response to just be used on a Link header object. + +If you previously relied on Guzzle\Http\Message\Header::raw(), then you will need to update your code to use the +HeaderInterface (e.g. toArray(), getAll(), etc). + +### Interface changes + +* Removed from interface: Guzzle\Http\ClientInterface::setUriTemplate +* Removed from interface: Guzzle\Http\ClientInterface::setCurlMulti() +* Removed Guzzle\Http\Message\Request::receivedRequestHeader() and implemented this functionality in + Guzzle\Http\Curl\RequestMediator +* Removed the optional $asString parameter from MessageInterface::getHeader(). Just cast the header to a string. +* Removed the optional $tryChunkedTransfer option from Guzzle\Http\Message\EntityEnclosingRequestInterface +* Removed the $asObjects argument from Guzzle\Http\Message\MessageInterface::getHeaders() + +### Removed deprecated functions + +* Removed Guzzle\Parser\ParserRegister::get(). Use getParser() +* Removed Guzzle\Parser\ParserRegister::set(). Use registerParser(). + +### Deprecations + +* The ability to case-insensitively search for header values +* Guzzle\Http\Message\Header::hasExactHeader +* Guzzle\Http\Message\Header::raw. Use getAll() +* Deprecated cache control specific methods on Guzzle\Http\Message\AbstractMessage. Use the CacheControl header object + instead. + +### Other changes + +* All response header helper functions return a string rather than mixing Header objects and strings inconsistently +* Removed cURL blacklist support. This is no longer necessary now that Expect, Accept, etc are managed by Guzzle + directly via interfaces +* Removed the injecting of a request object onto a response object. The methods to get and set a request still exist + but are a no-op until removed. +* Most classes that used to require a ``Guzzle\Service\Command\CommandInterface` typehint now request a + `Guzzle\Service\Command\ArrayCommandInterface`. +* Added `Guzzle\Http\Message\RequestInterface::startResponse()` to the RequestInterface to handle injecting a response + on a request while the request is still being transferred +* `Guzzle\Service\Command\CommandInterface` now extends from ToArrayInterface and ArrayAccess + +3.3 to 3.4 +---------- + +Base URLs of a client now follow the rules of http://tools.ietf.org/html/rfc3986#section-5.2.2 when merging URLs. + +3.2 to 3.3 +---------- + +### Response::getEtag() quote stripping removed + +`Guzzle\Http\Message\Response::getEtag()` no longer strips quotes around the ETag response header + +### Removed `Guzzle\Http\Utils` + +The `Guzzle\Http\Utils` class was removed. This class was only used for testing. + +### Stream wrapper and type + +`Guzzle\Stream\Stream::getWrapper()` and `Guzzle\Stream\Stream::getSteamType()` are no longer converted to lowercase. + +### curl.emit_io became emit_io + +Emitting IO events from a RequestMediator is now a parameter that must be set in a request's curl options using the +'emit_io' key. This was previously set under a request's parameters using 'curl.emit_io' + +3.1 to 3.2 +---------- + +### CurlMulti is no longer reused globally + +Before 3.2, the same CurlMulti object was reused globally for each client. This can cause issue where plugins added +to a single client can pollute requests dispatched from other clients. + +If you still wish to reuse the same CurlMulti object with each client, then you can add a listener to the +ServiceBuilder's `service_builder.create_client` event to inject a custom CurlMulti object into each client as it is +created. + +```php +$multi = new Guzzle\Http\Curl\CurlMulti(); +$builder = Guzzle\Service\Builder\ServiceBuilder::factory('/path/to/config.json'); +$builder->addListener('service_builder.create_client', function ($event) use ($multi) { + $event['client']->setCurlMulti($multi); +} +}); +``` + +### No default path + +URLs no longer have a default path value of '/' if no path was specified. + +Before: + +```php +$request = $client->get('http://www.foo.com'); +echo $request->getUrl(); +// >> http://www.foo.com/ +``` + +After: + +```php +$request = $client->get('http://www.foo.com'); +echo $request->getUrl(); +// >> http://www.foo.com +``` + +### Less verbose BadResponseException + +The exception message for `Guzzle\Http\Exception\BadResponseException` no longer contains the full HTTP request and +response information. You can, however, get access to the request and response object by calling `getRequest()` or +`getResponse()` on the exception object. + +### Query parameter aggregation + +Multi-valued query parameters are no longer aggregated using a callback function. `Guzzle\Http\Query` now has a +setAggregator() method that accepts a `Guzzle\Http\QueryAggregator\QueryAggregatorInterface` object. This object is +responsible for handling the aggregation of multi-valued query string variables into a flattened hash. + +2.8 to 3.x +---------- + +### Guzzle\Service\Inspector + +Change `\Guzzle\Service\Inspector::fromConfig` to `\Guzzle\Common\Collection::fromConfig` + +**Before** + +```php +use Guzzle\Service\Inspector; + +class YourClient extends \Guzzle\Service\Client +{ + public static function factory($config = array()) + { + $default = array(); + $required = array('base_url', 'username', 'api_key'); + $config = Inspector::fromConfig($config, $default, $required); + + $client = new self( + $config->get('base_url'), + $config->get('username'), + $config->get('api_key') + ); + $client->setConfig($config); + + $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json')); + + return $client; + } +``` + +**After** + +```php +use Guzzle\Common\Collection; + +class YourClient extends \Guzzle\Service\Client +{ + public static function factory($config = array()) + { + $default = array(); + $required = array('base_url', 'username', 'api_key'); + $config = Collection::fromConfig($config, $default, $required); + + $client = new self( + $config->get('base_url'), + $config->get('username'), + $config->get('api_key') + ); + $client->setConfig($config); + + $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json')); + + return $client; + } +``` + +### Convert XML Service Descriptions to JSON + +**Before** + +```xml + + + + + + Get a list of groups + + + Uses a search query to get a list of groups + + + + Create a group + + + + + Delete a group by ID + + + + + + + Update a group + + + + + + +``` + +**After** + +```json +{ + "name": "Zendesk REST API v2", + "apiVersion": "2012-12-31", + "description":"Provides access to Zendesk views, groups, tickets, ticket fields, and users", + "operations": { + "list_groups": { + "httpMethod":"GET", + "uri": "groups.json", + "summary": "Get a list of groups" + }, + "search_groups":{ + "httpMethod":"GET", + "uri": "search.json?query=\"{query} type:group\"", + "summary": "Uses a search query to get a list of groups", + "parameters":{ + "query":{ + "location": "uri", + "description":"Zendesk Search Query", + "type": "string", + "required": true + } + } + }, + "create_group": { + "httpMethod":"POST", + "uri": "groups.json", + "summary": "Create a group", + "parameters":{ + "data": { + "type": "array", + "location": "body", + "description":"Group JSON", + "filters": "json_encode", + "required": true + }, + "Content-Type":{ + "type": "string", + "location":"header", + "static": "application/json" + } + } + }, + "delete_group": { + "httpMethod":"DELETE", + "uri": "groups/{id}.json", + "summary": "Delete a group", + "parameters":{ + "id":{ + "location": "uri", + "description":"Group to delete by ID", + "type": "integer", + "required": true + } + } + }, + "get_group": { + "httpMethod":"GET", + "uri": "groups/{id}.json", + "summary": "Get a ticket", + "parameters":{ + "id":{ + "location": "uri", + "description":"Group to get by ID", + "type": "integer", + "required": true + } + } + }, + "update_group": { + "httpMethod":"PUT", + "uri": "groups/{id}.json", + "summary": "Update a group", + "parameters":{ + "id": { + "location": "uri", + "description":"Group to update by ID", + "type": "integer", + "required": true + }, + "data": { + "type": "array", + "location": "body", + "description":"Group JSON", + "filters": "json_encode", + "required": true + }, + "Content-Type":{ + "type": "string", + "location":"header", + "static": "application/json" + } + } + } +} +``` + +### Guzzle\Service\Description\ServiceDescription + +Commands are now called Operations + +**Before** + +```php +use Guzzle\Service\Description\ServiceDescription; + +$sd = new ServiceDescription(); +$sd->getCommands(); // @returns ApiCommandInterface[] +$sd->hasCommand($name); +$sd->getCommand($name); // @returns ApiCommandInterface|null +$sd->addCommand($command); // @param ApiCommandInterface $command +``` + +**After** + +```php +use Guzzle\Service\Description\ServiceDescription; + +$sd = new ServiceDescription(); +$sd->getOperations(); // @returns OperationInterface[] +$sd->hasOperation($name); +$sd->getOperation($name); // @returns OperationInterface|null +$sd->addOperation($operation); // @param OperationInterface $operation +``` + +### Guzzle\Common\Inflection\Inflector + +Namespace is now `Guzzle\Inflection\Inflector` + +### Guzzle\Http\Plugin + +Namespace is now `Guzzle\Plugin`. Many other changes occur within this namespace and are detailed in their own sections below. + +### Guzzle\Http\Plugin\LogPlugin and Guzzle\Common\Log + +Now `Guzzle\Plugin\Log\LogPlugin` and `Guzzle\Log` respectively. + +**Before** + +```php +use Guzzle\Common\Log\ClosureLogAdapter; +use Guzzle\Http\Plugin\LogPlugin; + +/** @var \Guzzle\Http\Client */ +$client; + +// $verbosity is an integer indicating desired message verbosity level +$client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $verbosity = LogPlugin::LOG_VERBOSE); +``` + +**After** + +```php +use Guzzle\Log\ClosureLogAdapter; +use Guzzle\Log\MessageFormatter; +use Guzzle\Plugin\Log\LogPlugin; + +/** @var \Guzzle\Http\Client */ +$client; + +// $format is a string indicating desired message format -- @see MessageFormatter +$client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $format = MessageFormatter::DEBUG_FORMAT); +``` + +### Guzzle\Http\Plugin\CurlAuthPlugin + +Now `Guzzle\Plugin\CurlAuth\CurlAuthPlugin`. + +### Guzzle\Http\Plugin\ExponentialBackoffPlugin + +Now `Guzzle\Plugin\Backoff\BackoffPlugin`, and other changes. + +**Before** + +```php +use Guzzle\Http\Plugin\ExponentialBackoffPlugin; + +$backoffPlugin = new ExponentialBackoffPlugin($maxRetries, array_merge( + ExponentialBackoffPlugin::getDefaultFailureCodes(), array(429) + )); + +$client->addSubscriber($backoffPlugin); +``` + +**After** + +```php +use Guzzle\Plugin\Backoff\BackoffPlugin; +use Guzzle\Plugin\Backoff\HttpBackoffStrategy; + +// Use convenient factory method instead -- see implementation for ideas of what +// you can do with chaining backoff strategies +$backoffPlugin = BackoffPlugin::getExponentialBackoff($maxRetries, array_merge( + HttpBackoffStrategy::getDefaultFailureCodes(), array(429) + )); +$client->addSubscriber($backoffPlugin); +``` + +### Known Issues + +#### [BUG] Accept-Encoding header behavior changed unintentionally. + +(See #217) (Fixed in 09daeb8c666fb44499a0646d655a8ae36456575e) + +In version 2.8 setting the `Accept-Encoding` header would set the CURLOPT_ENCODING option, which permitted cURL to +properly handle gzip/deflate compressed responses from the server. In versions affected by this bug this does not happen. +See issue #217 for a workaround, or use a version containing the fix. diff --git a/src/bb-vendor/guzzle/guzzle/build.xml b/src/bb-vendor/guzzle/guzzle/build.xml new file mode 100644 index 000000000..2aa62ba9a --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/build.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/bb-vendor/guzzle/guzzle/composer.json b/src/bb-vendor/guzzle/guzzle/composer.json new file mode 100644 index 000000000..59424b39b --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/composer.json @@ -0,0 +1,82 @@ +{ + "name": "guzzle/guzzle", + "type": "library", + "description": "PHP HTTP client. This library is deprecated in favor of https://packagist.org/packages/guzzlehttp/guzzle", + "keywords": ["framework", "http", "rest", "web service", "curl", "client", "HTTP client"], + "homepage": "http://guzzlephp.org/", + "license": "MIT", + + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Guzzle Community", + "homepage": "https://github.com/guzzle/guzzle/contributors" + } + ], + + "replace": { + "guzzle/batch": "self.version", + "guzzle/cache": "self.version", + "guzzle/common": "self.version", + "guzzle/http": "self.version", + "guzzle/inflection": "self.version", + "guzzle/iterator": "self.version", + "guzzle/log": "self.version", + "guzzle/parser": "self.version", + "guzzle/plugin": "self.version", + "guzzle/plugin-async": "self.version", + "guzzle/plugin-backoff": "self.version", + "guzzle/plugin-cache": "self.version", + "guzzle/plugin-cookie": "self.version", + "guzzle/plugin-curlauth": "self.version", + "guzzle/plugin-error-response": "self.version", + "guzzle/plugin-history": "self.version", + "guzzle/plugin-log": "self.version", + "guzzle/plugin-md5": "self.version", + "guzzle/plugin-mock": "self.version", + "guzzle/plugin-oauth": "self.version", + "guzzle/service": "self.version", + "guzzle/stream": "self.version" + }, + + "require": { + "php": ">=5.3.3", + "ext-curl": "*", + "symfony/event-dispatcher": "~2.1" + }, + + "autoload": { + "psr-0": { + "Guzzle": "src/", + "Guzzle\\Tests": "tests/" + } + }, + + "suggest": { + "guzzlehttp/guzzle": "Guzzle 5 has moved to a new package name. The package you have installed, Guzzle 3, is deprecated." + }, + + "scripts": { + "test": "phpunit" + }, + + "require-dev": { + "doctrine/cache": "~1.3", + "symfony/class-loader": "~2.1", + "monolog/monolog": "~1.0", + "psr/log": "~1.0", + "zendframework/zend-cache": "2.*,<2.3", + "zendframework/zend-log": "2.*,<2.3", + "phpunit/phpunit": "3.7.*" + }, + + "extra": { + "branch-alias": { + "dev-master": "3.9-dev" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/docs/Makefile b/src/bb-vendor/guzzle/guzzle/docs/Makefile new file mode 100644 index 000000000..d92e03f95 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/Makefile @@ -0,0 +1,153 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + -rm -rf $(BUILDDIR)/* + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Guzzle.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Guzzle.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/Guzzle" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Guzzle" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." diff --git a/src/bb-vendor/guzzle/guzzle/docs/_downloads/guzzle-schema-1.0.json b/src/bb-vendor/guzzle/guzzle/docs/_downloads/guzzle-schema-1.0.json new file mode 100644 index 000000000..81683026b --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/_downloads/guzzle-schema-1.0.json @@ -0,0 +1,176 @@ +{ + "additionalProperties": true, + "name": { + "type": "string", + "description": "Name of the web service" + }, + "apiVersion": { + "type": ["string", "number"], + "description": "Version identifier that the service description is compatible with" + }, + "baseUrl": { + "type": "string", + "description": "Base URL of the web service. Any relative URI specified in an operation will be merged with the baseUrl using the process defined in RFC 2396" + }, + "basePath": { + "type": "string", + "description": "Alias of baseUrl" + }, + "_description": { + "type": "string", + "description": "Short summary of the web service. This is actually called 'description' but this JSON schema wont validate using just description." + }, + "operations": { + "description": "Operations of the web service", + "type": "object", + "properties": { + "extends": { + "type": "string", + "description": "Extend from another operation by name. The parent operation must be defined before the child." + }, + "httpMethod": { + "type": "string", + "description": "HTTP method used with the operation (e.g. GET, POST, PUT, DELETE, PATCH, etc)" + }, + "uri": { + "type": "string", + "description": "URI of the operation. The uri attribute can contain URI templates. The variables of the URI template are parameters of the operation with a location value of uri" + }, + "summary": { + "type": "string", + "description": "Short summary of what the operation does" + }, + "class": { + "type": "string", + "description": "Custom class to instantiate instead of the default Guzzle\\Service\\Command\\OperationCommand" + }, + "responseClass": { + "type": "string", + "description": "This is what is returned from the method. Can be a primitive, class name, or model name." + }, + "responseNotes": { + "type": "string", + "description": "A description of the response returned by the operation" + }, + "responseType": { + "type": "string", + "description": "The type of response that the operation creates. If not specified, this value will be automatically inferred based on whether or not there is a model matching the name, if a matching class name is found, or set to 'primitive' by default.", + "enum": [ "primitive", "class", "model", "documentation" ] + }, + "deprecated": { + "type": "boolean", + "description": "Whether or not the operation is deprecated" + }, + "errorResponses": { + "description": "Errors that could occur while executing the operation", + "type": "array", + "items": { + "type": "object", + "properties": { + "code": { + "type": "number", + "description": "HTTP response status code of the error" + }, + "reason": { + "type": "string", + "description": "Response reason phrase or description of the error" + }, + "class": { + "type": "string", + "description": "A custom exception class that would be thrown if the error is encountered" + } + } + } + }, + "data": { + "type": "object", + "additionalProperties": "true" + }, + "parameters": { + "$ref": "parameters", + "description": "Parameters of the operation. Parameters are used to define how input data is serialized into a HTTP request." + }, + "additionalParameters": { + "$ref": "parameters", + "description": "Validation and serialization rules for any parameter supplied to the operation that was not explicitly defined." + } + } + }, + "models": { + "description": "Schema models that can be referenced throughout the service description. Models can be used to define how an HTTP response is parsed into a Guzzle\\Service\\Resource\\Model object.", + "type": "object", + "properties": { + "$ref": "parameters", + "description": "Parameters of the model. When a model is referenced in a responseClass attribute of an operation, parameters define how a HTTP response message is parsed into a Guzzle\\Service\\Resource\\Model." + } + }, + "includes": { + "description": "Service description files to include and extend from (can be a .json, .js, or .php file)", + "type": "array", + "items": { + "type": "string", + "pattern": ".+\\.(js|json|php)$" + } + }, + "definitions": { + "parameters": { + "extends": "http://json-schema.org/schema", + "id": "parameters", + "name": { + "type": "string", + "description": "Unique name of the parameter" + }, + "type": { + "type": ["string", "array"], + "description": "Type of variable (string, number, integer, boolean, object, array, numeric, null, any). Types are using for validation and determining the structure of a parameter. You can use a union type by providing an array of simple types. If one of the union types matches the provided value, then the value is valid." + }, + "instanceOf": { + "type": "string", + "description": "When the type is an object, you can specify the class that the object must implement" + }, + "required": { + "type": "boolean", + "description": "Whether or not the parameter is required" + }, + "default": { + "description": "Default value to use if no value is supplied" + }, + "static": { + "type": "bool", + "description": "Set to true to specify that the parameter value cannot be changed from the default setting" + }, + "description": { + "type": "string", + "description": "Documentation of the parameter" + }, + "location": { + "type": "string", + "description": "The location of a request used to apply a parameter. Custom locations can be registered with a command, but the defaults are uri, query, statusCode, reasonPhrase, header, body, json, xml, postField, postFile, responseBody" + }, + "sentAs": { + "type": "string", + "description": "Specifies how the data being modeled is sent over the wire. For example, you may wish to include certain headers in a response model that have a normalized casing of FooBar, but the actual header is x-foo-bar. In this case, sentAs would be set to x-foo-bar." + }, + "filters": { + "type": "array", + "description": "Array of static method names to to run a parameter value through. Each value in the array must be a string containing the full class path to a static method or an array of complex filter information. You can specify static methods of classes using the full namespace class name followed by ‘::’ (e.g. FooBar::baz()). Some filters require arguments in order to properly filter a value. For complex filters, use a hash containing a ‘method’ key pointing to a static method, and an ‘args’ key containing an array of positional arguments to pass to the method. Arguments can contain keywords that are replaced when filtering a value: '@value‘ is replaced with the value being validated, '@api‘ is replaced with the Parameter object.", + "items": { + "type": ["string", { + "object": { + "properties": { + "method": { + "type": "string", + "description": "PHP function to call", + "required": true + }, + "args": { + "type": "array" + } + } + } + }] + } + } + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/docs/_static/guzzle-icon.png b/src/bb-vendor/guzzle/guzzle/docs/_static/guzzle-icon.png new file mode 100644 index 000000000..f1017f7e6 Binary files /dev/null and b/src/bb-vendor/guzzle/guzzle/docs/_static/guzzle-icon.png differ diff --git a/src/bb-vendor/guzzle/guzzle/docs/_static/homepage.css b/src/bb-vendor/guzzle/guzzle/docs/_static/homepage.css new file mode 100644 index 000000000..70c46d8d5 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/_static/homepage.css @@ -0,0 +1,122 @@ +/* Hero unit on homepage */ + +.hero-unit h1 { + font-size: 49px; + margin-bottom: 12px; +} + +.hero-unit { + padding: 40px; +} + +.hero-unit p { + font-size: 17px; +} + +.masthead img { + float: left; + margin-right: 17px; +} + +.hero-unit ul li { + margin-left: 220px; +} + +.hero-unit .buttons { + text-align: center; +} + +.jumbotron { + position: relative; + padding: 40px 0; + color: #fff; + text-shadow: 0 1px 3px rgba(0,0,0,.4), 0 0 30px rgba(0,0,0,.075); + background: #00312F; + background: -moz-linear-gradient(45deg, #002F31 0%, #335A6D 100%); + background: -webkit-gradient(linear, left bottom, right top, color-stop(0%,#00312D), color-stop(100%,#33566D)); + background: -webkit-linear-gradient(45deg, #020031 0%,#334F6D 100%); + background: -o-linear-gradient(45deg, #002D31 0%,#334D6D 100%); + background: -ms-linear-gradient(45deg, #002F31 0%,#33516D 100%); + background: linear-gradient(45deg, #020031 0%,#33516D 100%); + filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#020031', endColorstr='#6d3353',GradientType=1 ); + -webkit-box-shadow: inset 0 3px 7px rgba(0, 0, 0, .2), inset 0 -3px 7px rgba(0, 0, 0, .2); + -moz-box-shadow: inset 0 3px 7px rgba(0,0,0,.2), inset 0 -3px 7px rgba(0,0,0,.2); + box-shadow: inset 0 3px 7px rgba(0, 0, 0, .2), inset 0 -3px 7px rgba(0, 0, 0, .2); +} + +.jumbotron h1 { + font-size: 80px; + font-weight: bold; + letter-spacing: -1px; + line-height: 1; +} + +.jumbotron p { + font-size: 24px; + font-weight: 300; + line-height: 1.25; + margin-bottom: 30px; +} + +.masthead { + padding: 40px 0 30px; + margin-bottom: 0; + color: #fff; + margin-top: -19px; +} + +.masthead h1 { + display: none; +} + +.masthead p { + font-size: 40px; + font-weight: 200; + line-height: 1.25; + margin: 12px 0 0 0; +} + +.masthead .btn { + padding: 19px 24px; + font-size: 24px; + font-weight: 200; + border: 0; +} + +/* Social bar on homepage */ + +.social { + padding: 2px 0; + text-align: center; + background-color: #f5f5f5; + border-top: 1px solid #fff; + border-bottom: 1px solid #ddd; + margin: 0 0 20px 0; +} + +.social ul { + margin-top: 0; +} + +.social-buttons { + margin-left: 0; + margin-bottom: 0; + padding-left: 0; + list-style: none; +} + +.social-buttons li { + display: inline-block; + padding: 5px 8px; + line-height: 1; + *display: inline; + *zoom: 1; +} + +.center-announcement { + padding: 10px; + background-color: rgb(238, 243, 255); + border-radius: 8px; + text-align: center; + margin: 24px 0; +} diff --git a/src/bb-vendor/guzzle/guzzle/docs/_static/logo.png b/src/bb-vendor/guzzle/guzzle/docs/_static/logo.png new file mode 100644 index 000000000..965a4ef41 Binary files /dev/null and b/src/bb-vendor/guzzle/guzzle/docs/_static/logo.png differ diff --git a/src/bb-vendor/guzzle/guzzle/docs/_static/prettify.css b/src/bb-vendor/guzzle/guzzle/docs/_static/prettify.css new file mode 100644 index 000000000..4d410b12e --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/_static/prettify.css @@ -0,0 +1,41 @@ +.com { + color: #93A1A1; +} +.lit { + color: #195F91; +} +.pun, .opn, .clo { + color: #93A1A1; +} +.fun { + color: #DC322F; +} +.str, .atv { + color: #DD1144; +} +.kwd, .linenums .tag { + color: #1E347B; +} +.typ, .atn, .dec, .var { + color: teal; +} +.pln { + color: #48484C; +} +.prettyprint { + background-color: #F7F7F9; + border: 1px solid #E1E1E8; + padding: 8px; +} +.prettyprint.linenums { + box-shadow: 40px 0 0 #FBFBFC inset, 41px 0 0 #ECECF0 inset; +} +ol.linenums { + margin: 0 0 0 33px; +} +ol.linenums li { + color: #BEBEC5; + line-height: 18px; + padding-left: 12px; + text-shadow: 0 1px 0 #FFFFFF; +} diff --git a/src/bb-vendor/guzzle/guzzle/docs/_static/prettify.js b/src/bb-vendor/guzzle/guzzle/docs/_static/prettify.js new file mode 100644 index 000000000..eef5ad7e6 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/_static/prettify.js @@ -0,0 +1,28 @@ +var q=null;window.PR_SHOULD_USE_CONTINUATION=!0; +(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a= +[],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;ci[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m), +l=[],p={},d=0,g=e.length;d=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/, +q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/, +q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g, +"");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a), +a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e} +for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"], +"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"], +H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"], +J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+ +I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]), +["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css", +/^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}), +["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes", +hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p=0){var k=k.match(g),f,b;if(b= +!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p + + + +
+
+ guzzle +

Guzzle

+

Guzzle is a PHP HTTP client
& framework for building RESTful web service clients.

+

+ View Guzzle on GitHub + Read the docs +

+
+
+ + + +
+ +

Introducing Guzzle

+ +

Guzzle takes the pain out of sending HTTP requests and the redundancy out of creating web service clients. It's + a framework that includes the tools needed to create a robust web service client, including: + Service descriptions for defining the inputs and outputs of an API, resource iterators for traversing + paginated resources, batching for sending a large number of requests as efficiently as possible.

+ +
    +
  • All the power of cURL with a simple interface.
  • +
  • Persistent connections and parallel requests.
  • +
  • Streams request and response bodies
  • +
  • Service descriptions for quickly building clients.
  • +
  • Powered by the Symfony2 EventDispatcher.
  • +
  • Use all of the code or only specific components.
  • +
  • Plugins for caching, logging, OAuth, mocks, and more
  • +
  • Includes a custom node.js webserver to test your clients.
  • +
+ +
+ Guzzle is now part of Drupal 8 core and powers the official AWS SDK for PHP +
+ +

GitHub Example

+ +
<?php
+require_once 'vendor/autoload.php';
+use Guzzle\Http\Client;
+
+// Create a client and provide a base URL
+$client = new Client('https://api.github.com');
+// Create a request with basic Auth
+$request = $client->get('/user')->setAuth('user', 'pass');
+// Send the request and get the response
+$response = $request->send();
+echo $response->getBody();
+// >>> {"type":"User", ...
+echo $response->getHeader('Content-Length');
+// >>> 792
+
+ +

Twitter Example

+
<?php
+// Create a client to work with the Twitter API
+$client = new Client('https://api.twitter.com/{version}', array(
+    'version' => '1.1'
+));
+
+// Sign all requests with the OauthPlugin
+$client->addSubscriber(new Guzzle\Plugin\Oauth\OauthPlugin(array(
+    'consumer_key'  => '***',
+    'consumer_secret' => '***',
+    'token'       => '***',
+    'token_secret'  => '***'
+)));
+
+echo $client->get('statuses/user_timeline.json')->send()->getBody();
+// >>> {"public_gists":6,"type":"User" ...
+
+// Create a tweet using POST
+$request = $client->post('statuses/update.json', null, array(
+    'status' => 'Tweeted with Guzzle, http://guzzlephp.org'
+));
+
+// Send the request and parse the JSON response into an array
+$data = $request->send()->json();
+echo $data['text'];
+// >>> Tweeted with Guzzle, http://t.co/kngJMfRk
+
+
+ + diff --git a/src/bb-vendor/guzzle/guzzle/docs/_templates/leftbar.html b/src/bb-vendor/guzzle/guzzle/docs/_templates/leftbar.html new file mode 100644 index 000000000..e69de29bb diff --git a/src/bb-vendor/guzzle/guzzle/docs/_templates/nav_links.html b/src/bb-vendor/guzzle/guzzle/docs/_templates/nav_links.html new file mode 100644 index 000000000..d4f2165bb --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/_templates/nav_links.html @@ -0,0 +1,5 @@ +
  • Docs
  • +
  • API
  • +
  • GitHub
  • +
  • Forum
  • +
  • IRC
  • diff --git a/src/bb-vendor/guzzle/guzzle/docs/batching/batching.rst b/src/bb-vendor/guzzle/guzzle/docs/batching/batching.rst new file mode 100644 index 000000000..57f04d80f --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/batching/batching.rst @@ -0,0 +1,183 @@ +======== +Batching +======== + +Guzzle provides a fairly generic and very customizable batching framework that allows developers to efficiently +transfer requests in parallel. + +Sending requests and commands in parallel +----------------------------------------- + +You can send HTTP requests in parallel by passing an array of ``Guzzle\Http\Message\RequestInterface`` objects to +``Guzzle\Http\Client::send()``: + +.. code-block:: php + + $responses = $client->send(array( + $client->get('http://www.example.com/foo'), + $client->get('http://www.example.com/baz') + $client->get('http://www.example.com/bar') + )); + +You can send commands in parallel by passing an array of ``Guzzle\Service\Command\CommandInterface`` objects +``Guzzle\Service\Client::execute()``: + +.. code-block:: php + + $commands = $client->execute(array( + $client->getCommand('foo'), + $client->getCommand('baz'), + $client->getCommand('bar') + )); + +These approaches work well for most use-cases. When you need more control over the requests that are sent in +parallel or you need to send a large number of requests, you need to use the functionality provided in the +``Guzzle\Batch`` namespace. + +Batching overview +----------------- + +The batch object, ``Guzzle\Batch\Batch``, is a queue. You add requests to the queue until you are ready to transfer +all of the requests. In order to efficiently transfer the items in the queue, the batch object delegates the +responsibility of dividing the queue into manageable parts to a divisor (``Guzzle\Batch\BatchDivisorInterface``). +The batch object then iterates over each array of items created by the divisor and sends them to the batch object's +``Guzzle\Batch\BatchTransferInterface``. + +.. code-block:: php + + use Guzzle\Batch\Batch; + use Guzzle\Http\BatchRequestTransfer; + + // BatchRequestTransfer acts as both the divisor and transfer strategy + $transferStrategy = new BatchRequestTransfer(10); + $divisorStrategy = $transferStrategy; + + $batch = new Batch($transferStrategy, $divisorStrategy); + + // Add some requests to the batch queue + $batch->add($request1) + ->add($request2) + ->add($request3); + + // Flush the queue and retrieve the flushed items + $arrayOfTransferredRequests = $batch->flush(); + +.. note:: + + You might find that your transfer strategy will need to act as both the divisor and transfer strategy. + +Using the BatchBuilder +---------------------- + +The ``Guzzle\Batch\BatchBuilder`` makes it easier to create batch objects. The batch builder also provides an easier +way to add additional behaviors to your batch object. + +Transferring requests +~~~~~~~~~~~~~~~~~~~~~ + +The ``Guzzle\Http\BatchRequestTransfer`` class efficiently transfers HTTP requests in parallel by grouping batches of +requests by the curl_multi handle that is used to transfer the requests. + +.. code-block:: php + + use Guzzle\Batch\BatchBuilder; + + $batch = BatchBuilder::factory() + ->transferRequests(10) + ->build(); + +Transferring commands +~~~~~~~~~~~~~~~~~~~~~ + +The ``Guzzle\Service\Command\BatchCommandTransfer`` class efficiently transfers service commands by grouping commands +by the client that is used to transfer them. You can add commands to a batch object that are transferred by different +clients, and the batch will handle the rest. + +.. code-block:: php + + use Guzzle\Batch\BatchBuilder; + + $batch = BatchBuilder::factory() + ->transferCommands(10) + ->build(); + + $batch->add($client->getCommand('foo')) + ->add($client->getCommand('baz')) + ->add($client->getCommand('bar')); + + $commands = $batch->flush(); + +Batch behaviors +--------------- + +You can add various behaviors to your batch that allow for more customizable transfers. + +Automatically flushing a queue +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Use the ``Guzzle\Batch\FlushingBatch`` decorator when you want to pump a large number of items into a batch queue and +have the queue automatically flush when the size of the queue reaches a certain threshold. + +.. code-block:: php + + use Guzzle\Batch\BatchBuilder; + + $batch = BatchBuilder::factory() + ->transferRequests(10) + ->autoFlushAt(10) + ->build(); + +Batch builder method: ``autoFlushAt($threshold)`` + +Notifying on flush +~~~~~~~~~~~~~~~~~~ + +Use the ``Guzzle\Batch\NotifyingBatch`` decorator if you want a function to be notified each time the batch queue is +flushed. This is useful when paired with the flushing batch decorator. Pass a callable to the ``notify()`` method of +a batch builder to use this decorator with the builder. + +.. code-block:: php + + use Guzzle\Batch\BatchBuilder; + + $batch = BatchBuilder::factory() + ->transferRequests(10) + ->autoFlushAt(10) + ->notify(function (array $transferredItems) { + echo 'Transferred ' . count($transferredItems) . "items\n"; + }) + ->build(); + +Batch builder method:: ``notify(callable $callback)`` + +Keeping a history +~~~~~~~~~~~~~~~~~ + +Use the ``Guzzle\Batch\HistoryBatch`` decorator if you want to maintain a history of all the items transferred with +the batch queue. + +.. code-block:: php + + use Guzzle\Batch\BatchBuilder; + + $batch = BatchBuilder::factory() + ->transferRequests(10) + ->keepHistory() + ->build(); + +After transferring items, you can use the ``getHistory()`` of a batch to retrieve an array of transferred items. Be +sure to periodically clear the history using ``clearHistory()``. + +Batch builder method: ``keepHistory()`` + +Exception buffering +~~~~~~~~~~~~~~~~~~~ + +Use the ``Guzzle\Batch\ExceptionBufferingBatch`` decorator to buffer exceptions during a transfer so that you can +transfer as many items as possible then deal with the errored batches after the transfer completes. After transfer, +use the ``getExceptions()`` method of a batch to retrieve an array of +``Guzzle\Batch\Exception\BatchTransferException`` objects. You can use these exceptions to attempt to retry the +failed batches. Be sure to clear the buffered exceptions when you are done with them by using the +``clearExceptions()`` method. + +Batch builder method: ``bufferExceptions()`` diff --git a/src/bb-vendor/guzzle/guzzle/docs/conf.py b/src/bb-vendor/guzzle/guzzle/docs/conf.py new file mode 100644 index 000000000..92bc46bb5 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/conf.py @@ -0,0 +1,94 @@ +import sys, os +from sphinx.highlighting import lexers +from pygments.lexers.web import PhpLexer + +lexers['php'] = PhpLexer(startinline=True, linenos=1) +lexers['php-annotations'] = PhpLexer(startinline=True, linenos=1) +primary_domain = 'php' + +# -- General configuration ----------------------------------------------------- + +extensions = [] +templates_path = ['_templates'] +source_suffix = '.rst' +master_doc = 'index' + +project = u'Guzzle' +copyright = u'2012, Michael Dowling' +version = '3.0.0' +release = '3.0.0' + +exclude_patterns = ['_build'] + +# -- Options for HTML output --------------------------------------------------- + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +html_title = "Guzzle documentation" +html_short_title = "Guzzle" + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# Custom sidebar templates, maps document names to template names. +html_sidebars = { + '**': ['localtoc.html', 'leftbar.html', 'searchbox.html'] +} + +# Output file base name for HTML help builder. +htmlhelp_basename = 'Guzzledoc' + +# -- Guzzle Sphinx theme setup ------------------------------------------------ + +sys.path.insert(0, '/Users/dowling/projects/guzzle_sphinx_theme') + +import guzzle_sphinx_theme +html_translator_class = 'guzzle_sphinx_theme.HTMLTranslator' +html_theme_path = guzzle_sphinx_theme.html_theme_path() +html_theme = 'guzzle_sphinx_theme' + +# Guzzle theme options (see theme.conf for more information) +html_theme_options = { + "index_template": "index.html", + "project_nav_name": "Guzzle", + "github_user": "guzzle", + "github_repo": "guzzle", + "disqus_comments_shortname": "guzzle", + "google_analytics_account": "UA-22752917-1" +} + +# -- Options for LaTeX output -------------------------------------------------- + +latex_elements = {} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass [howto/manual]). +latex_documents = [ + ('index', 'Guzzle.tex', u'Guzzle Documentation', + u'Michael Dowling', 'manual'), +] + +# -- Options for manual page output -------------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'guzzle', u'Guzzle Documentation', + [u'Michael Dowling'], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + +# -- Options for Texinfo output ------------------------------------------------ + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'Guzzle', u'Guzzle Documentation', + u'Michael Dowling', 'Guzzle', 'One line description of project.', + 'Miscellaneous'), +] diff --git a/src/bb-vendor/guzzle/guzzle/docs/docs.rst b/src/bb-vendor/guzzle/guzzle/docs/docs.rst new file mode 100644 index 000000000..cf87908bd --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/docs.rst @@ -0,0 +1,73 @@ +.. title:: Guzzle | PHP HTTP client and framework for consuming RESTful web services + +==================== +Guzzle Documentation +==================== + +Getting started +--------------- + +.. toctree:: + :maxdepth: 1 + + getting-started/overview + getting-started/installation + getting-started/faq + +The HTTP client +--------------- + +.. toctree:: + :maxdepth: 2 + + http-client/client + http-client/request + http-client/response + http-client/entity-bodies + http-client/http-redirects + http-client/uri-templates + +Plugins +------- + +.. toctree:: + :maxdepth: 1 + + plugins/plugins-overview + plugins/creating-plugins + plugins/async-plugin + plugins/backoff-plugin + plugins/cache-plugin + plugins/cookie-plugin + plugins/curl-auth-plugin + plugins/history-plugin + plugins/log-plugin + plugins/md5-validator-plugin + plugins/mock-plugin + plugins/oauth-plugin + +The web service client +---------------------- + +.. toctree:: + :maxdepth: 1 + + webservice-client/webservice-client + webservice-client/using-the-service-builder + webservice-client/guzzle-service-descriptions + batching/batching + iterators/resource-iterators + iterators/guzzle-iterators + +Testing +------- + +.. toctree:: + :maxdepth: 2 + + testing/unit-testing + +API Docs +-------- + +`Read the API docs `_ diff --git a/src/bb-vendor/guzzle/guzzle/docs/getting-started/faq.rst b/src/bb-vendor/guzzle/guzzle/docs/getting-started/faq.rst new file mode 100644 index 000000000..a0a3fdbb6 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/getting-started/faq.rst @@ -0,0 +1,29 @@ +=== +FAQ +=== + +What should I do if I get this error: Fatal error: Maximum function nesting level of '100' reached, aborting! +------------------------------------------------------------------------------------------------------------- + +You could run into this error if you have the XDebug extension installed and you execute a lot of requests in +callbacks. This error message comes specifically from the XDebug extension. PHP itself does not have a function +nesting limit. Change this setting in your php.ini to increase the limit:: + + xdebug.max_nesting_level = 1000 + +[`source `_] + +How can I speed up my client? +----------------------------- + +There are several things you can do to speed up your client: + +1. Utilize a C based HTTP message parser (e.g. ``Guzzle\Parser\Message\PeclHttpMessageParser``) +2. Disable operation validation by setting the ``command.disable_validation`` option to true on a command + +Why am I getting a 417 error response? +-------------------------------------- + +This can occur for a number of reasons, but if you are sending PUT, POST, or PATCH requests with an +``Expect: 100-Continue`` header, a server that does not support this header will return a 417 response. You can work +around this by calling ``$request->removeHeader('Expect');`` after setting the entity body of a request. diff --git a/src/bb-vendor/guzzle/guzzle/docs/getting-started/installation.rst b/src/bb-vendor/guzzle/guzzle/docs/getting-started/installation.rst new file mode 100644 index 000000000..77d400131 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/getting-started/installation.rst @@ -0,0 +1,154 @@ +============ +Installation +============ + +Requirements +------------ + +#. PHP 5.3.3+ compiled with the cURL extension +#. A recent version of cURL 7.16.2+ compiled with OpenSSL and zlib + +Installing Guzzle +----------------- + +Composer +~~~~~~~~ + +The recommended way to install Guzzle is with `Composer `_. Composer is a dependency +management tool for PHP that allows you to declare the dependencies your project needs and installs them into your +project. + +.. code-block:: bash + + # Install Composer + curl -sS https://getcomposer.org/installer | php + + # Add Guzzle as a dependency + php composer.phar require guzzle/guzzle:~3.9 + +After installing, you need to require Composer's autoloader: + +.. code-block:: php + + require 'vendor/autoload.php'; + +You can find out more on how to install Composer, configure autoloading, and other best-practices for defining +dependencies at `getcomposer.org `_. + +Using only specific parts of Guzzle +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +While you can always just rely on ``guzzle/guzzle``, Guzzle provides several smaller parts of Guzzle as individual +packages available through Composer. + ++-----------------------------------------------------------------------------------------------+------------------------------------------+ +| Package name | Description | ++===============================================================================================+==========================================+ +| `guzzle/common `_ | Provides ``Guzzle\Common`` | ++-----------------------------------------------------------------------------------------------+------------------------------------------+ +| `guzzle/http `_ | Provides ``Guzzle\Http`` | ++-----------------------------------------------------------------------------------------------+------------------------------------------+ +| `guzzle/parser `_ | Provides ``Guzzle\Parser`` | ++-----------------------------------------------------------------------------------------------+------------------------------------------+ +| `guzzle/batch `_ | Provides ``Guzzle\Batch`` | ++-----------------------------------------------------------------------------------------------+------------------------------------------+ +| `guzzle/cache `_ | Provides ``Guzzle\Cache`` | ++-----------------------------------------------------------------------------------------------+------------------------------------------+ +| `guzzle/inflection `_ | Provides ``Guzzle\Inflection`` | ++-----------------------------------------------------------------------------------------------+------------------------------------------+ +| `guzzle/iterator `_ | Provides ``Guzzle\Iterator`` | ++-----------------------------------------------------------------------------------------------+------------------------------------------+ +| `guzzle/log `_ | Provides ``Guzzle\Log`` | ++-----------------------------------------------------------------------------------------------+------------------------------------------+ +| `guzzle/plugin `_ | Provides ``Guzzle\Plugin`` (all plugins) | ++-----------------------------------------------------------------------------------------------+------------------------------------------+ +| `guzzle/plugin-async `_ | Provides ``Guzzle\Plugin\Async`` | ++-----------------------------------------------------------------------------------------------+------------------------------------------+ +| `guzzle/plugin-backoff `_ | Provides ``Guzzle\Plugin\BackoffPlugin`` | ++-----------------------------------------------------------------------------------------------+------------------------------------------+ +| `guzzle/plugin-cache `_ | Provides ``Guzzle\Plugin\Cache`` | ++-----------------------------------------------------------------------------------------------+------------------------------------------+ +| `guzzle/plugin-cookie `_ | Provides ``Guzzle\Plugin\Cookie`` | ++-----------------------------------------------------------------------------------------------+------------------------------------------+ +| `guzzle/plugin-error-response `_ | Provides ``Guzzle\Plugin\ErrorResponse`` | ++-----------------------------------------------------------------------------------------------+------------------------------------------+ +| `guzzle/plugin-history `_ | Provides ``Guzzle\Plugin\History`` | ++-----------------------------------------------------------------------------------------------+------------------------------------------+ +| `guzzle/plugin-log `_ | Provides ``Guzzle\Plugin\Log`` | ++-----------------------------------------------------------------------------------------------+------------------------------------------+ +| `guzzle/plugin-md5 `_ | Provides ``Guzzle\Plugin\Md5`` | ++-----------------------------------------------------------------------------------------------+------------------------------------------+ +| `guzzle/plugin-mock `_ | Provides ``Guzzle\Plugin\Mock`` | ++-----------------------------------------------------------------------------------------------+------------------------------------------+ +| `guzzle/plugin-oauth `_ | Provides ``Guzzle\Plugin\Oauth`` | ++-----------------------------------------------------------------------------------------------+------------------------------------------+ +| `guzzle/service `_ | Provides ``Guzzle\Service`` | ++-----------------------------------------------------------------------------------------------+------------------------------------------+ +| `guzzle/stream `_ | Provides ``Guzzle\Stream`` | ++-----------------------------------------------------------------------------------------------+------------------------------------------+ + +Bleeding edge +^^^^^^^^^^^^^ + +During your development, you can keep up with the latest changes on the master branch by setting the version +requirement for Guzzle to ``dev-master``. + +.. code-block:: js + + { + "require": { + "guzzle/guzzle": "dev-master" + } + } + +PEAR +~~~~ + +Guzzle can be installed through PEAR: + +.. code-block:: bash + + pear channel-discover guzzlephp.org/pear + pear install guzzle/guzzle + +You can install a specific version of Guzzle by providing a version number suffix: + +.. code-block:: bash + + pear install guzzle/guzzle-3.9.0 + +Contributing to Guzzle +---------------------- + +In order to contribute, you'll need to checkout the source from GitHub and install Guzzle's dependencies using +Composer: + +.. code-block:: bash + + git clone https://github.com/guzzle/guzzle.git + cd guzzle && curl -s http://getcomposer.org/installer | php && ./composer.phar install --dev + +Guzzle is unit tested with PHPUnit. You will need to create your own phpunit.xml file in order to run the unit tests +(or just copy phpunit.xml.dist to phpunit.xml). Run the tests using the vendored PHPUnit binary: + +.. code-block:: bash + + vendor/bin/phpunit + +You'll need to install node.js v0.5.0 or newer in order to test the cURL implementation. + +Framework integrations +---------------------- + +Using Guzzle with Symfony +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Bundles are available on GitHub: + +- `DdeboerGuzzleBundle `_ for Guzzle 2 +- `MisdGuzzleBundle `_ for Guzzle 3 + +Using Guzzle with Silex +~~~~~~~~~~~~~~~~~~~~~~~ + +A `Guzzle Silex service provider `_ is available on GitHub. diff --git a/src/bb-vendor/guzzle/guzzle/docs/getting-started/overview.rst b/src/bb-vendor/guzzle/guzzle/docs/getting-started/overview.rst new file mode 100644 index 000000000..505b40978 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/getting-started/overview.rst @@ -0,0 +1,85 @@ +================= +Welcome to Guzzle +================= + +What is Guzzle? +~~~~~~~~~~~~~~~ + +Guzzle is a PHP HTTP client and framework for building web service clients. Guzzle takes the pain out of sending HTTP +requests and the redundancy out of creating web service clients. + +Features at a glance +-------------------- + +- All the power of cURL with a simple interface. +- Persistent connections and parallel requests. +- Streams request and response bodies +- Service descriptions for quickly building clients. +- Powered by the Symfony2 EventDispatcher. +- Use all of the code or only specific components. +- Plugins for caching, logging, OAuth, mocks, and more +- Includes a custom node.js webserver to test your clients. +- Service descriptions for defining the inputs and outputs of an API +- Resource iterators for traversing paginated resources +- Batching for sending a large number of requests as efficiently as possible + +.. code-block:: php + + // Really simple using a static facade + Guzzle\Http\StaticClient::mount(); + $response = Guzzle::get('http://guzzlephp.org'); + + // More control using a client class + $client = new \Guzzle\Http\Client('http://guzzlephp.org'); + $request = $client->get('/'); + $response = $request->send(); + +License +------- + +Licensed using the `MIT license `_. + + Copyright (c) 2013 Michael Dowling + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + +Contributing +------------ + +Guidelines +~~~~~~~~~~ + +This is still a work in progress, but there are only a few rules: + +1. Guzzle follows PSR-0, PSR-1, and PSR-2 +2. All pull requests must include unit tests to ensure the change works as expected and to prevent future regressions + +Reporting a security vulnerability +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +We want to ensure that Guzzle is a secure HTTP client library for everyone. If you've discovered a security +vulnerability in Guzzle, we appreciate your help in disclosing it to us in a +`responsible manner `_. + +Publicly disclosing a vulnerability can put the entire community at risk. If you've discovered a security concern, +please email us at security@guzzlephp.org. We'll work with you to make sure that we understand the scope of the issue, +and that we fully address your concern. We consider correspondence sent to security@guzzlephp.org our highest priority, +and work to address any issues that arise as quickly as possible. + +After a security vulnerability has been corrected, a security hotfix release will be deployed as soon as possible. diff --git a/src/bb-vendor/guzzle/guzzle/docs/http-client/client.rst b/src/bb-vendor/guzzle/guzzle/docs/http-client/client.rst new file mode 100644 index 000000000..723d729db --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/http-client/client.rst @@ -0,0 +1,569 @@ +====================== +The Guzzle HTTP client +====================== + +Guzzle gives PHP developers complete control over HTTP requests while utilizing HTTP/1.1 best practices. Guzzle's HTTP +functionality is a robust framework built on top of the `PHP libcurl bindings `_. + +The three main parts of the Guzzle HTTP client are: + ++--------------+-------------------------------------------------------------------------------------------------------+ +| Clients | ``Guzzle\Http\Client`` (creates and sends requests, associates a response with a request) | ++--------------+-------------------------------------------------------------------------------------------------------+ +| Requests | ``Guzzle\Http\Message\Request`` (requests with no body), | +| | ``Guzzle\Http\Message\EntityEnclosingRequest`` (requests with a body) | ++--------------+-------------------------------------------------------------------------------------------------------+ +| Responses | ``Guzzle\Http\Message\Response`` | ++--------------+-------------------------------------------------------------------------------------------------------+ + +Creating a Client +----------------- + +Clients create requests, send requests, and set responses on a request object. When instantiating a client object, +you can pass an optional "base URL" and optional array of configuration options. A base URL is a +:doc:`URI template ` that contains the URL of a remote server. When creating requests with a relative +URL, the base URL of a client will be merged into the request's URL. + +.. code-block:: php + + use Guzzle\Http\Client; + + // Create a client and provide a base URL + $client = new Client('https://api.github.com'); + + $request = $client->get('/user'); + $request->setAuth('user', 'pass'); + echo $request->getUrl(); + // >>> https://api.github.com/user + + // You must send a request in order for the transfer to occur + $response = $request->send(); + + echo $response->getBody(); + // >>> {"type":"User", ... + + echo $response->getHeader('Content-Length'); + // >>> 792 + + $data = $response->json(); + echo $data['type']; + // >>> User + +Base URLs +~~~~~~~~~ + +Notice that the URL provided to the client's ``get()`` method is relative. Relative URLs will always merge into the +base URL of the client. There are a few rules that control how the URLs are merged. + +.. tip:: + + Guzzle follows `RFC 3986 `_ when merging base URLs and + relative URLs. + +In the above example, we passed ``/user`` to the ``get()`` method of the client. This is a relative URL, so it will +merge into the base URL of the client-- resulting in the derived URL of ``https://api.github.com/users``. + +``/user`` is a relative URL but uses an absolute path because it contains the leading slash. Absolute paths will +overwrite any existing path of the base URL. If an absolute path is provided (e.g. ``/path/to/something``), then the +path specified in the base URL of the client will be replaced with the absolute path, and the query string provided +by the relative URL will replace the query string of the base URL. + +Omitting the leading slash and using relative paths will add to the path of the base URL of the client. So using a +client base URL of ``https://api.twitter.com/v1.1`` and creating a GET request with ``statuses/user_timeline.json`` +will result in a URL of ``https://api.twitter.com/v1.1/statuses/user_timeline.json``. If a relative path and a query +string are provided, then the relative path will be appended to the base URL path, and the query string provided will +be merged into the query string of the base URL. + +If an absolute URL is provided (e.g. ``http://httpbin.org/ip``), then the request will completely use the absolute URL +as-is without merging in any of the URL parts specified in the base URL. + +Configuration options +~~~~~~~~~~~~~~~~~~~~~ + +The second argument of the client's constructor is an array of configuration data. This can include URI template data +or special options that alter the client's behavior: + ++-------------------------------+-------------------------------------------------------------------------------------+ +| ``request.options`` | Associative array of :ref:`Request options ` to apply to every | +| | request created by the client. | ++-------------------------------+-------------------------------------------------------------------------------------+ +| ``redirect.disable`` | Disable HTTP redirects for every request created by the client. | ++-------------------------------+-------------------------------------------------------------------------------------+ +| ``curl.options`` | Associative array of cURL options to apply to every request created by the client. | +| | if either the key or value of an entry in the array is a string, Guzzle will | +| | attempt to find a matching defined cURL constant automatically (e.g. | +| | "CURLOPT_PROXY" will be converted to the constant ``CURLOPT_PROXY``). | ++-------------------------------+-------------------------------------------------------------------------------------+ +| ``ssl.certificate_authority`` | Set to true to use the Guzzle bundled SSL certificate bundle (this is used by | +| | default, 'system' to use the bundle on your system, a string pointing to a file to | +| | use a specific certificate file, a string pointing to a directory to use multiple | +| | certificates, or ``false`` to disable SSL validation (not recommended). | +| | | +| | When using Guzzle inside of a phar file, the bundled SSL certificate will be | +| | extracted to your system's temp folder, and each time a client is created an MD5 | +| | check will be performed to ensure the integrity of the certificate. | ++-------------------------------+-------------------------------------------------------------------------------------+ +| ``command.params`` | When using a ``Guzzle\Service\Client`` object, this is an associative array of | +| | default options to set on each command created by the client. | ++-------------------------------+-------------------------------------------------------------------------------------+ + +Here's an example showing how to set various configuration options, including default headers to send with each request, +default query string parameters to add to each request, a default auth scheme for each request, and a proxy to use for +each request. Values can be injected into the client's base URL using variables from the configuration array. + +.. code-block:: php + + use Guzzle\Http\Client; + + $client = new Client('https://api.twitter.com/{version}', array( + 'version' => 'v1.1', + 'request.options' => array( + 'headers' => array('Foo' => 'Bar'), + 'query' => array('testing' => '123'), + 'auth' => array('username', 'password', 'Basic|Digest|NTLM|Any'), + 'proxy' => 'tcp://localhost:80' + ) + )); + +Setting a custom User-Agent +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The default Guzzle User-Agent header is ``Guzzle/ curl/ PHP/``. You can +customize the User-Agent header of a client by calling the ``setUserAgent()`` method of a Client object. + +.. code-block:: php + + // Completely override the default User-Agent + $client->setUserAgent('Test/123'); + + // Prepend a string to the default User-Agent + $client->setUserAgent('Test/123', true); + +Creating requests with a client +------------------------------- + +A Client object exposes several methods used to create Request objects: + +* Create a custom HTTP request: ``$client->createRequest($method, $uri, array $headers, $body, $options)`` +* Create a GET request: ``$client->get($uri, array $headers, $options)`` +* Create a HEAD request: ``$client->head($uri, array $headers, $options)`` +* Create a DELETE request: ``$client->delete($uri, array $headers, $body, $options)`` +* Create a POST request: ``$client->post($uri, array $headers, $postBody, $options)`` +* Create a PUT request: ``$client->put($uri, array $headers, $body, $options)`` +* Create a PATCH request: ``$client->patch($uri, array $headers, $body, $options)`` + +.. code-block:: php + + use Guzzle\Http\Client; + + $client = new Client('http://baseurl.com/api/v1'); + + // Create a GET request using Relative to base URL + // URL of the request: http://baseurl.com/api/v1/path?query=123&value=abc) + $request = $client->get('path?query=123&value=abc'); + $response = $request->send(); + + // Create HEAD request using a relative URL with an absolute path + // URL of the request: http://baseurl.com/path?query=123&value=abc + $request = $client->head('/path?query=123&value=abc'); + $response = $request->send(); + + // Create a DELETE request using an absolute URL + $request = $client->delete('http://www.example.com/path?query=123&value=abc'); + $response = $request->send(); + + // Create a PUT request using the contents of a PHP stream as the body + // Specify custom HTTP headers + $request = $client->put('http://www.example.com/upload', array( + 'X-Header' => 'My Header' + ), fopen('http://www.test.com/', 'r')); + $response = $request->send(); + + // Create a POST request and add the POST files manually + $request = $client->post('http://localhost:8983/solr/update') + ->addPostFiles(array('file' => '/path/to/documents.xml')); + $response = $request->send(); + + // Check if a resource supports the DELETE method + $supportsDelete = $client->options('/path')->send()->isMethodAllowed('DELETE'); + $response = $request->send(); + +Client objects create Request objects using a request factory (``Guzzle\Http\Message\RequestFactoryInterface``). +You can inject a custom request factory into the Client using ``$client->setRequestFactory()``, but you can typically +rely on a Client's default request factory. + +Static clients +-------------- + +You can use Guzzle's static client facade to more easily send simple HTTP requests. + +.. code-block:: php + + // Mount the client so that you can access it at \Guzzle + Guzzle\Http\StaticClient::mount(); + $response = Guzzle::get('http://guzzlephp.org'); + +Each request method of the static client (e.g. ``get()``, ``post()`, ``put()``, etc) accepts an associative array of request +options to apply to the request. + +.. code-block:: php + + $response = Guzzle::post('http://test.com', array( + 'headers' => array('X-Foo' => 'Bar'), + 'body' => array('Test' => '123'), + 'timeout' => 10 + )); + +.. _request-options: + +Request options +--------------- + +Request options can be specified when creating a request or in the ``request.options`` parameter of a client. These +options can control various aspects of a request including: headers to send, query string data, where the response +should be downloaded, proxies, auth, etc. + +headers +~~~~~~~ + +Associative array of headers to apply to the request. When specified in the ``$options`` argument of a client creational +method (e.g. ``get()``, ``post()``, etc), the headers in the ``$options`` array will overwrite headers specified in the +``$headers`` array. + +.. code-block:: php + + $request = $client->get($url, array(), array( + 'headers' => array('X-Foo' => 'Bar') + )); + +Headers can be specified on a client to add default headers to every request sent by a client. + +.. code-block:: php + + $client = new Guzzle\Http\Client(); + + // Set a single header using path syntax + $client->setDefaultOption('headers/X-Foo', 'Bar'); + + // Set all headers + $client->setDefaultOption('headers', array('X-Foo' => 'Bar')); + +.. note:: + + In addition to setting request options when creating requests or using the ``setDefaultOption()`` method, any + default client request option can be set using a client's config object: + + .. code-block:: php + + $client->getConfig()->setPath('request.options/headers/X-Foo', 'Bar'); + +query +~~~~~ + +Associative array of query string parameters to the request. When specified in the ``$options`` argument of a client +creational method, the query string parameters in the ``$options`` array will overwrite query string parameters +specified in the `$url`. + +.. code-block:: php + + $request = $client->get($url, array(), array( + 'query' => array('abc' => '123') + )); + +Query string parameters can be specified on a client to add default query string parameters to every request sent by a +client. + +.. code-block:: php + + $client = new Guzzle\Http\Client(); + + // Set a single query string parameter using path syntax + $client->setDefaultOption('query/abc', '123'); + + // Set an array of default query string parameters + $client->setDefaultOption('query', array('abc' => '123')); + +body +~~~~ + +Sets the body of a request. The value supplied to the body option can be a ``Guzzle\Http\EntityBodyInterface``, string, +fopen resource, or array when sending POST requests. When a ``body`` request option is supplied, the option value will +overwrite the ``$body`` argument of a client creational method. + +auth +~~~~ + +Specifies and array of HTTP authorization parameters parameters to use with the request. The array must contain the +username in index [0], the password in index [1], and can optionally contain the authentication type in index [2]. +The available authentication types are: "Basic" (default), "Digest", "NTLM", or "Any". + +.. code-block:: php + + $request = $client->get($url, array(), array( + 'auth' => array('username', 'password', 'Digest') + )); + + // You can add auth headers to every request of a client + $client->setDefaultOption('auth', array('username', 'password', 'Digest')); + +cookies +~~~~~~~ + +Specifies an associative array of cookies to add to the request. + +allow_redirects +~~~~~~~~~~~~~~~ + +Specifies whether or not the request should follow redirects. Requests will follow redirects by default. Set +``allow_redirects`` to ``false`` to disable redirects. + +save_to +~~~~~~~ + +The ``save_to`` option specifies where the body of a response is downloaded. You can pass the path to a file, an fopen +resource, or a ``Guzzle\Http\EntityBodyInterface`` object. + +See :ref:`Changing where a response is downloaded ` for more information on setting the +`save_to` option. + +events +~~~~~~ + +The `events` option makes it easy to attach listeners to the various events emitted by a request object. The `events` +options must be an associative array mapping an event name to a Closure or array the contains a Closure and the +priority of the event. + +.. code-block:: php + + $request = $client->get($url, array(), array( + 'events' => array( + 'request.before_send' => function (\Guzzle\Common\Event $e) { + echo 'About to send ' . $e['request']; + } + ) + )); + + // Using the static client: + Guzzle::get($url, array( + 'events' => array( + 'request.before_send' => function (\Guzzle\Common\Event $e) { + echo 'About to send ' . $e['request']; + } + ) + )); + +plugins +~~~~~~~ + +The `plugins` options makes it easy to attach an array of plugins to a request. + +.. code-block:: php + + // Using the static client: + Guzzle::get($url, array( + 'plugins' => array( + new Guzzle\Plugin\Cache\CachePlugin(), + new Guzzle\Plugin\Cookie\CookiePlugin() + ) + )); + +exceptions +~~~~~~~~~~ + +The `exceptions` option can be used to disable throwing exceptions for unsuccessful HTTP response codes +(e.g. 404, 500, etc). Set `exceptions` to false to not throw exceptions. + +params +~~~~~~ + +The `params` options can be used to specify an associative array of data parameters to add to a request. Note that +these are not query string parameters. + +timeout / connect_timeout +~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can specify the maximum number of seconds to allow for an entire transfer to take place before timing out using +the `timeout` request option. You can specify the maximum number of seconds to wait while trying to connect using the +`connect_timeout` request option. Set either of these options to 0 to wait indefinitely. + +.. code-block:: php + + $request = $client->get('http://www.example.com', array(), array( + 'timeout' => 20, + 'connect_timeout' => 1.5 + )); + +verify +~~~~~~ + +Set to true to enable SSL certificate validation (the default), false to disable SSL certificate validation, or supply +the path to a CA bundle to enable verification using a custom certificate. + +cert +~~~~ + +The `cert` option lets you specify a PEM formatted SSL client certificate to use with servers that require one. If the +certificate requires a password, provide an array with the password as the second item. + +This would typically be used in conjunction with the `ssl_key` option. + +.. code-block:: php + + $request = $client->get('https://www.example.com', array(), array( + 'cert' => '/etc/pki/client_certificate.pem' + ) + + $request = $client->get('https://www.example.com', array(), array( + 'cert' => array('/etc/pki/client_certificate.pem', 's3cr3tp455w0rd') + ) + +ssl_key +~~~~~~~ + +The `ssl_key` option lets you specify a file containing your PEM formatted private key, optionally protected by a password. +Note: your password is sensitive, keep the PHP script containing it safe. + +This would typically be used in conjunction with the `cert` option. + +.. code-block:: php + + $request = $client->get('https://www.example.com', array(), array( + 'ssl_key' => '/etc/pki/private_key.pem' + ) + + $request = $client->get('https://www.example.com', array(), array( + 'ssl_key' => array('/etc/pki/private_key.pem', 's3cr3tp455w0rd') + ) + +proxy +~~~~~ + +The `proxy` option is used to specify an HTTP proxy (e.g. `http://username:password@192.168.16.1:10`). + +debug +~~~~~ + +The `debug` option is used to show verbose cURL output for a transfer. + +stream +~~~~~~ + +When using a static client, you can set the `stream` option to true to return a `Guzzle\Stream\Stream` object that can +be used to pull data from a stream as needed (rather than have cURL download the entire contents of a response to a +stream all at once). + +.. code-block:: php + + $stream = Guzzle::get('http://guzzlephp.org', array('stream' => true)); + while (!$stream->feof()) { + echo $stream->readLine(); + } + +Sending requests +---------------- + +Requests can be sent by calling the ``send()`` method of a Request object, but you can also send requests using the +``send()`` method of a Client. + +.. code-block:: php + + $request = $client->get('http://www.amazon.com'); + $response = $client->send($request); + +Sending requests in parallel +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The Client's ``send()`` method accept a single ``Guzzle\Http\Message\RequestInterface`` object or an array of +RequestInterface objects. When an array is specified, the requests will be sent in parallel. + +Sending many HTTP requests serially (one at a time) can cause an unnecessary delay in a script's execution. Each +request must complete before a subsequent request can be sent. By sending requests in parallel, a pool of HTTP +requests can complete at the speed of the slowest request in the pool, significantly reducing the amount of time +needed to execute multiple HTTP requests. Guzzle provides a wrapper for the curl_multi functions in PHP. + +Here's an example of sending three requests in parallel using a client object: + +.. code-block:: php + + use Guzzle\Common\Exception\MultiTransferException; + + try { + $responses = $client->send(array( + $client->get('http://www.google.com/'), + $client->head('http://www.google.com/'), + $client->get('https://www.github.com/') + )); + } catch (MultiTransferException $e) { + + echo "The following exceptions were encountered:\n"; + foreach ($e as $exception) { + echo $exception->getMessage() . "\n"; + } + + echo "The following requests failed:\n"; + foreach ($e->getFailedRequests() as $request) { + echo $request . "\n\n"; + } + + echo "The following requests succeeded:\n"; + foreach ($e->getSuccessfulRequests() as $request) { + echo $request . "\n\n"; + } + } + +If the requests succeed, an array of ``Guzzle\Http\Message\Response`` objects are returned. A single request failure +will not cause the entire pool of requests to fail. Any exceptions thrown while transferring a pool of requests will +be aggregated into a ``Guzzle\Common\Exception\MultiTransferException`` exception. + +Plugins and events +------------------ + +Guzzle provides easy to use request plugins that add behavior to requests based on signal slot event notifications +powered by the +`Symfony2 Event Dispatcher component `_. Any +event listener or subscriber attached to a Client object will automatically be attached to each request created by the +client. + +Using the same cookie session for each request +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Attach a ``Guzzle\Plugin\Cookie\CookiePlugin`` to a client which will in turn add support for cookies to every request +created by a client, and each request will use the same cookie session: + +.. code-block:: php + + use Guzzle\Plugin\Cookie\CookiePlugin; + use Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar; + + // Create a new cookie plugin + $cookiePlugin = new CookiePlugin(new ArrayCookieJar()); + + // Add the cookie plugin to the client + $client->addSubscriber($cookiePlugin); + +.. _client-events: + +Events emitted from a client +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A ``Guzzle\Http\Client`` object emits the following events: + ++------------------------------+--------------------------------------------+------------------------------------------+ +| Event name | Description | Event data | ++==============================+============================================+==========================================+ +| client.create_request | Called when a client creates a request | * client: The client | +| | | * request: The created request | ++------------------------------+--------------------------------------------+------------------------------------------+ + +.. code-block:: php + + use Guzzle\Common\Event; + use Guzzle\Http\Client; + + $client = new Client(); + + // Add a listener that will echo out requests as they are created + $client->getEventDispatcher()->addListener('client.create_request', function (Event $e) { + echo 'Client object: ' . spl_object_hash($e['client']) . "\n"; + echo "Request object: {$e['request']}\n"; + }); diff --git a/src/bb-vendor/guzzle/guzzle/docs/http-client/entity-bodies.rst b/src/bb-vendor/guzzle/guzzle/docs/http-client/entity-bodies.rst new file mode 100644 index 000000000..823b0c022 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/http-client/entity-bodies.rst @@ -0,0 +1,151 @@ +=========================== +Request and response bodies +=========================== + +`Entity body `_ is the term used for the body of an HTTP +message. The entity body of requests and responses is inherently a +`PHP stream `_ in Guzzle. The body of the request can be either a string or +a PHP stream which are converted into a ``Guzzle\Http\EntityBody`` object using its factory method. When using a +string, the entity body is stored in a `temp PHP stream `_. The use of +temp PHP streams helps to protect your application from running out of memory when sending or receiving large entity +bodies in your messages. When more than 2MB of data is stored in a temp stream, it automatically stores the data on +disk rather than in memory. + +EntityBody objects provide a great deal of functionality: compression, decompression, calculate the Content-MD5, +calculate the Content-Length (when the resource is repeatable), guessing the Content-Type, and more. Guzzle doesn't +need to load an entire entity body into a string when sending or retrieving data; entity bodies are streamed when +being uploaded and downloaded. + +Here's an example of gzip compressing a text file then sending the file to a URL: + +.. code-block:: php + + use Guzzle\Http\EntityBody; + + $body = EntityBody::factory(fopen('/path/to/file.txt', 'r+')); + echo $body->read(1024); + $body->seek(0, SEEK_END); + $body->write('foo'); + echo $body->ftell(); + $body->rewind(); + + // Send a request using the body + $response = $client->put('http://localhost:8080/uploads', null, $body)->send(); + +The body of the request can be specified in the ``Client::put()`` or ``Client::post()`` method, or, you can specify +the body of the request by calling the ``setBody()`` method of any +``Guzzle\Http\Message\EntityEnclosingRequestInterface`` object. + +Compression +----------- + +You can compress the contents of an EntityBody object using the ``compress()`` method. The compress method accepts a +filter that must match to one of the supported +`PHP stream filters `_ on your system (e.g. `zlib.deflate`, +``bzip2.compress``, etc). Compressing an entity body will stream the entire entity body through a stream compression +filter into a temporary PHP stream. You can uncompress an entity body using the ``uncompress()`` method and passing +the PHP stream filter to use when decompressing the stream (e.g. ``zlib.inflate``). + +.. code-block:: php + + use Guzzle\Http\EntityBody; + + $body = EntityBody::factory(fopen('/tmp/test.txt', 'r+')); + echo $body->getSize(); + // >>> 1048576 + + // Compress using the default zlib.deflate filter + $body->compress(); + echo $body->getSize(); + // >>> 314572 + + // Decompress the stream + $body->uncompress(); + echo $body->getSize(); + // >>> 1048576 + +Decorators +---------- + +Guzzle provides several EntityBody decorators that can be used to add functionality to an EntityBody at runtime. + +IoEmittingEntityBody +~~~~~~~~~~~~~~~~~~~~ + +This decorator will emit events when data is read from a stream or written to a stream. Add an event subscriber to the +entity body's ``body.read`` or ``body.write`` methods to receive notifications when data data is transferred. + +.. code-block:: php + + use Guzzle\Common\Event; + use Guzzle\Http\EntityBody; + use Guzzle\Http\IoEmittingEntityBody; + + $original = EntityBody::factory(fopen('/tmp/test.txt', 'r+')); + $body = new IoEmittingEntityBody($original); + + // Listen for read events + $body->getEventDispatcher()->addListener('body.read', function (Event $e) { + // Grab data from the event + $entityBody = $e['body']; + // Amount of data retrieved from the body + $lengthOfData = $e['length']; + // The actual data that was read + $data = $e['read']; + }); + + // Listen for write events + $body->getEventDispatcher()->addListener('body.write', function (Event $e) { + // Grab data from the event + $entityBody = $e['body']; + // The data that was written + $data = $e['write']; + // The actual amount of data that was written + $data = $e['read']; + }); + +ReadLimitEntityBody +~~~~~~~~~~~~~~~~~~~ + +The ReadLimitEntityBody decorator can be used to transfer a subset or slice of an existing EntityBody object. This can +be useful for breaking a large file into smaller pieces to be sent in chunks (e.g. Amazon S3's multipart upload API). + +.. code-block:: php + + use Guzzle\Http\EntityBody; + use Guzzle\Http\ReadLimitEntityBody; + + $original = EntityBody::factory(fopen('/tmp/test.txt', 'r+')); + echo $original->getSize(); + // >>> 1048576 + + // Limit the size of the body to 1024 bytes and start reading from byte 2048 + $body = new ReadLimitEntityBody($original, 1024, 2048); + echo $body->getSize(); + // >>> 1024 + echo $body->ftell(); + // >>> 0 + +CachingEntityBody +~~~~~~~~~~~~~~~~~ + +The CachingEntityBody decorator is used to allow seeking over previously read bytes on non-seekable read streams. This +can be useful when transferring a non-seekable entity body fails due to needing to rewind the stream (for example, +resulting from a redirect). Data that is read from the remote stream will be buffered in a PHP temp stream so that +previously read bytes are cached first in memory, then on disk. + +.. code-block:: php + + use Guzzle\Http\EntityBody; + use Guzzle\Http\CachingEntityBody; + + $original = EntityBody::factory(fopen('http://www.google.com', 'r')); + $body = new CachingEntityBody($original); + + $body->read(1024); + echo $body->ftell(); + // >>> 1024 + + $body->seek(0); + echo $body->ftell(); + // >>> 0 diff --git a/src/bb-vendor/guzzle/guzzle/docs/http-client/http-redirects.rst b/src/bb-vendor/guzzle/guzzle/docs/http-client/http-redirects.rst new file mode 100644 index 000000000..32ba26891 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/http-client/http-redirects.rst @@ -0,0 +1,99 @@ +============== +HTTP redirects +============== + +By default, Guzzle will automatically follow redirects using the non-RFC compliant implementation used by most web +browsers. This means that redirects for POST requests are followed by a GET request. You can force RFC compliance by +enabling the strict mode on a request's parameter object: + +.. code-block:: php + + // Set per request + $request = $client->post(); + $request->getParams()->set('redirect.strict', true); + + // You can set globally on a client so all requests use strict redirects + $client->getConfig()->set('request.params', array( + 'redirect.strict' => true + )); + +By default, Guzzle will redirect up to 5 times before throwing a ``Guzzle\Http\Exception\TooManyRedirectsException``. +You can raise or lower this value using the ``redirect.max`` parameter of a request object: + +.. code-block:: php + + $request->getParams()->set('redirect.max', 2); + +Redirect history +---------------- + +You can get the number of redirects of a request using the resulting response object's ``getRedirectCount()`` method. +Similar to cURL's ``effective_url`` property, Guzzle provides the effective URL, or the last redirect URL that returned +the request, in a response's ``getEffectiveUrl()`` method. + +When testing or debugging, it is often useful to see a history of redirects for a particular request. This can be +achieved using the HistoryPlugin. + +.. code-block:: php + + $request = $client->get('/'); + $history = new Guzzle\Plugin\History\HistoryPlugin(); + $request->addSubscriber($history); + $response = $request->send(); + + // Get the last redirect URL or the URL of the request that received + // this response + echo $response->getEffectiveUrl(); + + // Get the number of redirects + echo $response->getRedirectCount(); + + // Iterate over each sent request and response + foreach ($history->getAll() as $transaction) { + // Request object + echo $transaction['request']->getUrl() . "\n"; + // Response object + echo $transaction['response']->getEffectiveUrl() . "\n"; + } + + // Or, simply cast the HistoryPlugin to a string to view each request and response + echo $history; + +Disabling redirects +------------------- + +You can disable redirects on a client by passing a configuration option in the client's constructor: + +.. code-block:: php + + $client = new Client(null, array('redirect.disable' => true)); + +You can also disable redirects per request: + +.. code-block:: php + + $request = $client->get($url, array(), array('allow_redirects' => false)); + +Redirects and non-repeatable streams +------------------------------------ + +If you are redirected when sending data from a non-repeatable stream and some of the data has been read off of the +stream, then you will get a ``Guzzle\Http\Exception\CouldNotRewindStreamException``. You can get around this error by +adding a custom rewind method to the entity body object being sent in the request. + +.. code-block:: php + + $request = $client->post( + 'http://httpbin.com/redirect/2', + null, + fopen('http://httpbin.com/get', 'r') + ); + + // Add a custom function that can be used to rewind the stream + // (reopen in this example) + $request->getBody()->setRewindFunction(function ($body) { + $body->setStream(fopen('http://httpbin.com/get', 'r')); + return true; + ); + + $response = $client->send(); diff --git a/src/bb-vendor/guzzle/guzzle/docs/http-client/request.rst b/src/bb-vendor/guzzle/guzzle/docs/http-client/request.rst new file mode 100644 index 000000000..a8387a915 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/http-client/request.rst @@ -0,0 +1,667 @@ +===================== +Using Request objects +===================== + +HTTP request messages +--------------------- + +Request objects are all about building an HTTP message. Each part of an HTTP request message can be set individually +using methods on the request object or set in bulk using the ``setUrl()`` method. Here's the format of an HTTP request +with each part of the request referencing the method used to change it:: + + PUT(a) /path(b)?query=123(c) HTTP/1.1(d) + X-Header(e): header + Content-Length(e): 4 + + data(f) + ++-------------------------+---------------------------------------------------------------------------------+ +| a. **Method** | The request method can only be set when instantiating a request | ++-------------------------+---------------------------------------------------------------------------------+ +| b. **Path** | ``$request->setPath('/path');`` | ++-------------------------+---------------------------------------------------------------------------------+ +| c. **Query** | ``$request->getQuery()->set('query', '123');`` | ++-------------------------+---------------------------------------------------------------------------------+ +| d. **Protocol version** | ``$request->setProtocolVersion('1.1');`` | ++-------------------------+---------------------------------------------------------------------------------+ +| e. **Header** | ``$request->setHeader('X-Header', 'header');`` | ++-------------------------+---------------------------------------------------------------------------------+ +| f. **Entity Body** | ``$request->setBody('data'); // Only available with PUT, POST, PATCH, DELETE`` | ++-------------------------+---------------------------------------------------------------------------------+ + +Creating requests with a client +------------------------------- + +Client objects are responsible for creating HTTP request objects. + +GET requests +~~~~~~~~~~~~ + +`GET requests `_ are the most common form of HTTP +requests. When you visit a website in your browser, the HTML of the website is downloaded using a GET request. GET +requests are idempotent requests that are typically used to download content (an entity) identified by a request URL. + +.. code-block:: php + + use Guzzle\Http\Client; + + $client = new Client(); + + // Create a request that has a query string and an X-Foo header + $request = $client->get('http://www.amazon.com?a=1', array('X-Foo' => 'Bar')); + + // Send the request and get the response + $response = $request->send(); + +You can change where the body of a response is downloaded on any request using the +``$request->setResponseBody(string|EntityBodyInterface|resource)`` method of a request. You can also set the ``save_to`` +option of a request: + +.. code-block:: php + + // Send the response body to a file + $request = $client->get('http://test.com', array(), array('save_to' => '/path/to/file')); + + // Send the response body to an fopen resource + $request = $client->get('http://test.com', array(), array('save_to' => fopen('/path/to/file', 'w'))); + +HEAD requests +~~~~~~~~~~~~~ + +`HEAD requests `_ work exactly like GET requests except +that they do not actually download the response body (entity) of the response message. HEAD requests are useful for +retrieving meta information about an entity identified by a Request-URI. + +.. code-block:: php + + $client = new Guzzle\Http\Client(); + $request = $client->head('http://www.amazon.com'); + $response = $request->send(); + echo $response->getContentLength(); + // >>> Will output the Content-Length header value + +DELETE requests +~~~~~~~~~~~~~~~ + +A `DELETE method `_ requests that the origin server +delete the resource identified by the Request-URI. + +.. code-block:: php + + $client = new Guzzle\Http\Client(); + $request = $client->delete('http://example.com'); + $response = $request->send(); + +POST requests +~~~~~~~~~~~~~ + +While `POST requests `_ can be used for a number of +reasons, POST requests are often used when submitting HTML form data to a website. POST requests can include an entity +body in the HTTP request. + +POST requests in Guzzle are sent with an ``application/x-www-form-urlencoded`` Content-Type header if POST fields are +present but no files are being sent in the POST. If files are specified in the POST request, then the Content-Type +header will become ``multipart/form-data``. + +The ``post()`` method of a client object accepts four arguments: the URL, optional headers, post fields, and an array of +request options. To send files in the POST request, prepend the ``@`` symbol to the array value (just like you would if +you were using the PHP ``curl_setopt`` function). + +Here's how to create a multipart/form-data POST request containing files and fields: + +.. code-block:: php + + $request = $client->post('http://httpbin.org/post', array(), array( + 'custom_field' => 'my custom value', + 'file_field' => '@/path/to/file.xml' + )); + + $response = $request->send(); + +.. note:: + + Remember to **always** sanitize user input when sending POST requests: + + .. code-block:: php + + // Prevent users from accessing sensitive files by sanitizing input + $_POST = array('firstname' => '@/etc/passwd'); + $request = $client->post('http://www.example.com', array(), array ( + 'firstname' => str_replace('@', '', $_POST['firstname']) + )); + +You can alternatively build up the contents of a POST request. + +.. code-block:: php + + $request = $client->post('http://httpbin.org/post') + ->setPostField('custom_field', 'my custom value') + ->addPostFile('file', '/path/to/file.xml'); + + $response = $request->send(); + +Raw POST data +^^^^^^^^^^^^^ + +POST requests can also contain raw POST data that is not related to HTML forms. + +.. code-block:: php + + $request = $client->post('http://httpbin.org/post', array(), 'this is the body'); + $response = $request->send(); + +You can set the body of POST request using the ``setBody()`` method of the +``Guzzle\Http\Message\EntityEnclosingRequest`` object. This method accepts a string, a resource returned from +``fopen``, or a ``Guzzle\Http\EntityBodyInterface`` object. + +.. code-block:: php + + $request = $client->post('http://httpbin.org/post'); + // Set the body of the POST to stream the contents of /path/to/large_body.txt + $request->setBody(fopen('/path/to/large_body.txt', 'r')); + $response = $request->send(); + +PUT requests +~~~~~~~~~~~~ + +The `PUT method `_ requests that the enclosed entity be +stored under the supplied Request-URI. PUT requests are similar to POST requests in that they both can send an entity +body in the request message. + +The body of a PUT request (any any ``Guzzle\Http\Message\EntityEnclosingRequestInterface`` object) is always stored as +a ``Guzzle\Http\Message\EntityBodyInterface`` object. This allows a great deal of flexibility when sending data to a +remote server. For example, you can stream the contents of a stream returned by fopen, stream the contents of a +callback function, or simply send a string of data. + +.. code-block:: php + + $request = $client->put('http://httpbin.org/put', array(), 'this is the body'); + $response = $request->send(); + +Just like with POST, PATH, and DELETE requests, you can set the body of a PUT request using the ``setBody()`` method. + +.. code-block:: php + + $request = $client->put('http://httpbin.org/put'); + $request->setBody(fopen('/path/to/large_body.txt', 'r')); + $response = $request->send(); + +PATCH requests +~~~~~~~~~~~~~~ + +`PATCH requests `_ are used to modify a resource. + +.. code-block:: php + + $request = $client->patch('http://httpbin.org', array(), 'this is the body'); + $response = $request->send(); + +OPTIONS requests +~~~~~~~~~~~~~~~~ + +The `OPTIONS method `_ represents a request for +information about the communication options available on the request/response chain identified by the Request-URI. + +.. code-block:: php + + $request = $client->options('http://httpbin.org'); + $response = $request->send(); + + // Check if the PUT method is supported by this resource + var_export($response->isMethodAllows('PUT')); + +Custom requests +~~~~~~~~~~~~~~~ + +You can create custom HTTP requests that use non-standard HTTP methods using the ``createRequest()`` method of a +client object. + +.. code-block:: php + + $request = $client->createRequest('COPY', 'http://example.com/foo', array( + 'Destination' => 'http://example.com/bar', + 'Overwrite' => 'T' + )); + $response = $request->send(); + +Query string parameters +----------------------- + +Query string parameters of a request are owned by a request's ``Guzzle\Http\Query`` object that is accessible by +calling ``$request->getQuery()``. The Query class extends from ``Guzzle\Common\Collection`` and allows you to set one +or more query string parameters as key value pairs. You can set a parameter on a Query object using the +``set($key, $value)`` method or access the query string object like an associative array. Any previously specified +value for a key will be overwritten when using ``set()``. Use ``add($key, $value)`` to add a value to query string +object, and in the event of a collision with an existing value at a specific key, the value will be converted to an +array that contains all of the previously set values. + +.. code-block:: php + + $request = new Guzzle\Http\Message\Request('GET', 'http://www.example.com?foo=bar&abc=123'); + + $query = $request->getQuery(); + echo "{$query}\n"; + // >>> foo=bar&abc=123 + + $query->remove('abc'); + echo "{$query}\n"; + // >>> foo=bar + + $query->set('foo', 'baz'); + echo "{$query}\n"; + // >>> foo=baz + + $query->add('foo', 'bar'); + echo "{$query}\n"; + // >>> foo%5B0%5D=baz&foo%5B1%5D=bar + +Whoah! What happened there? When ``foo=bar`` was added to the existing ``foo=baz`` query string parameter, the +aggregator associated with the Query object was used to help convert multi-value query string parameters into a string. +Let's disable URL-encoding to better see what's happening. + +.. code-block:: php + + $query->useUrlEncoding(false); + echo "{$query}\n"; + // >>> foo[0]=baz&foo[1]=bar + +.. note:: + + URL encoding can be disabled by passing false, enabled by passing true, set to use RFC 1738 by passing + ``Query::FORM_URLENCODED`` (internally uses PHP's ``urlencode`` function), or set to RFC 3986 by passing + ``Query::RFC_3986`` (this is the default and internally uses PHP's ``rawurlencode`` function). + +As you can see, the multiple values were converted into query string parameters following the default PHP convention of +adding numerically indexed square bracket suffixes to each key (``foo[0]=baz&foo[1]=bar``). The strategy used to convert +multi-value parameters into a string can be customized using the ``setAggregator()`` method of the Query class. Guzzle +ships with the following query string aggregators by default: + +1. ``Guzzle\Http\QueryAggregator\PhpAggregator``: Aggregates using PHP style brackets (e.g. ``foo[0]=baz&foo[1]=bar``) +2. ``Guzzle\Http\QueryAggregator\DuplicateAggregator``: Performs no aggregation and allows for key value pairs to be + repeated in a URL (e.g. ``foo=baz&foo=bar``) +3. ``Guzzle\Http\QueryAggregator\CommaAggregator``: Aggregates using commas (e.g. ``foo=baz,bar``) + +.. _http-message-headers: + +HTTP Message Headers +-------------------- + +HTTP message headers are case insensitive, multiple occurrences of any header can be present in an HTTP message +(whether it's valid or not), and some servers require specific casing of particular headers. Because of this, request +and response headers are stored in ``Guzzle\Http\Message\Header`` objects. The Header object can be cast as a string, +counted, or iterated to retrieve each value from the header. Casting a Header object to a string will return all of +the header values concatenated together using a glue string (typically ", "). + +A request (and response) object have several methods that allow you to retrieve and modify headers. + +* ``getHeaders()``: Get all of the headers of a message as a ``Guzzle\Http\Message\Header\HeaderCollection`` object. +* ``getHeader($header)``: Get a specific header from a message. If the header exists, you'll get a + ``Guzzle\Http\Message\Header`` object. If the header does not exist, this methods returns ``null``. +* ``hasHeader($header)``: Returns true or false based on if the message has a particular header. +* ``setHeader($header, $value)``: Set a header value and overwrite any previously set value for this header. +* ``addHeader($header, $value)``: Add a header with a particular name. If a previous value was already set by the same, + then the header will contain multiple values. +* ``removeHeader($header)``: Remove a header by name from the message. + +.. code-block:: php + + $request = new Request('GET', 'http://httpbin.com/cookies'); + // addHeader will set and append to any existing header values + $request->addHeader('Foo', 'bar'); + $request->addHeader('foo', 'baz'); + // setHeader overwrites any existing values + $request->setHeader('Test', '123'); + + // Request headers can be cast as a string + echo $request->getHeader('Foo'); + // >>> bar, baz + echo $request->getHeader('Test'); + // >>> 123 + + // You can count the number of headers of a particular case insensitive name + echo count($request->getHeader('foO')); + // >>> 2 + + // You can iterate over Header objects + foreach ($request->getHeader('foo') as $header) { + echo $header . "\n"; + } + + // You can get all of the request headers as a Guzzle\Http\Message\Header\HeaderCollection object + $headers = $request->getHeaders(); + + // Missing headers return NULL + var_export($request->getHeader('Missing')); + // >>> null + + // You can see all of the different variations of a header by calling raw() on the Header + var_export($request->getHeader('foo')->raw()); + +Setting the body of a request +----------------------------- + +Requests that can send a body (e.g. PUT, POST, DELETE, PATCH) are instances of +``Guzzle\Http\Message\EntityEnclosingRequestInterface``. Entity enclosing requests contain several methods that allow +you to specify the body to send with a request. + +Use the ``setBody()`` method of a request to set the body that will be sent with a request. This method accepts a +string, a resource returned by ``fopen()``, an array, or an instance of ``Guzzle\Http\EntityBodyInterface``. The body +will then be streamed from the underlying ``EntityBodyInterface`` object owned by the request. When setting the body +of the request, you can optionally specify a Content-Type header and whether or not to force the request to use +chunked Transfer-Encoding. + +.. code-block:: php + + $request = $client->put('/user.json'); + $request->setBody('{"foo":"baz"}', 'application/json'); + +Content-Type header +~~~~~~~~~~~~~~~~~~~ + +Guzzle will automatically add a Content-Type header to a request if the Content-Type can be guessed based on the file +extension of the payload being sent or the file extension present in the path of a request. + +.. code-block:: php + + $request = $client->put('/user.json', array(), '{"foo":"bar"}'); + // The Content-Type was guessed based on the path of the request + echo $request->getHeader('Content-Type'); + // >>> application/json + + $request = $client->put('/user.json'); + $request->setBody(fopen('/tmp/user_data.json', 'r')); + // The Content-Type was guessed based on the path of the entity body + echo $request->getHeader('Content-Type'); + // >>> application/json + +Transfer-Encoding: chunked header +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When sending HTTP requests that contain a payload, you must let the remote server know how to determine when the entire +message has been sent. This usually is done by supplying a ``Content-Length`` header that tells the origin server the +size of the body that is to be sent. In some cases, the size of the payload being sent in a request cannot be known +before initiating the transfer. In these cases (when using HTTP/1.1), you can use the ``Transfer-Encoding: chunked`` +header. + +If the Content-Length cannot be determined (i.e. using a PHP ``http://`` stream), then Guzzle will automatically add +the ``Transfer-Encoding: chunked`` header to the request. + +.. code-block:: php + + $request = $client->put('/user.json'); + $request->setBody(fopen('http://httpbin.org/get', 'r')); + + // The Content-Length could not be determined + echo $request->getHeader('Transfer-Encoding'); + // >>> chunked + +See :doc:`/http-client/entity-bodies` for more information on entity bodies. + +Expect: 100-Continue header +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The ``Expect: 100-Continue`` header is used to help a client prevent sending a large payload to a server that will +reject the request. This allows clients to fail fast rather than waste bandwidth sending an erroneous payload. Guzzle +will automatically add the ``Expect: 100-Continue`` header to a request when the size of the payload exceeds 1MB or if +the body of the request is not seekable (this helps to prevent errors when a non-seekable body request is redirected). + +.. note:: + + If you find that your larger requests are taking too long to complete, you should first check if the + ``Expect: 100-Continue`` header is being sent with the request. Some servers do not respond well to this header, + which causes cURL to sleep for `1 second `_. + +POST fields and files +~~~~~~~~~~~~~~~~~~~~~ + +Any entity enclosing request can send POST style fields and files. This includes POST, PUT, PATCH, and DELETE requests. +Any request that has set POST fields or files will use cURL's POST message functionality. + +.. code-block:: php + + $request = $client->post('/post'); + // Set an overwrite any previously specified value + $request->setPostField('foo', 'bar'); + // Append a value to any existing values + $request->getPostFields()->add('foo', 'baz'); + // Remove a POST field by name + $request->removePostField('fizz'); + + // Add a file to upload (forces multipart/form-data) + $request->addPostFile('my_file', '/path/to/file', 'plain/text'); + // Remove a POST file by POST key name + $request->removePostFile('my_other_file'); + +.. tip:: + + Adding a large number of POST fields to a POST request is faster if you use the ``addPostFields()`` method so that + you can add and process multiple fields with a single call. Adding multiple POST files is also faster using + ``addPostFiles()``. + +Working with cookies +-------------------- + +Cookies can be modified and retrieved from a request using the following methods: + +.. code-block:: php + + $request->addCookie($name, $value); + $request->removeCookie($name); + $value = $request->getCookie($name); + $valueArray = $request->getCookies(); + +Use the :doc:`cookie plugin ` if you need to reuse cookies between requests. + +.. _request-set-response-body: + +Changing where a response is downloaded +---------------------------------------- + +When a request is sent, the body of the response will be stored in a PHP temp stream by default. You can change the +location in which the response will be downloaded using ``$request->setResponseBody($body)`` or the ``save_to`` request +option. This can be useful for downloading the contents of a URL to a specific file. + +Here's an example of using request options: + +.. code-block:: php + + $request = $this->client->get('http://example.com/large.mov', array(), array( + 'save_to' => '/tmp/large_file.mov' + )); + $request->send(); + var_export(file_exists('/tmp/large_file.mov')); + // >>> true + +Here's an example of using ``setResponseBody()``: + +.. code-block:: php + + $body = fopen('/tmp/large_file.mov', 'w'); + $request = $this->client->get('http://example.com/large.mov'); + $request->setResponseBody($body); + + // You can more easily specify the name of a file to save the contents + // of the response to by passing a string to ``setResponseBody()``. + + $request = $this->client->get('http://example.com/large.mov'); + $request->setResponseBody('/tmp/large_file.mov'); + +Custom cURL options +------------------- + +Most of the functionality implemented in the libcurl bindings has been simplified and abstracted by Guzzle. Developers +who need access to `cURL specific functionality `_ can still add cURL handle +specific behavior to Guzzle HTTP requests by modifying the cURL options collection of a request: + +.. code-block:: php + + $request->getCurlOptions()->set(CURLOPT_LOW_SPEED_LIMIT, 200); + +Other special options that can be set in the ``curl.options`` array include: + ++-------------------------+---------------------------------------------------------------------------------+ +| debug | Adds verbose cURL output to a temp stream owned by the cURL handle object | ++-------------------------+---------------------------------------------------------------------------------+ +| progress | Instructs cURL to emit events when IO events occur. This allows you to be | +| | notified when bytes are transferred over the wire by subscribing to a request's | +| | ``curl.callback.read``, ``curl.callback.write``, and ``curl.callback.progress`` | +| | events. | ++-------------------------+---------------------------------------------------------------------------------+ + +Request options +--------------- + +Requests options can be specified when creating a request or in the ``request.options`` parameter of a client. These +options can control various aspects of a request including: headers to send, query string data, where the response +should be downloaded, proxies, auth, etc. + +.. code-block:: php + + $request = $client->get($url, $headers, array('proxy' => 'http://proxy.com')); + +See :ref:`Request options ` for more information. + +Working with errors +------------------- + +HTTP errors +~~~~~~~~~~~ + +Requests that receive a 4xx or 5xx response will throw a ``Guzzle\Http\Exception\BadResponseException``. More +specifically, 4xx errors throw a ``Guzzle\Http\Exception\ClientErrorResponseException``, and 5xx errors throw a +``Guzzle\Http\Exception\ServerErrorResponseException``. You can catch the specific exceptions or just catch the +BadResponseException to deal with either type of error. Here's an example of catching a generic BadResponseException: + +.. code-block:: php + + try { + $response = $client->get('/not_found.xml')->send(); + } catch (Guzzle\Http\Exception\BadResponseException $e) { + echo 'Uh oh! ' . $e->getMessage(); + echo 'HTTP request URL: ' . $e->getRequest()->getUrl() . "\n"; + echo 'HTTP request: ' . $e->getRequest() . "\n"; + echo 'HTTP response status: ' . $e->getResponse()->getStatusCode() . "\n"; + echo 'HTTP response: ' . $e->getResponse() . "\n"; + } + +Throwing an exception when a 4xx or 5xx response is encountered is the default behavior of Guzzle requests. This +behavior can be overridden by adding an event listener with a higher priority than -255 that stops event propagation. +You can subscribe to ``request.error`` to receive notifications any time an unsuccessful response is received. + +You can change the response that will be associated with the request by calling ``setResponse()`` on the +``$event['request']`` object passed into your listener, or by changing the ``$event['response']`` value of the +``Guzzle\Common\Event`` object that is passed to your listener. Transparently changing the response associated with a +request by modifying the event allows you to retry failed requests without complicating the code that uses the client. +This might be useful for sending requests to a web service that has expiring auth tokens. When a response shows that +your token has expired, you can get a new token, retry the request with the new token, and return the successful +response to the user. + +Here's an example of retrying a request using updated authorization credentials when a 401 response is received, +overriding the response of the original request with the new response, and still allowing the default exception +behavior to be called when other non-200 response status codes are encountered: + +.. code-block:: php + + // Add custom error handling to any request created by this client + $client->getEventDispatcher()->addListener('request.error', function(Event $event) { + + if ($event['response']->getStatusCode() == 401) { + + $newRequest = $event['request']->clone(); + $newRequest->setHeader('X-Auth-Header', MyApplication::getNewAuthToken()); + $newResponse = $newRequest->send(); + + // Set the response object of the request without firing more events + $event['response'] = $newResponse; + + // You can also change the response and fire the normal chain of + // events by calling $event['request']->setResponse($newResponse); + + // Stop other events from firing when you override 401 responses + $event->stopPropagation(); + } + + }); + +cURL errors +~~~~~~~~~~~ + +Connection problems and cURL specific errors can also occur when transferring requests using Guzzle. When Guzzle +encounters cURL specific errors while transferring a single request, a ``Guzzle\Http\Exception\CurlException`` is +thrown with an informative error message and access to the cURL error message. + +A ``Guzzle\Http\Exception\MultiTransferException`` exception is thrown when a cURL specific error occurs while +transferring multiple requests in parallel. You can then iterate over all of the exceptions encountered during the +transfer. + +Plugins and events +------------------ + +Guzzle request objects expose various events that allow you to hook in custom logic. A request object owns a +``Symfony\Component\EventDispatcher\EventDispatcher`` object that can be accessed by calling +``$request->getEventDispatcher()``. You can use the event dispatcher to add listeners (a simple callback function) or +event subscribers (classes that listen to specific events of a dispatcher). You can add event subscribers to a request +directly by just calling ``$request->addSubscriber($mySubscriber);``. + +.. _request-events: + +Events emitted from a request +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A ``Guzzle\Http\Message\Request`` and ``Guzzle\Http\Message\EntityEnclosingRequest`` object emit the following events: + ++------------------------------+--------------------------------------------+------------------------------------------+ +| Event name | Description | Event data | ++==============================+============================================+==========================================+ +| request.before_send | About to send request | * request: Request to be sent | ++------------------------------+--------------------------------------------+------------------------------------------+ +| request.sent | Sent the request | * request: Request that was sent | +| | | * response: Received response | ++------------------------------+--------------------------------------------+------------------------------------------+ +| request.complete | Completed a full HTTP transaction | * request: Request that was sent | +| | | * response: Received response | ++------------------------------+--------------------------------------------+------------------------------------------+ +| request.success | Completed a successful request | * request: Request that was sent | +| | | * response: Received response | ++------------------------------+--------------------------------------------+------------------------------------------+ +| request.error | Completed an unsuccessful request | * request: Request that was sent | +| | | * response: Received response | ++------------------------------+--------------------------------------------+------------------------------------------+ +| request.exception | An unsuccessful response was | * request: Request | +| | received. | * response: Received response | +| | | * exception: BadResponseException | ++------------------------------+--------------------------------------------+------------------------------------------+ +| request.receive.status_line | Received the start of a response | * line: Full response start line | +| | | * status_code: Status code | +| | | * reason_phrase: Reason phrase | +| | | * previous_response: (e.g. redirect) | ++------------------------------+--------------------------------------------+------------------------------------------+ +| curl.callback.progress | cURL progress event (only dispatched when | * handle: CurlHandle | +| | ``emit_io`` is set on a request's curl | * download_size: Total download size | +| | options) | * downloaded: Bytes downloaded | +| | | * upload_size: Total upload bytes | +| | | * uploaded: Bytes uploaded | ++------------------------------+--------------------------------------------+------------------------------------------+ +| curl.callback.write | cURL event called when data is written to | * request: Request | +| | an outgoing stream | * write: Data being written | ++------------------------------+--------------------------------------------+------------------------------------------+ +| curl.callback.read | cURL event called when data is written to | * request: Request | +| | an incoming stream | * read: Data being read | ++------------------------------+--------------------------------------------+------------------------------------------+ + +Creating a request event listener +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Here's an example that listens to the ``request.complete`` event of a request and prints the request and response. + +.. code-block:: php + + use Guzzle\Common\Event; + + $request = $client->get('http://www.google.com'); + + // Echo out the response that was received + $request->getEventDispatcher()->addListener('request.complete', function (Event $e) { + echo $e['request'] . "\n\n"; + echo $e['response']; + }); diff --git a/src/bb-vendor/guzzle/guzzle/docs/http-client/response.rst b/src/bb-vendor/guzzle/guzzle/docs/http-client/response.rst new file mode 100644 index 000000000..ba487316f --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/http-client/response.rst @@ -0,0 +1,141 @@ +====================== +Using Response objects +====================== + +Sending a request will return a ``Guzzle\Http\Message\Response`` object. You can view the raw HTTP response message by +casting the Response object to a string. Casting the response to a string will return the entity body of the response +as a string too, so this might be an expensive operation if the entity body is stored in a file or network stream. If +you only want to see the response headers, you can call ``getRawHeaders()``. + +Response status line +-------------------- + +The different parts of a response's `status line `_ +(the first line of the response HTTP message) are easily retrievable. + +.. code-block:: php + + $response = $client->get('http://www.amazon.com')->send(); + + echo $response->getStatusCode(); // >>> 200 + echo $response->getReasonPhrase(); // >>> OK + echo $response->getProtocol(); // >>> HTTP + echo $response->getProtocolVersion(); // >>> 1.1 + +You can determine the type of the response using several helper methods: + +.. code-block:: php + + $response->isSuccessful(); // true + $response->isInformational(); + $response->isRedirect(); + $response->isClientError(); + $response->isServerError(); + +Response headers +---------------- + +The Response object contains helper methods for retrieving common response headers. These helper methods normalize the +variations of HTTP response headers. + +.. code-block:: php + + $response->getCacheControl(); + $response->getContentType(); + $response->getContentLength(); + $response->getContentEncoding(); + $response->getContentMd5(); + $response->getEtag(); + // etc... There are methods for every known response header + +You can interact with the Response headers using the same exact methods used to interact with Request headers. See +:ref:`http-message-headers` for more information. + +.. code-block:: php + + echo $response->getHeader('Content-Type'); + echo $response->getHeader('Content-Length'); + echo $response->getHeaders()['Content-Type']; // PHP 5.4 + +Response body +------------- + +The entity body object of a response can be retrieved by calling ``$response->getBody()``. The response EntityBody can +be cast to a string, or you can pass ``true`` to this method to retrieve the body as a string. + +.. code-block:: php + + $request = $client->get('http://www.amazon.com'); + $response = $request->send(); + echo $response->getBody(); + +See :doc:`/http-client/entity-bodies` for more information on entity bodies. + +JSON Responses +~~~~~~~~~~~~~~ + +You can easily parse and use a JSON response as an array using the ``json()`` method of a response. This method will +always return an array if the response is valid JSON or if the response body is empty. You will get an exception if you +call this method and the response is not valid JSON. + +.. code-block:: php + + $data = $response->json(); + echo gettype($data); + // >>> array + +XML Responses +~~~~~~~~~~~~~ + +You can easily parse and use a XML response as SimpleXMLElement object using the ``xml()`` method of a response. This +method will always return a SimpleXMLElement object if the response is valid XML or if the response body is empty. You +will get an exception if you call this method and the response is not valid XML. + +.. code-block:: php + + $xml = $response->xml(); + echo $xml->foo; + // >>> Bar! + +Streaming responses +------------------- + +Some web services provide streaming APIs that allow a client to keep a HTTP request open for an extended period of +time while polling and reading. Guzzle provides a simple way to convert HTTP request messages into +``Guzzle\Stream\Stream`` objects so that you can send the initial headers of a request, read the response headers, and +pull in the response body manually as needed. + +Here's an example using the Twitter Streaming API to track the keyword "bieber": + +.. code-block:: php + + use Guzzle\Http\Client; + use Guzzle\Stream\PhpStreamRequestFactory; + + $client = new Client('https://stream.twitter.com/1'); + + $request = $client->post('statuses/filter.json', null, array( + 'track' => 'bieber' + )); + + $request->setAuth('myusername', 'mypassword'); + + $factory = new PhpStreamRequestFactory(); + $stream = $factory->fromRequest($request); + + // Read until the stream is closed + while (!$stream->feof()) { + // Read a line from the stream + $line = $stream->readLine(); + // JSON decode the line of data + $data = json_decode($line, true); + } + +You can use the ``stream`` request option when using a static client to more easily create a streaming response. + +.. code-block:: php + + $stream = Guzzle::get('http://guzzlephp.org', array('stream' => true)); + while (!$stream->feof()) { + echo $stream->readLine(); + } diff --git a/src/bb-vendor/guzzle/guzzle/docs/http-client/uri-templates.rst b/src/bb-vendor/guzzle/guzzle/docs/http-client/uri-templates.rst new file mode 100644 index 000000000..c18ac3e8d --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/http-client/uri-templates.rst @@ -0,0 +1,52 @@ +============= +URI templates +============= + +The ``$uri`` passed to one of the client's request creational methods or the base URL of a client can utilize URI +templates. Guzzle supports the entire `URI templates RFC `_. URI templates add a +special syntax to URIs that replace template place holders with user defined variables. + +Every request created by a Guzzle HTTP client passes through a URI template so that URI template expressions are +automatically expanded: + +.. code-block:: php + + $client = new Guzzle\Http\Client('https://example.com/', array('a' => 'hi')); + $request = $client->get('/{a}'); + +Because of URI template expansion, the URL of the above request will become ``https://example.com/hi``. Notice that +the template was expanded using configuration variables of the client. You can pass in custom URI template variables +by passing the URI of your request as an array where the first index of the array is the URI template and the second +index of the array are template variables that are merged into the client's configuration variables. + +.. code-block:: php + + $request = $client->get(array('/test{?a,b}', array('b' => 'there'))); + +The URL for this request will become ``https://test.com?a=hi&b=there``. URI templates aren't limited to just simple +variable replacements; URI templates can provide an enormous amount of flexibility when creating request URIs. + +.. code-block:: php + + $request = $client->get(array('http://example.com{+path}{/segments*}{?query,data*}', array( + 'path' => '/foo/bar', + 'segments' => array('one', 'two'), + 'query' => 'test', + 'data' => array( + 'more' => 'value' + ) + ))); + +The resulting URL would become ``http://example.com/foo/bar/one/two?query=test&more=value``. + +By default, URI template expressions are enclosed in an opening and closing brace (e.g. ``{var}``). If you are working +with a web service that actually uses braces (e.g. Solr), then you can specify a custom regular expression to use to +match URI template expressions. + +.. code-block:: php + + $client->getUriTemplate()->setRegex('/\<\$(.+)\>/'); + $client->get('/<$a>'); + +You can learn about all of the different features of URI templates by reading the +`URI templates RFC `_. diff --git a/src/bb-vendor/guzzle/guzzle/docs/index.rst b/src/bb-vendor/guzzle/guzzle/docs/index.rst new file mode 100644 index 000000000..f76f3bbe6 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/index.rst @@ -0,0 +1,5 @@ +.. title:: Guzzle | PHP HTTP client and framework for consuming RESTful web services +.. toctree:: + :hidden: + + docs.rst diff --git a/src/bb-vendor/guzzle/guzzle/docs/iterators/guzzle-iterators.rst b/src/bb-vendor/guzzle/guzzle/docs/iterators/guzzle-iterators.rst new file mode 100644 index 000000000..a5c7fd33f --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/iterators/guzzle-iterators.rst @@ -0,0 +1,97 @@ +================ +Guzzle iterators +================ + +Guzzle provides several SPL iterators that can be used with other SPL iterators, including Guzzle resource iterators. +Guzzle's ``guzzle/iterator`` component can also be used independently of the rest of Guzzle through Packagist and +Composer: https://packagist.org/packages/guzzle/iterator + +ChunkedIterator +--------------- + +Pulls out multiple values from an inner iterator and yields and array of values for each outer iteration -- essentially +pulling out chunks of values from the inner iterator. + +.. code-block:: php + + use Guzzle\Iterator\ChunkedIterator; + + $inner = new ArrayIterator(range(0, 8)); + $chunkedIterator = new ChunkedIterator($inner, 2); + + foreach ($chunkedIterator as $chunk) { + echo implode(', ', $chunk) . "\n"; + } + + // >>> 0, 1 + // >>> 2, 3 + // >>> 4, 5 + // >>> 6, 7 + // >>> 8 + +FilterIterator +-------------- + +This iterator is used to filter values out of the inner iterator. This iterator can be used when PHP 5.4's +CallbackFilterIterator is not available. + +.. code-block:: php + + use Guzzle\Iterator\FilterIterator; + + $inner = new ArrayIterator(range(1, 10)); + $filterIterator = new FilterIterator($inner, function ($value) { + return $value % 2; + }); + + foreach ($filterIterator as $value) { + echo $value . "\n"; + } + + // >>> 2 + // >>> 4 + // >>> 6 + // >>> 8 + // >>> 10 + +MapIterator +----------- + +This iterator modifies the values of the inner iterator before yielding. + +.. code-block:: php + + use Guzzle\Iterator\MapIterator; + + $inner = new ArrayIterator(range(0, 3)); + + $mapIterator = new MapIterator($inner, function ($value) { + return $value * 10; + }); + + foreach ($mapIterator as $value) { + echo $value . "\n"; + } + + // >>> 0 + // >>> 10 + // >>> 20 + // >>> 30 + +MethodProxyIterator +------------------- + +This decorator is useful when you need to expose a specific method from an inner iterator that might be wrapper +by one or more iterator decorators. This decorator proxies missing method calls to each inner iterator until one +of the inner iterators can fulfill the call. + +.. code-block:: php + + use Guzzle\Iterator\MethodProxyIterator; + + $inner = new \ArrayIterator(); + $proxy = new MethodProxyIterator($inner); + + // Proxy method calls to the ArrayIterator + $proxy->append('a'); + $proxy->append('b'); diff --git a/src/bb-vendor/guzzle/guzzle/docs/iterators/resource-iterators.rst b/src/bb-vendor/guzzle/guzzle/docs/iterators/resource-iterators.rst new file mode 100644 index 000000000..ce0bee59f --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/iterators/resource-iterators.rst @@ -0,0 +1,149 @@ +================== +Resource iterators +================== + +Web services often implement pagination in their responses which requires the end-user to issue a series of consecutive +requests in order to fetch all of the data they asked for. Users of your web service client should not be responsible +for implementing the logic involved in iterating through pages of results. Guzzle provides a simple resource iterator +foundation to make it easier on web service client developers to offer a useful abstraction layer. + +Getting an iterator from a client +--------------------------------- + + ResourceIteratorInterface Guzzle\Service\Client::getIterator($command [, array $commandOptions, array $iteratorOptions ]) + +The ``getIterator`` method of a ``Guzzle\Service\ClientInterface`` object provides a convenient interface for +instantiating a resource iterator for a specific command. This method implicitly uses a +``Guzzle\Service\Resource\ResourceIteratorFactoryInterface`` object to create resource iterators. Pass an +instantiated command object or the name of a command in the first argument. When passing the name of a command, the +command factory of the client will create the command by name using the ``$commandOptions`` array. The third argument +may be used to pass an array of options to the constructor of the instantiated ``ResourceIteratorInterface`` object. + +.. code-block:: php + + $iterator = $client->getIterator('get_users'); + + foreach ($iterator as $user) { + echo $user['name'] . ' age ' . $user['age'] . PHP_EOL; + } + +The above code sample might execute a single request or a thousand requests. As a consumer of a web service, I don't +care. I just want to iterate over all of the users. + +Iterator options +~~~~~~~~~~~~~~~~ + +The two universal options that iterators should support are ``limit`` and ``page_size``. Using the ``limit`` option +tells the resource iterator to attempt to limit the total number of iterated resources to a specific amount. Keep in +mind that this is not always possible due to limitations that may be inherent to a web service. The ``page_size`` +option is used to tell a resource iterator how many resources to request per page of results. Much like the ``limit`` +option, you can not rely on getting back exactly the number of resources your specify in the ``page_size`` option. + +.. note:: + + The ``limit`` and ``page_size`` options can also be specified on an iterator using the ``setLimit($limit)`` and + ``setPageSize($pageSize)`` methods. + +Resolving iterator class names +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The default resource iterator factory of a client object expects that your iterators are stored under the ``Model`` +folder of your client and that an iterator is names after the CamelCase name of a command followed by the word +"Iterator". For example, if you wanted to create an iterator for the ``get_users`` command, then your iterator class +would be ``Model\GetUsersIterator`` and would be stored in ``Model/GetUsersIterator.php``. + +Creating an iterator +-------------------- + +While not required, resource iterators in Guzzle typically iterate using a ``Guzzle\Service\Command\CommandInterface`` +object. ``Guzzle\Service\Resource\ResourceIterator``, the default iterator implementation that you should extend, +accepts a command object and array of iterator options in its constructor. The command object passed to the resource +iterator is expected to be ready to execute and not previously executed. The resource iterator keeps a reference of +this command and clones the original command each time a subsequent request needs to be made to fetch more data. + +Implement the sendRequest method +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The most important thing (and usually the only thing) you need to do when creating a resource iterator is to implement +the ``sendRequest()`` method of the resource iterator. The ``sendRequest()`` method is called when you begin +iterating or if there are no resources left to iterate and it you expect to retrieve more resources by making a +subsequent request. The ``$this->command`` property of the resource iterator is updated with a cloned copy of the +original command object passed into the constructor of the iterator. Use this command object to issue your subsequent +requests. + +The ``sendRequest()`` method must return an array of the resources you retrieved from making the subsequent call. +Returning an empty array will stop the iteration. If you suspect that your web service client will occasionally return +an empty result set but still requires further iteration, then you must implement a sort of loop in your +``sendRequest()`` method that will continue to issue subsequent requests until your reach the end of the paginated +result set or until additional resources are retrieved from the web service. + +Update the nextToken property +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Beyond fetching more results, the ``sendRequest()`` method is responsible for updating the ``$this->nextToken`` +property of the iterator. Setting this property to anything other than null tells the iterator that issuing a +subsequent request using the nextToken value will probably return more results. You must continually update this +value in your ``sendRequest()`` method as each response is received from the web service. + +Example iterator +---------------- + +Let's say you want to implement a resource iterator for the ``get_users`` command of your web service. The +``get_users`` command receives a response that contains a list of users, and if there are more pages of results to +retrieve, returns a value called ``next_user``. This return value is known as the **next token** and should be used to +issue subsequent requests. + +Assume the response to a ``get_users`` command returns JSON data that looks like this: + +.. code-block:: javascript + + { + "users": [ + { "name": "Craig Johnson", "age": 10 }, + { "name": "Tom Barker", "age": 20 }, + { "name": "Bob Mitchell", "age": 74 } + ], + "next_user": "Michael Dowling" + } + +Assume that because there is a ``next_user`` value, there will be more users if a subsequent request is issued. If the +``next_user`` value is missing or null, then we know there are no more results to fetch. Let's implement a resource +iterator for this command. + +.. code-block:: php + + namespace MyService\Model; + + use Guzzle\Service\Resource\ResourceIterator; + + /** + * Iterate over a get_users command + */ + class GetUsersIterator extends ResourceIterator + { + protected function sendRequest() + { + // If a next token is set, then add it to the command + if ($this->nextToken) { + $this->command->set('next_user', $this->nextToken); + } + + // Execute the command and parse the result + $result = $this->command->execute(); + + // Parse the next token + $this->nextToken = isset($result['next_user']) ? $result['next_user'] : false; + + return $result['users']; + } + } + +As you can see, it's pretty simple to implement an iterator. There are a few things that you should notice from this +example: + +1. You do not need to create a new command in the ``sendRequest()`` method. A new command object is cloned from the + original command passed into the constructor of the iterator before the ``sendRequest()`` method is called. + Remember that the resource iterator expects a command that has not been executed. +2. When the ``sendRequest()`` method is first called, you will not have a ``$this->nextToken`` value, so always check + before setting it on a command. Notice that the next token is being updated each time a request is sent. +3. After fetching more resources from the service, always return an array of resources. diff --git a/src/bb-vendor/guzzle/guzzle/docs/plugins/async-plugin.rst b/src/bb-vendor/guzzle/guzzle/docs/plugins/async-plugin.rst new file mode 100644 index 000000000..9bd8f4251 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/plugins/async-plugin.rst @@ -0,0 +1,18 @@ +============ +Async plugin +============ + +The AsyncPlugin allows you to send requests that do not wait on a response. This is handled through cURL by utilizing +the progress event. When a request has sent all of its data to the remote server, Guzzle adds a 1ms timeout on the +request and instructs cURL to not download the body of the response. The async plugin then catches the exception and +adds a mock response to the request, along with an X-Guzzle-Async header to let you know that the response was not +fully downloaded. + +.. code-block:: php + + use Guzzle\Http\Client; + use Guzzle\Plugin\Async\AsyncPlugin; + + $client = new Client('http://www.example.com'); + $client->addSubscriber(new AsyncPlugin()); + $response = $client->get()->send(); diff --git a/src/bb-vendor/guzzle/guzzle/docs/plugins/backoff-plugin.rst b/src/bb-vendor/guzzle/guzzle/docs/plugins/backoff-plugin.rst new file mode 100644 index 000000000..5a7694141 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/plugins/backoff-plugin.rst @@ -0,0 +1,22 @@ +==================== +Backoff retry plugin +==================== + +The ``Guzzle\Plugin\Backoff\BackoffPlugin`` automatically retries failed HTTP requests using custom backoff strategies: + +.. code-block:: php + + use Guzzle\Http\Client; + use Guzzle\Plugin\Backoff\BackoffPlugin; + + $client = new Client('http://www.test.com/'); + // Use a static factory method to get a backoff plugin using the exponential backoff strategy + $backoffPlugin = BackoffPlugin::getExponentialBackoff(); + + // Add the backoff plugin to the client object + $client->addSubscriber($backoffPlugin); + +The BackoffPlugin's constructor accepts a ``Guzzle\Plugin\Backoff\BackoffStrategyInterface`` object that is used to +determine when a retry should be issued and how long to delay between retries. The above code example shows how to +attach a BackoffPlugin to a client that is pre-configured to retry failed 500 and 503 responses using truncated +exponential backoff (emulating the behavior of Guzzle 2's ExponentialBackoffPlugin). diff --git a/src/bb-vendor/guzzle/guzzle/docs/plugins/cache-plugin.rst b/src/bb-vendor/guzzle/guzzle/docs/plugins/cache-plugin.rst new file mode 100644 index 000000000..d2fd5df26 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/plugins/cache-plugin.rst @@ -0,0 +1,169 @@ +================= +HTTP Cache plugin +================= + +Guzzle can leverage HTTP's caching specifications using the ``Guzzle\Plugin\Cache\CachePlugin``. The CachePlugin +provides a private transparent proxy cache that caches HTTP responses. The caching logic, based on +`RFC 2616 `_, uses HTTP headers to control caching behavior, +cache lifetime, and supports Vary, ETag, and Last-Modified based revalidation: + +.. code-block:: php + + use Guzzle\Http\Client; + use Doctrine\Common\Cache\FilesystemCache; + use Guzzle\Cache\DoctrineCacheAdapter; + use Guzzle\Plugin\Cache\CachePlugin; + use Guzzle\Plugin\Cache\DefaultCacheStorage; + + $client = new Client('http://www.test.com/'); + + $cachePlugin = new CachePlugin(array( + 'storage' => new DefaultCacheStorage( + new DoctrineCacheAdapter( + new FilesystemCache('/path/to/cache/files') + ) + ) + )); + + // Add the cache plugin to the client object + $client->addSubscriber($cachePlugin); + $client->get('http://www.wikipedia.org/')->send(); + + // The next request will revalidate against the origin server to see if it + // has been modified. If a 304 response is received the response will be + // served from cache + $client->get('http://www.wikipedia.org/')->send(); + +The cache plugin intercepts GET and HEAD requests before they are actually transferred to the origin server. The cache +plugin then generates a hash key based on the request method and URL, and checks to see if a response exists in the cache. If +a response exists in the cache, the cache adapter then checks to make sure that the caching rules associated with the response +satisfy the request, and ensures that response still fresh. If the response is acceptable for the request any required +revalidation, then the cached response is served instead of contacting the origin server. + +Vary +---- + +Cache keys are derived from a request method and a request URL. Multiple responses can map to the same cache key and +stored in Guzzle's underlying cache storage object. You should use the ``Vary`` HTTP header to tell the cache storage +object that the cache response must have been cached for a request that matches the headers specified in the Vary header +of the request. This allows you to have specific cache entries for the same request URL but variations in a request's +headers determine which cache entry is served. Please see the http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.44 +for more information. + +Cache options +------------- + +There are several options you can add to requests or clients to modify the behavior of the cache plugin. + +Override cache TTL +~~~~~~~~~~~~~~~~~~ + +You can override the number of seconds a cacheable response is stored in the cache by setting the +``cache.override_ttl`` parameter on the params object of a request: + +.. code-block:: php + + // If the response to the request is cacheable, then the response will be cached for 100 seconds + $request->getParams()->set('cache.override_ttl', 100); + +If a response doesn't specify any freshness policy, it will be kept in cache for 3600 seconds by default. + +Custom caching decision +~~~~~~~~~~~~~~~~~~~~~~~ + +If the service you are interacting with does not return caching headers or returns responses that are normally +something that would not be cached, you can set a custom ``can_cache`` object on the constructor of the CachePlugin +and provide a ``Guzzle\Plugin\Cache\CanCacheInterface`` object. You can use the +``Guzzle\Plugin\Cache\CallbackCanCacheStrategy`` to easily make a caching decision based on an HTTP request and +response. + +Revalidation options +~~~~~~~~~~~~~~~~~~~~ + +You can change the revalidation behavior of a request using the ``cache.revalidate`` parameter. Setting this +parameter to ``never`` will ensure that a revalidation request is never sent, and the response is always served from +the origin server. Setting this parameter to ``skip`` will never revalidate and uses the response stored in the cache. + +Normalizing requests for caching +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Use the ``cache.key_filter`` parameter if you wish to strip certain query string parameters from your +request before creating a unique hash for the request. This parameter can be useful if your requests have query +string values that cause each request URL to be unique (thus preventing a cache hit). The ``cache.key_filter`` +format is simply a comma separated list of query string values to remove from the URL when creating a cache key. +For example, here we are saying that the ``a`` and ``q`` query string variables should be ignored when generating a +cache key for the request: + +.. code-block:: php + + $request->getParams()->set('cache.key_filter', 'a, q'); + +Other options +~~~~~~~~~~~~~ + +There are many other options available to the CachePlugin that can meet almost any caching requirement, including +custom revalidation implementations, custom cache key generators, custom caching decision strategies, and custom +cache storage objects. Take a look the constructor of ``Guzzle\Plugin\Cache\CachePlugin`` for more information. + +Setting Client-wide cache settings +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can specify cache settings for every request created by a client by adding cache settings to the configuration +options of a client. + +.. code-block:: php + + $client = new Guzzle\Http\Client('http://www.test.com', array( + 'request.params' => array( + 'cache.override_ttl' => 3600, + 'params.cache.revalidate' => 'never' + ) + )); + + echo $client->get('/')->getParams()->get('cache.override_ttl'); + // >>> 3600 + + echo $client->get('/')->getParams()->get('cache.revalidate'); + // >>> never + +Cache revalidation +------------------ + +If the cache plugin determines that a response to a GET request needs revalidation, a conditional GET is transferred +to the origin server. If the origin server returns a 304 response, then a response containing the merged headers of +the cached response with the new response and the entity body of the cached response is returned. Custom revalidation +strategies can be injected into a CachePlugin if needed. + +Cache adapters +-------------- + +Guzzle doesn't try to reinvent the wheel when it comes to caching or logging. Plenty of other frameworks have +excellent solutions in place that you are probably already using in your applications. Guzzle uses adapters for +caching and logging. The cache plugin requires a cache adapter so that is can store responses in a cache. Guzzle +currently supports cache adapters for `Doctrine 2.0 `_ and the +`Zend Framework `_. + +Doctrine cache adapter +~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: php + + use Doctrine\Common\Cache\ArrayCache; + use Guzzle\Cache\DoctrineCacheAdapter; + use Guzzle\Plugin\Cache\CachePlugin; + + $backend = new ArrayCache(); + $adapter = new DoctrineCacheAdapter($backend); + $cache = new CachePlugin($adapter); + +Zend Framework cache adapter +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: php + + use Guzzle\Cache\ZendCacheAdapter; + use Zend\Cache\Backend\TestBackend; + + $backend = new TestBackend(); + $adapter = new ZendCacheAdapter($backend); + $cache = new CachePlugin($adapter); diff --git a/src/bb-vendor/guzzle/guzzle/docs/plugins/cookie-plugin.rst b/src/bb-vendor/guzzle/guzzle/docs/plugins/cookie-plugin.rst new file mode 100644 index 000000000..a6cc7d924 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/plugins/cookie-plugin.rst @@ -0,0 +1,33 @@ +============= +Cookie plugin +============= + +Some web services require a Cookie in order to maintain a session. The ``Guzzle\Plugin\Cookie\CookiePlugin`` will add +cookies to requests and parse cookies from responses using a CookieJar object: + +.. code-block:: php + + use Guzzle\Http\Client; + use Guzzle\Plugin\Cookie\CookiePlugin; + use Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar; + + $cookiePlugin = new CookiePlugin(new ArrayCookieJar()); + + // Add the cookie plugin to a client + $client = new Client('http://www.test.com/'); + $client->addSubscriber($cookiePlugin); + + // Send the request with no cookies and parse the returned cookies + $client->get('http://www.yahoo.com/')->send(); + + // Send the request again, noticing that cookies are being sent + $request = $client->get('http://www.yahoo.com/'); + $request->send(); + + echo $request; + +You can disable cookies per-request by setting the ``cookies.disable`` value to true on a request's params object. + +.. code-block:: php + + $request->getParams()->set('cookies.disable', true); diff --git a/src/bb-vendor/guzzle/guzzle/docs/plugins/creating-plugins.rst b/src/bb-vendor/guzzle/guzzle/docs/plugins/creating-plugins.rst new file mode 100644 index 000000000..0870155b5 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/plugins/creating-plugins.rst @@ -0,0 +1,93 @@ +================ +Creating plugins +================ + +.. highlight:: php + +Guzzle is extremely extensible because of the behavioral modifications that can be added to requests, clients, and +commands using an event system. Before and after the majority of actions are taken in the library, an event is emitted +with the name of the event and context surrounding the event. Observers can subscribe to a subject and modify the +subject based on the events received. Guzzle's event system utilizes the Symfony2 EventDispatcher and is the backbone +of its plugin architecture. + +Overview +-------- + +Plugins must implement the ``Symfony\Component\EventDispatcher\EventSubscriberInterface`` interface. The +``EventSubscriberInterface`` requires that your class implements a static method, ``getSubscribedEvents()``, that +returns an associative array mapping events to methods on the object. See the +`Symfony2 documentation `_ for more information. + +Plugins can be attached to any subject, or object in Guzzle that implements that +``Guzzle\Common\HasDispatcherInterface``. + +Subscribing to a subject +~~~~~~~~~~~~~~~~~~~~~~~~ + +You can subscribe an instantiated observer to an event by calling ``addSubscriber`` on a subject. + +.. code-block:: php + + $testPlugin = new TestPlugin(); + $client->addSubscriber($testPlugin); + +You can also subscribe to only specific events using a closure:: + + $client->getEventDispatcher()->addListener('request.create', function(Event $event) { + echo $event->getName(); + echo $event['request']; + }); + +``Guzzle\Common\Event`` objects are passed to notified functions. The Event object has a ``getName()`` method which +return the name of the emitted event and may contain contextual information that can be accessed like an array. + +Knowing what events to listen to +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Any class that implements the ``Guzzle\Common\HasDispatcherInterface`` must implement a static method, +``getAllEvents()``, that returns an array of the events that are emitted from the object. You can browse the source +to see each event, or you can call the static method directly in your code to get a list of available events. + +Event hooks +----------- + +* :ref:`client-events` +* :ref:`service-client-events` +* :ref:`request-events` +* ``Guzzle\Http\Curl\CurlMulti``: +* :ref:`service-builder-events` + +Examples of the event system +---------------------------- + +Simple Echo plugin +~~~~~~~~~~~~~~~~~~ + +This simple plugin prints a string containing the request that is about to be sent by listening to the +``request.before_send`` event:: + + use Symfony\Component\EventDispatcher\EventSubscriberInterface; + + class EchoPlugin implements EventSubscriberInterface + { + public static function getSubscribedEvents() + { + return array('request.before_send' => 'onBeforeSend'); + } + + public function onBeforeSend(Guzzle\Common\Event $event) + { + echo 'About to send a request: ' . $event['request'] . "\n"; + } + } + + $client = new Guzzle\Service\Client('http://www.test.com/'); + + // Create the plugin and add it as an event subscriber + $plugin = new EchoPlugin(); + $client->addSubscriber($plugin); + + // Send a request and notice that the request is printed to the screen + $client->get('/')->send(); + +Running the above code will print a string containing the HTTP request that is about to be sent. diff --git a/src/bb-vendor/guzzle/guzzle/docs/plugins/curl-auth-plugin.rst b/src/bb-vendor/guzzle/guzzle/docs/plugins/curl-auth-plugin.rst new file mode 100644 index 000000000..66d4a01e3 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/plugins/curl-auth-plugin.rst @@ -0,0 +1,32 @@ +========================== +cURL authentication plugin +========================== + +.. warning:: + + The CurlAuthPlugin is deprecated. You should use the `auth` parameter of a client to add authorization headers to + every request created by a client. + + .. code-block:: php + + $client->setDefaultOption('auth', array('username', 'password', 'Basic|Digest|NTLM|Any')); + +If your web service client requires basic authorization, then you can use the CurlAuthPlugin to easily add an +Authorization header to each request sent by the client. + +.. code-block:: php + + use Guzzle\Http\Client; + use Guzzle\Plugin\CurlAuth\CurlAuthPlugin; + + $client = new Client('http://www.test.com/'); + + // Add the auth plugin to the client object + $authPlugin = new CurlAuthPlugin('username', 'password'); + $client->addSubscriber($authPlugin); + + $response = $client->get('projects/1/people')->send(); + $xml = new SimpleXMLElement($response->getBody(true)); + foreach ($xml->person as $person) { + echo $person->email . "\n"; + } diff --git a/src/bb-vendor/guzzle/guzzle/docs/plugins/history-plugin.rst b/src/bb-vendor/guzzle/guzzle/docs/plugins/history-plugin.rst new file mode 100644 index 000000000..b96befe79 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/plugins/history-plugin.rst @@ -0,0 +1,24 @@ +============== +History plugin +============== + +The history plugin tracks all of the requests and responses sent through a request or client. This plugin can be +useful for crawling or unit testing. By default, the history plugin stores up to 10 requests and responses. + +.. code-block:: php + + use Guzzle\Http\Client; + use Guzzle\Plugin\History\HistoryPlugin; + + $client = new Client('http://www.test.com/'); + + // Add the history plugin to the client object + $history = new HistoryPlugin(); + $history->setLimit(5); + $client->addSubscriber($history); + + $client->get('http://www.yahoo.com/')->send(); + + echo $history->getLastRequest(); + echo $history->getLastResponse(); + echo count($history); diff --git a/src/bb-vendor/guzzle/guzzle/docs/plugins/log-plugin.rst b/src/bb-vendor/guzzle/guzzle/docs/plugins/log-plugin.rst new file mode 100644 index 000000000..3e2b22944 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/plugins/log-plugin.rst @@ -0,0 +1,69 @@ +========== +Log plugin +========== + +Use the ``Guzzle\Plugin\Log\LogPlugin`` to view all data sent over the wire, including entity bodies and redirects. + +.. code-block:: php + + use Guzzle\Http\Client; + use Guzzle\Log\Zf1LogAdapter; + use Guzzle\Plugin\Log\LogPlugin; + use Guzzle\Log\MessageFormatter; + + $client = new Client('http://www.test.com/'); + + $adapter = new Zf1LogAdapter( + new \Zend_Log(new \Zend_Log_Writer_Stream('php://output')) + ); + $logPlugin = new LogPlugin($adapter, MessageFormatter::DEBUG_FORMAT); + + // Attach the plugin to the client, which will in turn be attached to all + // requests generated by the client + $client->addSubscriber($logPlugin); + + $response = $client->get('http://google.com')->send(); + +The code sample above wraps a ``Zend_Log`` object using a ``Guzzle\Log\Zf1LogAdapter``. After attaching the plugin to +the client, all data sent over the wire will be logged to stdout. + +The first argument of the LogPlugin's constructor accepts a ``Guzzle\Log\LogAdapterInterface`` object. This object is +an adapter that allows you to use the logging capabilities of your favorite log implementation. The second argument of +the constructor accepts a ``Guzzle\Log\MessageFormatter`` or a log messaged format string. The format string uses +variable substitution and allows you to define the log data that is important to your application. The different +variables that can be injected are as follows: + +================== ==================================================================================== +Variable Substitution +================== ==================================================================================== +{request} Full HTTP request message +{response} Full HTTP response message +{ts} Timestamp +{host} Host of the request +{method} Method of the request +{url} URL of the request +{host} Host of the request +{protocol} Request protocol +{version} Protocol version +{resource} Resource of the request (path + query + fragment) +{port} Port of the request +{hostname} Hostname of the machine that sent the request +{code} Status code of the response (if available) +{phrase} Reason phrase of the response (if available) +{curl_error} Curl error message (if available) +{curl_code} Curl error code (if available) +{curl_stderr} Curl standard error (if available) +{connect_time} Time in seconds it took to establish the connection (if available) +{total_time} Total transaction time in seconds for last transfer (if available) +{req_header_*} Replace `*` with the lowercased name of a request header to add to the message +{res_header_*} Replace `*` with the lowercased name of a response header to add to the message +{req_body} Request body +{res_body} Response body +================== ==================================================================================== + +The LogPlugin has a helper method that can be used when debugging that will output the full HTTP request and +response of a transaction: + +.. code-block:: php + + $client->addSubscriber(LogPlugin::getDebugPlugin()); diff --git a/src/bb-vendor/guzzle/guzzle/docs/plugins/md5-validator-plugin.rst b/src/bb-vendor/guzzle/guzzle/docs/plugins/md5-validator-plugin.rst new file mode 100644 index 000000000..1b1cfa8a8 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/plugins/md5-validator-plugin.rst @@ -0,0 +1,29 @@ +==================== +MD5 validator plugin +==================== + +Entity bodies can sometimes be modified over the wire due to a faulty TCP transport or misbehaving proxy. If an HTTP +response contains a Content-MD5 header, then a MD5 hash of the entity body of a response can be compared against the +Content-MD5 header of the response to determine if the response was delivered intact. The +``Guzzle\Plugin\Md5\Md5ValidatorPlugin`` will throw an ``UnexpectedValueException`` if the calculated MD5 hash does +not match the Content-MD5 header value: + +.. code-block:: php + + use Guzzle\Http\Client; + use Guzzle\Plugin\Md5\Md5ValidatorPlugin; + + $client = new Client('http://www.test.com/'); + + $md5Plugin = new Md5ValidatorPlugin(); + + // Add the md5 plugin to the client object + $client->addSubscriber($md5Plugin); + + $request = $client->get('http://www.yahoo.com/'); + $request->send(); + +Calculating the MD5 hash of a large entity body or an entity body that was transferred using a Content-Encoding is an +expensive operation. When working in high performance applications, you might consider skipping the MD5 hash +validation for entity bodies bigger than a certain size or Content-Encoded entity bodies +(see ``Guzzle\Plugin\Md5\Md5ValidatorPlugin`` for more information). diff --git a/src/bb-vendor/guzzle/guzzle/docs/plugins/mock-plugin.rst b/src/bb-vendor/guzzle/guzzle/docs/plugins/mock-plugin.rst new file mode 100644 index 000000000..4900cb565 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/plugins/mock-plugin.rst @@ -0,0 +1,27 @@ +=========== +Mock plugin +=========== + +The mock plugin is useful for testing Guzzle clients. The mock plugin allows you to queue an array of responses that +will satisfy requests sent from a client by consuming the request queue in FIFO order. + +.. code-block:: php + + use Guzzle\Http\Client; + use Guzzle\Plugin\Mock\MockPlugin; + use Guzzle\Http\Message\Response; + + $client = new Client('http://www.test.com/'); + + $mock = new MockPlugin(); + $mock->addResponse(new Response(200)) + ->addResponse(new Response(404)); + + // Add the mock plugin to the client object + $client->addSubscriber($mock); + + // The following request will receive a 200 response from the plugin + $client->get('http://www.example.com/')->send(); + + // The following request will receive a 404 response from the plugin + $client->get('http://www.test.com/')->send(); diff --git a/src/bb-vendor/guzzle/guzzle/docs/plugins/oauth-plugin.rst b/src/bb-vendor/guzzle/guzzle/docs/plugins/oauth-plugin.rst new file mode 100644 index 000000000..e67eabaa1 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/plugins/oauth-plugin.rst @@ -0,0 +1,30 @@ +============ +OAuth plugin +============ + +Guzzle ships with an OAuth 1.0 plugin that can sign requests using a consumer key, consumer secret, OAuth token, +and OAuth secret. Here's an example showing how to send an authenticated request to the Twitter REST API: + +.. code-block:: php + + use Guzzle\Http\Client; + use Guzzle\Plugin\Oauth\OauthPlugin; + + $client = new Client('http://api.twitter.com/1'); + $oauth = new OauthPlugin(array( + 'consumer_key' => 'my_key', + 'consumer_secret' => 'my_secret', + 'token' => 'my_token', + 'token_secret' => 'my_token_secret' + )); + $client->addSubscriber($oauth); + + $response = $client->get('statuses/public_timeline.json')->send(); + +If you need to use a custom signing method, you can pass a ``signature_method`` configuration option in the +constructor of the OAuth plugin. The ``signature_method`` option must be a callable variable that accepts a string to +sign and signing key and returns a signed string. + +.. note:: + + You can omit the ``token`` and ``token_secret`` options to use two-legged OAuth. diff --git a/src/bb-vendor/guzzle/guzzle/docs/plugins/plugins-list.rst.inc b/src/bb-vendor/guzzle/guzzle/docs/plugins/plugins-list.rst.inc new file mode 100644 index 000000000..8d6d09b46 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/plugins/plugins-list.rst.inc @@ -0,0 +1,9 @@ +* :doc:`/plugins/async-plugin` +* :doc:`/plugins/backoff-plugin` +* :doc:`/plugins/cache-plugin` +* :doc:`/plugins/cookie-plugin` +* :doc:`/plugins/history-plugin` +* :doc:`/plugins/log-plugin` +* :doc:`/plugins/md5-validator-plugin` +* :doc:`/plugins/mock-plugin` +* :doc:`/plugins/oauth-plugin` diff --git a/src/bb-vendor/guzzle/guzzle/docs/plugins/plugins-overview.rst b/src/bb-vendor/guzzle/guzzle/docs/plugins/plugins-overview.rst new file mode 100644 index 000000000..19ae57ece --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/plugins/plugins-overview.rst @@ -0,0 +1,59 @@ +====================== +Plugin system overview +====================== + +The workflow of sending a request and parsing a response is driven by Guzzle's event system, which is powered by the +`Symfony2 Event Dispatcher component `_. + +Any object in Guzzle that emits events will implement the ``Guzzle\Common\HasEventDispatcher`` interface. You can add +event subscribers directly to these objects using the ``addSubscriber()`` method, or you can grab the +``Symfony\Component\EventDispatcher\EventDispatcher`` object owned by the object using ``getEventDispatcher()`` and +add a listener or event subscriber. + +Adding event subscribers to clients +----------------------------------- + +Any event subscriber or event listener attached to the EventDispatcher of a ``Guzzle\Http\Client`` or +``Guzzle\Service\Client`` object will automatically be attached to all request objects created by the client. This +allows you to attach, for example, a HistoryPlugin to a client object, and from that point on, every request sent +through that client will utilize the HistoryPlugin. + +.. code-block:: php + + use Guzzle\Plugin\History\HistoryPlugin; + use Guzzle\Service\Client; + + $client = new Client(); + + // Create a history plugin and attach it to the client + $history = new HistoryPlugin(); + $client->addSubscriber($history); + + // Create and send a request. This request will also utilize the HistoryPlugin + $client->get('http://httpbin.org')->send(); + + // Echo out the last sent request by the client + echo $history->getLastRequest(); + +.. tip:: + + :doc:`Create event subscribers `, or *plugins*, to implement reusable logic that can be + shared across clients. Event subscribers are also easier to test than anonymous functions. + +Pre-Built plugins +----------------- + +Guzzle provides easy to use request plugins that add behavior to requests based on signal slot event notifications +powered by the Symfony2 Event Dispatcher component. + +* :doc:`async-plugin` +* :doc:`backoff-plugin` +* :doc:`cache-plugin` +* :doc:`cookie-plugin` +* :doc:`curl-auth-plugin` +* :doc:`history-plugin` +* :doc:`log-plugin` +* :doc:`md5-validator-plugin` +* :doc:`mock-plugin` +* :doc:`oauth-plugin` + diff --git a/src/bb-vendor/guzzle/guzzle/docs/requirements.txt b/src/bb-vendor/guzzle/guzzle/docs/requirements.txt new file mode 100644 index 000000000..f62e31837 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/requirements.txt @@ -0,0 +1,2 @@ +Sphinx>=1.2b1 +guzzle_sphinx_theme>=0.5.0 diff --git a/src/bb-vendor/guzzle/guzzle/docs/testing/unit-testing.rst b/src/bb-vendor/guzzle/guzzle/docs/testing/unit-testing.rst new file mode 100644 index 000000000..f4297af30 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/testing/unit-testing.rst @@ -0,0 +1,201 @@ +=========================== +Unit Testing Guzzle clients +=========================== + +Guzzle provides several tools that will enable you to easily unit test your web service clients. + +* PHPUnit integration +* Mock responses +* node.js web server for integration testing + +PHPUnit integration +------------------- + +Guzzle is unit tested using `PHPUnit `_. Your web service client's unit tests should extend +``Guzzle\Tests\GuzzleTestCase`` so that you can take advantage of some of the built in helpers. + +In order to unit test your client, a developer would need to copy phpunit.xml.dist to phpunit.xml and make any needed +modifications. As a best practice and security measure for you and your contributors, it is recommended to add an +ignore statement to your SCM so that phpunit.xml is ignored. + +Bootstrapping +~~~~~~~~~~~~~ + +Your web service client should have a tests/ folder that contains a bootstrap.php file. The bootstrap.php file +responsible for autoloading and configuring a ``Guzzle\Service\Builder\ServiceBuilder`` that is used throughout your +unit tests for loading a configured client. You can add custom parameters to your phpunit.xml file that expects users +to provide the path to their configuration data. + +.. code-block:: php + + Guzzle\Tests\GuzzleTestCase::setServiceBuilder(Aws\Common\Aws::factory($_SERVER['CONFIG'])); + + Guzzle\Tests\GuzzleTestCase::setServiceBuilder(Guzzle\Service\Builder\ServiceBuilder::factory(array( + 'test.unfuddle' => array( + 'class' => 'Guzzle.Unfuddle.UnfuddleClient', + 'params' => array( + 'username' => 'test_user', + 'password' => '****', + 'subdomain' => 'test' + ) + ) + ))); + +The above code registers a service builder that can be used throughout your unit tests. You would then be able to +retrieve an instantiated and configured Unfuddle client by calling ``$this->getServiceBuilder()->get('test.unfuddle)``. +The above code assumes that ``$_SERVER['CONFIG']`` contains the path to a file that stores service description +configuration. + +Unit testing remote APIs +------------------------ + +Mock responses +~~~~~~~~~~~~~~ + +One of the benefits of unit testing is the ability to quickly determine if there are errors in your code. If your +unit tests run slowly, then they become tedious and will likely be run less frequently. Guzzle's philosophy on unit +testing web service clients is that no network access should be required to run the unit tests. This means that +responses are served from mock responses or local servers. By adhering to this principle, tests will run much faster +and will not require an external resource to be available. The problem with this approach is that your mock responses +must first be gathered and then subsequently updated each time the remote API changes. + +Integration testing over the internet +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can perform integration testing with a web service over the internet by making calls directly to the service. If +the web service you are requesting uses a complex signing algorithm or some other specific implementation, then you +may want to include at least one actual network test that can be run specifically through the command line using +`PHPUnit group annotations `_. + +@group internet annotation +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +When creating tests that require an internet connection, it is recommended that you add ``@group internet`` annotations +to your unit tests to specify which tests require network connectivity. + +You can then `run PHPUnit tests `_ that exclude the @internet +group by running ``phpunit --exclude-group internet``. + +API credentials +^^^^^^^^^^^^^^^ + +If API credentials are required to run your integration tests, you must add ```` parameters to your +phpunit.xml.dist file and extract these parameters in your bootstrap.php file. + +.. code-block:: xml + + + + + + + + + + + + + ./Tests + + + + +You can then extract the ``server`` variables in your bootstrap.php file by grabbing them from the ``$_SERVER`` +superglobal: ``$apiUser = $_SERVER['API_USER'];`` + +Further reading +^^^^^^^^^^^^^^^ + +A good discussion on the topic of testing remote APIs can be found in Sebastian Bergmann's +`Real-World Solutions for Developing High-Quality PHP Frameworks and Applications `_. + +Queueing Mock responses +----------------------- + +Mock responses can be used to test if requests are being generated correctly and responses and handled correctly by +your client. Mock responses can be queued up for a client using the ``$this->setMockResponse($client, $path)`` method +of your test class. Pass the client you are adding mock responses to and a single path or array of paths to mock +response files relative to the ``/tests/mock/ folder``. This will queue one or more mock responses for your client by +creating a simple observer on the client. Mock response files must contain a full HTTP response message: + +.. code-block:: none + + HTTP/1.1 200 OK + Date: Wed, 25 Nov 2009 12:00:00 GMT + Connection: close + Server: AmazonS3 + Content-Type: application/xml + + + EU + +After queuing mock responses for a client, you can get an array of the requests that were sent by the client that +were issued a mock response by calling ``$this->getMockedRequests()``. + +You can also use the ``Guzzle\Plugin\Mock\MockPlugin`` object directly with your clients. + +.. code-block:: php + + $plugin = new Guzzle\Plugin\Mock\MockPlugin(); + $plugin->addResponse(new Guzzle\Http\Message\Response(200)); + $client = new Guzzle\Http\Client(); + $client->addSubscriber($plugin); + + // The following request will get the mock response from the plugin in FIFO order + $request = $client->get('http://www.test.com/'); + $request->send(); + + // The MockPlugin maintains a list of requests that were mocked + $this->assertContainsOnly($request, $plugin->getReceivedRequests()); + +node.js web server for integration testing +------------------------------------------ + +Using mock responses is usually enough when testing a web service client. If your client needs to add custom cURL +options to requests, then you should use the node.js test web server to ensure that your HTTP request message is +being created correctly. + +Guzzle is based around PHP's libcurl bindings. cURL sometimes modifies an HTTP request message based on +``CURLOPT_*`` options. Headers that are added to your request by cURL will not be accounted for if you inject mock +responses into your tests. Additionally, some request entity bodies cannot be loaded by the client before transmitting +it to the sever (for example, when using a client as a sort of proxy and streaming content from a remote server). You +might also need to inspect the entity body of a ``multipart/form-data`` POST request. + +.. note:: + + You can skip all of the tests that require the node.js test web server by excluding the ``server`` group: + ``phpunit --exclude-group server`` + +Using the test server +~~~~~~~~~~~~~~~~~~~~~ + +The node.js test server receives requests and returns queued responses. The test server exposes a simple API that is +used to enqueue responses and inspect the requests that it has received. + +Retrieve the server object by calling ``$this->getServer()``. If the node.js server is not running, it will be +started as a forked process and an object that interfaces with the server will be returned. (note: stopping the +server is handled internally by Guzzle.) + +You can queue an HTTP response or an array of responses by calling ``$this->getServer()->enqueue()``: + +.. code-block:: php + + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + +The above code queues a single 200 response with an empty body. Responses are queued using a FIFO order; this +response will be returned by the server when it receives the first request and then removed from the queue. If a +request is received by a server with no queued responses, an exception will be thrown in your unit test. + +You can inspect the requests that the server has retrieved by calling ``$this->getServer()->getReceivedRequests()``. +This method accepts an optional ``$hydrate`` parameter that specifies if you are retrieving an array of string HTTP +requests or an array of ``Guzzle\Http\RequestInterface`` subclassed objects. "Hydrating" the requests will allow +greater flexibility in your unit tests so that you can easily assert the state of the various parts of a request. + +You will need to modify the base_url of your web service client in order to use it against the test server. + +.. code-block:: php + + $client = $this->getServiceBuilder()->get('my_client'); + $client->setBaseUrl($this->getServer()->getUrl()); + +After running the above code, all calls made from the ``$client`` object will be sent to the test web server. diff --git a/src/bb-vendor/guzzle/guzzle/docs/webservice-client/guzzle-service-descriptions.rst b/src/bb-vendor/guzzle/guzzle/docs/webservice-client/guzzle-service-descriptions.rst new file mode 100644 index 000000000..ad6070b27 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/webservice-client/guzzle-service-descriptions.rst @@ -0,0 +1,619 @@ +=========================== +Guzzle service descriptions +=========================== + +Guzzle allows you to serialize HTTP requests and parse HTTP responses using a DSL called a service descriptions. +Service descriptions define web service APIs by documenting each operation, the operation's parameters, validation +options for each parameter, an operation's response, how the response is parsed, and any errors that can be raised for +an operation. Writing a service description for a web service allows you to more quickly consume a web service than +writing concrete commands for each web service operation. + +Guzzle service descriptions can be representing using a PHP array or JSON document. Guzzle's service descriptions are +heavily inspired by `Swagger `_. + +Service description schema +========================== + +A Guzzle Service description must match the following JSON schema document. This document can also serve as a guide when +implementing a Guzzle service description. + +Download the schema here: :download:`Guzzle JSON schema document ` + +.. class:: overflow-height-500px + + .. literalinclude:: ../_downloads/guzzle-schema-1.0.json + :language: json + +Top-level attributes +-------------------- + +Service descriptions are comprised of the following top-level attributes: + +.. code-block:: json + + { + "name": "string", + "apiVersion": "string|number", + "baseUrl": "string", + "description": "string", + "operations": {}, + "models": {}, + "includes": ["string.php", "string.json"] + } + ++-----------------------------------------+-------------------------+-----------------------------------------------------------------------------------------------------------------------+ +| Property Name | Value | Description | ++=========================================+=========================+=======================================================================================================================+ +| name | string | Name of the web service | ++-----------------------------------------+-------------------------+-----------------------------------------------------------------------------------------------------------------------+ +| apiVersion | string|number | Version identifier that the service description is compatible with | ++-----------------------------------------+-------------------------+-----------------------------------------------------------------------------------------------------------------------+ +| baseUrl or basePath | string | Base URL of the web service. Any relative URI specified in an operation will be merged with the baseUrl using the | +| | | process defined in RFC 2396. Some clients require custom logic to determine the baseUrl. In those cases, it is best | +| | | to not include a baseUrl in the service description, but rather allow the factory method of the client to configure | +| | | the client’s baseUrl. | ++-----------------------------------------+-------------------------+-----------------------------------------------------------------------------------------------------------------------+ +| description | string | Short summary of the web service | ++-----------------------------------------+-------------------------+-----------------------------------------------------------------------------------------------------------------------+ +| operations | object containing | Operations of the service. The key is the name of the operation and value is the attributes of the operation. | +| | :ref:`operation-schema` | | +| | | | ++-----------------------------------------+-------------------------+-----------------------------------------------------------------------------------------------------------------------+ +| models | object containing | Schema models that can be referenced throughout the service description. Models can be used to define how an HTTP | +| | :ref:`model-schema` | response is parsed into a ``Guzzle\Service\Resource\Model`` object when an operation uses a ``model`` ``responseType``| ++-----------------------------------------+-------------------------+-----------------------------------------------------------------------------------------------------------------------+ +| includes | array of .js, | Service description files to include and extend from (can be a .json, .js, or .php file) | +| | .json, or .php | | +| | files. | | ++-----------------------------------------+-------------------------+-----------------------------------------------------------------------------------------------------------------------+ +| (any additional properties) | mixed | Any additional properties specified as top-level attributes are allowed and will be treated as arbitrary data | ++-----------------------------------------+-------------------------+-----------------------------------------------------------------------------------------------------------------------+ + +.. _operation-schema: + +Operations +---------- + +Operations are the actions that can be taken on a service. Each operation is given a unique name and has a distinct +endpoint and HTTP method. If an API has a ``DELETE /users/:id`` operation, a satisfactory operation name might be +``DeleteUser`` with a parameter of ``id`` that is inserted into the URI. + +.. class:: overflow-height-250px + + .. code-block:: json + + { + "operations": { + "operationName": { + "extends": "string", + "httpMethod": "GET|POST|PUT|DELETE|PATCH|string", + "uri": "string", + "summary": "string", + "class": "string", + "responseClass": "string", + "responseNotes": "string", + "type": "string", + "description": "string", + "responseType": "primitive|class|(model by name)|documentation|(string)", + "deprecated": false, + "errorResponses": [ + { + "code": 500, + "reason": "Unexpected Error", + "class": "string" + } + ], + "data": { + "foo": "bar", + "baz": "bam" + }, + "parameters": {} + } + } + } + +.. csv-table:: + :header: "Property Name", "Value", "Description" + :widths: 20, 15, 65 + + "extends", "string", "Extend from another operation by name. The parent operation must be defined before the child." + "httpMethod", "string", "HTTP method used with the operation (e.g. GET, POST, PUT, DELETE, PATCH, etc)" + "uri", "string", "URI of the operation. The uri attribute can contain URI templates. The variables of the URI template are parameters of the operation with a location value of uri" + "summary", "string", "Short summary of what the operation does" + "class", "string", "Custom class to instantiate instead of the default Guzzle\\Service\\Command\\OperationCommand. Using this attribute allows you to define an operation using a service description, but allows more customized logic to be implemented in user-land code." + "responseClass", "string", "Defined what is returned from the method. Can be a primitive, class name, or model name. You can specify the name of a class to return a more customized result from the operation (for example, a domain model object). When using the name of a PHP class, the class must implement ``Guzzle\Service\Command\ResponseClassInterface``." + "responseNotes", "string", "A description of the response returned by the operation" + "responseType", "string", "The type of response that the operation creates: one of primitive, class, model, or documentation. If not specified, this value will be automatically inferred based on whether or not there is a model matching the name, if a matching class name is found, or set to 'primitive' by default." + "deprecated", "boolean", "Whether or not the operation is deprecated" + "errorResponses", "array", "Errors that could occur while executing the operation. Each item of the array is an object that can contain a 'code' (HTTP response status code of the error), 'reason' (reason phrase or description of the error), and 'class' (an exception class that will be raised when this error is encountered)" + "data", "object", "Any arbitrary data to associate with the operation" + "parameters", "object containing :ref:`parameter-schema` objects", "Parameters of the operation. Parameters are used to define how input data is serialized into a HTTP request." + "additionalParameters", "A single :ref:`parameter-schema` object", "Validation and serialization rules for any parameter supplied to the operation that was not explicitly defined." + +additionalParameters +~~~~~~~~~~~~~~~~~~~~ + +When a webservice offers a large number of parameters that all are set in the same location (for example the query +string or a JSON document), defining each parameter individually can require a lot of time and repetition. Furthermore, +some web services allow for completely arbitrary parameters to be supplied for an operation. The +``additionalParameters`` attribute can be used to solve both of these issues. + +As an example, we can define a Twitter API operation quite easily using ``additionalParameters``. The +GetMentions operation accepts a large number of query string parameters. Defining each of these parameters +is ideal because it provide much more introspection for the client and opens the possibility to use the description with +other tools (e.g. a documentation generator). However, you can very quickly provide a "catch-all" serialization rule +that will place any custom parameters supplied to an operation the generated request's query string parameters. + +.. class:: overflow-height-250px + + .. code-block:: json + + { + "name": "Twitter", + "apiVersion": "1.1", + "baseUrl": "https://api.twitter.com/1.1", + "operations": { + "GetMentions": { + "httpMethod": "GET", + "uri": "statuses/mentions_timeline.json", + "responseClass": "GetMentionsOutput", + "additionalParameters": { + "location": "query" + } + } + }, + "models": { + "GetMentionsOutput": { + "type": "object", + "additionalProperties": { + "location": "json" + } + } + } + } + +responseClass +~~~~~~~~~~~~~ + +The ``responseClass`` attribute is used to define the return value of an operation (what is returned by calling the +``getResult()`` method of a command object). The value set in the responseClass attribute can be one of "primitive" +(meaning the result with be primitive type like a string), a class name meaning the result will be an instance of a +specific user-land class, or a model name meaning the result will be a ``Guzzle\Service\Resource\Model`` object that +uses a :ref:`model schema ` to define how the HTTP response is parsed. + +.. note:: + + Using a class name with a ``responseClass`` will only work if it is supported by the ``class`` that is instantiated + for the operation. Keep this in mind when specifying a custom ``class`` attribute that points to a custom + ``Guzzle\Service\Command\CommandInterface`` class. The default ``class``, + ``Guzzle\Service\Command\OperationCommand``, does support setting custom ``class`` attributes. + +You can specify the name of a class to return a more customized result from the operation (for example, a domain model +object). When using the name of a PHP class, the class must implement ``Guzzle\Service\Command\ResponseClassInterface``. +Here's a very simple example of implementing a custom responseClass object. + +.. code-block:: json + + { + "operations": { + "test": { + "responseClass": "MyApplication\\User" + } + } + } + +.. code-block:: php + + namespace MyApplication; + + use Guzzle\Service\Command\ResponseClassInterface; + use Guzzle\Service\Command\OperationCommand; + + class User implements ResponseClassInterface + { + protected $name; + + public static function fromCommand(OperationCommand $command) + { + $response = $command->getResponse(); + $xml = $response->xml(); + + return new self((string) $xml->name); + } + + public function __construct($name) + { + $this->name = $name; + } + } + +errorResponses +~~~~~~~~~~~~~~ + +``errorResponses`` is an array containing objects that define the errors that could occur while executing the +operation. Each item of the array is an object that can contain a 'code' (HTTP response status code of the error), +'reason' (reason phrase or description of the error), and 'class' (an exception class that will be raised when this +error is encountered). + +ErrorResponsePlugin +^^^^^^^^^^^^^^^^^^^ + +Error responses are by default only used for documentation. If you don't need very complex exception logic for your web +service errors, then you can use the ``Guzzle\Plugin\ErrorResponse\ErrorResponsePlugin`` to automatically throw defined +exceptions when one of the ``errorResponse`` rules are matched. The error response plugin will listen for the +``request.complete`` event of a request created by a command object. Every response (including a successful response) is +checked against the list of error responses for an exact match using the following order of checks: + +1. Does the errorResponse have a defined ``class``? +2. Is the errorResponse ``code`` equal to the status code of the response? +3. Is the errorResponse ``reason`` equal to the reason phrase of the response? +4. Throw the exception stored in the ``class`` attribute of the errorResponse. + +The ``class`` attribute must point to a class that implements +``Guzzle\Plugin\ErrorResponse\ErrorResponseExceptionInterface``. This interface requires that an error response class +implements ``public static function fromCommand(CommandInterface $command, Response $response)``. This method must +return an object that extends from ``\Exception``. After an exception is returned, it is thrown by the plugin. + +.. _parameter-schema: + +Parameter schema +---------------- + +Parameters in both operations and models are represented using the +`JSON schema `_ syntax. + +.. csv-table:: + :header: "Property Name", "Value", "Description" + :widths: 20, 15, 65 + + "name", "string", "Unique name of the parameter" + "type", "string|array", "Type of variable (string, number, integer, boolean, object, array, numeric, null, any). Types are using for validation and determining the structure of a parameter. You can use a union type by providing an array of simple types. If one of the union types matches the provided value, then the value is valid." + "instanceOf", "string", "When the type is an object, you can specify the class that the object must implement" + "required", "boolean", "Whether or not the parameter is required" + "default", "mixed", "Default value to use if no value is supplied" + "static", "boolean", "Set to true to specify that the parameter value cannot be changed from the default setting" + "description", "string", "Documentation of the parameter" + "location", "string", "The location of a request used to apply a parameter. Custom locations can be registered with a command, but the defaults are uri, query, statusCode, reasonPhrase, header, body, json, xml, postField, postFile, responseBody" + "sentAs", "string", "Specifies how the data being modeled is sent over the wire. For example, you may wish to include certain headers in a response model that have a normalized casing of FooBar, but the actual header is x-foo-bar. In this case, sentAs would be set to x-foo-bar." + "filters", "array", "Array of functions to to run a parameter value through." + +filters +~~~~~~~ + +Each value in the array must be a string containing the full class path to a static method or an array of complex +filter information. You can specify static methods of classes using the full namespace class name followed by +"::" (e.g. ``FooBar::baz()``). Some filters require arguments in order to properly filter a value. For complex filters, +use an object containing a ``method`` attribute pointing to a function, and an ``args`` attribute containing an +array of positional arguments to pass to the function. Arguments can contain keywords that are replaced when filtering +a value: ``@value`` is replaced with the value being filtered, and ``@api`` is replaced with the actual Parameter +object. + +.. code-block:: json + + { + "filters": [ + "strtolower", + { + "method": "MyClass::convertString", + "args": [ "test", "@value", "@api" ] + } + ] + } + +The above example will filter a parameter using ``strtolower``. It will then call the ``convertString`` static method +of ``MyClass``, passing in "test", the actual value of the parameter, and a ``Guzzle\Service\Description\Parameter`` +object. + +Operation parameter location attributes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The location field of top-level parameters control how a parameter is serialized when generating a request. + +uri location +^^^^^^^^^^^^ + +Parameters are injected into the ``uri`` attribute of the operation using +`URI-template expansion `_. + +.. code-block:: json + + { + "operations": { + "uriTest": { + "uri": "/test/{testValue}", + "parameters": { + "testValue": { + "location": "uri" + } + } + } + } + } + +query location +^^^^^^^^^^^^^^ + +Parameters are injected into the query string of a request. Query values can be nested, which would result in a PHP +style nested query string. The name of a parameter is the default name of the query string parameter added to the +request. You can override this behavior by specifying the ``sentAs`` attribute on the parameter. + +.. code-block:: json + + { + "operations": { + "queryTest": { + "parameters": { + "testValue": { + "location": "query", + "sentAs": "test_value" + } + } + } + } + } + +header location +^^^^^^^^^^^^^^^ + +Parameters are injected as headers on an HTTP request. The name of the parameter is used as the name of the header by +default. You can change the name of the header created by the parameter using the ``sentAs`` attribute. + +Headers that are of type ``object`` will be added as multiple headers to a request using the key of the input array as +the header key. Setting a ``sentAs`` attribute along with a type ``object`` will use the value of ``sentAs`` as a +prefix for each header key. + +body location +^^^^^^^^^^^^^ + +Parameters are injected as the body of a request. The input of these parameters may be anything that can be cast to a +string or a ``Guzzle\Http\EntityBodyInterface`` object. + +postField location +^^^^^^^^^^^^^^^^^^ + +Parameters are inserted as POST fields in a request. Nested values may be supplied and will be represented using +PHP style nested query strings. The POST field name is the same as the parameter name by default. You can use the +``sentAs`` parameter to override the POST field name. + +postFile location +^^^^^^^^^^^^^^^^^ + +Parameters are added as POST files. A postFile value may be a string pointing to a local filename or a +``Guzzle\Http\Message\PostFileInterface`` object. The name of the POST file will be the name of the parameter by +default. You can use a custom POST file name by using the ``sentAs`` attribute. + +Supports "string" and "array" types. + +json location +^^^^^^^^^^^^^ + +Parameters are added to the body of a request as top level keys of a JSON document. Nested values may be specified, +with any number of nested ``Guzzle\Common\ToArrayInterface`` objects. When JSON parameters are specified, the +``Content-Type`` of the request will change to ``application/json`` if a ``Content-Type`` has not already been specified +on the request. + +xml location +^^^^^^^^^^^^ + +Parameters are added to the body of a request as top level nodes of an XML document. Nested values may be specified, +with any number of nested ``Guzzle\Common\ToArrayInterface`` objects. When XML parameters are specified, the +``Content-Type`` of the request will change to ``application/xml`` if a ``Content-Type`` has not already been specified +on the request. + +responseBody location +^^^^^^^^^^^^^^^^^^^^^ + +Specifies the EntityBody of a response. This can be used to download the response body to a file or a custom Guzzle +EntityBody object. + +No location +^^^^^^^^^^^ + +If a parameter has no location attribute, then the parameter is simply used as a data value. + +Other locations +^^^^^^^^^^^^^^^ + +Custom locations can be registered as new locations or override default locations if needed. + +.. _model-schema: + +Model Schema +------------ + +Models are used in service descriptions to provide generic JSON schema definitions that can be extended from or used in +``$ref`` attributes. Models can also be referenced in a ``responseClass`` attribute to provide valuable output to an +operation. Models are JSON schema documents and use the exact syntax and attributes used in parameters. + +Response Models +~~~~~~~~~~~~~~~ + +Response models describe how a response is parsed into a ``Guzzle\Service\Resource\Model`` object. Response models are +always modeled as JSON schema objects. When an HTTP response is parsed using a response model, the rules specified on +each property of a response model will translate 1:1 as keys in a PHP associative array. When a ``sentAs`` attribute is +found in response model parameters, the value retrieved from the HTTP response is retrieved using the ``sentAs`` +parameter but stored in the response model using the name of the parameter. + +The location field of top-level parameters in a response model tell response parsers how data is retrieved from a +response. + +statusCode location +^^^^^^^^^^^^^^^^^^^ + +Retrieves the status code of the response. + +reasonPhrase location +^^^^^^^^^^^^^^^^^^^^^ + +Retrieves the reason phrase of the response. + +header location +^^^^^^^^^^^^^^^ + +Retrieves a header from the HTTP response. + +body location +^^^^^^^^^^^^^ + +Retrieves the body of an HTTP response. + +json location +^^^^^^^^^^^^^ + +Retrieves a top-level parameter from a JSON document contained in an HTTP response. + +You can use ``additionalProperties`` if the JSON document is wrapped in an outer array. This allows you to parse the +contents of each item in the array using the parsing rules defined in the ``additionalProperties`` schema. + +xml location +^^^^^^^^^^^^ + +Retrieves a top-level node value from an XML document contained in an HTTP response. + +Other locations +^^^^^^^^^^^^^^^ + +Custom locations can be registered as new locations or override default locations if needed. + +Example service description +--------------------------- + +Let's say you're interacting with a web service called 'Foo' that allows for the following routes and methods:: + + GET/POST /users + GET/DELETE /users/:id + +The following JSON service description implements this simple web service: + +.. class:: overflow-height-500px + + .. code-block:: json + + { + "name": "Foo", + "apiVersion": "2012-10-14", + "baseUrl": "http://api.foo.com", + "description": "Foo is an API that allows you to Baz Bar", + "operations": { + "GetUsers": { + "httpMethod": "GET", + "uri": "/users", + "summary": "Gets a list of users", + "responseClass": "GetUsersOutput" + }, + "CreateUser": { + "httpMethod": "POST", + "uri": "/users", + "summary": "Creates a new user", + "responseClass": "CreateUserOutput", + "parameters": { + "name": { + "location": "json", + "type": "string" + }, + "age": { + "location": "json", + "type": "integer" + } + } + }, + "GetUser": { + "httpMethod": "GET", + "uri": "/users/{id}", + "summary": "Retrieves a single user", + "responseClass": "GetUserOutput", + "parameters": { + "id": { + "location": "uri", + "description": "User to retrieve by ID", + "required": true + } + } + }, + "DeleteUser": { + "httpMethod": "DELETE", + "uri": "/users/{id}", + "summary": "Deletes a user", + "responseClass": "DeleteUserOutput", + "parameters": { + "id": { + "location": "uri", + "description": "User to delete by ID", + "required": true + } + } + } + }, + "models": { + "GetUsersOutput": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "location": "json", + "type": "string" + }, + "age": { + "location": "json", + "type": "integer" + } + } + } + }, + "CreateUserOutput": { + "type": "object", + "properties": { + "id": { + "location": "json", + "type": "string" + }, + "location": { + "location": "header", + "sentAs": "Location", + "type": "string" + } + } + }, + "GetUserOutput": { + "type": "object", + "properties": { + "name": { + "location": "json", + "type": "string" + }, + "age": { + "location": "json", + "type": "integer" + } + } + }, + "DeleteUserOutput": { + "type": "object", + "properties": { + "status": { + "location": "statusCode", + "type": "integer" + } + } + } + } + } + +If you attach this service description to a client, you would completely configure the client to interact with the +Foo web service and provide valuable response models for each operation. + +.. code-block:: php + + use Guzzle\Service\Description\ServiceDescription; + + $description = ServiceDescription::factory('/path/to/client.json'); + $client->setDescription($description); + + $command = $client->getCommand('DeleteUser', array('id' => 123)); + $responseModel = $client->execute($command); + echo $responseModel['status']; + +.. note:: + + You can add the service description to your client's factory method or constructor. diff --git a/src/bb-vendor/guzzle/guzzle/docs/webservice-client/using-the-service-builder.rst b/src/bb-vendor/guzzle/guzzle/docs/webservice-client/using-the-service-builder.rst new file mode 100644 index 000000000..b7113d68b --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/webservice-client/using-the-service-builder.rst @@ -0,0 +1,316 @@ +======================= +Using a service builder +======================= + +The best way to instantiate Guzzle web service clients is to let Guzzle handle building the clients for you using a +ServiceBuilder. A ServiceBuilder is responsible for creating concrete client objects based on configuration settings +and helps to manage credentials for different environments. + +You don't have to use a service builder, but they help to decouple your application from concrete classes and help to +share configuration data across multiple clients. Consider the following example. Here we are creating two clients that +require the same API public key and secret key. The clients are created using their ``factory()`` methods. + +.. code-block:: php + + use MyService\FooClient; + use MyService\BarClient; + + $foo = FooClient::factory(array( + 'key' => 'abc', + 'secret' => '123', + 'custom' => 'and above all' + )); + + $bar = BarClient::factory(array( + 'key' => 'abc', + 'secret' => '123', + 'custom' => 'listen to me' + )); + +The redundant specification of the API keys can be removed using a service builder. + +.. code-block:: php + + use Guzzle\Service\Builder\ServiceBuilder; + + $builder = ServiceBuilder::factory(array( + 'services' => array( + 'abstract_client' => array( + 'params' => array( + 'key' => 'abc', + 'secret' => '123' + ) + ), + 'foo' => array( + 'extends' => 'abstract_client', + 'class' => 'MyService\FooClient', + 'params' => array( + 'custom' => 'and above all' + ) + ), + 'bar' => array( + 'extends' => 'abstract_client', + 'class' => 'MyService\FooClient', + 'params' => array( + 'custom' => 'listen to me' + ) + ) + ) + )); + + $foo = $builder->get('foo'); + $bar = $builder->get('bar'); + +You can make managing your API keys even easier by saving the service builder configuration in a JSON format in a +.json file. + +Creating a service builder +-------------------------- + +A ServiceBuilder can source information from an array, an PHP include file that returns an array, or a JSON file. + +.. code-block:: php + + use Guzzle\Service\Builder\ServiceBuilder; + + // Source service definitions from a JSON file + $builder = ServiceBuilder::factory('services.json'); + +Sourcing data from an array +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Data can be source from a PHP array. The array must contain an associative ``services`` array that maps the name of a +client to the configuration information used by the service builder to create the client. Clients are given names +which are used to identify how a client is retrieved from a service builder. This can be useful for using multiple +accounts for the same service or creating development clients vs. production clients. + +.. code-block:: php + + $services = array( + 'includes' => array( + '/path/to/other/services.json', + '/path/to/other/php_services.php' + ), + 'services' => array( + 'abstract.foo' => array( + 'params' => array( + 'username' => 'foo', + 'password' => 'bar' + ) + ), + 'bar' => array( + 'extends' => 'abstract.foo', + 'class' => 'MyClientClass', + 'params' => array( + 'other' => 'abc' + ) + ) + ) + ); + +A service builder configuration array contains two top-level array keys: + ++------------+---------------------------------------------------------------------------------------------------------+ +| Key | Description | ++============+=========================================================================================================+ +| includes | Array of paths to JSON or PHP include files to include in the configuration. | ++------------+---------------------------------------------------------------------------------------------------------+ +| services | Associative array of defined services that can be created by the service builder. Each service can | +| | contain the following keys: | +| | | +| | +------------+----------------------------------------------------------------------------------------+ | +| | | Key | Description | | +| | +============+========================================================================================+ | +| | | class | The concrete class to instantiate that implements the | | +| | | | ``Guzzle\Common\FromConfigInterface``. | | +| | +------------+----------------------------------------------------------------------------------------+ | +| | | extends | The name of a previously defined service to extend from | | +| | +------------+----------------------------------------------------------------------------------------+ | +| | | params | Associative array of parameters to pass to the factory method of the service it is | | +| | | | instantiated | | +| | +------------+----------------------------------------------------------------------------------------+ | +| | | alias | An alias that can be used in addition to the array key for retrieving a client from | | +| | | | the service builder. | | +| | +------------+----------------------------------------------------------------------------------------+ | ++------------+---------------------------------------------------------------------------------------------------------+ + +The first client defined, ``abstract.foo``, is used as a placeholder of shared configuration values. Any service +extending abstract.foo will inherit its params. As an example, this can be useful when clients share the same username +and password. + +The next client, ``bar``, extends from ``abstract.foo`` using the ``extends`` attribute referencing the client from +which to extend. Additional parameters can be merged into the original service definition when extending a parent +service. + +.. important:: + + Each client that you intend to instantiate must specify a ``class`` attribute that references the full class name + of the client being created. The class referenced in the ``class`` parameter must implement a static ``factory()`` + method that accepts an array or ``Guzzle\Common\Collection`` object and returns an instantiated object. + +Sourcing from a PHP include +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can create service builder configurations using a PHP include file. This can be useful if you wish to take +advantage of an opcode cache like APC to speed up the process of loading and processing the configuration. The PHP +include file is the same format as an array, but you simply create a PHP script that returns an array and save the +file with the .php file extension. + +.. code-block:: php + + '...'); + // Saved as config.php + +This configuration file can then be used with a service builder. + +.. code-block:: php + + $builder = ServiceBuilder::factory('/path/to/config.php'); + +Sourcing from a JSON document +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can use JSON documents to serialize your service descriptions. The JSON format uses the exact same structure as +the PHP array syntax, but it's just serialized using JSON. + +.. code-block:: javascript + + { + "includes": ["/path/to/other/services.json", "/path/to/other/php_services.php"], + "services": { + "abstract.foo": { + "params": { + "username": "foo", + "password": "bar" + } + }, + "bar": { + "extends": "abstract.foo", + "class": "MyClientClass", + "params": { + "other": "abc" + } + } + } + } + +Referencing other clients in parameters +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If one of your clients depends on another client as one of its parameters, you can reference that client by name by +enclosing the client's reference key in ``{}``. + +.. code-block:: javascript + + { + "services": { + "token": { + "class": "My\Token\TokenFactory", + "params": { + "access_key": "xyz" + } + }, + "client": { + "class": "My\Client", + "params": { + "token_client": "{token}", + "version": "1.0" + } + } + } + } + +When ``client`` is constructed by the service builder, the service builder will first create the ``token`` service +and then inject the token service into ``client``'s factory method in the ``token_client`` parameter. + +Retrieving clients from a service builder +----------------------------------------- + +Clients are referenced using a customizable name you provide in your service definition. The ServiceBuilder is a sort +of multiton object-- it will only instantiate a client once and return that client for subsequent retrievals. Clients +are retrieved by name (the array key used in the configuration) or by the ``alias`` setting of a service. + +Here's an example of retrieving a client from your ServiceBuilder: + +.. code-block:: php + + $client = $builder->get('foo'); + + // You can also use the ServiceBuilder object as an array + $client = $builder['foo']; + +Creating throwaway clients +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can get a "throwaway" client (a client that is not persisted by the ServiceBuilder) by passing ``true`` in the +second argument of ``ServiceBuilder::get()``. This allows you to create a client that will not be returned by other +parts of your code that use the service builder. Instead of passing ``true``, you can pass an array of configuration +settings that will override the configuration settings specified in the service builder. + +.. code-block:: php + + // Get a throwaway client and overwrite the "custom" setting of the client + $foo = $builder->get('foo', array( + 'custom' => 'in this world there are rules' + )); + +Getting raw configuration settings +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can get the raw configuration settings provided to the service builder for a specific service using the +``getData($name)`` method of a service builder. This method will null if the service was not found in the service +builder or an array of configuration settings if the service was found. + +.. code-block:: php + + $data = $builder->getData('foo'); + echo $data['key'] . "\n"; + echo $data['secret'] . "\n"; + echo $data['custom'] . "\n"; + +Adding a plugin to all clients +------------------------------ + +You can add a plugin to all clients created by a service builder using the ``addGlobalPlugin($plugin)`` method of a +service builder and passing a ``Symfony\Component\EventDispatcher\EventSubscriberInterface`` object. The service builder +will then attach each global plugin to every client as it is created. This allows you to, for example, add a LogPlugin +to every request created by a service builder for easy debugging. + +.. code-block:: php + + use Guzzle\Plugin\Log\LogPlugin; + + // Add a debug log plugin to every client as it is created + $builder->addGlobalPlugin(LogPlugin::getDebugPlugin()); + + $foo = $builder->get('foo'); + $foo->get('/')->send(); + // Should output all of the data sent over the wire + +.. _service-builder-events: + +Events emitted from a service builder +------------------------------------- + +A ``Guzzle\Service\Builder\ServiceBuilder`` object emits the following events: + ++-------------------------------+--------------------------------------------+-----------------------------------------+ +| Event name | Description | Event data | ++===============================+============================================+=========================================+ +| service_builder.create_client | Called when a client is created | * client: The created client object | ++-------------------------------+--------------------------------------------+-----------------------------------------+ + +.. code-block:: php + + use Guzzle\Common\Event; + use Guzzle\Service\Builder\ServiceBuilder; + + $builder = ServiceBuilder::factory('/path/to/config.json'); + + // Add an event listener to print out each client client as it is created + $builder->getEventDispatcher()->addListener('service_builder.create_client', function (Event $e) { + echo 'Client created: ' . get_class($e['client']) . "\n"; + }); + + $foo = $builder->get('foo'); + // Should output the class used for the "foo" client diff --git a/src/bb-vendor/guzzle/guzzle/docs/webservice-client/webservice-client.rst b/src/bb-vendor/guzzle/guzzle/docs/webservice-client/webservice-client.rst new file mode 100644 index 000000000..7ec771e1c --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/docs/webservice-client/webservice-client.rst @@ -0,0 +1,659 @@ +====================== +The web service client +====================== + +The ``Guzzle\Service`` namespace contains various abstractions that help to make it easier to interact with a web +service API, including commands, service descriptions, and resource iterators. + +In this chapter, we'll build a simple `Twitter API client `_. + +Creating a client +================= + +A class that extends from ``Guzzle\Service\Client`` or implements ``Guzzle\Service\ClientInterface`` must implement a +``factory()`` method in order to be used with a :doc:`service builder `. + +Factory method +-------------- + +You can use the ``factory()`` method of a client directly if you do not need a service builder. + +.. code-block:: php + + use mtdowling\TwitterClient; + + // Create a client and pass an array of configuration data + $twitter = TwitterClient::factory(array( + 'consumer_key' => '****', + 'consumer_secret' => '****', + 'token' => '****', + 'token_secret' => '****' + )); + +.. note:: + + If you'd like to follow along, here's how to get your Twitter API credentials: + + 1. Visit https://dev.twitter.com/apps + 2. Click on an application that you've created + 3. Click on the "OAuth tool" tab + 4. Copy all of the settings under "OAuth Settings" + +Implementing a factory method +----------------------------- + +Creating a client and its factory method is pretty simple. You just need to implement ``Guzzle\Service\ClientInterface`` +or extend from ``Guzzle\Service\Client``. + +.. code-block:: php + + namespace mtdowling; + + use Guzzle\Common\Collection; + use Guzzle\Plugin\Oauth\OauthPlugin; + use Guzzle\Service\Client; + use Guzzle\Service\Description\ServiceDescription; + + /** + * A simple Twitter API client + */ + class TwitterClient extends Client + { + public static function factory($config = array()) + { + // Provide a hash of default client configuration options + $default = array('base_url' => 'https://api.twitter.com/1.1'); + + // The following values are required when creating the client + $required = array( + 'base_url', + 'consumer_key', + 'consumer_secret', + 'token', + 'token_secret' + ); + + // Merge in default settings and validate the config + $config = Collection::fromConfig($config, $default, $required); + + // Create a new Twitter client + $client = new self($config->get('base_url'), $config); + + // Ensure that the OauthPlugin is attached to the client + $client->addSubscriber(new OauthPlugin($config->toArray())); + + return $client; + } + } + +Service Builder +--------------- + +A service builder is used to easily create web service clients, provides a simple configuration driven approach to +creating clients, and allows you to share configuration settings across multiple clients. You can find out more about +Guzzle's service builder in :doc:`using-the-service-builder`. + +.. code-block:: php + + use Guzzle\Service\Builder\ServiceBuilder; + + // Create a service builder and provide client configuration data + $builder = ServiceBuilder::factory('/path/to/client_config.json'); + + // Get the client from the service builder by name + $twitter = $builder->get('twitter'); + +The above example assumes you have JSON data similar to the following stored in "/path/to/client_config.json": + +.. code-block:: json + + { + "services": { + "twitter": { + "class": "mtdowling\\TwitterClient", + "params": { + "consumer_key": "****", + "consumer_secret": "****", + "token": "****", + "token_secret": "****" + } + } + } + } + +.. note:: + + A service builder becomes much more valuable when using multiple web service clients in a single application or + if you need to utilize the same client with varying configuration settings (e.g. multiple accounts). + +Commands +======== + +Commands are a concept in Guzzle that helps to hide the underlying implementation of an API by providing an easy to use +parameter driven object for each action of an API. A command is responsible for accepting an array of configuration +parameters, serializing an HTTP request, and parsing an HTTP response. Following the +`command pattern `_, commands in Guzzle offer a greater level of +flexibility when implementing and utilizing a web service client. + +Executing commands +------------------ + +You must explicitly execute a command after creating a command using the ``getCommand()`` method. A command has an +``execute()`` method that may be called, or you can use the ``execute()`` method of a client object and pass in the +command object. Calling either of these execute methods will return the result value of the command. The result value is +the result of parsing the HTTP response with the ``process()`` method. + +.. code-block:: php + + // Get a command from the client and pass an array of parameters + $command = $twitter->getCommand('getMentions', array( + 'count' => 5 + )); + + // Other parameters can be set on the command after it is created + $command['trim_user'] = false; + + // Execute the command using the command object. + // The result value contains an array of JSON data from the response + $result = $command->execute(); + + // You can retrieve the result of the command later too + $result = $command->getResult(). + +Command object also contains methods that allow you to inspect the HTTP request and response that was utilized with +the command. + +.. code-block:: php + + $request = $command->getRequest(); + $response = $command->getResponse(); + +.. note:: + + The format and notation used to retrieve commands from a client can be customized by injecting a custom command + factory, ``Guzzle\Service\Command\Factory\FactoryInterface``, on the client using ``$client->setCommandFactory()``. + +Executing with magic methods +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When using method missing magic methods with a command, the command will be executed right away and the result of the +command is returned. + +.. code-block:: php + + $jsonData = $twitter->getMentions(array( + 'count' => 5, + 'trim_user' => true + )); + +Creating commands +----------------- + +Commands are created using either the ``getCommand()`` method of a client or a magic missing method of a client. Using +the ``getCommand()`` method allows you to create a command without executing it, allowing for customization of the +command or the request serialized by the command. + +When a client attempts to create a command, it uses the client's ``Guzzle\Service\Command\Factory\FactoryInterface``. +By default, Guzzle will utilize a command factory that first looks for a concrete class for a particular command +(concrete commands) followed by a command defined by a service description (operation commands). We'll learn more about +concrete commands and operation commands later in this chapter. + +.. code-block:: php + + // Get a command from the twitter client. + $command = $twitter->getCommand('getMentions'); + $result = $command->execute(); + +Unless you've skipped ahead, running the above code will throw an exception. + + PHP Fatal error: Uncaught exception 'Guzzle\Common\Exception\InvalidArgumentException' with message + 'Command was not found matching getMentions' + +This exception was thrown because the "getMentions" command has not yet been implemented. Let's implement one now. + +Concrete commands +~~~~~~~~~~~~~~~~~ + +Commands can be created in one of two ways: create a concrete command class that extends +``Guzzle\Service\Command\AbstractCommand`` or +:doc:`create an OperationCommand based on a service description `. The recommended +approach is to use a service description to define your web service, but you can use concrete commands when custom +logic must be implemented for marshaling or unmarshaling a HTTP message. + +Commands are the method in which you abstract away the underlying format of the requests that need to be sent to take +action on a web service. Commands in Guzzle are meant to be built by executing a series of setter methods on a command +object. Commands are only validated right before they are executed. A ``Guzzle\Service\Client`` object is responsible +for executing commands. Commands created for your web service must implement +``Guzzle\Service\Command\CommandInterface``, but it's easier to extend the ``Guzzle\Service\Command\AbstractCommand`` +class, implement the ``build()`` method, and optionally implement the ``process()`` method. + +Serializing requests +^^^^^^^^^^^^^^^^^^^^ + +The ``build()`` method of a command is responsible for using the arguments of the command to build and serialize a +HTTP request and set the request on the ``$request`` property of the command object. This step is usually taken care of +for you when using a service description driven command that uses the default +``Guzzle\Service\Command\OperationCommand``. You may wish to implement the process method yourself when you aren't +using a service description or need to implement more complex request serialization. + +.. important:::: + + When implementing a custom ``build()`` method, be sure to set the class property of ``$this->request`` to an + instantiated and ready to send request. + +The following example shows how to implement the ``getMentions`` +`Twitter API `_ method using a concrete command. + +.. code-block:: php + + namespace mtdowling\Twitter\Command; + + use Guzzle\Service\Command\AbstractCommand; + + class GetMentions extends AbstractCommand + { + protected function build() + { + // Create the request property of the command + $this->request = $this->client->get('statuses/mentions_timeline.json'); + + // Grab the query object of the request because we will use it for + // serializing command parameters on the request + $query = $this->request->getQuery(); + + if ($this['count']) { + $query->set('count', $this['count']); + } + + if ($this['since_id']) { + $query->set('since_id', $this['since_id']); + } + + if ($this['max_id']) { + $query->set('max_id', $this['max_id']); + } + + if ($this['trim_user'] !== null) { + $query->set('trim_user', $this['trim_user'] ? 'true' : 'false'); + } + + if ($this['contributor_details'] !== null) { + $query->set('contributor_details', $this['contributor_details'] ? 'true' : 'false'); + } + + if ($this['include_entities'] !== null) { + $query->set('include_entities', $this['include_entities'] ? 'true' : 'false'); + } + } + } + +By default, a client will attempt to find concrete command classes under the ``Command`` namespace of a client. First +the client will attempt to find an exact match for the name of the command to the name of the command class. If an +exact match is not found, the client will calculate a class name using inflection. This is calculated based on the +folder hierarchy of a command and converting the CamelCased named commands into snake_case. Here are some examples on +how the command names are calculated: + +#. ``Foo\Command\JarJar`` **->** jar_jar +#. ``Foo\Command\Test`` **->** test +#. ``Foo\Command\People\GetCurrentPerson`` **->** people.get_current_person + +Notice how any sub-namespace beneath ``Command`` is converted from ``\`` to ``.`` (a period). CamelCasing is converted +to lowercased snake_casing (e.g. JarJar == jar_jar). + +Parsing responses +^^^^^^^^^^^^^^^^^ + +The ``process()`` method of a command is responsible for converting an HTTP response into something more useful. For +example, a service description operation that has specified a model object in the ``responseClass`` attribute of the +operation will set a ``Guzzle\Service\Resource\Model`` object as the result of the command. This behavior can be +completely modified as needed-- even if you are using operations and responseClass models. Simply implement a custom +``process()`` method that sets the ``$this->result`` class property to whatever you choose. You can reuse parts of the +default Guzzle response parsing functionality or get inspiration from existing code by using +``Guzzle\Service\Command\OperationResponseParser`` and ``Guzzle\Service\Command\DefaultResponseParser`` classes. + +If you do not implement a custom ``process()`` method and are not using a service description, then Guzzle will attempt +to guess how a response should be processed based on the Content-Type header of the response. Because the Twitter API +sets a ``Content-Type: application/json`` header on this response, we do not need to implement any custom response +parsing. + +Operation commands +~~~~~~~~~~~~~~~~~~ + +Operation commands are commands in which the serialization of an HTTP request and the parsing of an HTTP response are +driven by a Guzzle service description. Because request serialization, validation, and response parsing are +described using a DSL, creating operation commands is a much faster process than writing concrete commands. + +Creating operation commands for our Twitter client can remove a great deal of redundancy from the previous concrete +command, and allows for a deeper runtime introspection of the API. Here's an example service description we can use to +create the Twitter API client: + +.. code-block:: json + + { + "name": "Twitter", + "apiVersion": "1.1", + "baseUrl": "https://api.twitter.com/1.1", + "description": "Twitter REST API client", + "operations": { + "GetMentions": { + "httpMethod": "GET", + "uri": "statuses/mentions_timeline.json", + "summary": "Returns the 20 most recent mentions for the authenticating user.", + "responseClass": "GetMentionsOutput", + "parameters": { + "count": { + "description": "Specifies the number of tweets to try and retrieve", + "type": "integer", + "location": "query" + }, + "since_id": { + "description": "Returns results with an ID greater than the specified ID", + "type": "integer", + "location": "query" + }, + "max_id": { + "description": "Returns results with an ID less than or equal to the specified ID.", + "type": "integer", + "location": "query" + }, + "trim_user": { + "description": "Limits the amount of data returned for each user", + "type": "boolean", + "location": "query" + }, + "contributor_details": { + "description": "Adds more data to contributor elements", + "type": "boolean", + "location": "query" + }, + "include_entities": { + "description": "The entities node will be disincluded when set to false.", + "type": "boolean", + "location": "query" + } + } + } + }, + "models": { + "GetMentionsOutput": { + "type": "object", + "additionalProperties": { + "location": "json" + } + } + } + } + +If you're lazy, you can define the API in a less descriptive manner using ``additionalParameters``. +``additionalParameters`` define the serialization and validation rules of parameters that are not explicitly defined +in a service description. + +.. code-block:: json + + { + "name": "Twitter", + "apiVersion": "1.1", + "baseUrl": "https://api.twitter.com/1.1", + "description": "Twitter REST API client", + "operations": { + "GetMentions": { + "httpMethod": "GET", + "uri": "statuses/mentions_timeline.json", + "summary": "Returns the 20 most recent mentions for the authenticating user.", + "responseClass": "GetMentionsOutput", + "additionalParameters": { + "location": "query" + } + } + }, + "models": { + "GetMentionsOutput": { + "type": "object", + "additionalProperties": { + "location": "json" + } + } + } + } + +You should attach the service description to the client at the end of the client's factory method: + +.. code-block:: php + + // ... + class TwitterClient extends Client + { + public static function factory($config = array()) + { + // ... same code as before ... + + // Set the service description + $client->setDescription(ServiceDescription::factory('path/to/twitter.json')); + + return $client; + } + } + +The client can now use operations defined in the service description instead of requiring you to create concrete +command classes. Feel free to delete the concrete command class we created earlier. + +.. code-block:: php + + $jsonData = $twitter->getMentions(array( + 'count' => 5, + 'trim_user' => true + )); + +Executing commands in parallel +------------------------------ + +Much like HTTP requests, Guzzle allows you to send multiple commands in parallel. You can send commands in parallel by +passing an array of command objects to a client's ``execute()`` method. The client will serialize each request and +send them all in parallel. If an error is encountered during the transfer, then a +``Guzzle\Service\Exception\CommandTransferException`` is thrown, which allows you to retrieve a list of commands that +succeeded and a list of commands that failed. + +.. code-block:: php + + use Guzzle\Service\Exception\CommandTransferException; + + $commands = array(); + $commands[] = $twitter->getCommand('getMentions'); + $commands[] = $twitter->getCommand('otherCommandName'); + // etc... + + try { + $result = $client->execute($commands); + foreach ($result as $command) { + echo $command->getName() . ': ' . $command->getResponse()->getStatusCode() . "\n"; + } + } catch (CommandTransferException $e) { + // Get an array of the commands that succeeded + foreach ($e->getSuccessfulCommands() as $command) { + echo $command->getName() . " succeeded\n"; + } + // Get an array of the commands that failed + foreach ($e->getFailedCommands() as $command) { + echo $command->getName() . " failed\n"; + } + } + +.. note:: + + All commands executed from a client using an array must originate from the same client. + +Special command options +----------------------- + +Guzzle exposes several options that help to control how commands are validated, serialized, and parsed. +Command options can be specified when creating a command or in the ``command.params`` parameter in the +``Guzzle\Service\Client``. + +=========================== ============================================================================================ +command.request_options Option used to add :ref:`Request options ` to the request created by a + command +command.hidden_params An array of the names of parameters ignored by the ``additionalParameters`` parameter schema +command.disable_validation Set to true to disable JSON schema validation of the command's input parameters +command.response_processing Determines how the default response parser will parse the command. One of "raw" no parsing, + "model" (the default method used to parse commands using response models defined in service + descriptions) +command.headers (deprecated) Option used to specify custom headers. Use ``command.request_options`` instead +command.on_complete (deprecated) Option used to add an onComplete method to a command. Use + ``command.after_send`` event instead +command.response_body (deprecated) Option used to change the entity body used to store a response. + Use ``command.request_options`` instead +=========================== ============================================================================================ + +Advanced client configuration +============================= + +Default command parameters +-------------------------- + +When creating a client object, you can specify default command parameters to pass into all commands. Any key value pair +present in the ``command.params`` settings of a client will be added as default parameters to any command created +by the client. + +.. code-block:: php + + $client = new Guzzle\Service\Client(array( + 'command.params' => array( + 'default_1' => 'foo', + 'another' => 'bar' + ) + )); + +Magic methods +------------- + +Client objects will, by default, attempt to create and execute commands when a missing method is invoked on a client. +This powerful concept applies to both concrete commands and operation commands powered by a service description. This +makes it appear to the end user that you have defined actual methods on a client object, when in fact, the methods are +invoked using PHP's magic ``__call`` method. + +The ``__call`` method uses the ``getCommand()`` method of a client, which uses the client's internal +``Guzzle\Service\Command\Factory\FactoryInterface`` object. The default command factory allows you to instantiate +operations defined in a client's service description. The method in which a client determines which command to +execute is defined as follows: + +1. The client will first try to find a literal match for an operation in the service description. +2. If the literal match is not found, the client will try to uppercase the first character of the operation and find + the match again. +3. If a match is still not found, the command factory will inflect the method name from CamelCase to snake_case and + attempt to find a matching command. +4. If a command still does not match, an exception is thrown. + +.. code-block:: php + + // Use the magic method + $result = $twitter->getMentions(); + + // This is exactly the same as: + $result = $twitter->getCommand('getMentions')->execute(); + +You can disable magic methods on a client by passing ``false`` to the ``enableMagicMethod()`` method. + +Custom command factory +---------------------- + +A client by default uses the ``Guzzle\Service\Command\Factory\CompositeFactory`` which allows multiple command +factories to attempt to create a command by a certain name. The default CompositeFactory uses a ``ConcreteClassFactory`` +and a ``ServiceDescriptionFactory`` if a service description is specified on a client. You can specify a custom +command factory if your client requires custom command creation logic using the ``setCommandFactory()`` method of +a client. + +Custom resource Iterator factory +-------------------------------- + +Resource iterators can be retrieved from a client using the ``getIterator($name)`` method of a client. This method uses +a client's internal ``Guzzle\Service\Resource\ResourceIteratorFactoryInterface`` object. A client by default uses a +``Guzzle\Service\Resource\ResourceIteratorClassFactory`` to attempt to find concrete classes that implement resource +iterators. The default factory will first look for matching iterators in the ``Iterator`` subdirectory of the client +followed by the ``Model`` subdirectory of a client. Use the ``setResourceIteratorFactory()`` method of a client to +specify a custom resource iterator factory. + +Plugins and events +================== + +``Guzzle\Service\Client`` exposes various events that allow you to hook in custom logic. A client object owns a +``Symfony\Component\EventDispatcher\EventDispatcher`` object that can be accessed by calling +``$client->getEventDispatcher()``. You can use the event dispatcher to add listeners (a simple callback function) or +event subscribers (classes that listen to specific events of a dispatcher). + +.. _service-client-events: + +Events emitted from a Service Client +------------------------------------ + +A ``Guzzle\Service\Client`` object emits the following events: + ++------------------------------+--------------------------------------------+------------------------------------------+ +| Event name | Description | Event data | ++==============================+============================================+==========================================+ +| client.command.create | The client created a command object | * client: Client object | +| | | * command: Command object | ++------------------------------+--------------------------------------------+------------------------------------------+ +| command.before_prepare | Before a command is validated and built. | * command: Command being prepared | +| | This is also before a request is created. | | ++------------------------------+--------------------------------------------+------------------------------------------+ +| command.after_prepare | After a command instantiates and | * command: Command that was prepared | +| | configures its request object. | | ++------------------------------+--------------------------------------------+------------------------------------------+ +| command.before_send | The client is about to execute a prepared | * command: Command to execute | +| | command | | ++------------------------------+--------------------------------------------+------------------------------------------+ +| command.after_send | The client successfully completed | * command: The command that was executed | +| | executing a command | | ++------------------------------+--------------------------------------------+------------------------------------------+ +| command.parse_response | Called when ``responseType`` is ``class`` | * command: The command with a response | +| | and the response is about to be parsed. | about to be parsed. | ++------------------------------+--------------------------------------------+------------------------------------------+ + +.. code-block:: php + + use Guzzle\Common\Event; + use Guzzle\Service\Client; + + $client = new Client(); + + // create an event listener that operates on request objects + $client->getEventDispatcher()->addListener('command.after_prepare', function (Event $event) { + $command = $event['command']; + $request = $command->getRequest(); + + // do something with request + }); + +.. code-block:: php + + use Guzzle\Common\Event; + use Guzzle\Common\Client; + use Symfony\Component\EventDispatcher\EventSubscriberInterface; + + class EventSubscriber implements EventSubscriberInterface + { + public static function getSubscribedEvents() + { + return array( + 'client.command.create' => 'onCommandCreate', + 'command.parse_response' => 'onParseResponse' + ); + } + + public function onCommandCreate(Event $event) + { + $client = $event['client']; + $command = $event['command']; + // operate on client and command + } + + public function onParseResponse(Event $event) + { + $command = $event['command']; + // operate on the command + } + } + + $client = new Client(); + + $client->addSubscriber(new EventSubscriber()); diff --git a/src/bb-vendor/guzzle/guzzle/phar-stub.php b/src/bb-vendor/guzzle/guzzle/phar-stub.php new file mode 100644 index 000000000..cc2b53f4f --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/phar-stub.php @@ -0,0 +1,16 @@ +registerNamespaces(array( + 'Guzzle' => 'phar://guzzle.phar/src', + 'Symfony\\Component\\EventDispatcher' => 'phar://guzzle.phar/vendor/symfony/event-dispatcher', + 'Doctrine' => 'phar://guzzle.phar/vendor/doctrine/common/lib', + 'Monolog' => 'phar://guzzle.phar/vendor/monolog/monolog/src' +)); +$classLoader->register(); + +__HALT_COMPILER(); diff --git a/src/bb-vendor/guzzle/guzzle/phing/build.properties.dist b/src/bb-vendor/guzzle/guzzle/phing/build.properties.dist new file mode 100644 index 000000000..c60d3d9cf --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/phing/build.properties.dist @@ -0,0 +1,16 @@ +# you may need to update this if you're working on a fork. +guzzle.remote=git@github.com:guzzle/guzzle.git + +# github credentials -- only used by GitHub API calls to create subtree repos +github.basicauth=username:password +# for the subtree split and testing +github.org=guzzle + +# your git path +cmd.git=git + +# your composer command +cmd.composer=composer + +# test server start +cmd.testserver=node diff --git a/src/bb-vendor/guzzle/guzzle/phing/imports/dependencies.xml b/src/bb-vendor/guzzle/guzzle/phing/imports/dependencies.xml new file mode 100644 index 000000000..e40e037c2 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/phing/imports/dependencies.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + using git at ${cmd.git} + + + + found git at ${cmd.git} + + + + + + + + + + diff --git a/src/bb-vendor/guzzle/guzzle/phing/imports/deploy.xml b/src/bb-vendor/guzzle/guzzle/phing/imports/deploy.xml new file mode 100644 index 000000000..109e5ec4f --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/phing/imports/deploy.xml @@ -0,0 +1,142 @@ + + + + + + + + + + + + On branch ${head} + + + + + + + + + + working directory clean + + + ${git.status} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ChangeLog Match: ${version.changelog} + Guzzle\Common\Version Match: ${version.version} + + + + releasing: phing -Dnew.version=3.0.x -Dhead=master release + -- + + + + + + + + + + + + + + + BEGINNING RELEASE FOR ${new.version} + + + + + + + + + + + + + + + + + + + + + + + + Tip: to create a new release, do: phing -Dnew.version=[TAG] -Dhead=[BRANCH] release + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/bb-vendor/guzzle/guzzle/phing/tasks/ComposerLintTask.php b/src/bb-vendor/guzzle/guzzle/phing/tasks/ComposerLintTask.php new file mode 100644 index 000000000..3b7040982 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/phing/tasks/ComposerLintTask.php @@ -0,0 +1,152 @@ + + * @license http://claylo.mit-license.org/2012/ MIT License + */ + +require_once 'phing/Task.php'; + +class ComposerLintTask extends Task +{ + protected $dir = null; + protected $file = null; + protected $passthru = false; + protected $composer = null; + + /** + * The setter for the dir + * + * @param string $str Directory to crawl recursively for composer files + */ + public function setDir($str) + { + $this->dir = $str; + } + + /** + * The setter for the file + * + * @param string $str Individual file to validate + */ + public function setFile($str) + { + $this->file = $str; + } + + /** + * Whether to use PHP's passthru() function instead of exec() + * + * @param boolean $passthru If passthru shall be used + */ + public function setPassthru($passthru) + { + $this->passthru = (bool) $passthru; + } + + /** + * Composer to execute. If unset, will attempt composer.phar in project + * basedir, and if that fails, will attempt global composer + * installation. + * + * @param string $str Individual file to validate + */ + public function setComposer($str) + { + $this->file = $str; + } + + /** + * The init method: do init steps + */ + public function init() + { + // nothing needed here + } + + /** + * The main entry point + */ + public function main() + { + if ($this->composer === null) { + $this->findComposer(); + } + + $files = array(); + if (!empty($this->file) && file_exists($this->file)) { + $files[] = $this->file; + } + + if (!empty($this->dir)) { + $found = $this->findFiles(); + foreach ($found as $file) { + $files[] = $this->dir . DIRECTORY_SEPARATOR . $file; + } + } + + foreach ($files as $file) { + + $cmd = $this->composer . ' validate ' . $file; + $cmd = escapeshellcmd($cmd); + + if ($this->passthru) { + $retval = null; + passthru($cmd, $retval); + if ($retval == 1) { + throw new BuildException('invalid composer.json'); + } + } else { + $out = array(); + $retval = null; + exec($cmd, $out, $retval); + if ($retval == 1) { + $err = join("\n", $out); + throw new BuildException($err); + } else { + $this->log($out[0]); + } + } + + } + + } + + /** + * Find the composer.json files using Phing's directory scanner + * + * @return array + */ + protected function findFiles() + { + $ds = new DirectoryScanner(); + $ds->setBasedir($this->dir); + $ds->setIncludes(array('**/composer.json')); + $ds->scan(); + return $ds->getIncludedFiles(); + } + + /** + * Find composer installation + * + */ + protected function findComposer() + { + $basedir = $this->project->getBasedir(); + $php = $this->project->getProperty('php.interpreter'); + + if (file_exists($basedir . '/composer.phar')) { + $this->composer = "$php $basedir/composer.phar"; + } else { + $out = array(); + exec('which composer', $out); + if (empty($out)) { + throw new BuildException( + 'Could not determine composer location.' + ); + } + $this->composer = $out[0]; + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/phing/tasks/GuzzlePearPharPackageTask.php b/src/bb-vendor/guzzle/guzzle/phing/tasks/GuzzlePearPharPackageTask.php new file mode 100644 index 000000000..f72a6b5d0 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/phing/tasks/GuzzlePearPharPackageTask.php @@ -0,0 +1,338 @@ + + * @license http://claylo.mit-license.org/2012/ MIT License + */ + +require_once 'phing/Task.php'; +require_once 'PEAR/PackageFileManager2.php'; +require_once 'PEAR/PackageFileManager/File.php'; +require_once 'PEAR/Packager.php'; + +class GuzzlePearPharPackageTask extends Task +{ + private $version; + private $deploy = true; + private $makephar = true; + + private $subpackages = array(); + + public function setVersion($str) + { + $this->version = $str; + } + + public function getVersion() + { + return $this->version; + } + + public function setDeploy($deploy) + { + $this->deploy = (bool) $deploy; + } + + public function getDeploy() + { + return $this->deploy; + } + + public function setMakephar($makephar) + { + $this->makephar = (bool) $makephar; + } + + public function getMakephar() + { + return $this->makephar; + } + + private $basedir; + private $guzzleinfo; + private $changelog_release_date; + private $changelog_notes = '-'; + + public function main() + { + $this->basedir = $this->getProject()->getBasedir(); + + if (!is_dir((string) $this->basedir.'/.subsplit')) { + throw new BuildException('PEAR packaging requires .subsplit directory'); + } + + // main composer file + $composer_file = file_get_contents((string) $this->basedir.'/.subsplit/composer.json'); + $this->guzzleinfo = json_decode($composer_file, true); + + // make sure we have a target + $pearwork = (string) $this->basedir . '/build/pearwork'; + if (!is_dir($pearwork)) { + mkdir($pearwork, 0777, true); + } + $pearlogs = (string) $this->basedir . '/build/artifacts/logs'; + if (!is_dir($pearlogs)) { + mkdir($pearlogs, 0777, true); + } + + $version = $this->getVersion(); + $this->grabChangelog(); + if ($version[0] == '2') { + $this->log('building single PEAR package'); + $this->buildSinglePackage(); + } else { + // $this->log("building PEAR subpackages"); + // $this->createSubPackages(); + // $this->log("building PEAR bundle package"); + $this->buildSinglePackage(); + } + + if ($this->getMakephar()) { + $this->log("building PHAR"); + $this->getProject()->executeTarget('package-phar'); + } + + if ($this->getDeploy()) { + $this->doDeployment(); + } + } + + public function doDeployment() + { + $basedir = (string) $this->basedir; + $this->log('beginning PEAR/PHAR deployment'); + + chdir($basedir . '/build/pearwork'); + if (!is_dir('./channel')) { + mkdir('./channel'); + } + + // Pull the PEAR channel down locally + passthru('aws s3 sync s3://pear.guzzlephp.org ./channel'); + + // add PEAR packages + foreach (scandir('./') as $file) { + if (substr($file, -4) == '.tgz') { + passthru('pirum add ./channel ' . $file); + } + } + + // if we have a new phar, add it + if ($this->getMakephar() && file_exists($basedir . '/build/artifacts/guzzle.phar')) { + rename($basedir . '/build/artifacts/guzzle.phar', './channel/guzzle.phar'); + } + + // Sync up with the S3 bucket + chdir($basedir . '/build/pearwork/channel'); + passthru('aws s3 sync . s3://pear.guzzlephp.org'); + } + + public function buildSinglePackage() + { + $v = $this->getVersion(); + $apiversion = $v[0] . '.0.0'; + + $opts = array( + 'packagedirectory' => (string) $this->basedir . '/.subsplit/src/', + 'filelistgenerator' => 'file', + 'ignore' => array('*composer.json'), + 'baseinstalldir' => '/', + 'packagefile' => 'package.xml' + //'outputdirectory' => (string) $this->basedir . '/build/pearwork/' + ); + $pfm = new PEAR_PackageFileManager2(); + $pfm->setOptions($opts); + $pfm->addRole('md', 'doc'); + $pfm->addRole('pem', 'php'); + $pfm->setPackage('Guzzle'); + $pfm->setSummary("Object-oriented PHP HTTP Client for PHP 5.3+"); + $pfm->setDescription($this->guzzleinfo['description']); + $pfm->setPackageType('php'); + $pfm->setChannel('guzzlephp.org/pear'); + $pfm->setAPIVersion($apiversion); + $pfm->setReleaseVersion($this->getVersion()); + $pfm->setAPIStability('stable'); + $pfm->setReleaseStability('stable'); + $pfm->setNotes($this->changelog_notes); + $pfm->setPackageType('php'); + $pfm->setLicense('MIT', 'http://github.com/guzzle/guzzle/blob/master/LICENSE'); + $pfm->addMaintainer('lead', 'mtdowling', 'Michael Dowling', 'mtdowling@gmail.com', 'yes'); + $pfm->setDate($this->changelog_release_date); + $pfm->generateContents(); + + $phpdep = $this->guzzleinfo['require']['php']; + $phpdep = str_replace('>=', '', $phpdep); + $pfm->setPhpDep($phpdep); + $pfm->addExtensionDep('required', 'curl'); + $pfm->setPearinstallerDep('1.4.6'); + $pfm->addPackageDepWithChannel('required', 'EventDispatcher', 'pear.symfony.com', '2.1.0'); + if (!empty($this->subpackages)) { + foreach ($this->subpackages as $package) { + $pkg = dirname($package); + $pkg = str_replace('/', '_', $pkg); + $pfm->addConflictingPackageDepWithChannel($pkg, 'guzzlephp.org/pear', false, $apiversion); + } + } + + ob_start(); + $startdir = getcwd(); + chdir((string) $this->basedir . '/build/pearwork'); + + echo "DEBUGGING GENERATED PACKAGE FILE\n"; + $result = $pfm->debugPackageFile(); + if ($result) { + $out = $pfm->writePackageFile(); + echo "\n\n\nWRITE PACKAGE FILE RESULT:\n"; + var_dump($out); + // load up package file and build package + $packager = new PEAR_Packager(); + echo "\n\n\nBUILDING PACKAGE FROM PACKAGE FILE:\n"; + $dest_package = $packager->package($opts['packagedirectory'].'package.xml'); + var_dump($dest_package); + } else { + echo "\n\n\nDEBUGGING RESULT:\n"; + var_dump($result); + } + echo "removing package.xml"; + unlink($opts['packagedirectory'].'package.xml'); + $log = ob_get_clean(); + file_put_contents((string) $this->basedir . '/build/artifacts/logs/pear_package.log', $log); + chdir($startdir); + } + + public function createSubPackages() + { + $this->findComponents(); + + foreach ($this->subpackages as $package) { + $baseinstalldir = dirname($package); + $dir = (string) $this->basedir.'/.subsplit/src/' . $baseinstalldir; + $composer_file = file_get_contents((string) $this->basedir.'/.subsplit/src/'. $package); + $package_info = json_decode($composer_file, true); + $this->log('building ' . $package_info['target-dir'] . ' subpackage'); + $this->buildSubPackage($dir, $baseinstalldir, $package_info); + } + } + + public function buildSubPackage($dir, $baseinstalldir, $info) + { + $package = str_replace('/', '_', $baseinstalldir); + $opts = array( + 'packagedirectory' => $dir, + 'filelistgenerator' => 'file', + 'ignore' => array('*composer.json', '*package.xml'), + 'baseinstalldir' => '/' . $info['target-dir'], + 'packagefile' => 'package.xml' + ); + $pfm = new PEAR_PackageFileManager2(); + $pfm->setOptions($opts); + $pfm->setPackage($package); + $pfm->setSummary($info['description']); + $pfm->setDescription($info['description']); + $pfm->setPackageType('php'); + $pfm->setChannel('guzzlephp.org/pear'); + $pfm->setAPIVersion('3.0.0'); + $pfm->setReleaseVersion($this->getVersion()); + $pfm->setAPIStability('stable'); + $pfm->setReleaseStability('stable'); + $pfm->setNotes($this->changelog_notes); + $pfm->setPackageType('php'); + $pfm->setLicense('MIT', 'http://github.com/guzzle/guzzle/blob/master/LICENSE'); + $pfm->addMaintainer('lead', 'mtdowling', 'Michael Dowling', 'mtdowling@gmail.com', 'yes'); + $pfm->setDate($this->changelog_release_date); + $pfm->generateContents(); + + $phpdep = $this->guzzleinfo['require']['php']; + $phpdep = str_replace('>=', '', $phpdep); + $pfm->setPhpDep($phpdep); + $pfm->setPearinstallerDep('1.4.6'); + + foreach ($info['require'] as $type => $version) { + if ($type == 'php') { + continue; + } + if ($type == 'symfony/event-dispatcher') { + $pfm->addPackageDepWithChannel('required', 'EventDispatcher', 'pear.symfony.com', '2.1.0'); + } + if ($type == 'ext-curl') { + $pfm->addExtensionDep('required', 'curl'); + } + if (substr($type, 0, 6) == 'guzzle') { + $gdep = str_replace('/', ' ', $type); + $gdep = ucwords($gdep); + $gdep = str_replace(' ', '_', $gdep); + $pfm->addPackageDepWithChannel('required', $gdep, 'guzzlephp.org/pear', $this->getVersion()); + } + } + + // can't have main Guzzle package AND sub-packages + $pfm->addConflictingPackageDepWithChannel('Guzzle', 'guzzlephp.org/pear', false, $apiversion); + + ob_start(); + $startdir = getcwd(); + chdir((string) $this->basedir . '/build/pearwork'); + + echo "DEBUGGING GENERATED PACKAGE FILE\n"; + $result = $pfm->debugPackageFile(); + if ($result) { + $out = $pfm->writePackageFile(); + echo "\n\n\nWRITE PACKAGE FILE RESULT:\n"; + var_dump($out); + // load up package file and build package + $packager = new PEAR_Packager(); + echo "\n\n\nBUILDING PACKAGE FROM PACKAGE FILE:\n"; + $dest_package = $packager->package($opts['packagedirectory'].'/package.xml'); + var_dump($dest_package); + } else { + echo "\n\n\nDEBUGGING RESULT:\n"; + var_dump($result); + } + echo "removing package.xml"; + unlink($opts['packagedirectory'].'/package.xml'); + $log = ob_get_clean(); + file_put_contents((string) $this->basedir . '/build/artifacts/logs/pear_package_'.$package.'.log', $log); + chdir($startdir); + } + + public function findComponents() + { + $ds = new DirectoryScanner(); + $ds->setBasedir((string) $this->basedir.'/.subsplit/src'); + $ds->setIncludes(array('**/composer.json')); + $ds->scan(); + $files = $ds->getIncludedFiles(); + $this->subpackages = $files; + } + + public function grabChangelog() + { + $cl = file((string) $this->basedir.'/.subsplit/CHANGELOG.md'); + $notes = ''; + $in_version = false; + $release_date = null; + + foreach ($cl as $line) { + $line = trim($line); + if (preg_match('/^\* '.$this->getVersion().' \(([0-9\-]+)\)$/', $line, $matches)) { + $release_date = $matches[1]; + $in_version = true; + continue; + } + if ($in_version && empty($line) && empty($notes)) { + continue; + } + if ($in_version && ! empty($line)) { + $notes .= $line."\n"; + } + if ($in_version && empty($line) && !empty($notes)) { + $in_version = false; + } + } + $this->changelog_release_date = $release_date; + + if (! empty($notes)) { + $this->changelog_notes = $notes; + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/phing/tasks/GuzzleSubSplitTask.php b/src/bb-vendor/guzzle/guzzle/phing/tasks/GuzzleSubSplitTask.php new file mode 100644 index 000000000..5d56a5bd5 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/phing/tasks/GuzzleSubSplitTask.php @@ -0,0 +1,385 @@ + + * @license http://claylo.mit-license.org/2012/ MIT License + */ + +require_once 'phing/tasks/ext/git/GitBaseTask.php'; + +// base - base of tree to split out +// subIndicatorFile - composer.json, package.xml? +class GuzzleSubSplitTask extends GitBaseTask +{ + /** + * What git repository to pull from and publish to + */ + protected $remote = null; + + /** + * Publish for comma-separated heads instead of all heads + */ + protected $heads = null; + + /** + * Publish for comma-separated tags instead of all tags + */ + protected $tags = null; + + /** + * Base of the tree RELATIVE TO .subsplit working dir + */ + protected $base = null; + + /** + * The presence of this file will indicate that the directory it resides + * in is at the top level of a split. + */ + protected $subIndicatorFile = 'composer.json'; + + /** + * Do everything except actually send the update. + */ + protected $dryRun = null; + + /** + * Do not sync any heads. + */ + protected $noHeads = false; + + /** + * Do not sync any tags. + */ + protected $noTags = false; + + /** + * The splits we found in the heads + */ + protected $splits; + + public function setRemote($str) + { + $this->remote = $str; + } + + public function getRemote() + { + return $this->remote; + } + + public function setHeads($str) + { + $this->heads = explode(',', $str); + } + + public function getHeads() + { + return $this->heads; + } + + public function setTags($str) + { + $this->tags = explode(',', $str); + } + + public function getTags() + { + return $this->tags; + } + + public function setBase($str) + { + $this->base = $str; + } + + public function getBase() + { + return $this->base; + } + + public function setSubIndicatorFile($str) + { + $this->subIndicatorFile = $str; + } + + public function getSubIndicatorFile() + { + return $this->subIndicatorFile; + } + + public function setDryRun($bool) + { + $this->dryRun = (bool) $bool; + } + + public function getDryRun() + { + return $this->dryRun; + } + + public function setNoHeads($bool) + { + $this->noHeads = (bool) $bool; + } + + public function getNoHeads() + { + return $this->noHeads; + } + + public function setNoTags($bool) + { + $this->noTags = (bool) $bool; + } + + public function getNoTags() + { + return $this->noTags; + } + + /** + * GitClient from VersionControl_Git + */ + protected $client = null; + + /** + * The main entry point + */ + public function main() + { + $repo = $this->getRepository(); + if (empty($repo)) { + throw new BuildException('"repository" is a required parameter'); + } + + $remote = $this->getRemote(); + if (empty($remote)) { + throw new BuildException('"remote" is a required parameter'); + } + + chdir($repo); + $this->client = $this->getGitClient(false, $repo); + + // initalized yet? + if (!is_dir('.subsplit')) { + $this->subsplitInit(); + } else { + // update + $this->subsplitUpdate(); + } + + // find all splits based on heads requested + $this->findSplits(); + + // check that GitHub has the repos + $this->verifyRepos(); + + // execute the subsplits + $this->publish(); + } + + public function publish() + { + $this->log('DRY RUN ONLY FOR NOW'); + $base = $this->getBase(); + $base = rtrim($base, '/') . '/'; + $org = $this->getOwningTarget()->getProject()->getProperty('github.org'); + + $splits = array(); + + $heads = $this->getHeads(); + foreach ($heads as $head) { + foreach ($this->splits[$head] as $component => $meta) { + $splits[] = $base . $component . ':git@github.com:'. $org.'/'.$meta['repo']; + } + + $cmd = 'git subsplit publish '; + $cmd .= escapeshellarg(implode(' ', $splits)); + + if ($this->getNoHeads()) { + $cmd .= ' --no-heads'; + } else { + $cmd .= ' --heads='.$head; + } + + if ($this->getNoTags()) { + $cmd .= ' --no-tags'; + } else { + if ($this->getTags()) { + $cmd .= ' --tags=' . escapeshellarg(implode(' ', $this->getTags())); + } + } + + passthru($cmd); + } + } + + /** + * Runs `git subsplit update` + */ + public function subsplitUpdate() + { + $repo = $this->getRepository(); + $this->log('git-subsplit update...'); + $cmd = $this->client->getCommand('subsplit'); + $cmd->addArgument('update'); + try { + $cmd->execute(); + } catch (Exception $e) { + throw new BuildException('git subsplit update failed'. $e); + } + chdir($repo . '/.subsplit'); + passthru('php ../composer.phar update --dev'); + chdir($repo); + } + + /** + * Runs `git subsplit init` based on the remote repository. + */ + public function subsplitInit() + { + $remote = $this->getRemote(); + $cmd = $this->client->getCommand('subsplit'); + $this->log('running git-subsplit init ' . $remote); + + $cmd->setArguments(array( + 'init', + $remote + )); + + try { + $output = $cmd->execute(); + } catch (Exception $e) { + throw new BuildException('git subsplit init failed'. $e); + } + $this->log(trim($output), Project::MSG_INFO); + $repo = $this->getRepository(); + chdir($repo . '/.subsplit'); + passthru('php ../composer.phar install --dev'); + chdir($repo); + } + + /** + * Find the composer.json files using Phing's directory scanner + * + * @return array + */ + protected function findSplits() + { + $this->log("checking heads for subsplits"); + $repo = $this->getRepository(); + $base = $this->getBase(); + + $splits = array(); + $heads = $this->getHeads(); + + if (!empty($base)) { + $base = '/' . ltrim($base, '/'); + } else { + $base = '/'; + } + + chdir($repo . '/.subsplit'); + foreach ($heads as $head) { + $splits[$head] = array(); + + // check each head requested *BEFORE* the actual subtree split command gets it + passthru("git checkout '$head'"); + $ds = new DirectoryScanner(); + $ds->setBasedir($repo . '/.subsplit' . $base); + $ds->setIncludes(array('**/'.$this->subIndicatorFile)); + $ds->scan(); + $files = $ds->getIncludedFiles(); + + // Process the files we found + foreach ($files as $file) { + $pkg = file_get_contents($repo . '/.subsplit' . $base .'/'. $file); + $pkg_json = json_decode($pkg, true); + $name = $pkg_json['name']; + $component = str_replace('/composer.json', '', $file); + // keep this for split cmd + $tmpreponame = explode('/', $name); + $reponame = $tmpreponame[1]; + $splits[$head][$component]['repo'] = $reponame; + $nscomponent = str_replace('/', '\\', $component); + $splits[$head][$component]['desc'] = "[READ ONLY] Subtree split of $nscomponent: " . $pkg_json['description']; + } + } + + // go back to how we found it + passthru("git checkout master"); + chdir($repo); + $this->splits = $splits; + } + + /** + * Based on list of repositories we determined we *should* have, talk + * to GitHub and make sure they're all there. + * + */ + protected function verifyRepos() + { + $this->log('verifying GitHub target repos'); + $github_org = $this->getOwningTarget()->getProject()->getProperty('github.org'); + $github_creds = $this->getOwningTarget()->getProject()->getProperty('github.basicauth'); + + if ($github_creds == 'username:password') { + $this->log('Skipping GitHub repo checks. Update github.basicauth in build.properties to verify repos.', 1); + return; + } + + $ch = curl_init('https://api.github.com/orgs/'.$github_org.'/repos?type=all'); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_USERPWD, $github_creds); + // change this when we know we can use our bundled CA bundle! + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + $result = curl_exec($ch); + curl_close($ch); + $repos = json_decode($result, true); + $existing_repos = array(); + + // parse out the repos we found on GitHub + foreach ($repos as $repo) { + $tmpreponame = explode('/', $repo['full_name']); + $reponame = $tmpreponame[1]; + $existing_repos[$reponame] = $repo['description']; + } + + $heads = $this->getHeads(); + foreach ($heads as $head) { + foreach ($this->splits[$head] as $component => $meta) { + + $reponame = $meta['repo']; + + if (!isset($existing_repos[$reponame])) { + $this->log("Creating missing repo $reponame"); + $payload = array( + 'name' => $reponame, + 'description' => $meta['desc'], + 'homepage' => 'http://www.guzzlephp.org/', + 'private' => true, + 'has_issues' => false, + 'has_wiki' => false, + 'has_downloads' => true, + 'auto_init' => false + ); + $ch = curl_init('https://api.github.com/orgs/'.$github_org.'/repos'); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_USERPWD, $github_creds); + curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload)); + // change this when we know we can use our bundled CA bundle! + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + $result = curl_exec($ch); + echo "Response code: ".curl_getinfo($ch, CURLINFO_HTTP_CODE)."\n"; + curl_close($ch); + } else { + $this->log("Repo $reponame exists", 2); + } + } + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/phpunit.xml.dist b/src/bb-vendor/guzzle/guzzle/phpunit.xml.dist new file mode 100644 index 000000000..208fdc08e --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/phpunit.xml.dist @@ -0,0 +1,48 @@ + + + + + + ./tests/Guzzle/Tests + + + + + + + + + + ./src/Guzzle + + ./src/Guzzle + ./src/Guzzle/Common/Exception/GuzzleException.php + ./src/Guzzle/Http/Exception/HttpException.php + ./src/Guzzle/Http/Exception/ServerErrorResponseException.php + ./src/Guzzle/Http/Exception/ClientErrorResponseException.php + ./src/Guzzle/Http/Exception/TooManyRedirectsException.php + ./src/Guzzle/Http/Exception/CouldNotRewindStreamException.php + ./src/Guzzle/Common/Exception/BadMethodCallException.php + ./src/Guzzle/Common/Exception/InvalidArgumentException.php + ./src/Guzzle/Common/Exception/RuntimeException.php + ./src/Guzzle/Common/Exception/UnexpectedValueException.php + ./src/Guzzle/Service/Exception/ClientNotFoundException.php + ./src/Guzzle/Service/Exception/CommandException.php + ./src/Guzzle/Service/Exception/DescriptionBuilderException.php + ./src/Guzzle/Service/Exception/ServiceBuilderException.php + ./src/Guzzle/Service/Exception/ServiceNotFoundException.php + ./src/Guzzle/Service/Exception/ValidationException.php + ./src/Guzzle/Service/Exception/JsonException.php + + + + + diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/AbstractBatchDecorator.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/AbstractBatchDecorator.php new file mode 100644 index 000000000..0625d71c3 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/AbstractBatchDecorator.php @@ -0,0 +1,66 @@ +decoratedBatch = $decoratedBatch; + } + + /** + * Allow decorators to implement custom methods + * + * @param string $method Missing method name + * @param array $args Method arguments + * + * @return mixed + * @codeCoverageIgnore + */ + public function __call($method, array $args) + { + return call_user_func_array(array($this->decoratedBatch, $method), $args); + } + + public function add($item) + { + $this->decoratedBatch->add($item); + + return $this; + } + + public function flush() + { + return $this->decoratedBatch->flush(); + } + + public function isEmpty() + { + return $this->decoratedBatch->isEmpty(); + } + + /** + * Trace the decorators associated with the batch + * + * @return array + */ + public function getDecorators() + { + $found = array($this); + if (method_exists($this->decoratedBatch, 'getDecorators')) { + $found = array_merge($found, $this->decoratedBatch->getDecorators()); + } + + return $found; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/Batch.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/Batch.php new file mode 100644 index 000000000..4d41c54f8 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/Batch.php @@ -0,0 +1,92 @@ +transferStrategy = $transferStrategy; + $this->divisionStrategy = $divisionStrategy; + $this->queue = new \SplQueue(); + $this->queue->setIteratorMode(\SplQueue::IT_MODE_DELETE); + $this->dividedBatches = array(); + } + + public function add($item) + { + $this->queue->enqueue($item); + + return $this; + } + + public function flush() + { + $this->createBatches(); + + $items = array(); + foreach ($this->dividedBatches as $batchIndex => $dividedBatch) { + while ($dividedBatch->valid()) { + $batch = $dividedBatch->current(); + $dividedBatch->next(); + try { + $this->transferStrategy->transfer($batch); + $items = array_merge($items, $batch); + } catch (\Exception $e) { + throw new BatchTransferException($batch, $items, $e, $this->transferStrategy, $this->divisionStrategy); + } + } + // Keep the divided batch down to a minimum in case of a later exception + unset($this->dividedBatches[$batchIndex]); + } + + return $items; + } + + public function isEmpty() + { + return count($this->queue) == 0 && count($this->dividedBatches) == 0; + } + + /** + * Create batches for any queued items + */ + protected function createBatches() + { + if (count($this->queue)) { + if ($batches = $this->divisionStrategy->createBatches($this->queue)) { + // Convert arrays into iterators + if (is_array($batches)) { + $batches = new \ArrayIterator($batches); + } + $this->dividedBatches[] = $batches; + } + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/BatchBuilder.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/BatchBuilder.php new file mode 100644 index 000000000..ea99b4dd0 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/BatchBuilder.php @@ -0,0 +1,199 @@ + 'Guzzle\Batch\BatchRequestTransfer', + 'command' => 'Guzzle\Batch\BatchCommandTransfer' + ); + + /** + * Create a new instance of the BatchBuilder + * + * @return BatchBuilder + */ + public static function factory() + { + return new self(); + } + + /** + * Automatically flush the batch when the size of the queue reaches a certain threshold. Adds {@see FlushingBatch}. + * + * @param $threshold Number of items to allow in the queue before a flush + * + * @return BatchBuilder + */ + public function autoFlushAt($threshold) + { + $this->autoFlush = $threshold; + + return $this; + } + + /** + * Maintain a history of all items that have been transferred using the batch. Adds {@see HistoryBatch}. + * + * @return BatchBuilder + */ + public function keepHistory() + { + $this->history = true; + + return $this; + } + + /** + * Buffer exceptions thrown during transfer so that you can transfer as much as possible, and after a transfer + * completes, inspect each exception that was thrown. Enables the {@see ExceptionBufferingBatch} decorator. + * + * @return BatchBuilder + */ + public function bufferExceptions() + { + $this->exceptionBuffering = true; + + return $this; + } + + /** + * Notify a callable each time a batch flush completes. Enables the {@see NotifyingBatch} decorator. + * + * @param mixed $callable Callable function to notify + * + * @return BatchBuilder + * @throws InvalidArgumentException if the argument is not callable + */ + public function notify($callable) + { + $this->afterFlush = $callable; + + return $this; + } + + /** + * Configures the batch to transfer batches of requests. Associates a {@see \Guzzle\Http\BatchRequestTransfer} + * object as both the transfer and divisor strategy. + * + * @param int $batchSize Batch size for each batch of requests + * + * @return BatchBuilder + */ + public function transferRequests($batchSize = 50) + { + $className = self::$mapping['request']; + $this->transferStrategy = new $className($batchSize); + $this->divisorStrategy = $this->transferStrategy; + + return $this; + } + + /** + * Configures the batch to transfer batches commands. Associates as + * {@see \Guzzle\Service\Command\BatchCommandTransfer} as both the transfer and divisor strategy. + * + * @param int $batchSize Batch size for each batch of commands + * + * @return BatchBuilder + */ + public function transferCommands($batchSize = 50) + { + $className = self::$mapping['command']; + $this->transferStrategy = new $className($batchSize); + $this->divisorStrategy = $this->transferStrategy; + + return $this; + } + + /** + * Specify the strategy used to divide the queue into an array of batches + * + * @param BatchDivisorInterface $divisorStrategy Strategy used to divide a batch queue into batches + * + * @return BatchBuilder + */ + public function createBatchesWith(BatchDivisorInterface $divisorStrategy) + { + $this->divisorStrategy = $divisorStrategy; + + return $this; + } + + /** + * Specify the strategy used to transport the items when flush is called + * + * @param BatchTransferInterface $transferStrategy How items are transferred + * + * @return BatchBuilder + */ + public function transferWith(BatchTransferInterface $transferStrategy) + { + $this->transferStrategy = $transferStrategy; + + return $this; + } + + /** + * Create and return the instantiated batch + * + * @return BatchInterface + * @throws RuntimeException if no transfer strategy has been specified + */ + public function build() + { + if (!$this->transferStrategy) { + throw new RuntimeException('No transfer strategy has been specified'); + } + + if (!$this->divisorStrategy) { + throw new RuntimeException('No divisor strategy has been specified'); + } + + $batch = new Batch($this->transferStrategy, $this->divisorStrategy); + + if ($this->exceptionBuffering) { + $batch = new ExceptionBufferingBatch($batch); + } + + if ($this->afterFlush) { + $batch = new NotifyingBatch($batch, $this->afterFlush); + } + + if ($this->autoFlush) { + $batch = new FlushingBatch($batch, $this->autoFlush); + } + + if ($this->history) { + $batch = new HistoryBatch($batch); + } + + return $batch; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/BatchClosureDivisor.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/BatchClosureDivisor.php new file mode 100644 index 000000000..e0a2d9568 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/BatchClosureDivisor.php @@ -0,0 +1,39 @@ +callable = $callable; + $this->context = $context; + } + + public function createBatches(\SplQueue $queue) + { + return call_user_func($this->callable, $queue, $this->context); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/BatchClosureTransfer.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/BatchClosureTransfer.php new file mode 100644 index 000000000..9cbf1aba4 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/BatchClosureTransfer.php @@ -0,0 +1,40 @@ +callable = $callable; + $this->context = $context; + } + + public function transfer(array $batch) + { + return empty($batch) ? null : call_user_func($this->callable, $batch, $this->context); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/BatchCommandTransfer.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/BatchCommandTransfer.php new file mode 100644 index 000000000..d55ac7d1f --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/BatchCommandTransfer.php @@ -0,0 +1,75 @@ +batchSize = $batchSize; + } + + /** + * Creates batches by grouping commands by their associated client + * {@inheritdoc} + */ + public function createBatches(\SplQueue $queue) + { + $groups = new \SplObjectStorage(); + foreach ($queue as $item) { + if (!$item instanceof CommandInterface) { + throw new InvalidArgumentException('All items must implement Guzzle\Service\Command\CommandInterface'); + } + $client = $item->getClient(); + if (!$groups->contains($client)) { + $groups->attach($client, new \ArrayObject(array($item))); + } else { + $groups[$client]->append($item); + } + } + + $batches = array(); + foreach ($groups as $batch) { + $batches = array_merge($batches, array_chunk($groups[$batch]->getArrayCopy(), $this->batchSize)); + } + + return $batches; + } + + public function transfer(array $batch) + { + if (empty($batch)) { + return; + } + + // Get the client of the first found command + $client = reset($batch)->getClient(); + + // Keep a list of all commands with invalid clients + $invalid = array_filter($batch, function ($command) use ($client) { + return $command->getClient() !== $client; + }); + + if (!empty($invalid)) { + throw new InconsistentClientTransferException($invalid); + } + + $client->execute($batch); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/BatchDivisorInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/BatchDivisorInterface.php new file mode 100644 index 000000000..0214f05f4 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/BatchDivisorInterface.php @@ -0,0 +1,18 @@ +batchSize = $batchSize; + } + + /** + * Creates batches of requests by grouping requests by their associated curl multi object. + * {@inheritdoc} + */ + public function createBatches(\SplQueue $queue) + { + // Create batches by client objects + $groups = new \SplObjectStorage(); + foreach ($queue as $item) { + if (!$item instanceof RequestInterface) { + throw new InvalidArgumentException('All items must implement Guzzle\Http\Message\RequestInterface'); + } + $client = $item->getClient(); + if (!$groups->contains($client)) { + $groups->attach($client, array($item)); + } else { + $current = $groups[$client]; + $current[] = $item; + $groups[$client] = $current; + } + } + + $batches = array(); + foreach ($groups as $batch) { + $batches = array_merge($batches, array_chunk($groups[$batch], $this->batchSize)); + } + + return $batches; + } + + public function transfer(array $batch) + { + if ($batch) { + reset($batch)->getClient()->send($batch); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/BatchSizeDivisor.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/BatchSizeDivisor.php new file mode 100644 index 000000000..67f90a581 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/BatchSizeDivisor.php @@ -0,0 +1,47 @@ +size = $size; + } + + /** + * Set the size of each batch + * + * @param int $size Size of each batch + * + * @return BatchSizeDivisor + */ + public function setSize($size) + { + $this->size = $size; + + return $this; + } + + /** + * Get the size of each batch + * + * @return int + */ + public function getSize() + { + return $this->size; + } + + public function createBatches(\SplQueue $queue) + { + return array_chunk(iterator_to_array($queue, false), $this->size); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/BatchTransferInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/BatchTransferInterface.php new file mode 100644 index 000000000..2e0b60dad --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/BatchTransferInterface.php @@ -0,0 +1,16 @@ +batch = $batch; + $this->transferredItems = $transferredItems; + $this->transferStrategy = $transferStrategy; + $this->divisorStrategy = $divisorStrategy; + parent::__construct( + 'Exception encountered while transferring batch: ' . $exception->getMessage(), + $exception->getCode(), + $exception + ); + } + + /** + * Get the batch that we being sent when the exception occurred + * + * @return array + */ + public function getBatch() + { + return $this->batch; + } + + /** + * Get the items transferred at the point in which the exception was encountered + * + * @return array + */ + public function getTransferredItems() + { + return $this->transferredItems; + } + + /** + * Get the transfer strategy + * + * @return TransferStrategy + */ + public function getTransferStrategy() + { + return $this->transferStrategy; + } + + /** + * Get the divisor strategy + * + * @return DivisorStrategy + */ + public function getDivisorStrategy() + { + return $this->divisorStrategy; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/ExceptionBufferingBatch.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/ExceptionBufferingBatch.php new file mode 100644 index 000000000..d7a892885 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/ExceptionBufferingBatch.php @@ -0,0 +1,50 @@ +decoratedBatch->isEmpty()) { + try { + $transferredItems = $this->decoratedBatch->flush(); + } catch (BatchTransferException $e) { + $this->exceptions[] = $e; + $transferredItems = $e->getTransferredItems(); + } + $items = array_merge($items, $transferredItems); + } + + return $items; + } + + /** + * Get the buffered exceptions + * + * @return array Array of BatchTransferException objects + */ + public function getExceptions() + { + return $this->exceptions; + } + + /** + * Clear the buffered exceptions + */ + public function clearExceptions() + { + $this->exceptions = array(); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/FlushingBatch.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/FlushingBatch.php new file mode 100644 index 000000000..367b68427 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/FlushingBatch.php @@ -0,0 +1,60 @@ +threshold = $threshold; + parent::__construct($decoratedBatch); + } + + /** + * Set the auto-flush threshold + * + * @param int $threshold The auto-flush threshold + * + * @return FlushingBatch + */ + public function setThreshold($threshold) + { + $this->threshold = $threshold; + + return $this; + } + + /** + * Get the auto-flush threshold + * + * @return int + */ + public function getThreshold() + { + return $this->threshold; + } + + public function add($item) + { + $this->decoratedBatch->add($item); + if (++$this->currentTotal >= $this->threshold) { + $this->currentTotal = 0; + $this->decoratedBatch->flush(); + } + + return $this; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/HistoryBatch.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/HistoryBatch.php new file mode 100644 index 000000000..e345fdc34 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/HistoryBatch.php @@ -0,0 +1,39 @@ +history[] = $item; + $this->decoratedBatch->add($item); + + return $this; + } + + /** + * Get the batch history + * + * @return array + */ + public function getHistory() + { + return $this->history; + } + + /** + * Clear the batch history + */ + public function clearHistory() + { + $this->history = array(); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/NotifyingBatch.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/NotifyingBatch.php new file mode 100644 index 000000000..96d04daa8 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/NotifyingBatch.php @@ -0,0 +1,38 @@ +callable = $callable; + parent::__construct($decoratedBatch); + } + + public function flush() + { + $items = $this->decoratedBatch->flush(); + call_user_func($this->callable, $items); + + return $items; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/composer.json b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/composer.json new file mode 100644 index 000000000..12404d381 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Batch/composer.json @@ -0,0 +1,31 @@ +{ + "name": "guzzle/batch", + "description": "Guzzle batch component for batching requests, commands, or custom transfers", + "homepage": "http://guzzlephp.org/", + "keywords": ["batch", "HTTP", "REST", "guzzle"], + "license": "MIT", + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "require": { + "php": ">=5.3.2", + "guzzle/common": "self.version" + }, + "autoload": { + "psr-0": { "Guzzle\\Batch": "" } + }, + "suggest": { + "guzzle/http": "self.version", + "guzzle/service": "self.version" + }, + "target-dir": "Guzzle/Batch", + "extra": { + "branch-alias": { + "dev-master": "3.7-dev" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Cache/AbstractCacheAdapter.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Cache/AbstractCacheAdapter.php new file mode 100644 index 000000000..a5c527167 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Cache/AbstractCacheAdapter.php @@ -0,0 +1,21 @@ +cache; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Cache/CacheAdapterFactory.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Cache/CacheAdapterFactory.php new file mode 100644 index 000000000..94e623463 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Cache/CacheAdapterFactory.php @@ -0,0 +1,117 @@ +newInstanceArgs($args); + } + } catch (\Exception $e) { + throw new RuntimeException($e->getMessage(), $e->getCode(), $e); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Cache/CacheAdapterInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Cache/CacheAdapterInterface.php new file mode 100644 index 000000000..970c9e228 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Cache/CacheAdapterInterface.php @@ -0,0 +1,55 @@ +callables = $callables; + } + + public function contains($id, array $options = null) + { + return call_user_func($this->callables['contains'], $id, $options); + } + + public function delete($id, array $options = null) + { + return call_user_func($this->callables['delete'], $id, $options); + } + + public function fetch($id, array $options = null) + { + return call_user_func($this->callables['fetch'], $id, $options); + } + + public function save($id, $data, $lifeTime = false, array $options = null) + { + return call_user_func($this->callables['save'], $id, $data, $lifeTime, $options); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Cache/DoctrineCacheAdapter.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Cache/DoctrineCacheAdapter.php new file mode 100644 index 000000000..e1aaf9f81 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Cache/DoctrineCacheAdapter.php @@ -0,0 +1,41 @@ +cache = $cache; + } + + public function contains($id, array $options = null) + { + return $this->cache->contains($id); + } + + public function delete($id, array $options = null) + { + return $this->cache->delete($id); + } + + public function fetch($id, array $options = null) + { + return $this->cache->fetch($id); + } + + public function save($id, $data, $lifeTime = false, array $options = null) + { + return $this->cache->save($id, $data, $lifeTime !== false ? $lifeTime : 0); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Cache/NullCacheAdapter.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Cache/NullCacheAdapter.php new file mode 100644 index 000000000..68bd4af97 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Cache/NullCacheAdapter.php @@ -0,0 +1,31 @@ +cache = $cache; + } + + public function contains($id, array $options = null) + { + return $this->cache->test($id); + } + + public function delete($id, array $options = null) + { + return $this->cache->remove($id); + } + + public function fetch($id, array $options = null) + { + return $this->cache->load($id); + } + + public function save($id, $data, $lifeTime = false, array $options = null) + { + return $this->cache->save($data, $id, array(), $lifeTime); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Cache/Zf2CacheAdapter.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Cache/Zf2CacheAdapter.php new file mode 100644 index 000000000..1fc18a555 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Cache/Zf2CacheAdapter.php @@ -0,0 +1,41 @@ +cache = $cache; + } + + public function contains($id, array $options = null) + { + return $this->cache->hasItem($id); + } + + public function delete($id, array $options = null) + { + return $this->cache->removeItem($id); + } + + public function fetch($id, array $options = null) + { + return $this->cache->getItem($id); + } + + public function save($id, $data, $lifeTime = false, array $options = null) + { + return $this->cache->setItem($id, $data); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Cache/composer.json b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Cache/composer.json new file mode 100644 index 000000000..a5d999bd6 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Cache/composer.json @@ -0,0 +1,27 @@ +{ + "name": "guzzle/cache", + "description": "Guzzle cache adapter component", + "homepage": "http://guzzlephp.org/", + "keywords": ["cache", "adapter", "zf", "doctrine", "guzzle"], + "license": "MIT", + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "require": { + "php": ">=5.3.2", + "guzzle/common": "self.version" + }, + "autoload": { + "psr-0": { "Guzzle\\Cache": "" } + }, + "target-dir": "Guzzle/Cache", + "extra": { + "branch-alias": { + "dev-master": "3.7-dev" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Common/AbstractHasDispatcher.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Common/AbstractHasDispatcher.php new file mode 100644 index 000000000..d1e842b1c --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Common/AbstractHasDispatcher.php @@ -0,0 +1,49 @@ +eventDispatcher = $eventDispatcher; + + return $this; + } + + public function getEventDispatcher() + { + if (!$this->eventDispatcher) { + $this->eventDispatcher = new EventDispatcher(); + } + + return $this->eventDispatcher; + } + + public function dispatch($eventName, array $context = array()) + { + return $this->getEventDispatcher()->dispatch($eventName, new Event($context)); + } + + public function addSubscriber(EventSubscriberInterface $subscriber) + { + $this->getEventDispatcher()->addSubscriber($subscriber); + + return $this; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Common/Collection.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Common/Collection.php new file mode 100644 index 000000000..5cb1535d0 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Common/Collection.php @@ -0,0 +1,403 @@ +data = $data; + } + + /** + * Create a new collection from an array, validate the keys, and add default values where missing + * + * @param array $config Configuration values to apply. + * @param array $defaults Default parameters + * @param array $required Required parameter names + * + * @return self + * @throws InvalidArgumentException if a parameter is missing + */ + public static function fromConfig(array $config = array(), array $defaults = array(), array $required = array()) + { + $data = $config + $defaults; + + if ($missing = array_diff($required, array_keys($data))) { + throw new InvalidArgumentException('Config is missing the following keys: ' . implode(', ', $missing)); + } + + return new self($data); + } + + public function count() + { + return count($this->data); + } + + public function getIterator() + { + return new \ArrayIterator($this->data); + } + + public function toArray() + { + return $this->data; + } + + /** + * Removes all key value pairs + * + * @return Collection + */ + public function clear() + { + $this->data = array(); + + return $this; + } + + /** + * Get all or a subset of matching key value pairs + * + * @param array $keys Pass an array of keys to retrieve only a subset of key value pairs + * + * @return array Returns an array of all matching key value pairs + */ + public function getAll(array $keys = null) + { + return $keys ? array_intersect_key($this->data, array_flip($keys)) : $this->data; + } + + /** + * Get a specific key value. + * + * @param string $key Key to retrieve. + * + * @return mixed|null Value of the key or NULL + */ + public function get($key) + { + return isset($this->data[$key]) ? $this->data[$key] : null; + } + + /** + * Set a key value pair + * + * @param string $key Key to set + * @param mixed $value Value to set + * + * @return Collection Returns a reference to the object + */ + public function set($key, $value) + { + $this->data[$key] = $value; + + return $this; + } + + /** + * Add a value to a key. If a key of the same name has already been added, the key value will be converted into an + * array and the new value will be pushed to the end of the array. + * + * @param string $key Key to add + * @param mixed $value Value to add to the key + * + * @return Collection Returns a reference to the object. + */ + public function add($key, $value) + { + if (!array_key_exists($key, $this->data)) { + $this->data[$key] = $value; + } elseif (is_array($this->data[$key])) { + $this->data[$key][] = $value; + } else { + $this->data[$key] = array($this->data[$key], $value); + } + + return $this; + } + + /** + * Remove a specific key value pair + * + * @param string $key A key to remove + * + * @return Collection + */ + public function remove($key) + { + unset($this->data[$key]); + + return $this; + } + + /** + * Get all keys in the collection + * + * @return array + */ + public function getKeys() + { + return array_keys($this->data); + } + + /** + * Returns whether or not the specified key is present. + * + * @param string $key The key for which to check the existence. + * + * @return bool + */ + public function hasKey($key) + { + return array_key_exists($key, $this->data); + } + + /** + * Case insensitive search the keys in the collection + * + * @param string $key Key to search for + * + * @return bool|string Returns false if not found, otherwise returns the key + */ + public function keySearch($key) + { + foreach (array_keys($this->data) as $k) { + if (!strcasecmp($k, $key)) { + return $k; + } + } + + return false; + } + + /** + * Checks if any keys contains a certain value + * + * @param string $value Value to search for + * + * @return mixed Returns the key if the value was found FALSE if the value was not found. + */ + public function hasValue($value) + { + return array_search($value, $this->data); + } + + /** + * Replace the data of the object with the value of an array + * + * @param array $data Associative array of data + * + * @return Collection Returns a reference to the object + */ + public function replace(array $data) + { + $this->data = $data; + + return $this; + } + + /** + * Add and merge in a Collection or array of key value pair data. + * + * @param Collection|array $data Associative array of key value pair data + * + * @return Collection Returns a reference to the object. + */ + public function merge($data) + { + foreach ($data as $key => $value) { + $this->add($key, $value); + } + + return $this; + } + + /** + * Over write key value pairs in this collection with all of the data from an array or collection. + * + * @param array|\Traversable $data Values to override over this config + * + * @return self + */ + public function overwriteWith($data) + { + if (is_array($data)) { + $this->data = $data + $this->data; + } elseif ($data instanceof Collection) { + $this->data = $data->toArray() + $this->data; + } else { + foreach ($data as $key => $value) { + $this->data[$key] = $value; + } + } + + return $this; + } + + /** + * Returns a Collection containing all the elements of the collection after applying the callback function to each + * one. The Closure should accept three parameters: (string) $key, (string) $value, (array) $context and return a + * modified value + * + * @param \Closure $closure Closure to apply + * @param array $context Context to pass to the closure + * @param bool $static Set to TRUE to use the same class as the return rather than returning a Collection + * + * @return Collection + */ + public function map(\Closure $closure, array $context = array(), $static = true) + { + $collection = $static ? new static() : new self(); + foreach ($this as $key => $value) { + $collection->add($key, $closure($key, $value, $context)); + } + + return $collection; + } + + /** + * Iterates over each key value pair in the collection passing them to the Closure. If the Closure function returns + * true, the current value from input is returned into the result Collection. The Closure must accept three + * parameters: (string) $key, (string) $value and return Boolean TRUE or FALSE for each value. + * + * @param \Closure $closure Closure evaluation function + * @param bool $static Set to TRUE to use the same class as the return rather than returning a Collection + * + * @return Collection + */ + public function filter(\Closure $closure, $static = true) + { + $collection = ($static) ? new static() : new self(); + foreach ($this->data as $key => $value) { + if ($closure($key, $value)) { + $collection->add($key, $value); + } + } + + return $collection; + } + + public function offsetExists($offset) + { + return isset($this->data[$offset]); + } + + public function offsetGet($offset) + { + return isset($this->data[$offset]) ? $this->data[$offset] : null; + } + + public function offsetSet($offset, $value) + { + $this->data[$offset] = $value; + } + + public function offsetUnset($offset) + { + unset($this->data[$offset]); + } + + /** + * Set a value into a nested array key. Keys will be created as needed to set the value. + * + * @param string $path Path to set + * @param mixed $value Value to set at the key + * + * @return self + * @throws RuntimeException when trying to setPath using a nested path that travels through a scalar value + */ + public function setPath($path, $value) + { + $current =& $this->data; + $queue = explode('/', $path); + while (null !== ($key = array_shift($queue))) { + if (!is_array($current)) { + throw new RuntimeException("Trying to setPath {$path}, but {$key} is set and is not an array"); + } elseif (!$queue) { + $current[$key] = $value; + } elseif (isset($current[$key])) { + $current =& $current[$key]; + } else { + $current[$key] = array(); + $current =& $current[$key]; + } + } + + return $this; + } + + /** + * Gets a value from the collection using an array path (e.g. foo/baz/bar would retrieve bar from two nested arrays) + * Allows for wildcard searches which recursively combine matches up to the level at which the wildcard occurs. This + * can be useful for accepting any key of a sub-array and combining matching keys from each diverging path. + * + * @param string $path Path to traverse and retrieve a value from + * @param string $separator Character used to add depth to the search + * @param mixed $data Optional data to descend into (used when wildcards are encountered) + * + * @return mixed|null + */ + public function getPath($path, $separator = '/', $data = null) + { + if ($data === null) { + $data =& $this->data; + } + + $path = is_array($path) ? $path : explode($separator, $path); + while (null !== ($part = array_shift($path))) { + if (!is_array($data)) { + return null; + } elseif (isset($data[$part])) { + $data =& $data[$part]; + } elseif ($part != '*') { + return null; + } else { + // Perform a wildcard search by diverging and merging paths + $result = array(); + foreach ($data as $value) { + if (!$path) { + $result = array_merge_recursive($result, (array) $value); + } elseif (null !== ($test = $this->getPath($path, $separator, $value))) { + $result = array_merge_recursive($result, (array) $test); + } + } + return $result; + } + } + + return $data; + } + + /** + * Inject configuration settings into an input string + * + * @param string $input Input to inject + * + * @return string + * @deprecated + */ + public function inject($input) + { + Version::warn(__METHOD__ . ' is deprecated'); + $replace = array(); + foreach ($this->data as $key => $val) { + $replace['{' . $key . '}'] = $val; + } + + return strtr($input, $replace); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Common/Event.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Common/Event.php new file mode 100644 index 000000000..fad76a9b8 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Common/Event.php @@ -0,0 +1,52 @@ +context = $context; + } + + public function getIterator() + { + return new \ArrayIterator($this->context); + } + + public function offsetGet($offset) + { + return isset($this->context[$offset]) ? $this->context[$offset] : null; + } + + public function offsetSet($offset, $value) + { + $this->context[$offset] = $value; + } + + public function offsetExists($offset) + { + return isset($this->context[$offset]); + } + + public function offsetUnset($offset) + { + unset($this->context[$offset]); + } + + public function toArray() + { + return $this->context; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Common/Exception/BadMethodCallException.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Common/Exception/BadMethodCallException.php new file mode 100644 index 000000000..08d1c7256 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Common/Exception/BadMethodCallException.php @@ -0,0 +1,5 @@ +shortMessage = $message; + } + + /** + * Set all of the exceptions + * + * @param array $exceptions Array of exceptions + * + * @return self + */ + public function setExceptions(array $exceptions) + { + $this->exceptions = array(); + foreach ($exceptions as $exception) { + $this->add($exception); + } + + return $this; + } + + /** + * Add exceptions to the collection + * + * @param ExceptionCollection|\Exception $e Exception to add + * + * @return ExceptionCollection; + */ + public function add($e) + { + $this->exceptions[] = $e; + if ($this->message) { + $this->message .= "\n"; + } + + $this->message .= $this->getExceptionMessage($e, 0); + + return $this; + } + + /** + * Get the total number of request exceptions + * + * @return int + */ + public function count() + { + return count($this->exceptions); + } + + /** + * Allows array-like iteration over the request exceptions + * + * @return \ArrayIterator + */ + public function getIterator() + { + return new \ArrayIterator($this->exceptions); + } + + /** + * Get the first exception in the collection + * + * @return \Exception + */ + public function getFirst() + { + return $this->exceptions ? $this->exceptions[0] : null; + } + + private function getExceptionMessage(\Exception $e, $depth = 0) + { + static $sp = ' '; + $prefix = $depth ? str_repeat($sp, $depth) : ''; + $message = "{$prefix}(" . get_class($e) . ') ' . $e->getFile() . ' line ' . $e->getLine() . "\n"; + + if ($e instanceof self) { + if ($e->shortMessage) { + $message .= "\n{$prefix}{$sp}" . str_replace("\n", "\n{$prefix}{$sp}", $e->shortMessage) . "\n"; + } + foreach ($e as $ee) { + $message .= "\n" . $this->getExceptionMessage($ee, $depth + 1); + } + } else { + $message .= "\n{$prefix}{$sp}" . str_replace("\n", "\n{$prefix}{$sp}", $e->getMessage()) . "\n"; + $message .= "\n{$prefix}{$sp}" . str_replace("\n", "\n{$prefix}{$sp}", $e->getTraceAsString()) . "\n"; + } + + return str_replace(getcwd(), '.', $message); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Common/Exception/GuzzleException.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Common/Exception/GuzzleException.php new file mode 100644 index 000000000..458e6f2ea --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Common/Exception/GuzzleException.php @@ -0,0 +1,8 @@ +=5.3.2", + "symfony/event-dispatcher": ">=2.1" + }, + "autoload": { + "psr-0": { "Guzzle\\Common": "" } + }, + "target-dir": "Guzzle/Common", + "extra": { + "branch-alias": { + "dev-master": "3.7-dev" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/AbstractEntityBodyDecorator.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/AbstractEntityBodyDecorator.php new file mode 100644 index 000000000..5005a887c --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/AbstractEntityBodyDecorator.php @@ -0,0 +1,221 @@ +body = $body; + } + + public function __toString() + { + return (string) $this->body; + } + + /** + * Allow decorators to implement custom methods + * + * @param string $method Missing method name + * @param array $args Method arguments + * + * @return mixed + */ + public function __call($method, array $args) + { + return call_user_func_array(array($this->body, $method), $args); + } + + public function close() + { + return $this->body->close(); + } + + public function setRewindFunction($callable) + { + $this->body->setRewindFunction($callable); + + return $this; + } + + public function rewind() + { + return $this->body->rewind(); + } + + public function compress($filter = 'zlib.deflate') + { + return $this->body->compress($filter); + } + + public function uncompress($filter = 'zlib.inflate') + { + return $this->body->uncompress($filter); + } + + public function getContentLength() + { + return $this->getSize(); + } + + public function getContentType() + { + return $this->body->getContentType(); + } + + public function getContentMd5($rawOutput = false, $base64Encode = false) + { + $hash = Stream::getHash($this, 'md5', $rawOutput); + + return $hash && $base64Encode ? base64_encode($hash) : $hash; + } + + public function getContentEncoding() + { + return $this->body->getContentEncoding(); + } + + public function getMetaData($key = null) + { + return $this->body->getMetaData($key); + } + + public function getStream() + { + return $this->body->getStream(); + } + + public function setStream($stream, $size = 0) + { + $this->body->setStream($stream, $size); + + return $this; + } + + public function detachStream() + { + $this->body->detachStream(); + + return $this; + } + + public function getWrapper() + { + return $this->body->getWrapper(); + } + + public function getWrapperData() + { + return $this->body->getWrapperData(); + } + + public function getStreamType() + { + return $this->body->getStreamType(); + } + + public function getUri() + { + return $this->body->getUri(); + } + + public function getSize() + { + return $this->body->getSize(); + } + + public function isReadable() + { + return $this->body->isReadable(); + } + + public function isRepeatable() + { + return $this->isSeekable() && $this->isReadable(); + } + + public function isWritable() + { + return $this->body->isWritable(); + } + + public function isConsumed() + { + return $this->body->isConsumed(); + } + + /** + * Alias of isConsumed() + * {@inheritdoc} + */ + public function feof() + { + return $this->isConsumed(); + } + + public function isLocal() + { + return $this->body->isLocal(); + } + + public function isSeekable() + { + return $this->body->isSeekable(); + } + + public function setSize($size) + { + $this->body->setSize($size); + + return $this; + } + + public function seek($offset, $whence = SEEK_SET) + { + return $this->body->seek($offset, $whence); + } + + public function read($length) + { + return $this->body->read($length); + } + + public function write($string) + { + return $this->body->write($string); + } + + public function readLine($maxLength = null) + { + return $this->body->readLine($maxLength); + } + + public function ftell() + { + return $this->body->ftell(); + } + + public function getCustomData($key) + { + return $this->body->getCustomData($key); + } + + public function setCustomData($key, $value) + { + $this->body->setCustomData($key, $value); + + return $this; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/CachingEntityBody.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/CachingEntityBody.php new file mode 100644 index 000000000..c65c13650 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/CachingEntityBody.php @@ -0,0 +1,229 @@ +remoteStream = $body; + $this->body = new EntityBody(fopen('php://temp', 'r+')); + } + + /** + * Will give the contents of the buffer followed by the exhausted remote stream. + * + * Warning: Loads the entire stream into memory + * + * @return string + */ + public function __toString() + { + $pos = $this->ftell(); + $this->rewind(); + + $str = ''; + while (!$this->isConsumed()) { + $str .= $this->read(16384); + } + + $this->seek($pos); + + return $str; + } + + public function getSize() + { + return max($this->body->getSize(), $this->remoteStream->getSize()); + } + + /** + * {@inheritdoc} + * @throws RuntimeException When seeking with SEEK_END or when seeking past the total size of the buffer stream + */ + public function seek($offset, $whence = SEEK_SET) + { + if ($whence == SEEK_SET) { + $byte = $offset; + } elseif ($whence == SEEK_CUR) { + $byte = $offset + $this->ftell(); + } else { + throw new RuntimeException(__CLASS__ . ' supports only SEEK_SET and SEEK_CUR seek operations'); + } + + // You cannot skip ahead past where you've read from the remote stream + if ($byte > $this->body->getSize()) { + throw new RuntimeException( + "Cannot seek to byte {$byte} when the buffered stream only contains {$this->body->getSize()} bytes" + ); + } + + return $this->body->seek($byte); + } + + public function rewind() + { + return $this->seek(0); + } + + /** + * Does not support custom rewind functions + * + * @throws RuntimeException + */ + public function setRewindFunction($callable) + { + throw new RuntimeException(__CLASS__ . ' does not support custom stream rewind functions'); + } + + public function read($length) + { + // Perform a regular read on any previously read data from the buffer + $data = $this->body->read($length); + $remaining = $length - strlen($data); + + // More data was requested so read from the remote stream + if ($remaining) { + // If data was written to the buffer in a position that would have been filled from the remote stream, + // then we must skip bytes on the remote stream to emulate overwriting bytes from that position. This + // mimics the behavior of other PHP stream wrappers. + $remoteData = $this->remoteStream->read($remaining + $this->skipReadBytes); + + if ($this->skipReadBytes) { + $len = strlen($remoteData); + $remoteData = substr($remoteData, $this->skipReadBytes); + $this->skipReadBytes = max(0, $this->skipReadBytes - $len); + } + + $data .= $remoteData; + $this->body->write($remoteData); + } + + return $data; + } + + public function write($string) + { + // When appending to the end of the currently read stream, you'll want to skip bytes from being read from + // the remote stream to emulate other stream wrappers. Basically replacing bytes of data of a fixed length. + $overflow = (strlen($string) + $this->ftell()) - $this->remoteStream->ftell(); + if ($overflow > 0) { + $this->skipReadBytes += $overflow; + } + + return $this->body->write($string); + } + + /** + * {@inheritdoc} + * @link http://php.net/manual/en/function.fgets.php + */ + public function readLine($maxLength = null) + { + $buffer = ''; + $size = 0; + while (!$this->isConsumed()) { + $byte = $this->read(1); + $buffer .= $byte; + // Break when a new line is found or the max length - 1 is reached + if ($byte == PHP_EOL || ++$size == $maxLength - 1) { + break; + } + } + + return $buffer; + } + + public function isConsumed() + { + return $this->body->isConsumed() && $this->remoteStream->isConsumed(); + } + + /** + * Close both the remote stream and buffer stream + */ + public function close() + { + return $this->remoteStream->close() && $this->body->close(); + } + + public function setStream($stream, $size = 0) + { + $this->remoteStream->setStream($stream, $size); + } + + public function getContentType() + { + return $this->remoteStream->getContentType(); + } + + public function getContentEncoding() + { + return $this->remoteStream->getContentEncoding(); + } + + public function getMetaData($key = null) + { + return $this->remoteStream->getMetaData($key); + } + + public function getStream() + { + return $this->remoteStream->getStream(); + } + + public function getWrapper() + { + return $this->remoteStream->getWrapper(); + } + + public function getWrapperData() + { + return $this->remoteStream->getWrapperData(); + } + + public function getStreamType() + { + return $this->remoteStream->getStreamType(); + } + + public function getUri() + { + return $this->remoteStream->getUri(); + } + + /** + * Always retrieve custom data from the remote stream + * {@inheritdoc} + */ + public function getCustomData($key) + { + return $this->remoteStream->getCustomData($key); + } + + /** + * Always set custom data on the remote stream + * {@inheritdoc} + */ + public function setCustomData($key, $value) + { + $this->remoteStream->setCustomData($key, $value); + + return $this; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Client.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Client.php new file mode 100644 index 000000000..3d7298dcd --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Client.php @@ -0,0 +1,524 @@ +setConfig($config ?: new Collection()); + $this->initSsl(); + $this->setBaseUrl($baseUrl); + $this->defaultHeaders = new Collection(); + $this->setRequestFactory(RequestFactory::getInstance()); + $this->userAgent = $this->getDefaultUserAgent(); + if (!$this->config[self::DISABLE_REDIRECTS]) { + $this->addSubscriber(new RedirectPlugin()); + } + } + + final public function setConfig($config) + { + if ($config instanceof Collection) { + $this->config = $config; + } elseif (is_array($config)) { + $this->config = new Collection($config); + } else { + throw new InvalidArgumentException('Config must be an array or Collection'); + } + + return $this; + } + + final public function getConfig($key = false) + { + return $key ? $this->config[$key] : $this->config; + } + + /** + * Set a default request option on the client that will be used as a default for each request + * + * @param string $keyOrPath request.options key (e.g. allow_redirects) or path to a nested key (e.g. headers/foo) + * @param mixed $value Value to set + * + * @return $this + */ + public function setDefaultOption($keyOrPath, $value) + { + $keyOrPath = self::REQUEST_OPTIONS . '/' . $keyOrPath; + $this->config->setPath($keyOrPath, $value); + + return $this; + } + + /** + * Retrieve a default request option from the client + * + * @param string $keyOrPath request.options key (e.g. allow_redirects) or path to a nested key (e.g. headers/foo) + * + * @return mixed|null + */ + public function getDefaultOption($keyOrPath) + { + $keyOrPath = self::REQUEST_OPTIONS . '/' . $keyOrPath; + + return $this->config->getPath($keyOrPath); + } + + final public function setSslVerification($certificateAuthority = true, $verifyPeer = true, $verifyHost = 2) + { + $opts = $this->config[self::CURL_OPTIONS] ?: array(); + + if ($certificateAuthority === true) { + // use bundled CA bundle, set secure defaults + $opts[CURLOPT_CAINFO] = __DIR__ . '/Resources/cacert.pem'; + $opts[CURLOPT_SSL_VERIFYPEER] = true; + $opts[CURLOPT_SSL_VERIFYHOST] = 2; + } elseif ($certificateAuthority === false) { + unset($opts[CURLOPT_CAINFO]); + $opts[CURLOPT_SSL_VERIFYPEER] = false; + $opts[CURLOPT_SSL_VERIFYHOST] = 0; + } elseif ($verifyPeer !== true && $verifyPeer !== false && $verifyPeer !== 1 && $verifyPeer !== 0) { + throw new InvalidArgumentException('verifyPeer must be 1, 0 or boolean'); + } elseif ($verifyHost !== 0 && $verifyHost !== 1 && $verifyHost !== 2) { + throw new InvalidArgumentException('verifyHost must be 0, 1 or 2'); + } else { + $opts[CURLOPT_SSL_VERIFYPEER] = $verifyPeer; + $opts[CURLOPT_SSL_VERIFYHOST] = $verifyHost; + if (is_file($certificateAuthority)) { + unset($opts[CURLOPT_CAPATH]); + $opts[CURLOPT_CAINFO] = $certificateAuthority; + } elseif (is_dir($certificateAuthority)) { + unset($opts[CURLOPT_CAINFO]); + $opts[CURLOPT_CAPATH] = $certificateAuthority; + } else { + throw new RuntimeException( + 'Invalid option passed to ' . self::SSL_CERT_AUTHORITY . ': ' . $certificateAuthority + ); + } + } + + $this->config->set(self::CURL_OPTIONS, $opts); + + return $this; + } + + public function createRequest($method = 'GET', $uri = null, $headers = null, $body = null, array $options = array()) + { + if (!$uri) { + $url = $this->getBaseUrl(); + } else { + if (!is_array($uri)) { + $templateVars = null; + } else { + list($uri, $templateVars) = $uri; + } + if (strpos($uri, '://')) { + // Use absolute URLs as-is + $url = $this->expandTemplate($uri, $templateVars); + } else { + $url = Url::factory($this->getBaseUrl())->combine($this->expandTemplate($uri, $templateVars)); + } + } + + // If default headers are provided, then merge them under any explicitly provided headers for the request + if (count($this->defaultHeaders)) { + if (!$headers) { + $headers = $this->defaultHeaders->toArray(); + } elseif (is_array($headers)) { + $headers += $this->defaultHeaders->toArray(); + } elseif ($headers instanceof Collection) { + $headers = $headers->toArray() + $this->defaultHeaders->toArray(); + } + } + + return $this->prepareRequest($this->requestFactory->create($method, (string) $url, $headers, $body), $options); + } + + public function getBaseUrl($expand = true) + { + return $expand ? $this->expandTemplate($this->baseUrl) : $this->baseUrl; + } + + public function setBaseUrl($url) + { + $this->baseUrl = $url; + + return $this; + } + + public function setUserAgent($userAgent, $includeDefault = false) + { + if ($includeDefault) { + $userAgent .= ' ' . $this->getDefaultUserAgent(); + } + $this->userAgent = $userAgent; + + return $this; + } + + /** + * Get the default User-Agent string to use with Guzzle + * + * @return string + */ + public function getDefaultUserAgent() + { + return 'Guzzle/' . Version::VERSION + . ' curl/' . CurlVersion::getInstance()->get('version') + . ' PHP/' . PHP_VERSION; + } + + public function get($uri = null, $headers = null, $options = array()) + { + // BC compat: $options can be a string, resource, etc to specify where the response body is downloaded + return is_array($options) + ? $this->createRequest('GET', $uri, $headers, null, $options) + : $this->createRequest('GET', $uri, $headers, $options); + } + + public function head($uri = null, $headers = null, array $options = array()) + { + return $this->createRequest('HEAD', $uri, $headers, null, $options); + } + + public function delete($uri = null, $headers = null, $body = null, array $options = array()) + { + return $this->createRequest('DELETE', $uri, $headers, $body, $options); + } + + public function put($uri = null, $headers = null, $body = null, array $options = array()) + { + return $this->createRequest('PUT', $uri, $headers, $body, $options); + } + + public function patch($uri = null, $headers = null, $body = null, array $options = array()) + { + return $this->createRequest('PATCH', $uri, $headers, $body, $options); + } + + public function post($uri = null, $headers = null, $postBody = null, array $options = array()) + { + return $this->createRequest('POST', $uri, $headers, $postBody, $options); + } + + public function options($uri = null, array $options = array()) + { + return $this->createRequest('OPTIONS', $uri, $options); + } + + public function send($requests) + { + if (!($requests instanceof RequestInterface)) { + return $this->sendMultiple($requests); + } + + try { + /** @var $requests RequestInterface */ + $this->getCurlMulti()->add($requests)->send(); + return $requests->getResponse(); + } catch (ExceptionCollection $e) { + throw $e->getFirst(); + } + } + + /** + * Set a curl multi object to be used internally by the client for transferring requests. + * + * @param CurlMultiInterface $curlMulti Multi object + * + * @return self + */ + public function setCurlMulti(CurlMultiInterface $curlMulti) + { + $this->curlMulti = $curlMulti; + + return $this; + } + + /** + * @return CurlMultiInterface|CurlMultiProxy + */ + public function getCurlMulti() + { + if (!$this->curlMulti) { + $this->curlMulti = new CurlMultiProxy( + self::MAX_HANDLES, + $this->getConfig('select_timeout') ?: self::DEFAULT_SELECT_TIMEOUT + ); + } + + return $this->curlMulti; + } + + public function setRequestFactory(RequestFactoryInterface $factory) + { + $this->requestFactory = $factory; + + return $this; + } + + /** + * Set the URI template expander to use with the client + * + * @param UriTemplateInterface $uriTemplate URI template expander + * + * @return self + */ + public function setUriTemplate(UriTemplateInterface $uriTemplate) + { + $this->uriTemplate = $uriTemplate; + + return $this; + } + + /** + * Expand a URI template while merging client config settings into the template variables + * + * @param string $template Template to expand + * @param array $variables Variables to inject + * + * @return string + */ + protected function expandTemplate($template, array $variables = null) + { + $expansionVars = $this->getConfig()->toArray(); + if ($variables) { + $expansionVars = $variables + $expansionVars; + } + + return $this->getUriTemplate()->expand($template, $expansionVars); + } + + /** + * Get the URI template expander used by the client + * + * @return UriTemplateInterface + */ + protected function getUriTemplate() + { + if (!$this->uriTemplate) { + $this->uriTemplate = ParserRegistry::getInstance()->getParser('uri_template'); + } + + return $this->uriTemplate; + } + + /** + * Send multiple requests in parallel + * + * @param array $requests Array of RequestInterface objects + * + * @return array Returns an array of Response objects + */ + protected function sendMultiple(array $requests) + { + $curlMulti = $this->getCurlMulti(); + foreach ($requests as $request) { + $curlMulti->add($request); + } + $curlMulti->send(); + + /** @var $request RequestInterface */ + $result = array(); + foreach ($requests as $request) { + $result[] = $request->getResponse(); + } + + return $result; + } + + /** + * Prepare a request to be sent from the Client by adding client specific behaviors and properties to the request. + * + * @param RequestInterface $request Request to prepare for the client + * @param array $options Options to apply to the request + * + * @return RequestInterface + */ + protected function prepareRequest(RequestInterface $request, array $options = array()) + { + $request->setClient($this)->setEventDispatcher(clone $this->getEventDispatcher()); + + if ($curl = $this->config[self::CURL_OPTIONS]) { + $request->getCurlOptions()->overwriteWith(CurlHandle::parseCurlConfig($curl)); + } + + if ($params = $this->config[self::REQUEST_PARAMS]) { + Version::warn('request.params is deprecated. Use request.options to add default request options.'); + $request->getParams()->overwriteWith($params); + } + + if ($this->userAgent && !$request->hasHeader('User-Agent')) { + $request->setHeader('User-Agent', $this->userAgent); + } + + if ($defaults = $this->config[self::REQUEST_OPTIONS]) { + $this->requestFactory->applyOptions($request, $defaults, RequestFactoryInterface::OPTIONS_AS_DEFAULTS); + } + + if ($options) { + $this->requestFactory->applyOptions($request, $options); + } + + $this->dispatch('client.create_request', array('client' => $this, 'request' => $request)); + + return $request; + } + + /** + * Initializes SSL settings + */ + protected function initSsl() + { + $authority = $this->config[self::SSL_CERT_AUTHORITY]; + + if ($authority === 'system') { + return; + } + + if ($authority === null) { + $authority = true; + } + + if ($authority === true && substr(__FILE__, 0, 7) == 'phar://') { + $authority = self::extractPharCacert(__DIR__ . '/Resources/cacert.pem'); + } + + $this->setSslVerification($authority); + } + + /** + * @deprecated + */ + public function getDefaultHeaders() + { + Version::warn(__METHOD__ . ' is deprecated. Use the request.options array to retrieve default request options'); + return $this->defaultHeaders; + } + + /** + * @deprecated + */ + public function setDefaultHeaders($headers) + { + Version::warn(__METHOD__ . ' is deprecated. Use the request.options array to specify default request options'); + if ($headers instanceof Collection) { + $this->defaultHeaders = $headers; + } elseif (is_array($headers)) { + $this->defaultHeaders = new Collection($headers); + } else { + throw new InvalidArgumentException('Headers must be an array or Collection'); + } + + return $this; + } + + /** + * @deprecated + */ + public function preparePharCacert($md5Check = true) + { + return sys_get_temp_dir() . '/guzzle-cacert.pem'; + } + + /** + * Copies the phar cacert from a phar into the temp directory. + * + * @param string $pharCacertPath Path to the phar cacert. For example: + * 'phar://aws.phar/Guzzle/Http/Resources/cacert.pem' + * + * @return string Returns the path to the extracted cacert file. + * @throws \RuntimeException Throws if the phar cacert cannot be found or + * the file cannot be copied to the temp dir. + */ + public static function extractPharCacert($pharCacertPath) + { + // Copy the cacert.pem file from the phar if it is not in the temp + // folder. + $certFile = sys_get_temp_dir() . '/guzzle-cacert.pem'; + + if (!file_exists($pharCacertPath)) { + throw new \RuntimeException("Could not find $pharCacertPath"); + } + + if (!file_exists($certFile) || + filesize($certFile) != filesize($pharCacertPath) + ) { + if (!copy($pharCacertPath, $certFile)) { + throw new \RuntimeException( + "Could not copy {$pharCacertPath} to {$certFile}: " + . var_export(error_get_last(), true) + ); + } + } + + return $certFile; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/ClientInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/ClientInterface.php new file mode 100644 index 000000000..10e4de2ab --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/ClientInterface.php @@ -0,0 +1,223 @@ +getCurlOptions(); + $mediator = new RequestMediator($request, $requestCurlOptions->get('emit_io')); + $tempContentLength = null; + $method = $request->getMethod(); + $bodyAsString = $requestCurlOptions->get(self::BODY_AS_STRING); + + // Prepare url + $url = (string)$request->getUrl(); + if(($pos = strpos($url, '#')) !== false ){ + // strip fragment from url + $url = substr($url, 0, $pos); + } + + // Array of default cURL options. + $curlOptions = array( + CURLOPT_URL => $url, + CURLOPT_CONNECTTIMEOUT => 150, + CURLOPT_RETURNTRANSFER => false, + CURLOPT_HEADER => false, + CURLOPT_PORT => $request->getPort(), + CURLOPT_HTTPHEADER => array(), + CURLOPT_WRITEFUNCTION => array($mediator, 'writeResponseBody'), + CURLOPT_HEADERFUNCTION => array($mediator, 'receiveResponseHeader'), + CURLOPT_HTTP_VERSION => $request->getProtocolVersion() === '1.0' + ? CURL_HTTP_VERSION_1_0 : CURL_HTTP_VERSION_1_1, + // Verifies the authenticity of the peer's certificate + CURLOPT_SSL_VERIFYPEER => 1, + // Certificate must indicate that the server is the server to which you meant to connect + CURLOPT_SSL_VERIFYHOST => 2 + ); + + if (defined('CURLOPT_PROTOCOLS')) { + // Allow only HTTP and HTTPS protocols + $curlOptions[CURLOPT_PROTOCOLS] = CURLPROTO_HTTP | CURLPROTO_HTTPS; + } + + // Add CURLOPT_ENCODING if Accept-Encoding header is provided + if ($acceptEncodingHeader = $request->getHeader('Accept-Encoding')) { + $curlOptions[CURLOPT_ENCODING] = (string) $acceptEncodingHeader; + // Let cURL set the Accept-Encoding header, prevents duplicate values + $request->removeHeader('Accept-Encoding'); + } + + // Enable curl debug information if the 'debug' param was set + if ($requestCurlOptions->get('debug')) { + $curlOptions[CURLOPT_STDERR] = fopen('php://temp', 'r+'); + // @codeCoverageIgnoreStart + if (false === $curlOptions[CURLOPT_STDERR]) { + throw new RuntimeException('Unable to create a stream for CURLOPT_STDERR'); + } + // @codeCoverageIgnoreEnd + $curlOptions[CURLOPT_VERBOSE] = true; + } + + // Specify settings according to the HTTP method + if ($method == 'GET') { + $curlOptions[CURLOPT_HTTPGET] = true; + } elseif ($method == 'HEAD') { + $curlOptions[CURLOPT_NOBODY] = true; + // HEAD requests do not use a write function + unset($curlOptions[CURLOPT_WRITEFUNCTION]); + } elseif (!($request instanceof EntityEnclosingRequest)) { + $curlOptions[CURLOPT_CUSTOMREQUEST] = $method; + } else { + + $curlOptions[CURLOPT_CUSTOMREQUEST] = $method; + + // Handle sending raw bodies in a request + if ($request->getBody()) { + // You can send the body as a string using curl's CURLOPT_POSTFIELDS + if ($bodyAsString) { + $curlOptions[CURLOPT_POSTFIELDS] = (string) $request->getBody(); + // Allow curl to add the Content-Length for us to account for the times when + // POST redirects are followed by GET requests + if ($tempContentLength = $request->getHeader('Content-Length')) { + $tempContentLength = (int) (string) $tempContentLength; + } + // Remove the curl generated Content-Type header if none was set manually + if (!$request->hasHeader('Content-Type')) { + $curlOptions[CURLOPT_HTTPHEADER][] = 'Content-Type:'; + } + } else { + $curlOptions[CURLOPT_UPLOAD] = true; + // Let cURL handle setting the Content-Length header + if ($tempContentLength = $request->getHeader('Content-Length')) { + $tempContentLength = (int) (string) $tempContentLength; + $curlOptions[CURLOPT_INFILESIZE] = $tempContentLength; + } + // Add a callback for curl to read data to send with the request only if a body was specified + $curlOptions[CURLOPT_READFUNCTION] = array($mediator, 'readRequestBody'); + // Attempt to seek to the start of the stream + $request->getBody()->seek(0); + } + + } else { + + // Special handling for POST specific fields and files + $postFields = false; + if (count($request->getPostFiles())) { + $postFields = $request->getPostFields()->useUrlEncoding(false)->urlEncode(); + foreach ($request->getPostFiles() as $key => $data) { + $prefixKeys = count($data) > 1; + foreach ($data as $index => $file) { + // Allow multiple files in the same key + $fieldKey = $prefixKeys ? "{$key}[{$index}]" : $key; + $postFields[$fieldKey] = $file->getCurlValue(); + } + } + } elseif (count($request->getPostFields())) { + $postFields = (string) $request->getPostFields()->useUrlEncoding(true); + } + + if ($postFields !== false) { + if ($method == 'POST') { + unset($curlOptions[CURLOPT_CUSTOMREQUEST]); + $curlOptions[CURLOPT_POST] = true; + } + $curlOptions[CURLOPT_POSTFIELDS] = $postFields; + $request->removeHeader('Content-Length'); + } + } + + // If the Expect header is not present, prevent curl from adding it + if (!$request->hasHeader('Expect')) { + $curlOptions[CURLOPT_HTTPHEADER][] = 'Expect:'; + } + } + + // If a Content-Length header was specified but we want to allow curl to set one for us + if (null !== $tempContentLength) { + $request->removeHeader('Content-Length'); + } + + // Set custom cURL options + foreach ($requestCurlOptions->toArray() as $key => $value) { + if (is_numeric($key)) { + $curlOptions[$key] = $value; + } + } + + // Do not set an Accept header by default + if (!isset($curlOptions[CURLOPT_ENCODING])) { + $curlOptions[CURLOPT_HTTPHEADER][] = 'Accept:'; + } + + // Add any custom headers to the request. Empty headers will cause curl to not send the header at all. + foreach ($request->getHeaderLines() as $line) { + $curlOptions[CURLOPT_HTTPHEADER][] = $line; + } + + // Add the content-length header back if it was temporarily removed + if (null !== $tempContentLength) { + $request->setHeader('Content-Length', $tempContentLength); + } + + // Apply the options to a new cURL handle. + $handle = curl_init(); + + // Enable the progress function if the 'progress' param was set + if ($requestCurlOptions->get('progress')) { + // Wrap the function in a function that provides the curl handle to the mediator's progress function + // Using this rather than injecting the handle into the mediator prevents a circular reference + $curlOptions[CURLOPT_PROGRESSFUNCTION] = function () use ($mediator, $handle) { + $args = func_get_args(); + $args[] = $handle; + + // PHP 5.5 pushed the handle onto the start of the args + if (is_resource($args[0])) { + array_shift($args); + } + + call_user_func_array(array($mediator, 'progress'), $args); + }; + $curlOptions[CURLOPT_NOPROGRESS] = false; + } + + curl_setopt_array($handle, $curlOptions); + + return new static($handle, $curlOptions); + } + + /** + * Construct a new CurlHandle object that wraps a cURL handle + * + * @param resource $handle Configured cURL handle resource + * @param Collection|array $options Curl options to use with the handle + * + * @throws InvalidArgumentException + */ + public function __construct($handle, $options) + { + if (!is_resource($handle)) { + throw new InvalidArgumentException('Invalid handle provided'); + } + if (is_array($options)) { + $this->options = new Collection($options); + } elseif ($options instanceof Collection) { + $this->options = $options; + } else { + throw new InvalidArgumentException('Expected array or Collection'); + } + $this->handle = $handle; + } + + /** + * Destructor + */ + public function __destruct() + { + $this->close(); + } + + /** + * Close the curl handle + */ + public function close() + { + if (is_resource($this->handle)) { + curl_close($this->handle); + } + $this->handle = null; + } + + /** + * Check if the handle is available and still OK + * + * @return bool + */ + public function isAvailable() + { + return is_resource($this->handle); + } + + /** + * Get the last error that occurred on the cURL handle + * + * @return string + */ + public function getError() + { + return $this->isAvailable() ? curl_error($this->handle) : ''; + } + + /** + * Get the last error number that occurred on the cURL handle + * + * @return int + */ + public function getErrorNo() + { + if ($this->errorNo) { + return $this->errorNo; + } + + return $this->isAvailable() ? curl_errno($this->handle) : CURLE_OK; + } + + /** + * Set the curl error number + * + * @param int $error Error number to set + * + * @return CurlHandle + */ + public function setErrorNo($error) + { + $this->errorNo = $error; + + return $this; + } + + /** + * Get cURL curl_getinfo data + * + * @param int $option Option to retrieve. Pass null to retrieve all data as an array. + * + * @return array|mixed + */ + public function getInfo($option = null) + { + if (!is_resource($this->handle)) { + return null; + } + + if (null !== $option) { + return curl_getinfo($this->handle, $option) ?: null; + } + + return curl_getinfo($this->handle) ?: array(); + } + + /** + * Get the stderr output + * + * @param bool $asResource Set to TRUE to get an fopen resource + * + * @return string|resource|null + */ + public function getStderr($asResource = false) + { + $stderr = $this->getOptions()->get(CURLOPT_STDERR); + if (!$stderr) { + return null; + } + + if ($asResource) { + return $stderr; + } + + fseek($stderr, 0); + $e = stream_get_contents($stderr); + fseek($stderr, 0, SEEK_END); + + return $e; + } + + /** + * Get the URL that this handle is connecting to + * + * @return Url + */ + public function getUrl() + { + return Url::factory($this->options->get(CURLOPT_URL)); + } + + /** + * Get the wrapped curl handle + * + * @return resource|null Returns the cURL handle or null if it was closed + */ + public function getHandle() + { + return $this->isAvailable() ? $this->handle : null; + } + + /** + * Get the cURL setopt options of the handle. Changing values in the return object will have no effect on the curl + * handle after it is created. + * + * @return Collection + */ + public function getOptions() + { + return $this->options; + } + + /** + * Update a request based on the log messages of the CurlHandle + * + * @param RequestInterface $request Request to update + */ + public function updateRequestFromTransfer(RequestInterface $request) + { + if (!$request->getResponse()) { + return; + } + + // Update the transfer stats of the response + $request->getResponse()->setInfo($this->getInfo()); + + if (!$log = $this->getStderr(true)) { + return; + } + + // Parse the cURL stderr output for outgoing requests + $headers = ''; + fseek($log, 0); + while (($line = fgets($log)) !== false) { + if ($line && $line[0] == '>') { + $headers = substr(trim($line), 2) . "\r\n"; + while (($line = fgets($log)) !== false) { + if ($line[0] == '*' || $line[0] == '<') { + break; + } else { + $headers .= trim($line) . "\r\n"; + } + } + } + } + + // Add request headers to the request exactly as they were sent + if ($headers) { + $parsed = ParserRegistry::getInstance()->getParser('message')->parseRequest($headers); + if (!empty($parsed['headers'])) { + $request->setHeaders(array()); + foreach ($parsed['headers'] as $name => $value) { + $request->setHeader($name, $value); + } + } + if (!empty($parsed['version'])) { + $request->setProtocolVersion($parsed['version']); + } + } + } + + /** + * Parse the config and replace curl.* configurators into the constant based values so it can be used elsewhere + * + * @param array|Collection $config The configuration we want to parse + * + * @return array + */ + public static function parseCurlConfig($config) + { + $curlOptions = array(); + foreach ($config as $key => $value) { + if (is_string($key) && defined($key)) { + // Convert constants represented as string to constant int values + $key = constant($key); + } + if (is_string($value) && defined($value)) { + $value = constant($value); + } + $curlOptions[$key] = $value; + } + + return $curlOptions; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlMulti.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlMulti.php new file mode 100644 index 000000000..9e4e63722 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlMulti.php @@ -0,0 +1,423 @@ + array('CURLM_BAD_HANDLE', 'The passed-in handle is not a valid CURLM handle.'), + CURLM_BAD_EASY_HANDLE => array('CURLM_BAD_EASY_HANDLE', "An easy handle was not good/valid. It could mean that it isn't an easy handle at all, or possibly that the handle already is in used by this or another multi handle."), + CURLM_OUT_OF_MEMORY => array('CURLM_OUT_OF_MEMORY', 'You are doomed.'), + CURLM_INTERNAL_ERROR => array('CURLM_INTERNAL_ERROR', 'This can only be returned if libcurl bugs. Please report it to us!') + ); + + /** @var float */ + protected $selectTimeout; + + public function __construct($selectTimeout = 1.0) + { + $this->selectTimeout = $selectTimeout; + $this->multiHandle = curl_multi_init(); + // @codeCoverageIgnoreStart + if ($this->multiHandle === false) { + throw new CurlException('Unable to create multi handle'); + } + // @codeCoverageIgnoreEnd + $this->reset(); + } + + public function __destruct() + { + if (is_resource($this->multiHandle)) { + curl_multi_close($this->multiHandle); + } + } + + public function add(RequestInterface $request) + { + $this->requests[] = $request; + // If requests are currently transferring and this is async, then the + // request must be prepared now as the send() method is not called. + $this->beforeSend($request); + $this->dispatch(self::ADD_REQUEST, array('request' => $request)); + + return $this; + } + + public function all() + { + return $this->requests; + } + + public function remove(RequestInterface $request) + { + $this->removeHandle($request); + if (($index = array_search($request, $this->requests, true)) !== false) { + $request = $this->requests[$index]; + unset($this->requests[$index]); + $this->requests = array_values($this->requests); + $this->dispatch(self::REMOVE_REQUEST, array('request' => $request)); + return true; + } + + return false; + } + + public function reset($hard = false) + { + // Remove each request + if ($this->requests) { + foreach ($this->requests as $request) { + $this->remove($request); + } + } + + $this->handles = new \SplObjectStorage(); + $this->requests = $this->resourceHash = $this->exceptions = $this->successful = array(); + } + + public function send() + { + $this->perform(); + $exceptions = $this->exceptions; + $successful = $this->successful; + $this->reset(); + + if ($exceptions) { + $this->throwMultiException($exceptions, $successful); + } + } + + public function count() + { + return count($this->requests); + } + + /** + * Build and throw a MultiTransferException + * + * @param array $exceptions Exceptions encountered + * @param array $successful Successful requests + * @throws MultiTransferException + */ + protected function throwMultiException(array $exceptions, array $successful) + { + $multiException = new MultiTransferException('Errors during multi transfer'); + + while ($e = array_shift($exceptions)) { + $multiException->addFailedRequestWithException($e['request'], $e['exception']); + } + + // Add successful requests + foreach ($successful as $request) { + if (!$multiException->containsRequest($request)) { + $multiException->addSuccessfulRequest($request); + } + } + + throw $multiException; + } + + /** + * Prepare for sending + * + * @param RequestInterface $request Request to prepare + * @throws \Exception on error preparing the request + */ + protected function beforeSend(RequestInterface $request) + { + try { + $state = $request->setState(RequestInterface::STATE_TRANSFER); + if ($state == RequestInterface::STATE_TRANSFER) { + $this->addHandle($request); + } else { + // Requests might decide they don't need to be sent just before + // transfer (e.g. CachePlugin) + $this->remove($request); + if ($state == RequestInterface::STATE_COMPLETE) { + $this->successful[] = $request; + } + } + } catch (\Exception $e) { + // Queue the exception to be thrown when sent + $this->removeErroredRequest($request, $e); + } + } + + private function addHandle(RequestInterface $request) + { + $handle = $this->createCurlHandle($request)->getHandle(); + $this->checkCurlResult( + curl_multi_add_handle($this->multiHandle, $handle) + ); + } + + /** + * Create a curl handle for a request + * + * @param RequestInterface $request Request + * + * @return CurlHandle + */ + protected function createCurlHandle(RequestInterface $request) + { + $wrapper = CurlHandle::factory($request); + $this->handles[$request] = $wrapper; + $this->resourceHash[(int) $wrapper->getHandle()] = $request; + + return $wrapper; + } + + /** + * Get the data from the multi handle + */ + protected function perform() + { + $event = new Event(array('curl_multi' => $this)); + + while ($this->requests) { + // Notify each request as polling + $blocking = $total = 0; + foreach ($this->requests as $request) { + ++$total; + $event['request'] = $request; + $request->getEventDispatcher()->dispatch(self::POLLING_REQUEST, $event); + // The blocking variable just has to be non-falsey to block the loop + if ($request->getParams()->hasKey(self::BLOCKING)) { + ++$blocking; + } + } + if ($blocking == $total) { + // Sleep to prevent eating CPU because no requests are actually pending a select call + usleep(500); + } else { + $this->executeHandles(); + } + } + } + + /** + * Execute and select curl handles + */ + private function executeHandles() + { + // The first curl_multi_select often times out no matter what, but is usually required for fast transfers + $selectTimeout = 0.001; + $active = false; + do { + while (($mrc = curl_multi_exec($this->multiHandle, $active)) == CURLM_CALL_MULTI_PERFORM); + $this->checkCurlResult($mrc); + $this->processMessages(); + if ($active && curl_multi_select($this->multiHandle, $selectTimeout) === -1) { + // Perform a usleep if a select returns -1: https://bugs.php.net/bug.php?id=61141 + usleep(150); + } + $selectTimeout = $this->selectTimeout; + } while ($active); + } + + /** + * Process any received curl multi messages + */ + private function processMessages() + { + while ($done = curl_multi_info_read($this->multiHandle)) { + $request = $this->resourceHash[(int) $done['handle']]; + try { + $this->processResponse($request, $this->handles[$request], $done); + $this->successful[] = $request; + } catch (\Exception $e) { + $this->removeErroredRequest($request, $e); + } + } + } + + /** + * Remove a request that encountered an exception + * + * @param RequestInterface $request Request to remove + * @param \Exception $e Exception encountered + */ + protected function removeErroredRequest(RequestInterface $request, \Exception $e = null) + { + $this->exceptions[] = array('request' => $request, 'exception' => $e); + $this->remove($request); + $this->dispatch(self::MULTI_EXCEPTION, array('exception' => $e, 'all_exceptions' => $this->exceptions)); + } + + /** + * Check for errors and fix headers of a request based on a curl response + * + * @param RequestInterface $request Request to process + * @param CurlHandle $handle Curl handle object + * @param array $curl Array returned from curl_multi_info_read + * + * @throws CurlException on Curl error + */ + protected function processResponse(RequestInterface $request, CurlHandle $handle, array $curl) + { + // Set the transfer stats on the response + $handle->updateRequestFromTransfer($request); + // Check if a cURL exception occurred, and if so, notify things + $curlException = $this->isCurlException($request, $handle, $curl); + + // Always remove completed curl handles. They can be added back again + // via events if needed (e.g. ExponentialBackoffPlugin) + $this->removeHandle($request); + + if (!$curlException) { + if ($this->validateResponseWasSet($request)) { + $state = $request->setState( + RequestInterface::STATE_COMPLETE, + array('handle' => $handle) + ); + // Only remove the request if it wasn't resent as a result of + // the state change + if ($state != RequestInterface::STATE_TRANSFER) { + $this->remove($request); + } + } + return; + } + + // Set the state of the request to an error + $state = $request->setState(RequestInterface::STATE_ERROR, array('exception' => $curlException)); + // Allow things to ignore the error if possible + if ($state != RequestInterface::STATE_TRANSFER) { + $this->remove($request); + } + + // The error was not handled, so fail + if ($state == RequestInterface::STATE_ERROR) { + /** @var CurlException $curlException */ + throw $curlException; + } + } + + /** + * Remove a curl handle from the curl multi object + * + * @param RequestInterface $request Request that owns the handle + */ + protected function removeHandle(RequestInterface $request) + { + if (isset($this->handles[$request])) { + $handle = $this->handles[$request]; + curl_multi_remove_handle($this->multiHandle, $handle->getHandle()); + unset($this->handles[$request]); + unset($this->resourceHash[(int) $handle->getHandle()]); + $handle->close(); + } + } + + /** + * Check if a cURL transfer resulted in what should be an exception + * + * @param RequestInterface $request Request to check + * @param CurlHandle $handle Curl handle object + * @param array $curl Array returned from curl_multi_info_read + * + * @return CurlException|bool + */ + private function isCurlException(RequestInterface $request, CurlHandle $handle, array $curl) + { + if (CURLM_OK == $curl['result'] || CURLM_CALL_MULTI_PERFORM == $curl['result']) { + return false; + } + + $handle->setErrorNo($curl['result']); + $e = new CurlException(sprintf('[curl] %s: %s [url] %s', + $handle->getErrorNo(), $handle->getError(), $handle->getUrl())); + $e->setCurlHandle($handle) + ->setRequest($request) + ->setCurlInfo($handle->getInfo()) + ->setError($handle->getError(), $handle->getErrorNo()); + + return $e; + } + + /** + * Throw an exception for a cURL multi response if needed + * + * @param int $code Curl response code + * @throws CurlException + */ + private function checkCurlResult($code) + { + if ($code != CURLM_OK && $code != CURLM_CALL_MULTI_PERFORM) { + throw new CurlException(isset($this->multiErrors[$code]) + ? "cURL error: {$code} ({$this->multiErrors[$code][0]}): cURL message: {$this->multiErrors[$code][1]}" + : 'Unexpected cURL error: ' . $code + ); + } + } + + /** + * @link https://github.com/guzzle/guzzle/issues/710 + */ + private function validateResponseWasSet(RequestInterface $request) + { + if ($request->getResponse()) { + return true; + } + + $body = $request instanceof EntityEnclosingRequestInterface + ? $request->getBody() + : null; + + if (!$body) { + $rex = new RequestException( + 'No response was received for a request with no body. This' + . ' could mean that you are saturating your network.' + ); + $rex->setRequest($request); + $this->removeErroredRequest($request, $rex); + } elseif (!$body->isSeekable() || !$body->seek(0)) { + // Nothing we can do with this. Sorry! + $rex = new RequestException( + 'The connection was unexpectedly closed. The request would' + . ' have been retried, but attempting to rewind the' + . ' request body failed.' + ); + $rex->setRequest($request); + $this->removeErroredRequest($request, $rex); + } else { + $this->remove($request); + // Add the request back to the batch to retry automatically. + $this->requests[] = $request; + $this->addHandle($request); + } + + return false; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlMultiInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlMultiInterface.php new file mode 100644 index 000000000..0ead75735 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlMultiInterface.php @@ -0,0 +1,58 @@ +maxHandles = $maxHandles; + $this->selectTimeout = $selectTimeout; + // You can get some weird "Too many open files" errors when sending a large amount of requests in parallel. + // These two statements autoload classes before a system runs out of file descriptors so that you can get back + // valuable error messages if you run out. + class_exists('Guzzle\Http\Message\Response'); + class_exists('Guzzle\Http\Exception\CurlException'); + } + + public function add(RequestInterface $request) + { + $this->queued[] = $request; + + return $this; + } + + public function all() + { + $requests = $this->queued; + foreach ($this->handles as $handle) { + $requests = array_merge($requests, $handle->all()); + } + + return $requests; + } + + public function remove(RequestInterface $request) + { + foreach ($this->queued as $i => $r) { + if ($request === $r) { + unset($this->queued[$i]); + return true; + } + } + + foreach ($this->handles as $handle) { + if ($handle->remove($request)) { + return true; + } + } + + return false; + } + + public function reset($hard = false) + { + $this->queued = array(); + $this->groups = array(); + foreach ($this->handles as $handle) { + $handle->reset(); + } + if ($hard) { + $this->handles = array(); + } + + return $this; + } + + public function send() + { + if ($this->queued) { + $group = $this->getAvailableHandle(); + // Add this handle to a list of handles than is claimed + $this->groups[] = $group; + while ($request = array_shift($this->queued)) { + $group->add($request); + } + try { + $group->send(); + array_pop($this->groups); + $this->cleanupHandles(); + } catch (\Exception $e) { + // Remove the group and cleanup if an exception was encountered and no more requests in group + if (!$group->count()) { + array_pop($this->groups); + $this->cleanupHandles(); + } + throw $e; + } + } + } + + public function count() + { + return count($this->all()); + } + + /** + * Get an existing available CurlMulti handle or create a new one + * + * @return CurlMulti + */ + protected function getAvailableHandle() + { + // Grab a handle that is not claimed + foreach ($this->handles as $h) { + if (!in_array($h, $this->groups, true)) { + return $h; + } + } + + // All are claimed, so create one + $handle = new CurlMulti($this->selectTimeout); + $handle->setEventDispatcher($this->getEventDispatcher()); + $this->handles[] = $handle; + + return $handle; + } + + /** + * Trims down unused CurlMulti handles to limit the number of open connections + */ + protected function cleanupHandles() + { + if ($diff = max(0, count($this->handles) - $this->maxHandles)) { + for ($i = count($this->handles) - 1; $i > 0 && $diff > 0; $i--) { + if (!count($this->handles[$i])) { + unset($this->handles[$i]); + $diff--; + } + } + $this->handles = array_values($this->handles); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlVersion.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlVersion.php new file mode 100644 index 000000000..c3f99dd25 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Curl/CurlVersion.php @@ -0,0 +1,66 @@ +version) { + $this->version = curl_version(); + } + + return $this->version; + } + + /** + * Get a specific type of curl information + * + * @param string $type Version information to retrieve. This value is one of: + * - version_number: cURL 24 bit version number + * - version: cURL version number, as a string + * - ssl_version_number: OpenSSL 24 bit version number + * - ssl_version: OpenSSL version number, as a string + * - libz_version: zlib version number, as a string + * - host: Information about the host where cURL was built + * - features: A bitmask of the CURL_VERSION_XXX constants + * - protocols: An array of protocols names supported by cURL + * + * @return string|float|bool if the $type is found, and false if not found + */ + public function get($type) + { + $version = $this->getAll(); + + return isset($version[$type]) ? $version[$type] : false; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Curl/RequestMediator.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Curl/RequestMediator.php new file mode 100644 index 000000000..5d1a0cd87 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Curl/RequestMediator.php @@ -0,0 +1,147 @@ +request = $request; + $this->emitIo = $emitIo; + } + + /** + * Receive a response header from curl + * + * @param resource $curl Curl handle + * @param string $header Received header + * + * @return int + */ + public function receiveResponseHeader($curl, $header) + { + static $normalize = array("\r", "\n"); + $length = strlen($header); + $header = str_replace($normalize, '', $header); + + if (strpos($header, 'HTTP/') === 0) { + + $startLine = explode(' ', $header, 3); + $code = $startLine[1]; + $status = isset($startLine[2]) ? $startLine[2] : ''; + + // Only download the body of the response to the specified response + // body when a successful response is received. + if ($code >= 200 && $code < 300) { + $body = $this->request->getResponseBody(); + } else { + $body = EntityBody::factory(); + } + + $response = new Response($code, null, $body); + $response->setStatus($code, $status); + $this->request->startResponse($response); + + $this->request->dispatch('request.receive.status_line', array( + 'request' => $this, + 'line' => $header, + 'status_code' => $code, + 'reason_phrase' => $status + )); + + } elseif ($pos = strpos($header, ':')) { + $this->request->getResponse()->addHeader( + trim(substr($header, 0, $pos)), + trim(substr($header, $pos + 1)) + ); + } + + return $length; + } + + /** + * Received a progress notification + * + * @param int $downloadSize Total download size + * @param int $downloaded Amount of bytes downloaded + * @param int $uploadSize Total upload size + * @param int $uploaded Amount of bytes uploaded + * @param resource $handle CurlHandle object + */ + public function progress($downloadSize, $downloaded, $uploadSize, $uploaded, $handle = null) + { + $this->request->dispatch('curl.callback.progress', array( + 'request' => $this->request, + 'handle' => $handle, + 'download_size' => $downloadSize, + 'downloaded' => $downloaded, + 'upload_size' => $uploadSize, + 'uploaded' => $uploaded + )); + } + + /** + * Write data to the response body of a request + * + * @param resource $curl Curl handle + * @param string $write Data that was received + * + * @return int + */ + public function writeResponseBody($curl, $write) + { + if ($this->emitIo) { + $this->request->dispatch('curl.callback.write', array( + 'request' => $this->request, + 'write' => $write + )); + } + + if ($response = $this->request->getResponse()) { + return $response->getBody()->write($write); + } else { + // Unexpected data received before response headers - abort transfer + return 0; + } + } + + /** + * Read data from the request body and send it to curl + * + * @param resource $ch Curl handle + * @param resource $fd File descriptor + * @param int $length Amount of data to read + * + * @return string + */ + public function readRequestBody($ch, $fd, $length) + { + if (!($body = $this->request->getBody())) { + return ''; + } + + $read = (string) $body->read($length); + if ($this->emitIo) { + $this->request->dispatch('curl.callback.read', array('request' => $this->request, 'read' => $read)); + } + + return $read; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/EntityBody.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/EntityBody.php new file mode 100644 index 000000000..b60d170f0 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/EntityBody.php @@ -0,0 +1,201 @@ +rewindFunction = $callable; + + return $this; + } + + public function rewind() + { + return $this->rewindFunction ? call_user_func($this->rewindFunction, $this) : parent::rewind(); + } + + /** + * Create a new EntityBody from a string + * + * @param string $string String of data + * + * @return EntityBody + */ + public static function fromString($string) + { + $stream = fopen('php://temp', 'r+'); + if ($string !== '') { + fwrite($stream, $string); + rewind($stream); + } + + return new static($stream); + } + + public function compress($filter = 'zlib.deflate') + { + $result = $this->handleCompression($filter); + $this->contentEncoding = $result ? $filter : false; + + return $result; + } + + public function uncompress($filter = 'zlib.inflate') + { + $offsetStart = 0; + + // When inflating gzipped data, the first 10 bytes must be stripped + // if a gzip header is present + if ($filter == 'zlib.inflate') { + // @codeCoverageIgnoreStart + if (!$this->isReadable() || ($this->isConsumed() && !$this->isSeekable())) { + return false; + } + // @codeCoverageIgnoreEnd + if (stream_get_contents($this->stream, 3, 0) === "\x1f\x8b\x08") { + $offsetStart = 10; + } + } + + $this->contentEncoding = false; + + return $this->handleCompression($filter, $offsetStart); + } + + public function getContentLength() + { + return $this->getSize(); + } + + public function getContentType() + { + return $this->getUri() ? Mimetypes::getInstance()->fromFilename($this->getUri()) : null; + } + + public function getContentMd5($rawOutput = false, $base64Encode = false) + { + if ($hash = self::getHash($this, 'md5', $rawOutput)) { + return $hash && $base64Encode ? base64_encode($hash) : $hash; + } else { + return false; + } + } + + /** + * Calculate the MD5 hash of an entity body + * + * @param EntityBodyInterface $body Entity body to calculate the hash for + * @param bool $rawOutput Whether or not to use raw output + * @param bool $base64Encode Whether or not to base64 encode raw output (only if raw output is true) + * + * @return bool|string Returns an MD5 string on success or FALSE on failure + * @deprecated This will be deprecated soon + * @codeCoverageIgnore + */ + public static function calculateMd5(EntityBodyInterface $body, $rawOutput = false, $base64Encode = false) + { + Version::warn(__CLASS__ . ' is deprecated. Use getContentMd5()'); + return $body->getContentMd5($rawOutput, $base64Encode); + } + + public function setStreamFilterContentEncoding($streamFilterContentEncoding) + { + $this->contentEncoding = $streamFilterContentEncoding; + + return $this; + } + + public function getContentEncoding() + { + return strtr($this->contentEncoding, array( + 'zlib.deflate' => 'gzip', + 'bzip2.compress' => 'compress' + )) ?: false; + } + + protected function handleCompression($filter, $offsetStart = 0) + { + // @codeCoverageIgnoreStart + if (!$this->isReadable() || ($this->isConsumed() && !$this->isSeekable())) { + return false; + } + // @codeCoverageIgnoreEnd + + $handle = fopen('php://temp', 'r+'); + $filter = @stream_filter_append($handle, $filter, STREAM_FILTER_WRITE); + if (!$filter) { + return false; + } + + // Seek to the offset start if possible + $this->seek($offsetStart); + while ($data = fread($this->stream, 8096)) { + fwrite($handle, $data); + } + + fclose($this->stream); + $this->stream = $handle; + stream_filter_remove($filter); + $stat = fstat($this->stream); + $this->size = $stat['size']; + $this->rebuildCache(); + $this->seek(0); + + // Remove any existing rewind function as the underlying stream has been replaced + $this->rewindFunction = null; + + return true; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/EntityBodyInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/EntityBodyInterface.php new file mode 100644 index 000000000..e640f5785 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/EntityBodyInterface.php @@ -0,0 +1,73 @@ +isClientError()) { + $label = 'Client error response'; + $class = __NAMESPACE__ . '\\ClientErrorResponseException'; + } elseif ($response->isServerError()) { + $label = 'Server error response'; + $class = __NAMESPACE__ . '\\ServerErrorResponseException'; + } else { + $label = 'Unsuccessful response'; + $class = __CLASS__; + } + + $message = $label . PHP_EOL . implode(PHP_EOL, array( + '[status code] ' . $response->getStatusCode(), + '[reason phrase] ' . $response->getReasonPhrase(), + '[url] ' . $request->getUrl(), + )); + + $e = new $class($message); + $e->setResponse($response); + $e->setRequest($request); + + return $e; + } + + /** + * Set the response that caused the exception + * + * @param Response $response Response to set + */ + public function setResponse(Response $response) + { + $this->response = $response; + } + + /** + * Get the response that caused the exception + * + * @return Response + */ + public function getResponse() + { + return $this->response; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Exception/ClientErrorResponseException.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Exception/ClientErrorResponseException.php new file mode 100644 index 000000000..04d7ddc05 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Exception/ClientErrorResponseException.php @@ -0,0 +1,8 @@ +curlError = $error; + $this->curlErrorNo = $number; + + return $this; + } + + /** + * Set the associated curl handle + * + * @param CurlHandle $handle Curl handle + * + * @return self + */ + public function setCurlHandle(CurlHandle $handle) + { + $this->handle = $handle; + + return $this; + } + + /** + * Get the associated cURL handle + * + * @return CurlHandle|null + */ + public function getCurlHandle() + { + return $this->handle; + } + + /** + * Get the associated cURL error message + * + * @return string|null + */ + public function getError() + { + return $this->curlError; + } + + /** + * Get the associated cURL error number + * + * @return int|null + */ + public function getErrorNo() + { + return $this->curlErrorNo; + } + + /** + * Returns curl information about the transfer + * + * @return array + */ + public function getCurlInfo() + { + return $this->curlInfo; + } + + /** + * Set curl transfer information + * + * @param array $info Array of curl transfer information + * + * @return self + * @link http://php.net/manual/en/function.curl-getinfo.php + */ + public function setCurlInfo(array $info) + { + $this->curlInfo = $info; + + return $this; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Exception/HttpException.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Exception/HttpException.php new file mode 100644 index 000000000..ee87295d3 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Exception/HttpException.php @@ -0,0 +1,10 @@ +successfulRequests, $this->failedRequests); + } + + /** + * Add to the array of successful requests + * + * @param RequestInterface $request Successful request + * + * @return self + */ + public function addSuccessfulRequest(RequestInterface $request) + { + $this->successfulRequests[] = $request; + + return $this; + } + + /** + * Add to the array of failed requests + * + * @param RequestInterface $request Failed request + * + * @return self + */ + public function addFailedRequest(RequestInterface $request) + { + $this->failedRequests[] = $request; + + return $this; + } + + /** + * Add to the array of failed requests and associate with exceptions + * + * @param RequestInterface $request Failed request + * @param \Exception $exception Exception to add and associate with + * + * @return self + */ + public function addFailedRequestWithException(RequestInterface $request, \Exception $exception) + { + $this->add($exception) + ->addFailedRequest($request) + ->exceptionForRequest[spl_object_hash($request)] = $exception; + + return $this; + } + + /** + * Get the Exception that caused the given $request to fail + * + * @param RequestInterface $request Failed command + * + * @return \Exception|null + */ + public function getExceptionForFailedRequest(RequestInterface $request) + { + $oid = spl_object_hash($request); + + return isset($this->exceptionForRequest[$oid]) ? $this->exceptionForRequest[$oid] : null; + } + + /** + * Set all of the successful requests + * + * @param array Array of requests + * + * @return self + */ + public function setSuccessfulRequests(array $requests) + { + $this->successfulRequests = $requests; + + return $this; + } + + /** + * Set all of the failed requests + * + * @param array Array of requests + * + * @return self + */ + public function setFailedRequests(array $requests) + { + $this->failedRequests = $requests; + + return $this; + } + + /** + * Get an array of successful requests sent in the multi transfer + * + * @return array + */ + public function getSuccessfulRequests() + { + return $this->successfulRequests; + } + + /** + * Get an array of failed requests sent in the multi transfer + * + * @return array + */ + public function getFailedRequests() + { + return $this->failedRequests; + } + + /** + * Check if the exception object contains a request + * + * @param RequestInterface $request Request to check + * + * @return bool + */ + public function containsRequest(RequestInterface $request) + { + return in_array($request, $this->failedRequests, true) || in_array($request, $this->successfulRequests, true); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Exception/RequestException.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Exception/RequestException.php new file mode 100644 index 000000000..274df2cb1 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Exception/RequestException.php @@ -0,0 +1,39 @@ +request = $request; + + return $this; + } + + /** + * Get the request that caused the exception + * + * @return RequestInterface + */ + public function getRequest() + { + return $this->request; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Exception/ServerErrorResponseException.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Exception/ServerErrorResponseException.php new file mode 100644 index 000000000..f0f7cfe48 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Exception/ServerErrorResponseException.php @@ -0,0 +1,8 @@ +eventDispatcher = $eventDispatcher; + + return $this; + } + + public function getEventDispatcher() + { + if (!$this->eventDispatcher) { + $this->eventDispatcher = new EventDispatcher(); + } + + return $this->eventDispatcher; + } + + public function dispatch($eventName, array $context = array()) + { + return $this->getEventDispatcher()->dispatch($eventName, new Event($context)); + } + + /** + * {@inheritdoc} + * @codeCoverageIgnore + */ + public function addSubscriber(EventSubscriberInterface $subscriber) + { + $this->getEventDispatcher()->addSubscriber($subscriber); + + return $this; + } + + public function read($length) + { + $event = array( + 'body' => $this, + 'length' => $length, + 'read' => $this->body->read($length) + ); + $this->dispatch('body.read', $event); + + return $event['read']; + } + + public function write($string) + { + $event = array( + 'body' => $this, + 'write' => $string, + 'result' => $this->body->write($string) + ); + $this->dispatch('body.write', $event); + + return $event['result']; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/AbstractMessage.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/AbstractMessage.php new file mode 100644 index 000000000..0d066ffce --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/AbstractMessage.php @@ -0,0 +1,220 @@ +params = new Collection(); + $this->headerFactory = new HeaderFactory(); + $this->headers = new HeaderCollection(); + } + + /** + * Set the header factory to use to create headers + * + * @param HeaderFactoryInterface $factory + * + * @return self + */ + public function setHeaderFactory(HeaderFactoryInterface $factory) + { + $this->headerFactory = $factory; + + return $this; + } + + public function getParams() + { + return $this->params; + } + + public function addHeader($header, $value) + { + if (isset($this->headers[$header])) { + $this->headers[$header]->add($value); + } elseif ($value instanceof HeaderInterface) { + $this->headers[$header] = $value; + } else { + $this->headers[$header] = $this->headerFactory->createHeader($header, $value); + } + + return $this; + } + + public function addHeaders(array $headers) + { + foreach ($headers as $key => $value) { + $this->addHeader($key, $value); + } + + return $this; + } + + public function getHeader($header) + { + return $this->headers[$header]; + } + + public function getHeaders() + { + return $this->headers; + } + + public function getHeaderLines() + { + $headers = array(); + foreach ($this->headers as $value) { + $headers[] = $value->getName() . ': ' . $value; + } + + return $headers; + } + + public function setHeader($header, $value) + { + unset($this->headers[$header]); + $this->addHeader($header, $value); + + return $this; + } + + public function setHeaders(array $headers) + { + $this->headers->clear(); + foreach ($headers as $key => $value) { + $this->addHeader($key, $value); + } + + return $this; + } + + public function hasHeader($header) + { + return isset($this->headers[$header]); + } + + public function removeHeader($header) + { + unset($this->headers[$header]); + + return $this; + } + + /** + * @deprecated Use $message->getHeader()->parseParams() + * @codeCoverageIgnore + */ + public function getTokenizedHeader($header, $token = ';') + { + Version::warn(__METHOD__ . ' is deprecated. Use $message->getHeader()->parseParams()'); + if ($this->hasHeader($header)) { + $data = new Collection(); + foreach ($this->getHeader($header)->parseParams() as $values) { + foreach ($values as $key => $value) { + if ($value === '') { + $data->set($data->count(), $key); + } else { + $data->add($key, $value); + } + } + } + return $data; + } + } + + /** + * @deprecated + * @codeCoverageIgnore + */ + public function setTokenizedHeader($header, $data, $token = ';') + { + Version::warn(__METHOD__ . ' is deprecated.'); + return $this; + } + + /** + * @deprecated + * @codeCoverageIgnore + */ + public function getCacheControlDirective($directive) + { + Version::warn(__METHOD__ . ' is deprecated. Use $message->getHeader(\'Cache-Control\')->getDirective()'); + if (!($header = $this->getHeader('Cache-Control'))) { + return null; + } + + return $header->getDirective($directive); + } + + /** + * @deprecated + * @codeCoverageIgnore + */ + public function hasCacheControlDirective($directive) + { + Version::warn(__METHOD__ . ' is deprecated. Use $message->getHeader(\'Cache-Control\')->hasDirective()'); + if ($header = $this->getHeader('Cache-Control')) { + return $header->hasDirective($directive); + } else { + return false; + } + } + + /** + * @deprecated + * @codeCoverageIgnore + */ + public function addCacheControlDirective($directive, $value = true) + { + Version::warn(__METHOD__ . ' is deprecated. Use $message->getHeader(\'Cache-Control\')->addDirective()'); + if (!($header = $this->getHeader('Cache-Control'))) { + $this->addHeader('Cache-Control', ''); + $header = $this->getHeader('Cache-Control'); + } + + $header->addDirective($directive, $value); + + return $this; + } + + /** + * @deprecated + * @codeCoverageIgnore + */ + public function removeCacheControlDirective($directive) + { + Version::warn(__METHOD__ . ' is deprecated. Use $message->getHeader(\'Cache-Control\')->removeDirective()'); + if ($header = $this->getHeader('Cache-Control')) { + $header->removeDirective($directive); + } + + return $this; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/EntityEnclosingRequest.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/EntityEnclosingRequest.php new file mode 100644 index 000000000..212850a25 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/EntityEnclosingRequest.php @@ -0,0 +1,247 @@ +postFields = new QueryString(); + parent::__construct($method, $url, $headers); + } + + /** + * @return string + */ + public function __toString() + { + // Only attempt to include the POST data if it's only fields + if (count($this->postFields) && empty($this->postFiles)) { + return parent::__toString() . (string) $this->postFields; + } + + return parent::__toString() . $this->body; + } + + public function setState($state, array $context = array()) + { + parent::setState($state, $context); + if ($state == self::STATE_TRANSFER && !$this->body && !count($this->postFields) && !count($this->postFiles)) { + $this->setHeader('Content-Length', 0)->removeHeader('Transfer-Encoding'); + } + + return $this->state; + } + + public function setBody($body, $contentType = null) + { + $this->body = EntityBody::factory($body); + + // Auto detect the Content-Type from the path of the request if possible + if ($contentType === null && !$this->hasHeader('Content-Type')) { + $contentType = $this->body->getContentType(); + } + + if ($contentType) { + $this->setHeader('Content-Type', $contentType); + } + + // Always add the Expect 100-Continue header if the body cannot be rewound. This helps with redirects. + if (!$this->body->isSeekable() && $this->expectCutoff !== false) { + $this->setHeader('Expect', '100-Continue'); + } + + // Set the Content-Length header if it can be determined + $size = $this->body->getContentLength(); + if ($size !== null && $size !== false) { + $this->setHeader('Content-Length', $size); + if ($size > $this->expectCutoff) { + $this->setHeader('Expect', '100-Continue'); + } + } elseif (!$this->hasHeader('Content-Length')) { + if ('1.1' == $this->protocolVersion) { + $this->setHeader('Transfer-Encoding', 'chunked'); + } else { + throw new RequestException( + 'Cannot determine Content-Length and cannot use chunked Transfer-Encoding when using HTTP/1.0' + ); + } + } + + return $this; + } + + public function getBody() + { + return $this->body; + } + + /** + * Set the size that the entity body of the request must exceed before adding the Expect: 100-Continue header. + * + * @param int|bool $size Cutoff in bytes. Set to false to never send the expect header (even with non-seekable data) + * + * @return self + */ + public function setExpectHeaderCutoff($size) + { + $this->expectCutoff = $size; + if ($size === false || !$this->body) { + $this->removeHeader('Expect'); + } elseif ($this->body && $this->body->getSize() && $this->body->getSize() > $size) { + $this->setHeader('Expect', '100-Continue'); + } + + return $this; + } + + public function configureRedirects($strict = false, $maxRedirects = 5) + { + $this->getParams()->set(RedirectPlugin::STRICT_REDIRECTS, $strict); + if ($maxRedirects == 0) { + $this->getParams()->set(RedirectPlugin::DISABLE, true); + } else { + $this->getParams()->set(RedirectPlugin::MAX_REDIRECTS, $maxRedirects); + } + + return $this; + } + + public function getPostField($field) + { + return $this->postFields->get($field); + } + + public function getPostFields() + { + return $this->postFields; + } + + public function setPostField($key, $value) + { + $this->postFields->set($key, $value); + $this->processPostFields(); + + return $this; + } + + public function addPostFields($fields) + { + $this->postFields->merge($fields); + $this->processPostFields(); + + return $this; + } + + public function removePostField($field) + { + $this->postFields->remove($field); + $this->processPostFields(); + + return $this; + } + + public function getPostFiles() + { + return $this->postFiles; + } + + public function getPostFile($fieldName) + { + return isset($this->postFiles[$fieldName]) ? $this->postFiles[$fieldName] : null; + } + + public function removePostFile($fieldName) + { + unset($this->postFiles[$fieldName]); + $this->processPostFields(); + + return $this; + } + + public function addPostFile($field, $filename = null, $contentType = null, $postname = null) + { + $data = null; + + if ($field instanceof PostFileInterface) { + $data = $field; + } elseif (is_array($filename)) { + // Allow multiple values to be set in a single key + foreach ($filename as $file) { + $this->addPostFile($field, $file, $contentType); + } + return $this; + } elseif (!is_string($filename)) { + throw new RequestException('The path to a file must be a string'); + } elseif (!empty($filename)) { + // Adding an empty file will cause cURL to error out + $data = new PostFile($field, $filename, $contentType, $postname); + } + + if ($data) { + if (!isset($this->postFiles[$data->getFieldName()])) { + $this->postFiles[$data->getFieldName()] = array($data); + } else { + $this->postFiles[$data->getFieldName()][] = $data; + } + $this->processPostFields(); + } + + return $this; + } + + public function addPostFiles(array $files) + { + foreach ($files as $key => $file) { + if ($file instanceof PostFileInterface) { + $this->addPostFile($file, null, null, false); + } elseif (is_string($file)) { + // Convert non-associative array keys into 'file' + if (is_numeric($key)) { + $key = 'file'; + } + $this->addPostFile($key, $file, null, false); + } else { + throw new RequestException('File must be a string or instance of PostFileInterface'); + } + } + + return $this; + } + + /** + * Determine what type of request should be sent based on post fields + */ + protected function processPostFields() + { + if (!$this->postFiles) { + $this->removeHeader('Expect')->setHeader('Content-Type', self::URL_ENCODED); + } else { + $this->setHeader('Content-Type', self::MULTIPART); + if ($this->expectCutoff !== false) { + $this->setHeader('Expect', '100-Continue'); + } + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/EntityEnclosingRequestInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/EntityEnclosingRequestInterface.php new file mode 100644 index 000000000..49ad4595d --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/EntityEnclosingRequestInterface.php @@ -0,0 +1,137 @@ + filenames where filename can be a string or PostFileInterface + * + * @return self + */ + public function addPostFiles(array $files); + + /** + * Configure how redirects are handled for the request + * + * @param bool $strict Set to true to follow strict RFC compliance when redirecting POST requests. Most + * browsers with follow a 301-302 redirect for a POST request with a GET request. This is + * the default behavior of Guzzle. Enable strict redirects to redirect these responses + * with a POST rather than a GET request. + * @param int $maxRedirects Specify the maximum number of allowed redirects. Set to 0 to disable redirects. + * + * @return self + */ + public function configureRedirects($strict = false, $maxRedirects = 5); +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header.php new file mode 100644 index 000000000..50597b2a6 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header.php @@ -0,0 +1,182 @@ +header = trim($header); + $this->glue = $glue; + + foreach ((array) $values as $value) { + foreach ((array) $value as $v) { + $this->values[] = $v; + } + } + } + + public function __toString() + { + return implode($this->glue . ' ', $this->toArray()); + } + + public function add($value) + { + $this->values[] = $value; + + return $this; + } + + public function getName() + { + return $this->header; + } + + public function setName($name) + { + $this->header = $name; + + return $this; + } + + public function setGlue($glue) + { + $this->glue = $glue; + + return $this; + } + + public function getGlue() + { + return $this->glue; + } + + /** + * Normalize the header to be a single header with an array of values. + * + * If any values of the header contains the glue string value (e.g. ","), then the value will be exploded into + * multiple entries in the header. + * + * @return self + */ + public function normalize() + { + $values = $this->toArray(); + + for ($i = 0, $total = count($values); $i < $total; $i++) { + if (strpos($values[$i], $this->glue) !== false) { + // Explode on glue when the glue is not inside of a comma + foreach (preg_split('/' . preg_quote($this->glue) . '(?=([^"]*"[^"]*")*[^"]*$)/', $values[$i]) as $v) { + $values[] = trim($v); + } + unset($values[$i]); + } + } + + $this->values = array_values($values); + + return $this; + } + + public function hasValue($searchValue) + { + return in_array($searchValue, $this->toArray()); + } + + public function removeValue($searchValue) + { + $this->values = array_values(array_filter($this->values, function ($value) use ($searchValue) { + return $value != $searchValue; + })); + + return $this; + } + + public function toArray() + { + return $this->values; + } + + public function count() + { + return count($this->toArray()); + } + + public function getIterator() + { + return new \ArrayIterator($this->toArray()); + } + + public function parseParams() + { + $params = $matches = array(); + $callback = array($this, 'trimHeader'); + + // Normalize the header into a single array and iterate over all values + foreach ($this->normalize()->toArray() as $val) { + $part = array(); + foreach (preg_split('/;(?=([^"]*"[^"]*")*[^"]*$)/', $val) as $kvp) { + if (!preg_match_all('/<[^>]+>|[^=]+/', $kvp, $matches)) { + continue; + } + $pieces = array_map($callback, $matches[0]); + $part[$pieces[0]] = isset($pieces[1]) ? $pieces[1] : ''; + } + if ($part) { + $params[] = $part; + } + } + + return $params; + } + + /** + * @deprecated + * @codeCoverageIgnore + */ + public function hasExactHeader($header) + { + Version::warn(__METHOD__ . ' is deprecated'); + return $this->header == $header; + } + + /** + * @deprecated + * @codeCoverageIgnore + */ + public function raw() + { + Version::warn(__METHOD__ . ' is deprecated. Use toArray()'); + return $this->toArray(); + } + + /** + * Trim a header by removing excess spaces and wrapping quotes + * + * @param $str + * + * @return string + */ + protected function trimHeader($str) + { + static $trimmed = "\"' \n\t"; + + return trim($str, $trimmed); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/CacheControl.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/CacheControl.php new file mode 100644 index 000000000..77789e51f --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/CacheControl.php @@ -0,0 +1,121 @@ +directives = null; + } + + public function removeValue($searchValue) + { + parent::removeValue($searchValue); + $this->directives = null; + } + + /** + * Check if a specific cache control directive exists + * + * @param string $param Directive to retrieve + * + * @return bool + */ + public function hasDirective($param) + { + $directives = $this->getDirectives(); + + return isset($directives[$param]); + } + + /** + * Get a specific cache control directive + * + * @param string $param Directive to retrieve + * + * @return string|bool|null + */ + public function getDirective($param) + { + $directives = $this->getDirectives(); + + return isset($directives[$param]) ? $directives[$param] : null; + } + + /** + * Add a cache control directive + * + * @param string $param Directive to add + * @param string $value Value to set + * + * @return self + */ + public function addDirective($param, $value) + { + $directives = $this->getDirectives(); + $directives[$param] = $value; + $this->updateFromDirectives($directives); + + return $this; + } + + /** + * Remove a cache control directive by name + * + * @param string $param Directive to remove + * + * @return self + */ + public function removeDirective($param) + { + $directives = $this->getDirectives(); + unset($directives[$param]); + $this->updateFromDirectives($directives); + + return $this; + } + + /** + * Get an associative array of cache control directives + * + * @return array + */ + public function getDirectives() + { + if ($this->directives === null) { + $this->directives = array(); + foreach ($this->parseParams() as $collection) { + foreach ($collection as $key => $value) { + $this->directives[$key] = $value === '' ? true : $value; + } + } + } + + return $this->directives; + } + + /** + * Updates the header value based on the parsed directives + * + * @param array $directives Array of cache control directives + */ + protected function updateFromDirectives(array $directives) + { + $this->directives = $directives; + $this->values = array(); + + foreach ($directives as $key => $value) { + $this->values[] = $value === true ? $key : "{$key}={$value}"; + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderCollection.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderCollection.php new file mode 100644 index 000000000..8c7f6aefb --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderCollection.php @@ -0,0 +1,108 @@ +headers = $headers; + } + + public function __clone() + { + foreach ($this->headers as &$header) { + $header = clone $header; + } + } + + /** + * Clears the header collection + */ + public function clear() + { + $this->headers = array(); + } + + /** + * Set a header on the collection + * + * @param HeaderInterface $header Header to add + * + * @return self + */ + public function add(HeaderInterface $header) + { + $this->headers[strtolower($header->getName())] = $header; + + return $this; + } + + /** + * Get an array of header objects + * + * @return array + */ + public function getAll() + { + return $this->headers; + } + + /** + * Alias of offsetGet + */ + public function get($key) + { + return $this->offsetGet($key); + } + + public function count() + { + return count($this->headers); + } + + public function offsetExists($offset) + { + return isset($this->headers[strtolower($offset)]); + } + + public function offsetGet($offset) + { + $l = strtolower($offset); + + return isset($this->headers[$l]) ? $this->headers[$l] : null; + } + + public function offsetSet($offset, $value) + { + $this->add($value); + } + + public function offsetUnset($offset) + { + unset($this->headers[strtolower($offset)]); + } + + public function getIterator() + { + return new \ArrayIterator($this->headers); + } + + public function toArray() + { + $result = array(); + foreach ($this->headers as $header) { + $result[$header->getName()] = $header->toArray(); + } + + return $result; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderFactory.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderFactory.php new file mode 100644 index 000000000..0273be52f --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderFactory.php @@ -0,0 +1,26 @@ + 'Guzzle\Http\Message\Header\CacheControl', + 'link' => 'Guzzle\Http\Message\Header\Link', + ); + + public function createHeader($header, $value = null) + { + $lowercase = strtolower($header); + + return isset($this->mapping[$lowercase]) + ? new $this->mapping[$lowercase]($header, $value) + : new Header($header, $value); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderFactoryInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderFactoryInterface.php new file mode 100644 index 000000000..9457cf64a --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/Header/HeaderFactoryInterface.php @@ -0,0 +1,19 @@ +", "rel=\"{$rel}\""); + + foreach ($params as $k => $v) { + $values[] = "{$k}=\"{$v}\""; + } + + return $this->add(implode('; ', $values)); + } + + /** + * Check if a specific link exists for a given rel attribute + * + * @param string $rel rel value + * + * @return bool + */ + public function hasLink($rel) + { + return $this->getLink($rel) !== null; + } + + /** + * Get a specific link for a given rel attribute + * + * @param string $rel Rel value + * + * @return array|null + */ + public function getLink($rel) + { + foreach ($this->getLinks() as $link) { + if (isset($link['rel']) && $link['rel'] == $rel) { + return $link; + } + } + + return null; + } + + /** + * Get an associative array of links + * + * For example: + * Link: ; rel=front; type="image/jpeg", ; rel=back; type="image/jpeg" + * + * + * var_export($response->getLinks()); + * array( + * array( + * 'url' => 'http:/.../front.jpeg', + * 'rel' => 'back', + * 'type' => 'image/jpeg', + * ) + * ) + * + * + * @return array + */ + public function getLinks() + { + $links = $this->parseParams(); + + foreach ($links as &$link) { + $key = key($link); + unset($link[$key]); + $link['url'] = trim($key, '<> '); + } + + return $links; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/MessageInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/MessageInterface.php new file mode 100644 index 000000000..62bcd4391 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/MessageInterface.php @@ -0,0 +1,102 @@ +fieldName = $fieldName; + $this->setFilename($filename); + $this->postname = $postname ? $postname : basename($filename); + $this->contentType = $contentType ?: $this->guessContentType(); + } + + public function setFieldName($name) + { + $this->fieldName = $name; + + return $this; + } + + public function getFieldName() + { + return $this->fieldName; + } + + public function setFilename($filename) + { + // Remove leading @ symbol + if (strpos($filename, '@') === 0) { + $filename = substr($filename, 1); + } + + if (!is_readable($filename)) { + throw new InvalidArgumentException("Unable to open {$filename} for reading"); + } + + $this->filename = $filename; + + return $this; + } + + public function setPostname($postname) + { + $this->postname = $postname; + + return $this; + } + + public function getFilename() + { + return $this->filename; + } + + public function getPostname() + { + return $this->postname; + } + + public function setContentType($type) + { + $this->contentType = $type; + + return $this; + } + + public function getContentType() + { + return $this->contentType; + } + + public function getCurlValue() + { + // PHP 5.5 introduced a CurlFile object that deprecates the old @filename syntax + // See: https://wiki.php.net/rfc/curl-file-upload + if (function_exists('curl_file_create')) { + return curl_file_create($this->filename, $this->contentType, $this->postname); + } + + // Use the old style if using an older version of PHP + $value = "@{$this->filename};filename=" . $this->postname; + if ($this->contentType) { + $value .= ';type=' . $this->contentType; + } + + return $value; + } + + /** + * @deprecated + * @codeCoverageIgnore + */ + public function getCurlString() + { + Version::warn(__METHOD__ . ' is deprecated. Use getCurlValue()'); + return $this->getCurlValue(); + } + + /** + * Determine the Content-Type of the file + */ + protected function guessContentType() + { + return Mimetypes::getInstance()->fromFilename($this->filename) ?: 'application/octet-stream'; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/PostFileInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/PostFileInterface.php new file mode 100644 index 000000000..7f0779d1e --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/PostFileInterface.php @@ -0,0 +1,83 @@ +method = strtoupper($method); + $this->curlOptions = new Collection(); + $this->setUrl($url); + + if ($headers) { + // Special handling for multi-value headers + foreach ($headers as $key => $value) { + // Deal with collisions with Host and Authorization + if ($key == 'host' || $key == 'Host') { + $this->setHeader($key, $value); + } elseif ($value instanceof HeaderInterface) { + $this->addHeader($key, $value); + } else { + foreach ((array) $value as $v) { + $this->addHeader($key, $v); + } + } + } + } + + $this->setState(self::STATE_NEW); + } + + public function __clone() + { + if ($this->eventDispatcher) { + $this->eventDispatcher = clone $this->eventDispatcher; + } + $this->curlOptions = clone $this->curlOptions; + $this->params = clone $this->params; + $this->url = clone $this->url; + $this->response = $this->responseBody = null; + $this->headers = clone $this->headers; + + $this->setState(RequestInterface::STATE_NEW); + $this->dispatch('request.clone', array('request' => $this)); + } + + /** + * Get the HTTP request as a string + * + * @return string + */ + public function __toString() + { + return $this->getRawHeaders() . "\r\n\r\n"; + } + + /** + * Default method that will throw exceptions if an unsuccessful response is received. + * + * @param Event $event Received + * @throws BadResponseException if the response is not successful + */ + public static function onRequestError(Event $event) + { + $e = BadResponseException::factory($event['request'], $event['response']); + $event['request']->setState(self::STATE_ERROR, array('exception' => $e) + $event->toArray()); + throw $e; + } + + public function setClient(ClientInterface $client) + { + $this->client = $client; + + return $this; + } + + public function getClient() + { + return $this->client; + } + + public function getRawHeaders() + { + $protocolVersion = $this->protocolVersion ?: '1.1'; + + return trim($this->method . ' ' . $this->getResource()) . ' ' + . strtoupper(str_replace('https', 'http', $this->url->getScheme())) + . '/' . $protocolVersion . "\r\n" . implode("\r\n", $this->getHeaderLines()); + } + + public function setUrl($url) + { + if ($url instanceof Url) { + $this->url = $url; + } else { + $this->url = Url::factory($url); + } + + // Update the port and host header + $this->setPort($this->url->getPort()); + + if ($this->url->getUsername() || $this->url->getPassword()) { + $this->setAuth($this->url->getUsername(), $this->url->getPassword()); + // Remove the auth info from the URL + $this->url->setUsername(null); + $this->url->setPassword(null); + } + + return $this; + } + + public function send() + { + if (!$this->client) { + throw new RuntimeException('A client must be set on the request'); + } + + return $this->client->send($this); + } + + public function getResponse() + { + return $this->response; + } + + public function getQuery($asString = false) + { + return $asString + ? (string) $this->url->getQuery() + : $this->url->getQuery(); + } + + public function getMethod() + { + return $this->method; + } + + public function getScheme() + { + return $this->url->getScheme(); + } + + public function setScheme($scheme) + { + $this->url->setScheme($scheme); + + return $this; + } + + public function getHost() + { + return $this->url->getHost(); + } + + public function setHost($host) + { + $this->url->setHost($host); + $this->setPort($this->url->getPort()); + + return $this; + } + + public function getProtocolVersion() + { + return $this->protocolVersion; + } + + public function setProtocolVersion($protocol) + { + $this->protocolVersion = $protocol; + + return $this; + } + + public function getPath() + { + return '/' . ltrim($this->url->getPath(), '/'); + } + + public function setPath($path) + { + $this->url->setPath($path); + + return $this; + } + + public function getPort() + { + return $this->url->getPort(); + } + + public function setPort($port) + { + $this->url->setPort($port); + + // Include the port in the Host header if it is not the default port for the scheme of the URL + $scheme = $this->url->getScheme(); + if ($port && (($scheme == 'http' && $port != 80) || ($scheme == 'https' && $port != 443))) { + $this->headers['host'] = $this->headerFactory->createHeader('Host', $this->url->getHost() . ':' . $port); + } else { + $this->headers['host'] = $this->headerFactory->createHeader('Host', $this->url->getHost()); + } + + return $this; + } + + public function getUsername() + { + return $this->username; + } + + public function getPassword() + { + return $this->password; + } + + public function setAuth($user, $password = '', $scheme = CURLAUTH_BASIC) + { + static $authMap = array( + 'basic' => CURLAUTH_BASIC, + 'digest' => CURLAUTH_DIGEST, + 'ntlm' => CURLAUTH_NTLM, + 'any' => CURLAUTH_ANY + ); + + // If we got false or null, disable authentication + if (!$user) { + $this->password = $this->username = null; + $this->removeHeader('Authorization'); + $this->getCurlOptions()->remove(CURLOPT_HTTPAUTH); + return $this; + } + + if (!is_numeric($scheme)) { + $scheme = strtolower($scheme); + if (!isset($authMap[$scheme])) { + throw new InvalidArgumentException($scheme . ' is not a valid authentication type'); + } + $scheme = $authMap[$scheme]; + } + + $this->username = $user; + $this->password = $password; + + // Bypass CURL when using basic auth to promote connection reuse + if ($scheme == CURLAUTH_BASIC) { + $this->getCurlOptions()->remove(CURLOPT_HTTPAUTH); + $this->setHeader('Authorization', 'Basic ' . base64_encode($this->username . ':' . $this->password)); + } else { + $this->getCurlOptions() + ->set(CURLOPT_HTTPAUTH, $scheme) + ->set(CURLOPT_USERPWD, $this->username . ':' . $this->password); + } + + return $this; + } + + public function getResource() + { + $resource = $this->getPath(); + if ($query = (string) $this->url->getQuery()) { + $resource .= '?' . $query; + } + + return $resource; + } + + public function getUrl($asObject = false) + { + return $asObject ? clone $this->url : (string) $this->url; + } + + public function getState() + { + return $this->state; + } + + public function setState($state, array $context = array()) + { + $oldState = $this->state; + $this->state = $state; + + switch ($state) { + case self::STATE_NEW: + $this->response = null; + break; + case self::STATE_TRANSFER: + if ($oldState !== $state) { + // Fix Content-Length and Transfer-Encoding collisions + if ($this->hasHeader('Transfer-Encoding') && $this->hasHeader('Content-Length')) { + $this->removeHeader('Transfer-Encoding'); + } + $this->dispatch('request.before_send', array('request' => $this)); + } + break; + case self::STATE_COMPLETE: + if ($oldState !== $state) { + $this->processResponse($context); + $this->responseBody = null; + } + break; + case self::STATE_ERROR: + if (isset($context['exception'])) { + $this->dispatch('request.exception', array( + 'request' => $this, + 'response' => isset($context['response']) ? $context['response'] : $this->response, + 'exception' => isset($context['exception']) ? $context['exception'] : null + )); + } + } + + return $this->state; + } + + public function getCurlOptions() + { + return $this->curlOptions; + } + + public function startResponse(Response $response) + { + $this->state = self::STATE_TRANSFER; + $response->setEffectiveUrl((string) $this->getUrl()); + $this->response = $response; + + return $this; + } + + public function setResponse(Response $response, $queued = false) + { + $response->setEffectiveUrl((string) $this->url); + + if ($queued) { + $ed = $this->getEventDispatcher(); + $ed->addListener('request.before_send', $f = function ($e) use ($response, &$f, $ed) { + $e['request']->setResponse($response); + $ed->removeListener('request.before_send', $f); + }, -9999); + } else { + $this->response = $response; + // If a specific response body is specified, then use it instead of the response's body + if ($this->responseBody && !$this->responseBody->getCustomData('default') && !$response->isRedirect()) { + $this->getResponseBody()->write((string) $this->response->getBody()); + } else { + $this->responseBody = $this->response->getBody(); + } + $this->setState(self::STATE_COMPLETE); + } + + return $this; + } + + public function setResponseBody($body) + { + // Attempt to open a file for writing if a string was passed + if (is_string($body)) { + // @codeCoverageIgnoreStart + if (!($body = fopen($body, 'w+'))) { + throw new InvalidArgumentException('Could not open ' . $body . ' for writing'); + } + // @codeCoverageIgnoreEnd + } + + $this->responseBody = EntityBody::factory($body); + + return $this; + } + + public function getResponseBody() + { + if ($this->responseBody === null) { + $this->responseBody = EntityBody::factory()->setCustomData('default', true); + } + + return $this->responseBody; + } + + /** + * Determine if the response body is repeatable (readable + seekable) + * + * @return bool + * @deprecated Use getResponseBody()->isSeekable() + * @codeCoverageIgnore + */ + public function isResponseBodyRepeatable() + { + Version::warn(__METHOD__ . ' is deprecated. Use $request->getResponseBody()->isRepeatable()'); + return !$this->responseBody ? true : $this->responseBody->isRepeatable(); + } + + public function getCookies() + { + if ($cookie = $this->getHeader('Cookie')) { + $data = ParserRegistry::getInstance()->getParser('cookie')->parseCookie($cookie); + return $data['cookies']; + } + + return array(); + } + + public function getCookie($name) + { + $cookies = $this->getCookies(); + + return isset($cookies[$name]) ? $cookies[$name] : null; + } + + public function addCookie($name, $value) + { + if (!$this->hasHeader('Cookie')) { + $this->setHeader('Cookie', "{$name}={$value}"); + } else { + $this->getHeader('Cookie')->add("{$name}={$value}"); + } + + // Always use semicolons to separate multiple cookie headers + $this->getHeader('Cookie')->setGlue(';'); + + return $this; + } + + public function removeCookie($name) + { + if ($cookie = $this->getHeader('Cookie')) { + foreach ($cookie as $cookieValue) { + if (strpos($cookieValue, $name . '=') === 0) { + $cookie->removeValue($cookieValue); + } + } + } + + return $this; + } + + public function setEventDispatcher(EventDispatcherInterface $eventDispatcher) + { + $this->eventDispatcher = $eventDispatcher; + $this->eventDispatcher->addListener('request.error', array(__CLASS__, 'onRequestError'), -255); + + return $this; + } + + public function getEventDispatcher() + { + if (!$this->eventDispatcher) { + $this->setEventDispatcher(new EventDispatcher()); + } + + return $this->eventDispatcher; + } + + public function dispatch($eventName, array $context = array()) + { + $context['request'] = $this; + + return $this->getEventDispatcher()->dispatch($eventName, new Event($context)); + } + + public function addSubscriber(EventSubscriberInterface $subscriber) + { + $this->getEventDispatcher()->addSubscriber($subscriber); + + return $this; + } + + /** + * Get an array containing the request and response for event notifications + * + * @return array + */ + protected function getEventArray() + { + return array( + 'request' => $this, + 'response' => $this->response + ); + } + + /** + * Process a received response + * + * @param array $context Contextual information + * @throws RequestException|BadResponseException on unsuccessful responses + */ + protected function processResponse(array $context = array()) + { + if (!$this->response) { + // If no response, then processResponse shouldn't have been called + $e = new RequestException('Error completing request'); + $e->setRequest($this); + throw $e; + } + + $this->state = self::STATE_COMPLETE; + + // A request was sent, but we don't know if we'll send more or if the final response will be successful + $this->dispatch('request.sent', $this->getEventArray() + $context); + + // Some response processors will remove the response or reset the state (example: ExponentialBackoffPlugin) + if ($this->state == RequestInterface::STATE_COMPLETE) { + + // The request completed, so the HTTP transaction is complete + $this->dispatch('request.complete', $this->getEventArray()); + + // If the response is bad, allow listeners to modify it or throw exceptions. You can change the response by + // modifying the Event object in your listeners or calling setResponse() on the request + if ($this->response->isError()) { + $event = new Event($this->getEventArray()); + $this->getEventDispatcher()->dispatch('request.error', $event); + // Allow events of request.error to quietly change the response + if ($event['response'] !== $this->response) { + $this->response = $event['response']; + } + } + + // If a successful response was received, dispatch an event + if ($this->response->isSuccessful()) { + $this->dispatch('request.success', $this->getEventArray()); + } + } + } + + /** + * @deprecated Use Guzzle\Plugin\Cache\DefaultCanCacheStrategy + * @codeCoverageIgnore + */ + public function canCache() + { + Version::warn(__METHOD__ . ' is deprecated. Use Guzzle\Plugin\Cache\DefaultCanCacheStrategy.'); + if (class_exists('Guzzle\Plugin\Cache\DefaultCanCacheStrategy')) { + $canCache = new \Guzzle\Plugin\Cache\DefaultCanCacheStrategy(); + return $canCache->canCacheRequest($this); + } else { + return false; + } + } + + /** + * @deprecated Use the history plugin (not emitting a warning as this is built-into the RedirectPlugin for now) + * @codeCoverageIgnore + */ + public function setIsRedirect($isRedirect) + { + $this->isRedirect = $isRedirect; + + return $this; + } + + /** + * @deprecated Use the history plugin + * @codeCoverageIgnore + */ + public function isRedirect() + { + Version::warn(__METHOD__ . ' is deprecated. Use the HistoryPlugin to track this.'); + return $this->isRedirect; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/RequestFactory.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/RequestFactory.php new file mode 100644 index 000000000..ba00a7676 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/RequestFactory.php @@ -0,0 +1,359 @@ +methods = array_flip(get_class_methods(__CLASS__)); + } + + public function fromMessage($message) + { + $parsed = ParserRegistry::getInstance()->getParser('message')->parseRequest($message); + + if (!$parsed) { + return false; + } + + $request = $this->fromParts($parsed['method'], $parsed['request_url'], + $parsed['headers'], $parsed['body'], $parsed['protocol'], + $parsed['version']); + + // EntityEnclosingRequest adds an "Expect: 100-Continue" header when using a raw request body for PUT or POST + // requests. This factory method should accurately reflect the message, so here we are removing the Expect + // header if one was not supplied in the message. + if (!isset($parsed['headers']['Expect']) && !isset($parsed['headers']['expect'])) { + $request->removeHeader('Expect'); + } + + return $request; + } + + public function fromParts( + $method, + array $urlParts, + $headers = null, + $body = null, + $protocol = 'HTTP', + $protocolVersion = '1.1' + ) { + return $this->create($method, Url::buildUrl($urlParts), $headers, $body) + ->setProtocolVersion($protocolVersion); + } + + public function create($method, $url, $headers = null, $body = null, array $options = array()) + { + $method = strtoupper($method); + + if ($method == 'GET' || $method == 'HEAD' || $method == 'TRACE') { + // Handle non-entity-enclosing request methods + $request = new $this->requestClass($method, $url, $headers); + if ($body) { + // The body is where the response body will be stored + $type = gettype($body); + if ($type == 'string' || $type == 'resource' || $type == 'object') { + $request->setResponseBody($body); + } + } + } else { + // Create an entity enclosing request by default + $request = new $this->entityEnclosingRequestClass($method, $url, $headers); + if ($body || $body === '0') { + // Add POST fields and files to an entity enclosing request if an array is used + if (is_array($body) || $body instanceof Collection) { + // Normalize PHP style cURL uploads with a leading '@' symbol + foreach ($body as $key => $value) { + if (is_string($value) && substr($value, 0, 1) == '@') { + $request->addPostFile($key, $value); + unset($body[$key]); + } + } + // Add the fields if they are still present and not all files + $request->addPostFields($body); + } else { + // Add a raw entity body body to the request + $request->setBody($body, (string) $request->getHeader('Content-Type')); + if ((string) $request->getHeader('Transfer-Encoding') == 'chunked') { + $request->removeHeader('Content-Length'); + } + } + } + } + + if ($options) { + $this->applyOptions($request, $options); + } + + return $request; + } + + /** + * Clone a request while changing the method. Emulates the behavior of + * {@see Guzzle\Http\Message\Request::clone}, but can change the HTTP method. + * + * @param RequestInterface $request Request to clone + * @param string $method Method to set + * + * @return RequestInterface + */ + public function cloneRequestWithMethod(RequestInterface $request, $method) + { + // Create the request with the same client if possible + if ($request->getClient()) { + $cloned = $request->getClient()->createRequest($method, $request->getUrl(), $request->getHeaders()); + } else { + $cloned = $this->create($method, $request->getUrl(), $request->getHeaders()); + } + + $cloned->getCurlOptions()->replace($request->getCurlOptions()->toArray()); + $cloned->setEventDispatcher(clone $request->getEventDispatcher()); + // Ensure that that the Content-Length header is not copied if changing to GET or HEAD + if (!($cloned instanceof EntityEnclosingRequestInterface)) { + $cloned->removeHeader('Content-Length'); + } elseif ($request instanceof EntityEnclosingRequestInterface) { + $cloned->setBody($request->getBody()); + } + $cloned->getParams()->replace($request->getParams()->toArray()); + $cloned->dispatch('request.clone', array('request' => $cloned)); + + return $cloned; + } + + public function applyOptions(RequestInterface $request, array $options = array(), $flags = self::OPTIONS_NONE) + { + // Iterate over each key value pair and attempt to apply a config using function visitors + foreach ($options as $key => $value) { + $method = "visit_{$key}"; + if (isset($this->methods[$method])) { + $this->{$method}($request, $value, $flags); + } + } + } + + protected function visit_headers(RequestInterface $request, $value, $flags) + { + if (!is_array($value)) { + throw new InvalidArgumentException('headers value must be an array'); + } + + if ($flags & self::OPTIONS_AS_DEFAULTS) { + // Merge headers in but do not overwrite existing values + foreach ($value as $key => $header) { + if (!$request->hasHeader($key)) { + $request->setHeader($key, $header); + } + } + } else { + $request->addHeaders($value); + } + } + + protected function visit_body(RequestInterface $request, $value, $flags) + { + if ($request instanceof EntityEnclosingRequestInterface) { + $request->setBody($value); + } else { + throw new InvalidArgumentException('Attempting to set a body on a non-entity-enclosing request'); + } + } + + protected function visit_allow_redirects(RequestInterface $request, $value, $flags) + { + if ($value === false) { + $request->getParams()->set(RedirectPlugin::DISABLE, true); + } + } + + protected function visit_auth(RequestInterface $request, $value, $flags) + { + if (!is_array($value)) { + throw new InvalidArgumentException('auth value must be an array'); + } + + $request->setAuth($value[0], isset($value[1]) ? $value[1] : null, isset($value[2]) ? $value[2] : 'basic'); + } + + protected function visit_query(RequestInterface $request, $value, $flags) + { + if (!is_array($value)) { + throw new InvalidArgumentException('query value must be an array'); + } + + if ($flags & self::OPTIONS_AS_DEFAULTS) { + // Merge query string values in but do not overwrite existing values + $query = $request->getQuery(); + $query->overwriteWith(array_diff_key($value, $query->toArray())); + } else { + $request->getQuery()->overwriteWith($value); + } + } + + protected function visit_cookies(RequestInterface $request, $value, $flags) + { + if (!is_array($value)) { + throw new InvalidArgumentException('cookies value must be an array'); + } + + foreach ($value as $name => $v) { + $request->addCookie($name, $v); + } + } + + protected function visit_events(RequestInterface $request, $value, $flags) + { + if (!is_array($value)) { + throw new InvalidArgumentException('events value must be an array'); + } + + foreach ($value as $name => $method) { + if (is_array($method)) { + $request->getEventDispatcher()->addListener($name, $method[0], $method[1]); + } else { + $request->getEventDispatcher()->addListener($name, $method); + } + } + } + + protected function visit_plugins(RequestInterface $request, $value, $flags) + { + if (!is_array($value)) { + throw new InvalidArgumentException('plugins value must be an array'); + } + + foreach ($value as $plugin) { + $request->addSubscriber($plugin); + } + } + + protected function visit_exceptions(RequestInterface $request, $value, $flags) + { + if ($value === false || $value === 0) { + $dispatcher = $request->getEventDispatcher(); + foreach ($dispatcher->getListeners('request.error') as $listener) { + if (is_array($listener) && $listener[0] == 'Guzzle\Http\Message\Request' && $listener[1] = 'onRequestError') { + $dispatcher->removeListener('request.error', $listener); + break; + } + } + } + } + + protected function visit_save_to(RequestInterface $request, $value, $flags) + { + $request->setResponseBody($value); + } + + protected function visit_params(RequestInterface $request, $value, $flags) + { + if (!is_array($value)) { + throw new InvalidArgumentException('params value must be an array'); + } + + $request->getParams()->overwriteWith($value); + } + + protected function visit_timeout(RequestInterface $request, $value, $flags) + { + if (defined('CURLOPT_TIMEOUT_MS')) { + $request->getCurlOptions()->set(CURLOPT_TIMEOUT_MS, $value * 1000); + } else { + $request->getCurlOptions()->set(CURLOPT_TIMEOUT, $value); + } + } + + protected function visit_connect_timeout(RequestInterface $request, $value, $flags) + { + if (defined('CURLOPT_CONNECTTIMEOUT_MS')) { + $request->getCurlOptions()->set(CURLOPT_CONNECTTIMEOUT_MS, $value * 1000); + } else { + $request->getCurlOptions()->set(CURLOPT_CONNECTTIMEOUT, $value); + } + } + + protected function visit_debug(RequestInterface $request, $value, $flags) + { + if ($value) { + $request->getCurlOptions()->set(CURLOPT_VERBOSE, true); + } + } + + protected function visit_verify(RequestInterface $request, $value, $flags) + { + $curl = $request->getCurlOptions(); + if ($value === true || is_string($value)) { + $curl[CURLOPT_SSL_VERIFYHOST] = 2; + $curl[CURLOPT_SSL_VERIFYPEER] = true; + if ($value !== true) { + $curl[CURLOPT_CAINFO] = $value; + } + } elseif ($value === false) { + unset($curl[CURLOPT_CAINFO]); + $curl[CURLOPT_SSL_VERIFYHOST] = 0; + $curl[CURLOPT_SSL_VERIFYPEER] = false; + } + } + + protected function visit_proxy(RequestInterface $request, $value, $flags) + { + $request->getCurlOptions()->set(CURLOPT_PROXY, $value, $flags); + } + + protected function visit_cert(RequestInterface $request, $value, $flags) + { + if (is_array($value)) { + $request->getCurlOptions()->set(CURLOPT_SSLCERT, $value[0]); + $request->getCurlOptions()->set(CURLOPT_SSLCERTPASSWD, $value[1]); + } else { + $request->getCurlOptions()->set(CURLOPT_SSLCERT, $value); + } + } + + protected function visit_ssl_key(RequestInterface $request, $value, $flags) + { + if (is_array($value)) { + $request->getCurlOptions()->set(CURLOPT_SSLKEY, $value[0]); + $request->getCurlOptions()->set(CURLOPT_SSLKEYPASSWD, $value[1]); + } else { + $request->getCurlOptions()->set(CURLOPT_SSLKEY, $value); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/RequestFactoryInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/RequestFactoryInterface.php new file mode 100644 index 000000000..6088f10e9 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Message/RequestFactoryInterface.php @@ -0,0 +1,105 @@ + 'Continue', + 101 => 'Switching Protocols', + 102 => 'Processing', + 200 => 'OK', + 201 => 'Created', + 202 => 'Accepted', + 203 => 'Non-Authoritative Information', + 204 => 'No Content', + 205 => 'Reset Content', + 206 => 'Partial Content', + 207 => 'Multi-Status', + 208 => 'Already Reported', + 226 => 'IM Used', + 300 => 'Multiple Choices', + 301 => 'Moved Permanently', + 302 => 'Found', + 303 => 'See Other', + 304 => 'Not Modified', + 305 => 'Use Proxy', + 307 => 'Temporary Redirect', + 308 => 'Permanent Redirect', + 400 => 'Bad Request', + 401 => 'Unauthorized', + 402 => 'Payment Required', + 403 => 'Forbidden', + 404 => 'Not Found', + 405 => 'Method Not Allowed', + 406 => 'Not Acceptable', + 407 => 'Proxy Authentication Required', + 408 => 'Request Timeout', + 409 => 'Conflict', + 410 => 'Gone', + 411 => 'Length Required', + 412 => 'Precondition Failed', + 413 => 'Request Entity Too Large', + 414 => 'Request-URI Too Long', + 415 => 'Unsupported Media Type', + 416 => 'Requested Range Not Satisfiable', + 417 => 'Expectation Failed', + 422 => 'Unprocessable Entity', + 423 => 'Locked', + 424 => 'Failed Dependency', + 425 => 'Reserved for WebDAV advanced collections expired proposal', + 426 => 'Upgrade required', + 428 => 'Precondition Required', + 429 => 'Too Many Requests', + 431 => 'Request Header Fields Too Large', + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Timeout', + 505 => 'HTTP Version Not Supported', + 506 => 'Variant Also Negotiates (Experimental)', + 507 => 'Insufficient Storage', + 508 => 'Loop Detected', + 510 => 'Not Extended', + 511 => 'Network Authentication Required', + ); + + /** @var EntityBodyInterface The response body */ + protected $body; + + /** @var string The reason phrase of the response (human readable code) */ + protected $reasonPhrase; + + /** @var string The status code of the response */ + protected $statusCode; + + /** @var array Information about the request */ + protected $info = array(); + + /** @var string The effective URL that returned this response */ + protected $effectiveUrl; + + /** @var array Cacheable response codes (see RFC 2616:13.4) */ + protected static $cacheResponseCodes = array(200, 203, 206, 300, 301, 410); + + /** + * Create a new Response based on a raw response message + * + * @param string $message Response message + * + * @return self|bool Returns false on error + */ + public static function fromMessage($message) + { + $data = ParserRegistry::getInstance()->getParser('message')->parseResponse($message); + if (!$data) { + return false; + } + + $response = new static($data['code'], $data['headers'], $data['body']); + $response->setProtocol($data['protocol'], $data['version']) + ->setStatus($data['code'], $data['reason_phrase']); + + // Set the appropriate Content-Length if the one set is inaccurate (e.g. setting to X) + $contentLength = (string) $response->getHeader('Content-Length'); + $actualLength = strlen($data['body']); + if (strlen($data['body']) > 0 && $contentLength != $actualLength) { + $response->setHeader('Content-Length', $actualLength); + } + + return $response; + } + + /** + * Construct the response + * + * @param string $statusCode The response status code (e.g. 200, 404, etc) + * @param ToArrayInterface|array $headers The response headers + * @param string|resource|EntityBodyInterface $body The body of the response + * + * @throws BadResponseException if an invalid response code is given + */ + public function __construct($statusCode, $headers = null, $body = null) + { + parent::__construct(); + $this->setStatus($statusCode); + $this->body = EntityBody::factory($body !== null ? $body : ''); + + if ($headers) { + if (is_array($headers)) { + $this->setHeaders($headers); + } elseif ($headers instanceof ToArrayInterface) { + $this->setHeaders($headers->toArray()); + } else { + throw new BadResponseException('Invalid headers argument received'); + } + } + } + + /** + * @return string + */ + public function __toString() + { + return $this->getMessage(); + } + + public function serialize() + { + return json_encode(array( + 'status' => $this->statusCode, + 'body' => (string) $this->body, + 'headers' => $this->headers->toArray() + )); + } + + public function unserialize($serialize) + { + $data = json_decode($serialize, true); + $this->__construct($data['status'], $data['headers'], $data['body']); + } + + /** + * Get the response entity body + * + * @param bool $asString Set to TRUE to return a string of the body rather than a full body object + * + * @return EntityBodyInterface|string + */ + public function getBody($asString = false) + { + return $asString ? (string) $this->body : $this->body; + } + + /** + * Set the response entity body + * + * @param EntityBodyInterface|string $body Body to set + * + * @return self + */ + public function setBody($body) + { + $this->body = EntityBody::factory($body); + + return $this; + } + + /** + * Set the protocol and protocol version of the response + * + * @param string $protocol Response protocol + * @param string $version Protocol version + * + * @return self + */ + public function setProtocol($protocol, $version) + { + $this->protocol = $protocol; + $this->protocolVersion = $version; + + return $this; + } + + /** + * Get the protocol used for the response (e.g. HTTP) + * + * @return string + */ + public function getProtocol() + { + return $this->protocol; + } + + /** + * Get the HTTP protocol version + * + * @return string + */ + public function getProtocolVersion() + { + return $this->protocolVersion; + } + + /** + * Get a cURL transfer information + * + * @param string $key A single statistic to check + * + * @return array|string|null Returns all stats if no key is set, a single stat if a key is set, or null if a key + * is set and not found + * @link http://www.php.net/manual/en/function.curl-getinfo.php + */ + public function getInfo($key = null) + { + if ($key === null) { + return $this->info; + } elseif (array_key_exists($key, $this->info)) { + return $this->info[$key]; + } else { + return null; + } + } + + /** + * Set the transfer information + * + * @param array $info Array of cURL transfer stats + * + * @return self + */ + public function setInfo(array $info) + { + $this->info = $info; + + return $this; + } + + /** + * Set the response status + * + * @param int $statusCode Response status code to set + * @param string $reasonPhrase Response reason phrase + * + * @return self + * @throws BadResponseException when an invalid response code is received + */ + public function setStatus($statusCode, $reasonPhrase = '') + { + $this->statusCode = (int) $statusCode; + + if (!$reasonPhrase && isset(self::$statusTexts[$this->statusCode])) { + $this->reasonPhrase = self::$statusTexts[$this->statusCode]; + } else { + $this->reasonPhrase = $reasonPhrase; + } + + return $this; + } + + /** + * Get the response status code + * + * @return integer + */ + public function getStatusCode() + { + return $this->statusCode; + } + + /** + * Get the entire response as a string + * + * @return string + */ + public function getMessage() + { + $message = $this->getRawHeaders(); + + // Only include the body in the message if the size is < 2MB + $size = $this->body->getSize(); + if ($size < 2097152) { + $message .= (string) $this->body; + } + + return $message; + } + + /** + * Get the the raw message headers as a string + * + * @return string + */ + public function getRawHeaders() + { + $headers = 'HTTP/1.1 ' . $this->statusCode . ' ' . $this->reasonPhrase . "\r\n"; + $lines = $this->getHeaderLines(); + if (!empty($lines)) { + $headers .= implode("\r\n", $lines) . "\r\n"; + } + + return $headers . "\r\n"; + } + + /** + * Get the response reason phrase- a human readable version of the numeric + * status code + * + * @return string + */ + public function getReasonPhrase() + { + return $this->reasonPhrase; + } + + /** + * Get the Accept-Ranges HTTP header + * + * @return string Returns what partial content range types this server supports. + */ + public function getAcceptRanges() + { + return (string) $this->getHeader('Accept-Ranges'); + } + + /** + * Calculate the age of the response + * + * @return integer + */ + public function calculateAge() + { + $age = $this->getHeader('Age'); + + if ($age === null && $this->getDate()) { + $age = time() - strtotime($this->getDate()); + } + + return $age === null ? null : (int) (string) $age; + } + + /** + * Get the Age HTTP header + * + * @return integer|null Returns the age the object has been in a proxy cache in seconds. + */ + public function getAge() + { + return (string) $this->getHeader('Age'); + } + + /** + * Get the Allow HTTP header + * + * @return string|null Returns valid actions for a specified resource. To be used for a 405 Method not allowed. + */ + public function getAllow() + { + return (string) $this->getHeader('Allow'); + } + + /** + * Check if an HTTP method is allowed by checking the Allow response header + * + * @param string $method Method to check + * + * @return bool + */ + public function isMethodAllowed($method) + { + $allow = $this->getHeader('Allow'); + if ($allow) { + foreach (explode(',', $allow) as $allowable) { + if (!strcasecmp(trim($allowable), $method)) { + return true; + } + } + } + + return false; + } + + /** + * Get the Cache-Control HTTP header + * + * @return string + */ + public function getCacheControl() + { + return (string) $this->getHeader('Cache-Control'); + } + + /** + * Get the Connection HTTP header + * + * @return string + */ + public function getConnection() + { + return (string) $this->getHeader('Connection'); + } + + /** + * Get the Content-Encoding HTTP header + * + * @return string|null + */ + public function getContentEncoding() + { + return (string) $this->getHeader('Content-Encoding'); + } + + /** + * Get the Content-Language HTTP header + * + * @return string|null Returns the language the content is in. + */ + public function getContentLanguage() + { + return (string) $this->getHeader('Content-Language'); + } + + /** + * Get the Content-Length HTTP header + * + * @return integer Returns the length of the response body in bytes + */ + public function getContentLength() + { + return (int) (string) $this->getHeader('Content-Length'); + } + + /** + * Get the Content-Location HTTP header + * + * @return string|null Returns an alternate location for the returned data (e.g /index.htm) + */ + public function getContentLocation() + { + return (string) $this->getHeader('Content-Location'); + } + + /** + * Get the Content-Disposition HTTP header + * + * @return string|null Returns the Content-Disposition header + */ + public function getContentDisposition() + { + return (string) $this->getHeader('Content-Disposition'); + } + + /** + * Get the Content-MD5 HTTP header + * + * @return string|null Returns a Base64-encoded binary MD5 sum of the content of the response. + */ + public function getContentMd5() + { + return (string) $this->getHeader('Content-MD5'); + } + + /** + * Get the Content-Range HTTP header + * + * @return string Returns where in a full body message this partial message belongs (e.g. bytes 21010-47021/47022). + */ + public function getContentRange() + { + return (string) $this->getHeader('Content-Range'); + } + + /** + * Get the Content-Type HTTP header + * + * @return string Returns the mime type of this content. + */ + public function getContentType() + { + return (string) $this->getHeader('Content-Type'); + } + + /** + * Checks if the Content-Type is of a certain type. This is useful if the + * Content-Type header contains charset information and you need to know if + * the Content-Type matches a particular type. + * + * @param string $type Content type to check against + * + * @return bool + */ + public function isContentType($type) + { + return stripos($this->getHeader('Content-Type'), $type) !== false; + } + + /** + * Get the Date HTTP header + * + * @return string|null Returns the date and time that the message was sent. + */ + public function getDate() + { + return (string) $this->getHeader('Date'); + } + + /** + * Get the ETag HTTP header + * + * @return string|null Returns an identifier for a specific version of a resource, often a Message digest. + */ + public function getEtag() + { + return (string) $this->getHeader('ETag'); + } + + /** + * Get the Expires HTTP header + * + * @return string|null Returns the date/time after which the response is considered stale. + */ + public function getExpires() + { + return (string) $this->getHeader('Expires'); + } + + /** + * Get the Last-Modified HTTP header + * + * @return string|null Returns the last modified date for the requested object, in RFC 2822 format + * (e.g. Tue, 15 Nov 1994 12:45:26 GMT) + */ + public function getLastModified() + { + return (string) $this->getHeader('Last-Modified'); + } + + /** + * Get the Location HTTP header + * + * @return string|null Used in redirection, or when a new resource has been created. + */ + public function getLocation() + { + return (string) $this->getHeader('Location'); + } + + /** + * Get the Pragma HTTP header + * + * @return Header|null Returns the implementation-specific headers that may have various effects anywhere along + * the request-response chain. + */ + public function getPragma() + { + return (string) $this->getHeader('Pragma'); + } + + /** + * Get the Proxy-Authenticate HTTP header + * + * @return string|null Authentication to access the proxy (e.g. Basic) + */ + public function getProxyAuthenticate() + { + return (string) $this->getHeader('Proxy-Authenticate'); + } + + /** + * Get the Retry-After HTTP header + * + * @return int|null If an entity is temporarily unavailable, this instructs the client to try again after a + * specified period of time. + */ + public function getRetryAfter() + { + return (string) $this->getHeader('Retry-After'); + } + + /** + * Get the Server HTTP header + * + * @return string|null A name for the server + */ + public function getServer() + { + return (string) $this->getHeader('Server'); + } + + /** + * Get the Set-Cookie HTTP header + * + * @return string|null An HTTP cookie. + */ + public function getSetCookie() + { + return (string) $this->getHeader('Set-Cookie'); + } + + /** + * Get the Trailer HTTP header + * + * @return string|null The Trailer general field value indicates that the given set of header fields is present in + * the trailer of a message encoded with chunked transfer-coding. + */ + public function getTrailer() + { + return (string) $this->getHeader('Trailer'); + } + + /** + * Get the Transfer-Encoding HTTP header + * + * @return string|null The form of encoding used to safely transfer the entity to the user + */ + public function getTransferEncoding() + { + return (string) $this->getHeader('Transfer-Encoding'); + } + + /** + * Get the Vary HTTP header + * + * @return string|null Tells downstream proxies how to match future request headers to decide whether the cached + * response can be used rather than requesting a fresh one from the origin server. + */ + public function getVary() + { + return (string) $this->getHeader('Vary'); + } + + /** + * Get the Via HTTP header + * + * @return string|null Informs the client of proxies through which the response was sent. + */ + public function getVia() + { + return (string) $this->getHeader('Via'); + } + + /** + * Get the Warning HTTP header + * + * @return string|null A general warning about possible problems with the entity body + */ + public function getWarning() + { + return (string) $this->getHeader('Warning'); + } + + /** + * Get the WWW-Authenticate HTTP header + * + * @return string|null Indicates the authentication scheme that should be used to access the requested entity + */ + public function getWwwAuthenticate() + { + return (string) $this->getHeader('WWW-Authenticate'); + } + + /** + * Checks if HTTP Status code is a Client Error (4xx) + * + * @return bool + */ + public function isClientError() + { + return $this->statusCode >= 400 && $this->statusCode < 500; + } + + /** + * Checks if HTTP Status code is Server OR Client Error (4xx or 5xx) + * + * @return boolean + */ + public function isError() + { + return $this->isClientError() || $this->isServerError(); + } + + /** + * Checks if HTTP Status code is Information (1xx) + * + * @return bool + */ + public function isInformational() + { + return $this->statusCode < 200; + } + + /** + * Checks if HTTP Status code is a Redirect (3xx) + * + * @return bool + */ + public function isRedirect() + { + return $this->statusCode >= 300 && $this->statusCode < 400; + } + + /** + * Checks if HTTP Status code is Server Error (5xx) + * + * @return bool + */ + public function isServerError() + { + return $this->statusCode >= 500 && $this->statusCode < 600; + } + + /** + * Checks if HTTP Status code is Successful (2xx | 304) + * + * @return bool + */ + public function isSuccessful() + { + return ($this->statusCode >= 200 && $this->statusCode < 300) || $this->statusCode == 304; + } + + /** + * Check if the response can be cached based on the response headers + * + * @return bool Returns TRUE if the response can be cached or false if not + */ + public function canCache() + { + // Check if the response is cacheable based on the code + if (!in_array((int) $this->getStatusCode(), self::$cacheResponseCodes)) { + return false; + } + + // Make sure a valid body was returned and can be cached + if ((!$this->getBody()->isReadable() || !$this->getBody()->isSeekable()) + && ($this->getContentLength() > 0 || $this->getTransferEncoding() == 'chunked')) { + return false; + } + + // Never cache no-store resources (this is a private cache, so private + // can be cached) + if ($this->getHeader('Cache-Control') && $this->getHeader('Cache-Control')->hasDirective('no-store')) { + return false; + } + + return $this->isFresh() || $this->getFreshness() === null || $this->canValidate(); + } + + /** + * Gets the number of seconds from the current time in which this response is still considered fresh + * + * @return int|null Returns the number of seconds + */ + public function getMaxAge() + { + if ($header = $this->getHeader('Cache-Control')) { + // s-max-age, then max-age, then Expires + if ($age = $header->getDirective('s-maxage')) { + return $age; + } + if ($age = $header->getDirective('max-age')) { + return $age; + } + } + + if ($this->getHeader('Expires')) { + return strtotime($this->getExpires()) - time(); + } + + return null; + } + + /** + * Check if the response is considered fresh. + * + * A response is considered fresh when its age is less than or equal to the freshness lifetime (maximum age) of the + * response. + * + * @return bool|null + */ + public function isFresh() + { + $fresh = $this->getFreshness(); + + return $fresh === null ? null : $fresh >= 0; + } + + /** + * Check if the response can be validated against the origin server using a conditional GET request. + * + * @return bool + */ + public function canValidate() + { + return $this->getEtag() || $this->getLastModified(); + } + + /** + * Get the freshness of the response by returning the difference of the maximum lifetime of the response and the + * age of the response (max-age - age). + * + * Freshness values less than 0 mean that the response is no longer fresh and is ABS(freshness) seconds expired. + * Freshness values of greater than zero is the number of seconds until the response is no longer fresh. A NULL + * result means that no freshness information is available. + * + * @return int + */ + public function getFreshness() + { + $maxAge = $this->getMaxAge(); + $age = $this->calculateAge(); + + return $maxAge && $age ? ($maxAge - $age) : null; + } + + /** + * Parse the JSON response body and return an array + * + * @return array|string|int|bool|float + * @throws RuntimeException if the response body is not in JSON format + */ + public function json() + { + $data = json_decode((string) $this->body, true); + if (JSON_ERROR_NONE !== json_last_error()) { + throw new RuntimeException('Unable to parse response body into JSON: ' . json_last_error()); + } + + return $data === null ? array() : $data; + } + + /** + * Parse the XML response body and return a \SimpleXMLElement. + * + * In order to prevent XXE attacks, this method disables loading external + * entities. If you rely on external entities, then you must parse the + * XML response manually by accessing the response body directly. + * + * @return \SimpleXMLElement + * @throws RuntimeException if the response body is not in XML format + * @link http://websec.io/2012/08/27/Preventing-XXE-in-PHP.html + */ + public function xml() + { + $errorMessage = null; + $internalErrors = libxml_use_internal_errors(true); + $disableEntities = libxml_disable_entity_loader(true); + libxml_clear_errors(); + + try { + $xml = new \SimpleXMLElement((string) $this->body ?: '', LIBXML_NONET); + if ($error = libxml_get_last_error()) { + $errorMessage = $error->message; + } + } catch (\Exception $e) { + $errorMessage = $e->getMessage(); + } + + libxml_clear_errors(); + libxml_use_internal_errors($internalErrors); + libxml_disable_entity_loader($disableEntities); + + if ($errorMessage) { + throw new RuntimeException('Unable to parse response body into XML: ' . $errorMessage); + } + + return $xml; + } + + /** + * Get the redirect count of this response + * + * @return int + */ + public function getRedirectCount() + { + return (int) $this->params->get(RedirectPlugin::REDIRECT_COUNT); + } + + /** + * Set the effective URL that resulted in this response (e.g. the last redirect URL) + * + * @param string $url The effective URL + * + * @return self + */ + public function setEffectiveUrl($url) + { + $this->effectiveUrl = $url; + + return $this; + } + + /** + * Get the effective URL that resulted in this response (e.g. the last redirect URL) + * + * @return string + */ + public function getEffectiveUrl() + { + return $this->effectiveUrl; + } + + /** + * @deprecated + * @codeCoverageIgnore + */ + public function getPreviousResponse() + { + Version::warn(__METHOD__ . ' is deprecated. Use the HistoryPlugin.'); + return null; + } + + /** + * @deprecated + * @codeCoverageIgnore + */ + public function setRequest($request) + { + Version::warn(__METHOD__ . ' is deprecated'); + return $this; + } + + /** + * @deprecated + * @codeCoverageIgnore + */ + public function getRequest() + { + Version::warn(__METHOD__ . ' is deprecated'); + return null; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Mimetypes.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Mimetypes.php new file mode 100644 index 000000000..d71586a05 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Mimetypes.php @@ -0,0 +1,962 @@ + 'text/vnd.in3d.3dml', + '3g2' => 'video/3gpp2', + '3gp' => 'video/3gpp', + '7z' => 'application/x-7z-compressed', + 'aab' => 'application/x-authorware-bin', + 'aac' => 'audio/x-aac', + 'aam' => 'application/x-authorware-map', + 'aas' => 'application/x-authorware-seg', + 'abw' => 'application/x-abiword', + 'ac' => 'application/pkix-attr-cert', + 'acc' => 'application/vnd.americandynamics.acc', + 'ace' => 'application/x-ace-compressed', + 'acu' => 'application/vnd.acucobol', + 'acutc' => 'application/vnd.acucorp', + 'adp' => 'audio/adpcm', + 'aep' => 'application/vnd.audiograph', + 'afm' => 'application/x-font-type1', + 'afp' => 'application/vnd.ibm.modcap', + 'ahead' => 'application/vnd.ahead.space', + 'ai' => 'application/postscript', + 'aif' => 'audio/x-aiff', + 'aifc' => 'audio/x-aiff', + 'aiff' => 'audio/x-aiff', + 'air' => 'application/vnd.adobe.air-application-installer-package+zip', + 'ait' => 'application/vnd.dvb.ait', + 'ami' => 'application/vnd.amiga.ami', + 'apk' => 'application/vnd.android.package-archive', + 'application' => 'application/x-ms-application', + 'apr' => 'application/vnd.lotus-approach', + 'asa' => 'text/plain', + 'asax' => 'application/octet-stream', + 'asc' => 'application/pgp-signature', + 'ascx' => 'text/plain', + 'asf' => 'video/x-ms-asf', + 'ashx' => 'text/plain', + 'asm' => 'text/x-asm', + 'asmx' => 'text/plain', + 'aso' => 'application/vnd.accpac.simply.aso', + 'asp' => 'text/plain', + 'aspx' => 'text/plain', + 'asx' => 'video/x-ms-asf', + 'atc' => 'application/vnd.acucorp', + 'atom' => 'application/atom+xml', + 'atomcat' => 'application/atomcat+xml', + 'atomsvc' => 'application/atomsvc+xml', + 'atx' => 'application/vnd.antix.game-component', + 'au' => 'audio/basic', + 'avi' => 'video/x-msvideo', + 'aw' => 'application/applixware', + 'axd' => 'text/plain', + 'azf' => 'application/vnd.airzip.filesecure.azf', + 'azs' => 'application/vnd.airzip.filesecure.azs', + 'azw' => 'application/vnd.amazon.ebook', + 'bat' => 'application/x-msdownload', + 'bcpio' => 'application/x-bcpio', + 'bdf' => 'application/x-font-bdf', + 'bdm' => 'application/vnd.syncml.dm+wbxml', + 'bed' => 'application/vnd.realvnc.bed', + 'bh2' => 'application/vnd.fujitsu.oasysprs', + 'bin' => 'application/octet-stream', + 'bmi' => 'application/vnd.bmi', + 'bmp' => 'image/bmp', + 'book' => 'application/vnd.framemaker', + 'box' => 'application/vnd.previewsystems.box', + 'boz' => 'application/x-bzip2', + 'bpk' => 'application/octet-stream', + 'btif' => 'image/prs.btif', + 'bz' => 'application/x-bzip', + 'bz2' => 'application/x-bzip2', + 'c' => 'text/x-c', + 'c11amc' => 'application/vnd.cluetrust.cartomobile-config', + 'c11amz' => 'application/vnd.cluetrust.cartomobile-config-pkg', + 'c4d' => 'application/vnd.clonk.c4group', + 'c4f' => 'application/vnd.clonk.c4group', + 'c4g' => 'application/vnd.clonk.c4group', + 'c4p' => 'application/vnd.clonk.c4group', + 'c4u' => 'application/vnd.clonk.c4group', + 'cab' => 'application/vnd.ms-cab-compressed', + 'car' => 'application/vnd.curl.car', + 'cat' => 'application/vnd.ms-pki.seccat', + 'cc' => 'text/x-c', + 'cct' => 'application/x-director', + 'ccxml' => 'application/ccxml+xml', + 'cdbcmsg' => 'application/vnd.contact.cmsg', + 'cdf' => 'application/x-netcdf', + 'cdkey' => 'application/vnd.mediastation.cdkey', + 'cdmia' => 'application/cdmi-capability', + 'cdmic' => 'application/cdmi-container', + 'cdmid' => 'application/cdmi-domain', + 'cdmio' => 'application/cdmi-object', + 'cdmiq' => 'application/cdmi-queue', + 'cdx' => 'chemical/x-cdx', + 'cdxml' => 'application/vnd.chemdraw+xml', + 'cdy' => 'application/vnd.cinderella', + 'cer' => 'application/pkix-cert', + 'cfc' => 'application/x-coldfusion', + 'cfm' => 'application/x-coldfusion', + 'cgm' => 'image/cgm', + 'chat' => 'application/x-chat', + 'chm' => 'application/vnd.ms-htmlhelp', + 'chrt' => 'application/vnd.kde.kchart', + 'cif' => 'chemical/x-cif', + 'cii' => 'application/vnd.anser-web-certificate-issue-initiation', + 'cil' => 'application/vnd.ms-artgalry', + 'cla' => 'application/vnd.claymore', + 'class' => 'application/java-vm', + 'clkk' => 'application/vnd.crick.clicker.keyboard', + 'clkp' => 'application/vnd.crick.clicker.palette', + 'clkt' => 'application/vnd.crick.clicker.template', + 'clkw' => 'application/vnd.crick.clicker.wordbank', + 'clkx' => 'application/vnd.crick.clicker', + 'clp' => 'application/x-msclip', + 'cmc' => 'application/vnd.cosmocaller', + 'cmdf' => 'chemical/x-cmdf', + 'cml' => 'chemical/x-cml', + 'cmp' => 'application/vnd.yellowriver-custom-menu', + 'cmx' => 'image/x-cmx', + 'cod' => 'application/vnd.rim.cod', + 'com' => 'application/x-msdownload', + 'conf' => 'text/plain', + 'cpio' => 'application/x-cpio', + 'cpp' => 'text/x-c', + 'cpt' => 'application/mac-compactpro', + 'crd' => 'application/x-mscardfile', + 'crl' => 'application/pkix-crl', + 'crt' => 'application/x-x509-ca-cert', + 'cryptonote' => 'application/vnd.rig.cryptonote', + 'cs' => 'text/plain', + 'csh' => 'application/x-csh', + 'csml' => 'chemical/x-csml', + 'csp' => 'application/vnd.commonspace', + 'css' => 'text/css', + 'cst' => 'application/x-director', + 'csv' => 'text/csv', + 'cu' => 'application/cu-seeme', + 'curl' => 'text/vnd.curl', + 'cww' => 'application/prs.cww', + 'cxt' => 'application/x-director', + 'cxx' => 'text/x-c', + 'dae' => 'model/vnd.collada+xml', + 'daf' => 'application/vnd.mobius.daf', + 'dataless' => 'application/vnd.fdsn.seed', + 'davmount' => 'application/davmount+xml', + 'dcr' => 'application/x-director', + 'dcurl' => 'text/vnd.curl.dcurl', + 'dd2' => 'application/vnd.oma.dd2+xml', + 'ddd' => 'application/vnd.fujixerox.ddd', + 'deb' => 'application/x-debian-package', + 'def' => 'text/plain', + 'deploy' => 'application/octet-stream', + 'der' => 'application/x-x509-ca-cert', + 'dfac' => 'application/vnd.dreamfactory', + 'dic' => 'text/x-c', + 'dir' => 'application/x-director', + 'dis' => 'application/vnd.mobius.dis', + 'dist' => 'application/octet-stream', + 'distz' => 'application/octet-stream', + 'djv' => 'image/vnd.djvu', + 'djvu' => 'image/vnd.djvu', + 'dll' => 'application/x-msdownload', + 'dmg' => 'application/octet-stream', + 'dms' => 'application/octet-stream', + 'dna' => 'application/vnd.dna', + 'doc' => 'application/msword', + 'docm' => 'application/vnd.ms-word.document.macroenabled.12', + 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'dot' => 'application/msword', + 'dotm' => 'application/vnd.ms-word.template.macroenabled.12', + 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', + 'dp' => 'application/vnd.osgi.dp', + 'dpg' => 'application/vnd.dpgraph', + 'dra' => 'audio/vnd.dra', + 'dsc' => 'text/prs.lines.tag', + 'dssc' => 'application/dssc+der', + 'dtb' => 'application/x-dtbook+xml', + 'dtd' => 'application/xml-dtd', + 'dts' => 'audio/vnd.dts', + 'dtshd' => 'audio/vnd.dts.hd', + 'dump' => 'application/octet-stream', + 'dvi' => 'application/x-dvi', + 'dwf' => 'model/vnd.dwf', + 'dwg' => 'image/vnd.dwg', + 'dxf' => 'image/vnd.dxf', + 'dxp' => 'application/vnd.spotfire.dxp', + 'dxr' => 'application/x-director', + 'ecelp4800' => 'audio/vnd.nuera.ecelp4800', + 'ecelp7470' => 'audio/vnd.nuera.ecelp7470', + 'ecelp9600' => 'audio/vnd.nuera.ecelp9600', + 'ecma' => 'application/ecmascript', + 'edm' => 'application/vnd.novadigm.edm', + 'edx' => 'application/vnd.novadigm.edx', + 'efif' => 'application/vnd.picsel', + 'ei6' => 'application/vnd.pg.osasli', + 'elc' => 'application/octet-stream', + 'eml' => 'message/rfc822', + 'emma' => 'application/emma+xml', + 'eol' => 'audio/vnd.digital-winds', + 'eot' => 'application/vnd.ms-fontobject', + 'eps' => 'application/postscript', + 'epub' => 'application/epub+zip', + 'es3' => 'application/vnd.eszigno3+xml', + 'esf' => 'application/vnd.epson.esf', + 'et3' => 'application/vnd.eszigno3+xml', + 'etx' => 'text/x-setext', + 'exe' => 'application/x-msdownload', + 'exi' => 'application/exi', + 'ext' => 'application/vnd.novadigm.ext', + 'ez' => 'application/andrew-inset', + 'ez2' => 'application/vnd.ezpix-album', + 'ez3' => 'application/vnd.ezpix-package', + 'f' => 'text/x-fortran', + 'f4v' => 'video/x-f4v', + 'f77' => 'text/x-fortran', + 'f90' => 'text/x-fortran', + 'fbs' => 'image/vnd.fastbidsheet', + 'fcs' => 'application/vnd.isac.fcs', + 'fdf' => 'application/vnd.fdf', + 'fe_launch' => 'application/vnd.denovo.fcselayout-link', + 'fg5' => 'application/vnd.fujitsu.oasysgp', + 'fgd' => 'application/x-director', + 'fh' => 'image/x-freehand', + 'fh4' => 'image/x-freehand', + 'fh5' => 'image/x-freehand', + 'fh7' => 'image/x-freehand', + 'fhc' => 'image/x-freehand', + 'fig' => 'application/x-xfig', + 'fli' => 'video/x-fli', + 'flo' => 'application/vnd.micrografx.flo', + 'flv' => 'video/x-flv', + 'flw' => 'application/vnd.kde.kivio', + 'flx' => 'text/vnd.fmi.flexstor', + 'fly' => 'text/vnd.fly', + 'fm' => 'application/vnd.framemaker', + 'fnc' => 'application/vnd.frogans.fnc', + 'for' => 'text/x-fortran', + 'fpx' => 'image/vnd.fpx', + 'frame' => 'application/vnd.framemaker', + 'fsc' => 'application/vnd.fsc.weblaunch', + 'fst' => 'image/vnd.fst', + 'ftc' => 'application/vnd.fluxtime.clip', + 'fti' => 'application/vnd.anser-web-funds-transfer-initiation', + 'fvt' => 'video/vnd.fvt', + 'fxp' => 'application/vnd.adobe.fxp', + 'fxpl' => 'application/vnd.adobe.fxp', + 'fzs' => 'application/vnd.fuzzysheet', + 'g2w' => 'application/vnd.geoplan', + 'g3' => 'image/g3fax', + 'g3w' => 'application/vnd.geospace', + 'gac' => 'application/vnd.groove-account', + 'gdl' => 'model/vnd.gdl', + 'geo' => 'application/vnd.dynageo', + 'gex' => 'application/vnd.geometry-explorer', + 'ggb' => 'application/vnd.geogebra.file', + 'ggt' => 'application/vnd.geogebra.tool', + 'ghf' => 'application/vnd.groove-help', + 'gif' => 'image/gif', + 'gim' => 'application/vnd.groove-identity-message', + 'gmx' => 'application/vnd.gmx', + 'gnumeric' => 'application/x-gnumeric', + 'gph' => 'application/vnd.flographit', + 'gqf' => 'application/vnd.grafeq', + 'gqs' => 'application/vnd.grafeq', + 'gram' => 'application/srgs', + 'gre' => 'application/vnd.geometry-explorer', + 'grv' => 'application/vnd.groove-injector', + 'grxml' => 'application/srgs+xml', + 'gsf' => 'application/x-font-ghostscript', + 'gtar' => 'application/x-gtar', + 'gtm' => 'application/vnd.groove-tool-message', + 'gtw' => 'model/vnd.gtw', + 'gv' => 'text/vnd.graphviz', + 'gxt' => 'application/vnd.geonext', + 'h' => 'text/x-c', + 'h261' => 'video/h261', + 'h263' => 'video/h263', + 'h264' => 'video/h264', + 'hal' => 'application/vnd.hal+xml', + 'hbci' => 'application/vnd.hbci', + 'hdf' => 'application/x-hdf', + 'hh' => 'text/x-c', + 'hlp' => 'application/winhlp', + 'hpgl' => 'application/vnd.hp-hpgl', + 'hpid' => 'application/vnd.hp-hpid', + 'hps' => 'application/vnd.hp-hps', + 'hqx' => 'application/mac-binhex40', + 'hta' => 'application/octet-stream', + 'htc' => 'text/html', + 'htke' => 'application/vnd.kenameaapp', + 'htm' => 'text/html', + 'html' => 'text/html', + 'hvd' => 'application/vnd.yamaha.hv-dic', + 'hvp' => 'application/vnd.yamaha.hv-voice', + 'hvs' => 'application/vnd.yamaha.hv-script', + 'i2g' => 'application/vnd.intergeo', + 'icc' => 'application/vnd.iccprofile', + 'ice' => 'x-conference/x-cooltalk', + 'icm' => 'application/vnd.iccprofile', + 'ico' => 'image/x-icon', + 'ics' => 'text/calendar', + 'ief' => 'image/ief', + 'ifb' => 'text/calendar', + 'ifm' => 'application/vnd.shana.informed.formdata', + 'iges' => 'model/iges', + 'igl' => 'application/vnd.igloader', + 'igm' => 'application/vnd.insors.igm', + 'igs' => 'model/iges', + 'igx' => 'application/vnd.micrografx.igx', + 'iif' => 'application/vnd.shana.informed.interchange', + 'imp' => 'application/vnd.accpac.simply.imp', + 'ims' => 'application/vnd.ms-ims', + 'in' => 'text/plain', + 'ini' => 'text/plain', + 'ipfix' => 'application/ipfix', + 'ipk' => 'application/vnd.shana.informed.package', + 'irm' => 'application/vnd.ibm.rights-management', + 'irp' => 'application/vnd.irepository.package+xml', + 'iso' => 'application/octet-stream', + 'itp' => 'application/vnd.shana.informed.formtemplate', + 'ivp' => 'application/vnd.immervision-ivp', + 'ivu' => 'application/vnd.immervision-ivu', + 'jad' => 'text/vnd.sun.j2me.app-descriptor', + 'jam' => 'application/vnd.jam', + 'jar' => 'application/java-archive', + 'java' => 'text/x-java-source', + 'jisp' => 'application/vnd.jisp', + 'jlt' => 'application/vnd.hp-jlyt', + 'jnlp' => 'application/x-java-jnlp-file', + 'joda' => 'application/vnd.joost.joda-archive', + 'jpe' => 'image/jpeg', + 'jpeg' => 'image/jpeg', + 'jpg' => 'image/jpeg', + 'jpgm' => 'video/jpm', + 'jpgv' => 'video/jpeg', + 'jpm' => 'video/jpm', + 'js' => 'text/javascript', + 'json' => 'application/json', + 'kar' => 'audio/midi', + 'karbon' => 'application/vnd.kde.karbon', + 'kfo' => 'application/vnd.kde.kformula', + 'kia' => 'application/vnd.kidspiration', + 'kml' => 'application/vnd.google-earth.kml+xml', + 'kmz' => 'application/vnd.google-earth.kmz', + 'kne' => 'application/vnd.kinar', + 'knp' => 'application/vnd.kinar', + 'kon' => 'application/vnd.kde.kontour', + 'kpr' => 'application/vnd.kde.kpresenter', + 'kpt' => 'application/vnd.kde.kpresenter', + 'ksp' => 'application/vnd.kde.kspread', + 'ktr' => 'application/vnd.kahootz', + 'ktx' => 'image/ktx', + 'ktz' => 'application/vnd.kahootz', + 'kwd' => 'application/vnd.kde.kword', + 'kwt' => 'application/vnd.kde.kword', + 'lasxml' => 'application/vnd.las.las+xml', + 'latex' => 'application/x-latex', + 'lbd' => 'application/vnd.llamagraphics.life-balance.desktop', + 'lbe' => 'application/vnd.llamagraphics.life-balance.exchange+xml', + 'les' => 'application/vnd.hhe.lesson-player', + 'lha' => 'application/octet-stream', + 'link66' => 'application/vnd.route66.link66+xml', + 'list' => 'text/plain', + 'list3820' => 'application/vnd.ibm.modcap', + 'listafp' => 'application/vnd.ibm.modcap', + 'log' => 'text/plain', + 'lostxml' => 'application/lost+xml', + 'lrf' => 'application/octet-stream', + 'lrm' => 'application/vnd.ms-lrm', + 'ltf' => 'application/vnd.frogans.ltf', + 'lvp' => 'audio/vnd.lucent.voice', + 'lwp' => 'application/vnd.lotus-wordpro', + 'lzh' => 'application/octet-stream', + 'm13' => 'application/x-msmediaview', + 'm14' => 'application/x-msmediaview', + 'm1v' => 'video/mpeg', + 'm21' => 'application/mp21', + 'm2a' => 'audio/mpeg', + 'm2v' => 'video/mpeg', + 'm3a' => 'audio/mpeg', + 'm3u' => 'audio/x-mpegurl', + 'm3u8' => 'application/vnd.apple.mpegurl', + 'm4a' => 'audio/mp4', + 'm4u' => 'video/vnd.mpegurl', + 'm4v' => 'video/mp4', + 'ma' => 'application/mathematica', + 'mads' => 'application/mads+xml', + 'mag' => 'application/vnd.ecowin.chart', + 'maker' => 'application/vnd.framemaker', + 'man' => 'text/troff', + 'mathml' => 'application/mathml+xml', + 'mb' => 'application/mathematica', + 'mbk' => 'application/vnd.mobius.mbk', + 'mbox' => 'application/mbox', + 'mc1' => 'application/vnd.medcalcdata', + 'mcd' => 'application/vnd.mcd', + 'mcurl' => 'text/vnd.curl.mcurl', + 'mdb' => 'application/x-msaccess', + 'mdi' => 'image/vnd.ms-modi', + 'me' => 'text/troff', + 'mesh' => 'model/mesh', + 'meta4' => 'application/metalink4+xml', + 'mets' => 'application/mets+xml', + 'mfm' => 'application/vnd.mfmp', + 'mgp' => 'application/vnd.osgeo.mapguide.package', + 'mgz' => 'application/vnd.proteus.magazine', + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mif' => 'application/vnd.mif', + 'mime' => 'message/rfc822', + 'mj2' => 'video/mj2', + 'mjp2' => 'video/mj2', + 'mlp' => 'application/vnd.dolby.mlp', + 'mmd' => 'application/vnd.chipnuts.karaoke-mmd', + 'mmf' => 'application/vnd.smaf', + 'mmr' => 'image/vnd.fujixerox.edmics-mmr', + 'mny' => 'application/x-msmoney', + 'mobi' => 'application/x-mobipocket-ebook', + 'mods' => 'application/mods+xml', + 'mov' => 'video/quicktime', + 'movie' => 'video/x-sgi-movie', + 'mp2' => 'audio/mpeg', + 'mp21' => 'application/mp21', + 'mp2a' => 'audio/mpeg', + 'mp3' => 'audio/mpeg', + 'mp4' => 'video/mp4', + 'mp4a' => 'audio/mp4', + 'mp4s' => 'application/mp4', + 'mp4v' => 'video/mp4', + 'mpc' => 'application/vnd.mophun.certificate', + 'mpe' => 'video/mpeg', + 'mpeg' => 'video/mpeg', + 'mpg' => 'video/mpeg', + 'mpg4' => 'video/mp4', + 'mpga' => 'audio/mpeg', + 'mpkg' => 'application/vnd.apple.installer+xml', + 'mpm' => 'application/vnd.blueice.multipass', + 'mpn' => 'application/vnd.mophun.application', + 'mpp' => 'application/vnd.ms-project', + 'mpt' => 'application/vnd.ms-project', + 'mpy' => 'application/vnd.ibm.minipay', + 'mqy' => 'application/vnd.mobius.mqy', + 'mrc' => 'application/marc', + 'mrcx' => 'application/marcxml+xml', + 'ms' => 'text/troff', + 'mscml' => 'application/mediaservercontrol+xml', + 'mseed' => 'application/vnd.fdsn.mseed', + 'mseq' => 'application/vnd.mseq', + 'msf' => 'application/vnd.epson.msf', + 'msh' => 'model/mesh', + 'msi' => 'application/x-msdownload', + 'msl' => 'application/vnd.mobius.msl', + 'msty' => 'application/vnd.muvee.style', + 'mts' => 'model/vnd.mts', + 'mus' => 'application/vnd.musician', + 'musicxml' => 'application/vnd.recordare.musicxml+xml', + 'mvb' => 'application/x-msmediaview', + 'mwf' => 'application/vnd.mfer', + 'mxf' => 'application/mxf', + 'mxl' => 'application/vnd.recordare.musicxml', + 'mxml' => 'application/xv+xml', + 'mxs' => 'application/vnd.triscape.mxs', + 'mxu' => 'video/vnd.mpegurl', + 'n-gage' => 'application/vnd.nokia.n-gage.symbian.install', + 'n3' => 'text/n3', + 'nb' => 'application/mathematica', + 'nbp' => 'application/vnd.wolfram.player', + 'nc' => 'application/x-netcdf', + 'ncx' => 'application/x-dtbncx+xml', + 'ngdat' => 'application/vnd.nokia.n-gage.data', + 'nlu' => 'application/vnd.neurolanguage.nlu', + 'nml' => 'application/vnd.enliven', + 'nnd' => 'application/vnd.noblenet-directory', + 'nns' => 'application/vnd.noblenet-sealer', + 'nnw' => 'application/vnd.noblenet-web', + 'npx' => 'image/vnd.net-fpx', + 'nsf' => 'application/vnd.lotus-notes', + 'oa2' => 'application/vnd.fujitsu.oasys2', + 'oa3' => 'application/vnd.fujitsu.oasys3', + 'oas' => 'application/vnd.fujitsu.oasys', + 'obd' => 'application/x-msbinder', + 'oda' => 'application/oda', + 'odb' => 'application/vnd.oasis.opendocument.database', + 'odc' => 'application/vnd.oasis.opendocument.chart', + 'odf' => 'application/vnd.oasis.opendocument.formula', + 'odft' => 'application/vnd.oasis.opendocument.formula-template', + 'odg' => 'application/vnd.oasis.opendocument.graphics', + 'odi' => 'application/vnd.oasis.opendocument.image', + 'odm' => 'application/vnd.oasis.opendocument.text-master', + 'odp' => 'application/vnd.oasis.opendocument.presentation', + 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', + 'odt' => 'application/vnd.oasis.opendocument.text', + 'oga' => 'audio/ogg', + 'ogg' => 'audio/ogg', + 'ogv' => 'video/ogg', + 'ogx' => 'application/ogg', + 'onepkg' => 'application/onenote', + 'onetmp' => 'application/onenote', + 'onetoc' => 'application/onenote', + 'onetoc2' => 'application/onenote', + 'opf' => 'application/oebps-package+xml', + 'oprc' => 'application/vnd.palm', + 'org' => 'application/vnd.lotus-organizer', + 'osf' => 'application/vnd.yamaha.openscoreformat', + 'osfpvg' => 'application/vnd.yamaha.openscoreformat.osfpvg+xml', + 'otc' => 'application/vnd.oasis.opendocument.chart-template', + 'otf' => 'application/x-font-otf', + 'otg' => 'application/vnd.oasis.opendocument.graphics-template', + 'oth' => 'application/vnd.oasis.opendocument.text-web', + 'oti' => 'application/vnd.oasis.opendocument.image-template', + 'otp' => 'application/vnd.oasis.opendocument.presentation-template', + 'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template', + 'ott' => 'application/vnd.oasis.opendocument.text-template', + 'oxt' => 'application/vnd.openofficeorg.extension', + 'p' => 'text/x-pascal', + 'p10' => 'application/pkcs10', + 'p12' => 'application/x-pkcs12', + 'p7b' => 'application/x-pkcs7-certificates', + 'p7c' => 'application/pkcs7-mime', + 'p7m' => 'application/pkcs7-mime', + 'p7r' => 'application/x-pkcs7-certreqresp', + 'p7s' => 'application/pkcs7-signature', + 'p8' => 'application/pkcs8', + 'pas' => 'text/x-pascal', + 'paw' => 'application/vnd.pawaafile', + 'pbd' => 'application/vnd.powerbuilder6', + 'pbm' => 'image/x-portable-bitmap', + 'pcf' => 'application/x-font-pcf', + 'pcl' => 'application/vnd.hp-pcl', + 'pclxl' => 'application/vnd.hp-pclxl', + 'pct' => 'image/x-pict', + 'pcurl' => 'application/vnd.curl.pcurl', + 'pcx' => 'image/x-pcx', + 'pdb' => 'application/vnd.palm', + 'pdf' => 'application/pdf', + 'pfa' => 'application/x-font-type1', + 'pfb' => 'application/x-font-type1', + 'pfm' => 'application/x-font-type1', + 'pfr' => 'application/font-tdpfr', + 'pfx' => 'application/x-pkcs12', + 'pgm' => 'image/x-portable-graymap', + 'pgn' => 'application/x-chess-pgn', + 'pgp' => 'application/pgp-encrypted', + 'php' => 'text/x-php', + 'phps' => 'application/x-httpd-phps', + 'pic' => 'image/x-pict', + 'pkg' => 'application/octet-stream', + 'pki' => 'application/pkixcmp', + 'pkipath' => 'application/pkix-pkipath', + 'plb' => 'application/vnd.3gpp.pic-bw-large', + 'plc' => 'application/vnd.mobius.plc', + 'plf' => 'application/vnd.pocketlearn', + 'pls' => 'application/pls+xml', + 'pml' => 'application/vnd.ctc-posml', + 'png' => 'image/png', + 'pnm' => 'image/x-portable-anymap', + 'portpkg' => 'application/vnd.macports.portpkg', + 'pot' => 'application/vnd.ms-powerpoint', + 'potm' => 'application/vnd.ms-powerpoint.template.macroenabled.12', + 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', + 'ppam' => 'application/vnd.ms-powerpoint.addin.macroenabled.12', + 'ppd' => 'application/vnd.cups-ppd', + 'ppm' => 'image/x-portable-pixmap', + 'pps' => 'application/vnd.ms-powerpoint', + 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroenabled.12', + 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', + 'ppt' => 'application/vnd.ms-powerpoint', + 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroenabled.12', + 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'pqa' => 'application/vnd.palm', + 'prc' => 'application/x-mobipocket-ebook', + 'pre' => 'application/vnd.lotus-freelance', + 'prf' => 'application/pics-rules', + 'ps' => 'application/postscript', + 'psb' => 'application/vnd.3gpp.pic-bw-small', + 'psd' => 'image/vnd.adobe.photoshop', + 'psf' => 'application/x-font-linux-psf', + 'pskcxml' => 'application/pskc+xml', + 'ptid' => 'application/vnd.pvi.ptid1', + 'pub' => 'application/x-mspublisher', + 'pvb' => 'application/vnd.3gpp.pic-bw-var', + 'pwn' => 'application/vnd.3m.post-it-notes', + 'pya' => 'audio/vnd.ms-playready.media.pya', + 'pyv' => 'video/vnd.ms-playready.media.pyv', + 'qam' => 'application/vnd.epson.quickanime', + 'qbo' => 'application/vnd.intu.qbo', + 'qfx' => 'application/vnd.intu.qfx', + 'qps' => 'application/vnd.publishare-delta-tree', + 'qt' => 'video/quicktime', + 'qwd' => 'application/vnd.quark.quarkxpress', + 'qwt' => 'application/vnd.quark.quarkxpress', + 'qxb' => 'application/vnd.quark.quarkxpress', + 'qxd' => 'application/vnd.quark.quarkxpress', + 'qxl' => 'application/vnd.quark.quarkxpress', + 'qxt' => 'application/vnd.quark.quarkxpress', + 'ra' => 'audio/x-pn-realaudio', + 'ram' => 'audio/x-pn-realaudio', + 'rar' => 'application/x-rar-compressed', + 'ras' => 'image/x-cmu-raster', + 'rb' => 'text/plain', + 'rcprofile' => 'application/vnd.ipunplugged.rcprofile', + 'rdf' => 'application/rdf+xml', + 'rdz' => 'application/vnd.data-vision.rdz', + 'rep' => 'application/vnd.businessobjects', + 'res' => 'application/x-dtbresource+xml', + 'resx' => 'text/xml', + 'rgb' => 'image/x-rgb', + 'rif' => 'application/reginfo+xml', + 'rip' => 'audio/vnd.rip', + 'rl' => 'application/resource-lists+xml', + 'rlc' => 'image/vnd.fujixerox.edmics-rlc', + 'rld' => 'application/resource-lists-diff+xml', + 'rm' => 'application/vnd.rn-realmedia', + 'rmi' => 'audio/midi', + 'rmp' => 'audio/x-pn-realaudio-plugin', + 'rms' => 'application/vnd.jcp.javame.midlet-rms', + 'rnc' => 'application/relax-ng-compact-syntax', + 'roff' => 'text/troff', + 'rp9' => 'application/vnd.cloanto.rp9', + 'rpss' => 'application/vnd.nokia.radio-presets', + 'rpst' => 'application/vnd.nokia.radio-preset', + 'rq' => 'application/sparql-query', + 'rs' => 'application/rls-services+xml', + 'rsd' => 'application/rsd+xml', + 'rss' => 'application/rss+xml', + 'rtf' => 'application/rtf', + 'rtx' => 'text/richtext', + 's' => 'text/x-asm', + 'saf' => 'application/vnd.yamaha.smaf-audio', + 'sbml' => 'application/sbml+xml', + 'sc' => 'application/vnd.ibm.secure-container', + 'scd' => 'application/x-msschedule', + 'scm' => 'application/vnd.lotus-screencam', + 'scq' => 'application/scvp-cv-request', + 'scs' => 'application/scvp-cv-response', + 'scurl' => 'text/vnd.curl.scurl', + 'sda' => 'application/vnd.stardivision.draw', + 'sdc' => 'application/vnd.stardivision.calc', + 'sdd' => 'application/vnd.stardivision.impress', + 'sdkd' => 'application/vnd.solent.sdkm+xml', + 'sdkm' => 'application/vnd.solent.sdkm+xml', + 'sdp' => 'application/sdp', + 'sdw' => 'application/vnd.stardivision.writer', + 'see' => 'application/vnd.seemail', + 'seed' => 'application/vnd.fdsn.seed', + 'sema' => 'application/vnd.sema', + 'semd' => 'application/vnd.semd', + 'semf' => 'application/vnd.semf', + 'ser' => 'application/java-serialized-object', + 'setpay' => 'application/set-payment-initiation', + 'setreg' => 'application/set-registration-initiation', + 'sfd-hdstx' => 'application/vnd.hydrostatix.sof-data', + 'sfs' => 'application/vnd.spotfire.sfs', + 'sgl' => 'application/vnd.stardivision.writer-global', + 'sgm' => 'text/sgml', + 'sgml' => 'text/sgml', + 'sh' => 'application/x-sh', + 'shar' => 'application/x-shar', + 'shf' => 'application/shf+xml', + 'sig' => 'application/pgp-signature', + 'silo' => 'model/mesh', + 'sis' => 'application/vnd.symbian.install', + 'sisx' => 'application/vnd.symbian.install', + 'sit' => 'application/x-stuffit', + 'sitx' => 'application/x-stuffitx', + 'skd' => 'application/vnd.koan', + 'skm' => 'application/vnd.koan', + 'skp' => 'application/vnd.koan', + 'skt' => 'application/vnd.koan', + 'sldm' => 'application/vnd.ms-powerpoint.slide.macroenabled.12', + 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', + 'slt' => 'application/vnd.epson.salt', + 'sm' => 'application/vnd.stepmania.stepchart', + 'smf' => 'application/vnd.stardivision.math', + 'smi' => 'application/smil+xml', + 'smil' => 'application/smil+xml', + 'snd' => 'audio/basic', + 'snf' => 'application/x-font-snf', + 'so' => 'application/octet-stream', + 'spc' => 'application/x-pkcs7-certificates', + 'spf' => 'application/vnd.yamaha.smaf-phrase', + 'spl' => 'application/x-futuresplash', + 'spot' => 'text/vnd.in3d.spot', + 'spp' => 'application/scvp-vp-response', + 'spq' => 'application/scvp-vp-request', + 'spx' => 'audio/ogg', + 'src' => 'application/x-wais-source', + 'sru' => 'application/sru+xml', + 'srx' => 'application/sparql-results+xml', + 'sse' => 'application/vnd.kodak-descriptor', + 'ssf' => 'application/vnd.epson.ssf', + 'ssml' => 'application/ssml+xml', + 'st' => 'application/vnd.sailingtracker.track', + 'stc' => 'application/vnd.sun.xml.calc.template', + 'std' => 'application/vnd.sun.xml.draw.template', + 'stf' => 'application/vnd.wt.stf', + 'sti' => 'application/vnd.sun.xml.impress.template', + 'stk' => 'application/hyperstudio', + 'stl' => 'application/vnd.ms-pki.stl', + 'str' => 'application/vnd.pg.format', + 'stw' => 'application/vnd.sun.xml.writer.template', + 'sub' => 'image/vnd.dvb.subtitle', + 'sus' => 'application/vnd.sus-calendar', + 'susp' => 'application/vnd.sus-calendar', + 'sv4cpio' => 'application/x-sv4cpio', + 'sv4crc' => 'application/x-sv4crc', + 'svc' => 'application/vnd.dvb.service', + 'svd' => 'application/vnd.svd', + 'svg' => 'image/svg+xml', + 'svgz' => 'image/svg+xml', + 'swa' => 'application/x-director', + 'swf' => 'application/x-shockwave-flash', + 'swi' => 'application/vnd.aristanetworks.swi', + 'sxc' => 'application/vnd.sun.xml.calc', + 'sxd' => 'application/vnd.sun.xml.draw', + 'sxg' => 'application/vnd.sun.xml.writer.global', + 'sxi' => 'application/vnd.sun.xml.impress', + 'sxm' => 'application/vnd.sun.xml.math', + 'sxw' => 'application/vnd.sun.xml.writer', + 't' => 'text/troff', + 'tao' => 'application/vnd.tao.intent-module-archive', + 'tar' => 'application/x-tar', + 'tcap' => 'application/vnd.3gpp2.tcap', + 'tcl' => 'application/x-tcl', + 'teacher' => 'application/vnd.smart.teacher', + 'tei' => 'application/tei+xml', + 'teicorpus' => 'application/tei+xml', + 'tex' => 'application/x-tex', + 'texi' => 'application/x-texinfo', + 'texinfo' => 'application/x-texinfo', + 'text' => 'text/plain', + 'tfi' => 'application/thraud+xml', + 'tfm' => 'application/x-tex-tfm', + 'thmx' => 'application/vnd.ms-officetheme', + 'tif' => 'image/tiff', + 'tiff' => 'image/tiff', + 'tmo' => 'application/vnd.tmobile-livetv', + 'torrent' => 'application/x-bittorrent', + 'tpl' => 'application/vnd.groove-tool-template', + 'tpt' => 'application/vnd.trid.tpt', + 'tr' => 'text/troff', + 'tra' => 'application/vnd.trueapp', + 'trm' => 'application/x-msterminal', + 'tsd' => 'application/timestamped-data', + 'tsv' => 'text/tab-separated-values', + 'ttc' => 'application/x-font-ttf', + 'ttf' => 'application/x-font-ttf', + 'ttl' => 'text/turtle', + 'twd' => 'application/vnd.simtech-mindmapper', + 'twds' => 'application/vnd.simtech-mindmapper', + 'txd' => 'application/vnd.genomatix.tuxedo', + 'txf' => 'application/vnd.mobius.txf', + 'txt' => 'text/plain', + 'u32' => 'application/x-authorware-bin', + 'udeb' => 'application/x-debian-package', + 'ufd' => 'application/vnd.ufdl', + 'ufdl' => 'application/vnd.ufdl', + 'umj' => 'application/vnd.umajin', + 'unityweb' => 'application/vnd.unity', + 'uoml' => 'application/vnd.uoml+xml', + 'uri' => 'text/uri-list', + 'uris' => 'text/uri-list', + 'urls' => 'text/uri-list', + 'ustar' => 'application/x-ustar', + 'utz' => 'application/vnd.uiq.theme', + 'uu' => 'text/x-uuencode', + 'uva' => 'audio/vnd.dece.audio', + 'uvd' => 'application/vnd.dece.data', + 'uvf' => 'application/vnd.dece.data', + 'uvg' => 'image/vnd.dece.graphic', + 'uvh' => 'video/vnd.dece.hd', + 'uvi' => 'image/vnd.dece.graphic', + 'uvm' => 'video/vnd.dece.mobile', + 'uvp' => 'video/vnd.dece.pd', + 'uvs' => 'video/vnd.dece.sd', + 'uvt' => 'application/vnd.dece.ttml+xml', + 'uvu' => 'video/vnd.uvvu.mp4', + 'uvv' => 'video/vnd.dece.video', + 'uvva' => 'audio/vnd.dece.audio', + 'uvvd' => 'application/vnd.dece.data', + 'uvvf' => 'application/vnd.dece.data', + 'uvvg' => 'image/vnd.dece.graphic', + 'uvvh' => 'video/vnd.dece.hd', + 'uvvi' => 'image/vnd.dece.graphic', + 'uvvm' => 'video/vnd.dece.mobile', + 'uvvp' => 'video/vnd.dece.pd', + 'uvvs' => 'video/vnd.dece.sd', + 'uvvt' => 'application/vnd.dece.ttml+xml', + 'uvvu' => 'video/vnd.uvvu.mp4', + 'uvvv' => 'video/vnd.dece.video', + 'uvvx' => 'application/vnd.dece.unspecified', + 'uvx' => 'application/vnd.dece.unspecified', + 'vcd' => 'application/x-cdlink', + 'vcf' => 'text/x-vcard', + 'vcg' => 'application/vnd.groove-vcard', + 'vcs' => 'text/x-vcalendar', + 'vcx' => 'application/vnd.vcx', + 'vis' => 'application/vnd.visionary', + 'viv' => 'video/vnd.vivo', + 'vor' => 'application/vnd.stardivision.writer', + 'vox' => 'application/x-authorware-bin', + 'vrml' => 'model/vrml', + 'vsd' => 'application/vnd.visio', + 'vsf' => 'application/vnd.vsf', + 'vss' => 'application/vnd.visio', + 'vst' => 'application/vnd.visio', + 'vsw' => 'application/vnd.visio', + 'vtu' => 'model/vnd.vtu', + 'vxml' => 'application/voicexml+xml', + 'w3d' => 'application/x-director', + 'wad' => 'application/x-doom', + 'wav' => 'audio/x-wav', + 'wax' => 'audio/x-ms-wax', + 'wbmp' => 'image/vnd.wap.wbmp', + 'wbs' => 'application/vnd.criticaltools.wbs+xml', + 'wbxml' => 'application/vnd.wap.wbxml', + 'wcm' => 'application/vnd.ms-works', + 'wdb' => 'application/vnd.ms-works', + 'weba' => 'audio/webm', + 'webm' => 'video/webm', + 'webp' => 'image/webp', + 'wg' => 'application/vnd.pmi.widget', + 'wgt' => 'application/widget', + 'wks' => 'application/vnd.ms-works', + 'wm' => 'video/x-ms-wm', + 'wma' => 'audio/x-ms-wma', + 'wmd' => 'application/x-ms-wmd', + 'wmf' => 'application/x-msmetafile', + 'wml' => 'text/vnd.wap.wml', + 'wmlc' => 'application/vnd.wap.wmlc', + 'wmls' => 'text/vnd.wap.wmlscript', + 'wmlsc' => 'application/vnd.wap.wmlscriptc', + 'wmv' => 'video/x-ms-wmv', + 'wmx' => 'video/x-ms-wmx', + 'wmz' => 'application/x-ms-wmz', + 'woff' => 'application/x-font-woff', + 'wpd' => 'application/vnd.wordperfect', + 'wpl' => 'application/vnd.ms-wpl', + 'wps' => 'application/vnd.ms-works', + 'wqd' => 'application/vnd.wqd', + 'wri' => 'application/x-mswrite', + 'wrl' => 'model/vrml', + 'wsdl' => 'application/wsdl+xml', + 'wspolicy' => 'application/wspolicy+xml', + 'wtb' => 'application/vnd.webturbo', + 'wvx' => 'video/x-ms-wvx', + 'x32' => 'application/x-authorware-bin', + 'x3d' => 'application/vnd.hzn-3d-crossword', + 'xap' => 'application/x-silverlight-app', + 'xar' => 'application/vnd.xara', + 'xbap' => 'application/x-ms-xbap', + 'xbd' => 'application/vnd.fujixerox.docuworks.binder', + 'xbm' => 'image/x-xbitmap', + 'xdf' => 'application/xcap-diff+xml', + 'xdm' => 'application/vnd.syncml.dm+xml', + 'xdp' => 'application/vnd.adobe.xdp+xml', + 'xdssc' => 'application/dssc+xml', + 'xdw' => 'application/vnd.fujixerox.docuworks', + 'xenc' => 'application/xenc+xml', + 'xer' => 'application/patch-ops-error+xml', + 'xfdf' => 'application/vnd.adobe.xfdf', + 'xfdl' => 'application/vnd.xfdl', + 'xht' => 'application/xhtml+xml', + 'xhtml' => 'application/xhtml+xml', + 'xhvml' => 'application/xv+xml', + 'xif' => 'image/vnd.xiff', + 'xla' => 'application/vnd.ms-excel', + 'xlam' => 'application/vnd.ms-excel.addin.macroenabled.12', + 'xlc' => 'application/vnd.ms-excel', + 'xlm' => 'application/vnd.ms-excel', + 'xls' => 'application/vnd.ms-excel', + 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroenabled.12', + 'xlsm' => 'application/vnd.ms-excel.sheet.macroenabled.12', + 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xlt' => 'application/vnd.ms-excel', + 'xltm' => 'application/vnd.ms-excel.template.macroenabled.12', + 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', + 'xlw' => 'application/vnd.ms-excel', + 'xml' => 'application/xml', + 'xo' => 'application/vnd.olpc-sugar', + 'xop' => 'application/xop+xml', + 'xpi' => 'application/x-xpinstall', + 'xpm' => 'image/x-xpixmap', + 'xpr' => 'application/vnd.is-xpr', + 'xps' => 'application/vnd.ms-xpsdocument', + 'xpw' => 'application/vnd.intercon.formnet', + 'xpx' => 'application/vnd.intercon.formnet', + 'xsl' => 'application/xml', + 'xslt' => 'application/xslt+xml', + 'xsm' => 'application/vnd.syncml+xml', + 'xspf' => 'application/xspf+xml', + 'xul' => 'application/vnd.mozilla.xul+xml', + 'xvm' => 'application/xv+xml', + 'xvml' => 'application/xv+xml', + 'xwd' => 'image/x-xwindowdump', + 'xyz' => 'chemical/x-xyz', + 'yaml' => 'text/yaml', + 'yang' => 'application/yang', + 'yin' => 'application/yin+xml', + 'yml' => 'text/yaml', + 'zaz' => 'application/vnd.zzazz.deck+xml', + 'zip' => 'application/zip', + 'zir' => 'application/vnd.zul', + 'zirz' => 'application/vnd.zul', + 'zmm' => 'application/vnd.handheld-entertainment+xml' + ); + + /** + * Get a singleton instance of the class + * + * @return self + * @codeCoverageIgnore + */ + public static function getInstance() + { + if (!self::$instance) { + self::$instance = new self(); + } + + return self::$instance; + } + + /** + * Get a mimetype value from a file extension + * + * @param string $extension File extension + * + * @return string|null + * + */ + public function fromExtension($extension) + { + $extension = strtolower($extension); + + return isset($this->mimetypes[$extension]) ? $this->mimetypes[$extension] : null; + } + + /** + * Get a mimetype from a filename + * + * @param string $filename Filename to generate a mimetype from + * + * @return string|null + */ + public function fromFilename($filename) + { + return $this->fromExtension(pathinfo($filename, PATHINFO_EXTENSION)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/CommaAggregator.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/CommaAggregator.php new file mode 100644 index 000000000..4b4e49d05 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/CommaAggregator.php @@ -0,0 +1,20 @@ +isUrlEncoding()) { + return array($query->encodeValue($key) => implode(',', array_map(array($query, 'encodeValue'), $value))); + } else { + return array($key => implode(',', $value)); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/DuplicateAggregator.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/DuplicateAggregator.php new file mode 100644 index 000000000..1bf1730e4 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/DuplicateAggregator.php @@ -0,0 +1,22 @@ +isUrlEncoding()) { + return array($query->encodeValue($key) => array_map(array($query, 'encodeValue'), $value)); + } else { + return array($key => $value); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/PhpAggregator.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/PhpAggregator.php new file mode 100644 index 000000000..133ea2bd9 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/PhpAggregator.php @@ -0,0 +1,27 @@ + $v) { + $k = "{$key}[{$k}]"; + if (is_array($v)) { + $ret = array_merge($ret, self::aggregate($k, $v, $query)); + } else { + $ret[$query->encodeValue($k)] = $query->encodeValue($v); + } + } + + return $ret; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/QueryAggregatorInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/QueryAggregatorInterface.php new file mode 100644 index 000000000..72bee620c --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/QueryAggregator/QueryAggregatorInterface.php @@ -0,0 +1,22 @@ +add($key, $value); + $foundDuplicates = true; + } elseif ($paramIsPhpStyleArray) { + $q[$key] = array($value); + } else { + $q[$key] = $value; + } + } else { + // Uses false by default to represent keys with no trailing "=" sign. + $q->add($key, false); + } + } + + // Use the duplicate aggregator if duplicates were found and not using PHP style arrays + if ($foundDuplicates && !$foundPhpStyle) { + $q->setAggregator(new DuplicateAggregator()); + } + + return $q; + } + + /** + * Convert the query string parameters to a query string string + * + * @return string + * @throws RuntimeException + */ + public function __toString() + { + if (!$this->data) { + return ''; + } + + $queryList = array(); + foreach ($this->prepareData($this->data) as $name => $value) { + $queryList[] = $this->convertKvp($name, $value); + } + + return implode($this->fieldSeparator, $queryList); + } + + /** + * Get the query string field separator + * + * @return string + */ + public function getFieldSeparator() + { + return $this->fieldSeparator; + } + + /** + * Get the query string value separator + * + * @return string + */ + public function getValueSeparator() + { + return $this->valueSeparator; + } + + /** + * Returns the type of URL encoding used by the query string + * + * One of: false, "RFC 3986", or "application/x-www-form-urlencoded" + * + * @return bool|string + */ + public function getUrlEncoding() + { + return $this->urlEncode; + } + + /** + * Returns true or false if using URL encoding + * + * @return bool + */ + public function isUrlEncoding() + { + return $this->urlEncode !== false; + } + + /** + * Provide a function for combining multi-valued query string parameters into a single or multiple fields + * + * @param null|QueryAggregatorInterface $aggregator Pass in a QueryAggregatorInterface object to handle converting + * deeply nested query string variables into a flattened array. + * Pass null to use the default PHP style aggregator. For legacy + * reasons, this function accepts a callable that must accepts a + * $key, $value, and query object. + * @return self + * @see \Guzzle\Http\QueryString::aggregateUsingComma() + */ + public function setAggregator(QueryAggregatorInterface $aggregator = null) + { + // Use the default aggregator if none was set + if (!$aggregator) { + if (!self::$defaultAggregator) { + self::$defaultAggregator = new PhpAggregator(); + } + $aggregator = self::$defaultAggregator; + } + + $this->aggregator = $aggregator; + + return $this; + } + + /** + * Set whether or not field names and values should be rawurlencoded + * + * @param bool|string $encode Set to TRUE to use RFC 3986 encoding (rawurlencode), false to disable encoding, or + * form_urlencoding to use application/x-www-form-urlencoded encoding (urlencode) + * @return self + */ + public function useUrlEncoding($encode) + { + $this->urlEncode = ($encode === true) ? self::RFC_3986 : $encode; + + return $this; + } + + /** + * Set the query string separator + * + * @param string $separator The query string separator that will separate fields + * + * @return self + */ + public function setFieldSeparator($separator) + { + $this->fieldSeparator = $separator; + + return $this; + } + + /** + * Set the query string value separator + * + * @param string $separator The query string separator that will separate values from fields + * + * @return self + */ + public function setValueSeparator($separator) + { + $this->valueSeparator = $separator; + + return $this; + } + + /** + * Returns an array of url encoded field names and values + * + * @return array + */ + public function urlEncode() + { + return $this->prepareData($this->data); + } + + /** + * URL encodes a value based on the url encoding type of the query string object + * + * @param string $value Value to encode + * + * @return string + */ + public function encodeValue($value) + { + if ($this->urlEncode == self::RFC_3986) { + return rawurlencode($value); + } elseif ($this->urlEncode == self::FORM_URLENCODED) { + return urlencode($value); + } else { + return (string) $value; + } + } + + /** + * Url encode parameter data and convert nested query strings into a flattened hash. + * + * @param array $data The data to encode + * + * @return array Returns an array of encoded values and keys + */ + protected function prepareData(array $data) + { + // If no aggregator is present then set the default + if (!$this->aggregator) { + $this->setAggregator(null); + } + + $temp = array(); + foreach ($data as $key => $value) { + if ($value === false || $value === null) { + // False and null will not include the "=". Use an empty string to include the "=". + $temp[$this->encodeValue($key)] = $value; + } elseif (is_array($value)) { + $temp = array_merge($temp, $this->aggregator->aggregate($key, $value, $this)); + } else { + $temp[$this->encodeValue($key)] = $this->encodeValue($value); + } + } + + return $temp; + } + + /** + * Converts a key value pair that can contain strings, nulls, false, or arrays + * into a single string. + * + * @param string $name Name of the field + * @param mixed $value Value of the field + * @return string + */ + private function convertKvp($name, $value) + { + if ($value === self::BLANK || $value === null || $value === false) { + return $name; + } elseif (!is_array($value)) { + return $name . $this->valueSeparator . $value; + } + + $result = ''; + foreach ($value as $v) { + $result .= $this->convertKvp($name, $v) . $this->fieldSeparator; + } + + return rtrim($result, $this->fieldSeparator); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/ReadLimitEntityBody.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/ReadLimitEntityBody.php new file mode 100644 index 000000000..ef282733b --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/ReadLimitEntityBody.php @@ -0,0 +1,122 @@ +setLimit($limit)->setOffset($offset); + } + + /** + * Returns only a subset of the decorated entity body when cast as a string + * {@inheritdoc} + */ + public function __toString() + { + if (!$this->body->isReadable() || + (!$this->body->isSeekable() && $this->body->isConsumed()) + ) { + return ''; + } + + $originalPos = $this->body->ftell(); + $this->body->seek($this->offset); + $data = ''; + while (!$this->feof()) { + $data .= $this->read(1048576); + } + $this->body->seek($originalPos); + + return (string) $data ?: ''; + } + + public function isConsumed() + { + return $this->body->isConsumed() || + ($this->body->ftell() >= $this->offset + $this->limit); + } + + /** + * Returns the Content-Length of the limited subset of data + * {@inheritdoc} + */ + public function getContentLength() + { + $length = $this->body->getContentLength(); + + return $length === false + ? $this->limit + : min($this->limit, min($length, $this->offset + $this->limit) - $this->offset); + } + + /** + * Allow for a bounded seek on the read limited entity body + * {@inheritdoc} + */ + public function seek($offset, $whence = SEEK_SET) + { + return $whence === SEEK_SET + ? $this->body->seek(max($this->offset, min($this->offset + $this->limit, $offset))) + : false; + } + + /** + * Set the offset to start limiting from + * + * @param int $offset Offset to seek to and begin byte limiting from + * + * @return self + */ + public function setOffset($offset) + { + $this->body->seek($offset); + $this->offset = $offset; + + return $this; + } + + /** + * Set the limit of bytes that the decorator allows to be read from the stream + * + * @param int $limit Total number of bytes to allow to be read from the stream + * + * @return self + */ + public function setLimit($limit) + { + $this->limit = $limit; + + return $this; + } + + public function read($length) + { + // Check if the current position is less than the total allowed bytes + original offset + $remaining = ($this->offset + $this->limit) - $this->body->ftell(); + if ($remaining > 0) { + // Only return the amount of requested data, ensuring that the byte limit is not exceeded + return $this->body->read(min($remaining, $length)); + } else { + return false; + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/RedirectPlugin.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/RedirectPlugin.php new file mode 100644 index 000000000..1a824b8b7 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/RedirectPlugin.php @@ -0,0 +1,250 @@ + array('onRequestSent', 100), + 'request.clone' => 'cleanupRequest', + 'request.before_send' => 'cleanupRequest' + ); + } + + /** + * Clean up the parameters of a request when it is cloned + * + * @param Event $event Event emitted + */ + public function cleanupRequest(Event $event) + { + $params = $event['request']->getParams(); + unset($params[self::REDIRECT_COUNT]); + unset($params[self::PARENT_REQUEST]); + } + + /** + * Called when a request receives a redirect response + * + * @param Event $event Event emitted + */ + public function onRequestSent(Event $event) + { + $response = $event['response']; + $request = $event['request']; + + // Only act on redirect requests with Location headers + if (!$response || $request->getParams()->get(self::DISABLE)) { + return; + } + + // Trace the original request based on parameter history + $original = $this->getOriginalRequest($request); + + // Terminating condition to set the effective response on the original request + if (!$response->isRedirect() || !$response->hasHeader('Location')) { + if ($request !== $original) { + // This is a terminating redirect response, so set it on the original request + $response->getParams()->set(self::REDIRECT_COUNT, $original->getParams()->get(self::REDIRECT_COUNT)); + $original->setResponse($response); + $response->setEffectiveUrl($request->getUrl()); + } + return; + } + + $this->sendRedirectRequest($original, $request, $response); + } + + /** + * Get the original request that initiated a series of redirects + * + * @param RequestInterface $request Request to get the original request from + * + * @return RequestInterface + */ + protected function getOriginalRequest(RequestInterface $request) + { + $original = $request; + // The number of redirects is held on the original request, so determine which request that is + while ($parent = $original->getParams()->get(self::PARENT_REQUEST)) { + $original = $parent; + } + + return $original; + } + + /** + * Create a redirect request for a specific request object + * + * Takes into account strict RFC compliant redirection (e.g. redirect POST with POST) vs doing what most clients do + * (e.g. redirect POST with GET). + * + * @param RequestInterface $request Request being redirected + * @param RequestInterface $original Original request + * @param int $statusCode Status code of the redirect + * @param string $location Location header of the redirect + * + * @return RequestInterface Returns a new redirect request + * @throws CouldNotRewindStreamException If the body needs to be rewound but cannot + */ + protected function createRedirectRequest( + RequestInterface $request, + $statusCode, + $location, + RequestInterface $original + ) { + $redirectRequest = null; + $strict = $original->getParams()->get(self::STRICT_REDIRECTS); + + // Switch method to GET for 303 redirects. 301 and 302 redirects also switch to GET unless we are forcing RFC + // compliance to emulate what most browsers do. NOTE: IE only switches methods on 301/302 when coming from a POST. + if ($request instanceof EntityEnclosingRequestInterface && ($statusCode == 303 || (!$strict && $statusCode <= 302))) { + $redirectRequest = RequestFactory::getInstance()->cloneRequestWithMethod($request, 'GET'); + } else { + $redirectRequest = clone $request; + } + + $redirectRequest->setIsRedirect(true); + // Always use the same response body when redirecting + $redirectRequest->setResponseBody($request->getResponseBody()); + + $location = Url::factory($location); + // If the location is not absolute, then combine it with the original URL + if (!$location->isAbsolute()) { + $originalUrl = $redirectRequest->getUrl(true); + // Remove query string parameters and just take what is present on the redirect Location header + $originalUrl->getQuery()->clear(); + $location = $originalUrl->combine((string) $location, true); + } + + $redirectRequest->setUrl($location); + + // Add the parent request to the request before it sends (make sure it's before the onRequestClone event too) + $redirectRequest->getEventDispatcher()->addListener( + 'request.before_send', + $func = function ($e) use (&$func, $request, $redirectRequest) { + $redirectRequest->getEventDispatcher()->removeListener('request.before_send', $func); + $e['request']->getParams()->set(RedirectPlugin::PARENT_REQUEST, $request); + } + ); + + // Rewind the entity body of the request if needed + if ($redirectRequest instanceof EntityEnclosingRequestInterface && $redirectRequest->getBody()) { + $body = $redirectRequest->getBody(); + // Only rewind the body if some of it has been read already, and throw an exception if the rewind fails + if ($body->ftell() && !$body->rewind()) { + throw new CouldNotRewindStreamException( + 'Unable to rewind the non-seekable entity body of the request after redirecting. cURL probably ' + . 'sent part of body before the redirect occurred. Try adding acustom rewind function using on the ' + . 'entity body of the request using setRewindFunction().' + ); + } + } + + return $redirectRequest; + } + + /** + * Prepare the request for redirection and enforce the maximum number of allowed redirects per client + * + * @param RequestInterface $original Original request + * @param RequestInterface $request Request to prepare and validate + * @param Response $response The current response + * + * @return RequestInterface + */ + protected function prepareRedirection(RequestInterface $original, RequestInterface $request, Response $response) + { + $params = $original->getParams(); + // This is a new redirect, so increment the redirect counter + $current = $params[self::REDIRECT_COUNT] + 1; + $params[self::REDIRECT_COUNT] = $current; + // Use a provided maximum value or default to a max redirect count of 5 + $max = isset($params[self::MAX_REDIRECTS]) ? $params[self::MAX_REDIRECTS] : $this->defaultMaxRedirects; + + // Throw an exception if the redirect count is exceeded + if ($current > $max) { + $this->throwTooManyRedirectsException($original, $max); + return false; + } else { + // Create a redirect request based on the redirect rules set on the request + return $this->createRedirectRequest( + $request, + $response->getStatusCode(), + trim($response->getLocation()), + $original + ); + } + } + + /** + * Send a redirect request and handle any errors + * + * @param RequestInterface $original The originating request + * @param RequestInterface $request The current request being redirected + * @param Response $response The response of the current request + * + * @throws BadResponseException|\Exception + */ + protected function sendRedirectRequest(RequestInterface $original, RequestInterface $request, Response $response) + { + // Validate and create a redirect request based on the original request and current response + if ($redirectRequest = $this->prepareRedirection($original, $request, $response)) { + try { + $redirectRequest->send(); + } catch (BadResponseException $e) { + $e->getResponse(); + if (!$e->getResponse()) { + throw $e; + } + } + } + } + + /** + * Throw a too many redirects exception for a request + * + * @param RequestInterface $original Request + * @param int $max Max allowed redirects + * + * @throws TooManyRedirectsException when too many redirects have been issued + */ + protected function throwTooManyRedirectsException(RequestInterface $original, $max) + { + $original->getEventDispatcher()->addListener( + 'request.complete', + $func = function ($e) use (&$func, $original, $max) { + $original->getEventDispatcher()->removeListener('request.complete', $func); + $str = "{$max} redirects were issued for this request:\n" . $e['request']->getRawHeaders(); + throw new TooManyRedirectsException($str); + } + ); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Resources/cacert.pem b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Resources/cacert.pem new file mode 100644 index 000000000..18ce70381 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Resources/cacert.pem @@ -0,0 +1,3870 @@ +## +## Bundle of CA Root Certificates +## +## Certificate data from Mozilla downloaded on: Wed Aug 13 21:49:32 2014 +## +## This is a bundle of X.509 certificates of public Certificate Authorities +## (CA). These were automatically extracted from Mozilla's root certificates +## file (certdata.txt). This file can be found in the mozilla source tree: +## http://hg.mozilla.org/releases/mozilla-release/raw-file/default/security/nss/lib/ckfw/builtins/certdata.txt +## +## It contains the certificates in PEM format and therefore +## can be directly used with curl / libcurl / php_curl, or with +## an Apache+mod_ssl webserver for SSL client authentication. +## Just configure this file as the SSLCACertificateFile. +## +## Conversion done with mk-ca-bundle.pl verison 1.22. +## SHA1: bf2c15b3019e696660321d2227d942936dc50aa7 +## + + +GTE CyberTrust Global Root +========================== +-----BEGIN CERTIFICATE----- +MIICWjCCAcMCAgGlMA0GCSqGSIb3DQEBBAUAMHUxCzAJBgNVBAYTAlVTMRgwFgYDVQQKEw9HVEUg +Q29ycG9yYXRpb24xJzAlBgNVBAsTHkdURSBDeWJlclRydXN0IFNvbHV0aW9ucywgSW5jLjEjMCEG +A1UEAxMaR1RFIEN5YmVyVHJ1c3QgR2xvYmFsIFJvb3QwHhcNOTgwODEzMDAyOTAwWhcNMTgwODEz +MjM1OTAwWjB1MQswCQYDVQQGEwJVUzEYMBYGA1UEChMPR1RFIENvcnBvcmF0aW9uMScwJQYDVQQL +Ex5HVEUgQ3liZXJUcnVzdCBTb2x1dGlvbnMsIEluYy4xIzAhBgNVBAMTGkdURSBDeWJlclRydXN0 +IEdsb2JhbCBSb290MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCVD6C28FCc6HrHiM3dFw4u +sJTQGz0O9pTAipTHBsiQl8i4ZBp6fmw8U+E3KHNgf7KXUwefU/ltWJTSr41tiGeA5u2ylc9yMcql +HHK6XALnZELn+aks1joNrI1CqiQBOeacPwGFVw1Yh0X404Wqk2kmhXBIgD8SFcd5tB8FLztimQID +AQABMA0GCSqGSIb3DQEBBAUAA4GBAG3rGwnpXtlR22ciYaQqPEh346B8pt5zohQDhT37qw4wxYMW +M4ETCJ57NE7fQMh017l93PR2VX2bY1QY6fDq81yx2YtCHrnAlU66+tXifPVoYb+O7AWXX1uw16OF +NMQkpw0PlZPvy5TYnh+dXIVtx6quTx8itc2VrbqnzPmrC3p/ +-----END CERTIFICATE----- + +Thawte Server CA +================ +-----BEGIN CERTIFICATE----- +MIIDEzCCAnygAwIBAgIBATANBgkqhkiG9w0BAQQFADCBxDELMAkGA1UEBhMCWkExFTATBgNVBAgT +DFdlc3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMR0wGwYDVQQKExRUaGF3dGUgQ29uc3Vs +dGluZyBjYzEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjEZMBcGA1UE +AxMQVGhhd3RlIFNlcnZlciBDQTEmMCQGCSqGSIb3DQEJARYXc2VydmVyLWNlcnRzQHRoYXd0ZS5j +b20wHhcNOTYwODAxMDAwMDAwWhcNMjAxMjMxMjM1OTU5WjCBxDELMAkGA1UEBhMCWkExFTATBgNV +BAgTDFdlc3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMR0wGwYDVQQKExRUaGF3dGUgQ29u +c3VsdGluZyBjYzEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjEZMBcG +A1UEAxMQVGhhd3RlIFNlcnZlciBDQTEmMCQGCSqGSIb3DQEJARYXc2VydmVyLWNlcnRzQHRoYXd0 +ZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANOkUG7I/1Zr5s9dtuoMaHVHoqrC2oQl +/Kj0R1HahbUgdJSGHg91yekIYfUGbTBuFRkC6VLAYttNmZ7iagxEOM3+vuNkCXDF/rFrKbYvScg7 +1CcEJRCXL+eQbcAoQpnXTEPew/UhbVSfXcNY4cDk2VuwuNy0e982OsK1ZiIS1ocNAgMBAAGjEzAR +MA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEEBQADgYEAB/pMaVz7lcxG7oWDTSEwjsrZqG9J +GubaUeNgcGyEYRGhGshIPllDfU+VPaGLtwtimHp1it2ITk6eQNuozDJ0uW8NxuOzRAvZim+aKZuZ +GCg70eNAKJpaPNW15yAbi8qkq43pUdniTCxZqdq5snUb9kLy78fyGPmJvKP/iiMucEc= +-----END CERTIFICATE----- + +Thawte Premium Server CA +======================== +-----BEGIN CERTIFICATE----- +MIIDJzCCApCgAwIBAgIBATANBgkqhkiG9w0BAQQFADCBzjELMAkGA1UEBhMCWkExFTATBgNVBAgT +DFdlc3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMR0wGwYDVQQKExRUaGF3dGUgQ29uc3Vs +dGluZyBjYzEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjEhMB8GA1UE +AxMYVGhhd3RlIFByZW1pdW0gU2VydmVyIENBMSgwJgYJKoZIhvcNAQkBFhlwcmVtaXVtLXNlcnZl +ckB0aGF3dGUuY29tMB4XDTk2MDgwMTAwMDAwMFoXDTIwMTIzMTIzNTk1OVowgc4xCzAJBgNVBAYT +AlpBMRUwEwYDVQQIEwxXZXN0ZXJuIENhcGUxEjAQBgNVBAcTCUNhcGUgVG93bjEdMBsGA1UEChMU +VGhhd3RlIENvbnN1bHRpbmcgY2MxKDAmBgNVBAsTH0NlcnRpZmljYXRpb24gU2VydmljZXMgRGl2 +aXNpb24xITAfBgNVBAMTGFRoYXd0ZSBQcmVtaXVtIFNlcnZlciBDQTEoMCYGCSqGSIb3DQEJARYZ +cHJlbWl1bS1zZXJ2ZXJAdGhhd3RlLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0jY2 +aovXwlue2oFBYo847kkEVdbQ7xwblRZH7xhINTpS9CtqBo87L+pW46+GjZ4X9560ZXUCTe/LCaIh +Udib0GfQug2SBhRz1JPLlyoAnFxODLz6FVL88kRu2hFKbgifLy3j+ao6hnO2RlNYyIkFvYMRuHM/ +qgeN9EJN50CdHDcCAwEAAaMTMBEwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQQFAAOBgQAm +SCwWwlj66BZ0DKqqX1Q/8tfJeGBeXm43YyJ3Nn6yF8Q0ufUIhfzJATj/Tb7yFkJD57taRvvBxhEf +8UqwKEbJw8RCfbz6q1lu1bdRiBHjpIUZa4JMpAwSremkrj/xw0llmozFyD4lt5SZu5IycQfwhl7t +UCemDaYj+bvLpgcUQg== +-----END CERTIFICATE----- + +Equifax Secure CA +================= +-----BEGIN CERTIFICATE----- +MIIDIDCCAomgAwIBAgIENd70zzANBgkqhkiG9w0BAQUFADBOMQswCQYDVQQGEwJVUzEQMA4GA1UE +ChMHRXF1aWZheDEtMCsGA1UECxMkRXF1aWZheCBTZWN1cmUgQ2VydGlmaWNhdGUgQXV0aG9yaXR5 +MB4XDTk4MDgyMjE2NDE1MVoXDTE4MDgyMjE2NDE1MVowTjELMAkGA1UEBhMCVVMxEDAOBgNVBAoT +B0VxdWlmYXgxLTArBgNVBAsTJEVxdWlmYXggU2VjdXJlIENlcnRpZmljYXRlIEF1dGhvcml0eTCB +nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAwV2xWGcIYu6gmi0fCG2RFGiYCh7+2gRvE4RiIcPR +fM6fBeC4AfBONOziipUEZKzxa1NfBbPLZ4C/QgKO/t0BCezhABRP/PvwDN1Dulsr4R+AcJkVV5MW +8Q+XarfCaCMczE1ZMKxRHjuvK9buY0V7xdlfUNLjUA86iOe/FP3gx7kCAwEAAaOCAQkwggEFMHAG +A1UdHwRpMGcwZaBjoGGkXzBdMQswCQYDVQQGEwJVUzEQMA4GA1UEChMHRXF1aWZheDEtMCsGA1UE +CxMkRXF1aWZheCBTZWN1cmUgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MQ0wCwYDVQQDEwRDUkwxMBoG +A1UdEAQTMBGBDzIwMTgwODIyMTY0MTUxWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAUSOZo+SvS +spXXR9gjIBBPM5iQn9QwHQYDVR0OBBYEFEjmaPkr0rKV10fYIyAQTzOYkJ/UMAwGA1UdEwQFMAMB +Af8wGgYJKoZIhvZ9B0EABA0wCxsFVjMuMGMDAgbAMA0GCSqGSIb3DQEBBQUAA4GBAFjOKer89961 +zgK5F7WF0bnj4JXMJTENAKaSbn+2kmOeUJXRmm/kEd5jhW6Y7qj/WsjTVbJmcVfewCHrPSqnI0kB +BIZCe/zuf6IWUrVnZ9NA2zsmWLIodz2uFHdh1voqZiegDfqnc1zqcPGUIWVEX/r87yloqaKHee95 +70+sB3c4 +-----END CERTIFICATE----- + +Verisign Class 3 Public Primary Certification Authority +======================================================= +-----BEGIN CERTIFICATE----- +MIICPDCCAaUCEHC65B0Q2Sk0tjjKewPMur8wDQYJKoZIhvcNAQECBQAwXzELMAkGA1UEBhMCVVMx +FzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAzIFB1YmxpYyBQcmltYXJ5 +IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTk2MDEyOTAwMDAwMFoXDTI4MDgwMTIzNTk1OVow +XzELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAz +IFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGfMA0GCSqGSIb3DQEBAQUA +A4GNADCBiQKBgQDJXFme8huKARS0EN8EQNvjV69qRUCPhAwL0TPZ2RHP7gJYHyX3KqhEBarsAx94 +f56TuZoAqiN91qyFomNFx3InzPRMxnVx0jnvT0Lwdd8KkMaOIG+YD/isI19wKTakyYbnsZogy1Ol +hec9vn2a/iRFM9x2Fe0PonFkTGUugWhFpwIDAQABMA0GCSqGSIb3DQEBAgUAA4GBALtMEivPLCYA +TxQT3ab7/AoRhIzzKBxnki98tsX63/Dolbwdj2wsqFHMc9ikwFPwTtYmwHYBV4GSXiHx0bH/59Ah +WM1pF+NEHJwZRDmJXNycAA9WjQKZ7aKQRUzkuxCkPfAyAw7xzvjoyVGM5mKf5p/AfbdynMk2Omuf +Tqj/ZA1k +-----END CERTIFICATE----- + +Verisign Class 3 Public Primary Certification Authority - G2 +============================================================ +-----BEGIN CERTIFICATE----- +MIIDAjCCAmsCEH3Z/gfPqB63EHln+6eJNMYwDQYJKoZIhvcNAQEFBQAwgcExCzAJBgNVBAYTAlVT +MRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5jLjE8MDoGA1UECxMzQ2xhc3MgMyBQdWJsaWMgUHJpbWFy +eSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEcyMTowOAYDVQQLEzEoYykgMTk5OCBWZXJpU2ln +biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MR8wHQYDVQQLExZWZXJpU2lnbiBUcnVz +dCBOZXR3b3JrMB4XDTk4MDUxODAwMDAwMFoXDTI4MDgwMTIzNTk1OVowgcExCzAJBgNVBAYTAlVT +MRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5jLjE8MDoGA1UECxMzQ2xhc3MgMyBQdWJsaWMgUHJpbWFy +eSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEcyMTowOAYDVQQLEzEoYykgMTk5OCBWZXJpU2ln +biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MR8wHQYDVQQLExZWZXJpU2lnbiBUcnVz +dCBOZXR3b3JrMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDMXtERXVxp0KvTuWpMmR9ZmDCO +FoUgRm1HP9SFIIThbbP4pO0M8RcPO/mn+SXXwc+EY/J8Y8+iR/LGWzOOZEAEaMGAuWQcRXfH2G71 +lSk8UOg013gfqLptQ5GVj0VXXn7F+8qkBOvqlzdUMG+7AUcyM83cV5tkaWH4mx0ciU9cZwIDAQAB +MA0GCSqGSIb3DQEBBQUAA4GBAFFNzb5cy5gZnBWyATl4Lk0PZ3BwmcYQWpSkU01UbSuvDV1Ai2TT +1+7eVmGSX6bEHRBhNtMsJzzoKQm5EWR0zLVznxxIqbxhAe7iF6YM40AIOw7n60RzKprxaZLvcRTD +Oaxxp5EJb+RxBrO6WVcmeQD2+A2iMzAo1KpYoJ2daZH9 +-----END CERTIFICATE----- + +GlobalSign Root CA +================== +-----BEGIN CERTIFICATE----- +MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx +GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds +b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV +BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD +VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa +DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc +THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb +Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP +c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX +gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV +HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF +AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj +Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG +j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH +hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC +X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A== +-----END CERTIFICATE----- + +GlobalSign Root CA - R2 +======================= +-----BEGIN CERTIFICATE----- +MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEgMB4GA1UECxMXR2xv +YmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkdsb2JhbFNpZ24xEzARBgNVBAMTCkdsb2Jh +bFNpZ24wHhcNMDYxMjE1MDgwMDAwWhcNMjExMjE1MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxT +aWduIFJvb3QgQ0EgLSBSMjETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2ln +bjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8omUVCxKs+IVSbC9N/hHD6 +ErPLv4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe+3t+c4isUoh7SqbKSaZeqKeMWhG8eoLrvozp +s6yWJQeXSpkqBy+0Hne/ig+1AnwblrjFuTosvNYSuetZfeLQBoZfXklqtTleiDTsvHgMCJiEbKjN +S7SgfQx5TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzdC9XZzPnqJworc5HGnRusyMvo4KD0L5CL +TfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pazq+r1feqCapgvdzZX99yqWATXgAByUr6P6TqBwMhAo6C +ygPCm48CAwEAAaOBnDCBmTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E +FgQUm+IHV2ccHsBqBt5ZtJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5nbG9i +YWxzaWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG3lm0mi3f3BmGLjAN +BgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4GsJ0/WwbgcQ3izDJr86iw8bmEbTUsp +9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4h4hO291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu +01yiPqFbQfXf5WRDLenVOavSot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG7 +9G+dwfCMNYxdAfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmgQWpzU/qlULRuJQ/7 +TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq/H5COEBkEveegeGTLg== +-----END CERTIFICATE----- + +ValiCert Class 1 VA +=================== +-----BEGIN CERTIFICATE----- +MIIC5zCCAlACAQEwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRp +b24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENs +YXNzIDEgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZh +bGljZXJ0LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTk5MDYyNTIy +MjM0OFoXDTE5MDYyNTIyMjM0OFowgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRpb24gTmV0 +d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENsYXNzIDEg +UG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0 +LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMIGfMA0GCSqGSIb3DQEBAQUA +A4GNADCBiQKBgQDYWYJ6ibiWuqYvaG9YLqdUHAZu9OqNSLwxlBfw8068srg1knaw0KWlAdcAAxIi +GQj4/xEjm84H9b9pGib+TunRf50sQB1ZaG6m+FiwnRqP0z/x3BkGgagO4DrdyFNFCQbmD3DD+kCm +DuJWBQ8YTfwggtFzVXSNdnKgHZ0dwN0/cQIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAFBoPUn0LBwG +lN+VYH+Wexf+T3GtZMjdd9LvWVXoP+iOBSoh8gfStadS/pyxtuJbdxdA6nLWI8sogTLDAHkY7FkX +icnGah5xyf23dKUlRWnFSKsZ4UWKJWsZ7uW7EvV/96aNUcPwnXS3qT6gpf+2SQMT2iLM7XGCK5nP +Orf1LXLI +-----END CERTIFICATE----- + +ValiCert Class 2 VA +=================== +-----BEGIN CERTIFICATE----- +MIIC5zCCAlACAQEwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRp +b24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENs +YXNzIDIgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZh +bGljZXJ0LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTk5MDYyNjAw +MTk1NFoXDTE5MDYyNjAwMTk1NFowgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRpb24gTmV0 +d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENsYXNzIDIg +UG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0 +LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMIGfMA0GCSqGSIb3DQEBAQUA +A4GNADCBiQKBgQDOOnHK5avIWZJV16vYdA757tn2VUdZZUcOBVXc65g2PFxTXdMwzzjsvUGJ7SVC +CSRrCl6zfN1SLUzm1NZ9WlmpZdRJEy0kTRxQb7XBhVQ7/nHk01xC+YDgkRoKWzk2Z/M/VXwbP7Rf +ZHM047QSv4dk+NoS/zcnwbNDu+97bi5p9wIDAQABMA0GCSqGSIb3DQEBBQUAA4GBADt/UG9vUJSZ +SWI4OB9L+KXIPqeCgfYrx+jFzug6EILLGACOTb2oWH+heQC1u+mNr0HZDzTuIYEZoDJJKPTEjlbV +UjP9UNV+mWwD5MlM/Mtsq2azSiGM5bUMMj4QssxsodyamEwCW/POuZ6lcg5Ktz885hZo+L7tdEy8 +W9ViH0Pd +-----END CERTIFICATE----- + +RSA Root Certificate 1 +====================== +-----BEGIN CERTIFICATE----- +MIIC5zCCAlACAQEwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRp +b24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENs +YXNzIDMgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZh +bGljZXJ0LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTk5MDYyNjAw +MjIzM1oXDTE5MDYyNjAwMjIzM1owgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRpb24gTmV0 +d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENsYXNzIDMg +UG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0 +LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMIGfMA0GCSqGSIb3DQEBAQUA +A4GNADCBiQKBgQDjmFGWHOjVsQaBalfDcnWTq8+epvzzFlLWLU2fNUSoLgRNB0mKOCn1dzfnt6td +3zZxFJmP3MKS8edgkpfs2Ejcv8ECIMYkpChMMFp2bbFc893enhBxoYjHW5tBbcqwuI4V7q0zK89H +BFx1cQqYJJgpp0lZpd34t0NiYfPT4tBVPwIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAFa7AliEZwgs +3x/be0kz9dNnnfS0ChCzycUs4pJqcXgn8nCDQtM+z6lU9PHYkhaM0QTLS6vJn0WuPIqpsHEzXcjF +V9+vqDWzf4mH6eglkrh/hXqu1rweN1gqZ8mRzyqBPu3GOd/APhmcGcwTTYJBtYze4D1gCCAPRX5r +on+jjBXu +-----END CERTIFICATE----- + +Verisign Class 3 Public Primary Certification Authority - G3 +============================================================ +-----BEGIN CERTIFICATE----- +MIIEGjCCAwICEQCbfgZJoz5iudXukEhxKe9XMA0GCSqGSIb3DQEBBQUAMIHKMQswCQYDVQQGEwJV +UzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdv +cmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl +IG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDMgUHVibGljIFByaW1hcnkgQ2VydGlmaWNh +dGlvbiBBdXRob3JpdHkgLSBHMzAeFw05OTEwMDEwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMIHKMQsw +CQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRy +dXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhv +cml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDMgUHVibGljIFByaW1hcnkg +Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC +ggEBAMu6nFL8eB8aHm8bN3O9+MlrlBIwT/A2R/XQkQr1F8ilYcEWQE37imGQ5XYgwREGfassbqb1 +EUGO+i2tKmFZpGcmTNDovFJbcCAEWNF6yaRpvIMXZK0Fi7zQWM6NjPXr8EJJC52XJ2cybuGukxUc +cLwgTS8Y3pKI6GyFVxEa6X7jJhFUokWWVYPKMIno3Nij7SqAP395ZVc+FSBmCC+Vk7+qRy+oRpfw +EuL+wgorUeZ25rdGt+INpsyow0xZVYnm6FNcHOqd8GIWC6fJXwzw3sJ2zq/3avL6QaaiMxTJ5Xpj +055iN9WFZZ4O5lMkdBteHRJTW8cs54NJOxWuimi5V5cCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEA +ERSWwauSCPc/L8my/uRan2Te2yFPhpk0djZX3dAVL8WtfxUfN2JzPtTnX84XA9s1+ivbrmAJXx5f +j267Cz3qWhMeDGBvtcC1IyIuBwvLqXTLR7sdwdela8wv0kL9Sd2nic9TutoAWii/gt/4uhMdUIaC +/Y4wjylGsB49Ndo4YhYYSq3mtlFs3q9i6wHQHiT+eo8SGhJouPtmmRQURVyu565pF4ErWjfJXir0 +xuKhXFSbplQAz/DxwceYMBo7Nhbbo27q/a2ywtrvAkcTisDxszGtTxzhT5yvDwyd93gN2PQ1VoDa +t20Xj50egWTh/sVFuq1ruQp6Tk9LhO5L8X3dEQ== +-----END CERTIFICATE----- + +Verisign Class 4 Public Primary Certification Authority - G3 +============================================================ +-----BEGIN CERTIFICATE----- +MIIEGjCCAwICEQDsoKeLbnVqAc/EfMwvlF7XMA0GCSqGSIb3DQEBBQUAMIHKMQswCQYDVQQGEwJV +UzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdv +cmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl +IG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDQgUHVibGljIFByaW1hcnkgQ2VydGlmaWNh +dGlvbiBBdXRob3JpdHkgLSBHMzAeFw05OTEwMDEwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMIHKMQsw +CQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRy +dXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhv +cml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDQgUHVibGljIFByaW1hcnkg +Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC +ggEBAK3LpRFpxlmr8Y+1GQ9Wzsy1HyDkniYlS+BzZYlZ3tCD5PUPtbut8XzoIfzk6AzufEUiGXaS +tBO3IFsJ+mGuqPKljYXCKtbeZjbSmwL0qJJgfJxptI8kHtCGUvYynEFYHiK9zUVilQhu0GbdU6LM +8BDcVHOLBKFGMzNcF0C5nk3T875Vg+ixiY5afJqWIpA7iCXy0lOIAgwLePLmNxdLMEYH5IBtptiW +Lugs+BGzOA1mppvqySNb247i8xOOGlktqgLw7KSHZtzBP/XYufTsgsbSPZUd5cBPhMnZo0QoBmrX +Razwa2rvTl/4EYIeOGM0ZlDUPpNz+jDDZq3/ky2X7wMCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEA +j/ola09b5KROJ1WrIhVZPMq1CtRK26vdoV9TxaBXOcLORyu+OshWv8LZJxA6sQU8wHcxuzrTBXtt +mhwwjIDLk5Mqg6sFUYICABFna/OIYUdfA5PVWw3g8dShMjWFsjrbsIKr0csKvE+MW8VLADsfKoKm +fjaF3H48ZwC15DtS4KjrXRX5xm3wrR0OhbepmnMUWluPQSjA1egtTaRezarZ7c7c2NU8Qh0XwRJd +RTjDOPP8hS6DRkiy1yBfkjaP53kPmF6Z6PDQpLv1U70qzlmwr25/bLvSHgCwIe34QWKCudiyxLtG +UPMxxY8BqHTr9Xgn2uf3ZkPznoM+IKrDNWCRzg== +-----END CERTIFICATE----- + +Entrust.net Secure Server CA +============================ +-----BEGIN CERTIFICATE----- +MIIE2DCCBEGgAwIBAgIEN0rSQzANBgkqhkiG9w0BAQUFADCBwzELMAkGA1UEBhMCVVMxFDASBgNV +BAoTC0VudHJ1c3QubmV0MTswOQYDVQQLEzJ3d3cuZW50cnVzdC5uZXQvQ1BTIGluY29ycC4gYnkg +cmVmLiAobGltaXRzIGxpYWIuKTElMCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRl +ZDE6MDgGA1UEAxMxRW50cnVzdC5uZXQgU2VjdXJlIFNlcnZlciBDZXJ0aWZpY2F0aW9uIEF1dGhv +cml0eTAeFw05OTA1MjUxNjA5NDBaFw0xOTA1MjUxNjM5NDBaMIHDMQswCQYDVQQGEwJVUzEUMBIG +A1UEChMLRW50cnVzdC5uZXQxOzA5BgNVBAsTMnd3dy5lbnRydXN0Lm5ldC9DUFMgaW5jb3JwLiBi +eSByZWYuIChsaW1pdHMgbGlhYi4pMSUwIwYDVQQLExwoYykgMTk5OSBFbnRydXN0Lm5ldCBMaW1p +dGVkMTowOAYDVQQDEzFFbnRydXN0Lm5ldCBTZWN1cmUgU2VydmVyIENlcnRpZmljYXRpb24gQXV0 +aG9yaXR5MIGdMA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQDNKIM0VBuJ8w+vN5Ex/68xYMmo6LIQ +aO2f55M28Qpku0f1BBc/I0dNxScZgSYMVHINiC3ZH5oSn7yzcdOAGT9HZnuMNSjSuQrfJNqc1lB5 +gXpa0zf3wkrYKZImZNHkmGw6AIr1NJtl+O3jEP/9uElY3KDegjlrgbEWGWG5VLbmQwIBA6OCAdcw +ggHTMBEGCWCGSAGG+EIBAQQEAwIABzCCARkGA1UdHwSCARAwggEMMIHeoIHboIHYpIHVMIHSMQsw +CQYDVQQGEwJVUzEUMBIGA1UEChMLRW50cnVzdC5uZXQxOzA5BgNVBAsTMnd3dy5lbnRydXN0Lm5l +dC9DUFMgaW5jb3JwLiBieSByZWYuIChsaW1pdHMgbGlhYi4pMSUwIwYDVQQLExwoYykgMTk5OSBF +bnRydXN0Lm5ldCBMaW1pdGVkMTowOAYDVQQDEzFFbnRydXN0Lm5ldCBTZWN1cmUgU2VydmVyIENl +cnRpZmljYXRpb24gQXV0aG9yaXR5MQ0wCwYDVQQDEwRDUkwxMCmgJ6AlhiNodHRwOi8vd3d3LmVu +dHJ1c3QubmV0L0NSTC9uZXQxLmNybDArBgNVHRAEJDAigA8xOTk5MDUyNTE2MDk0MFqBDzIwMTkw +NTI1MTYwOTQwWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAU8BdiE1U9s/8KAGv7UISX8+1i0Bow +HQYDVR0OBBYEFPAXYhNVPbP/CgBr+1CEl/PtYtAaMAwGA1UdEwQFMAMBAf8wGQYJKoZIhvZ9B0EA +BAwwChsEVjQuMAMCBJAwDQYJKoZIhvcNAQEFBQADgYEAkNwwAvpkdMKnCqV8IY00F6j7Rw7/JXyN +Ewr75Ji174z4xRAN95K+8cPV1ZVqBLssziY2ZcgxxufuP+NXdYR6Ee9GTxj005i7qIcyunL2POI9 +n9cd2cNgQ4xYDiKWL2KjLB+6rQXvqzJ4h6BUcxm1XAX5Uj5tLUUL9wqT6u0G+bI= +-----END CERTIFICATE----- + +Entrust.net Premium 2048 Secure Server CA +========================================= +-----BEGIN CERTIFICATE----- +MIIEKjCCAxKgAwIBAgIEOGPe+DANBgkqhkiG9w0BAQUFADCBtDEUMBIGA1UEChMLRW50cnVzdC5u +ZXQxQDA+BgNVBAsUN3d3dy5lbnRydXN0Lm5ldC9DUFNfMjA0OCBpbmNvcnAuIGJ5IHJlZi4gKGxp +bWl0cyBsaWFiLikxJTAjBgNVBAsTHChjKSAxOTk5IEVudHJ1c3QubmV0IExpbWl0ZWQxMzAxBgNV +BAMTKkVudHJ1c3QubmV0IENlcnRpZmljYXRpb24gQXV0aG9yaXR5ICgyMDQ4KTAeFw05OTEyMjQx +NzUwNTFaFw0yOTA3MjQxNDE1MTJaMIG0MRQwEgYDVQQKEwtFbnRydXN0Lm5ldDFAMD4GA1UECxQ3 +d3d3LmVudHJ1c3QubmV0L0NQU18yMDQ4IGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxpYWIuKTEl +MCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEGA1UEAxMqRW50cnVzdC5u +ZXQgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgKDIwNDgpMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A +MIIBCgKCAQEArU1LqRKGsuqjIAcVFmQqK0vRvwtKTY7tgHalZ7d4QMBzQshowNtTK91euHaYNZOL +Gp18EzoOH1u3Hs/lJBQesYGpjX24zGtLA/ECDNyrpUAkAH90lKGdCCmziAv1h3edVc3kw37XamSr +hRSGlVuXMlBvPci6Zgzj/L24ScF2iUkZ/cCovYmjZy/Gn7xxGWC4LeksyZB2ZnuU4q941mVTXTzW +nLLPKQP5L6RQstRIzgUyVYr9smRMDuSYB3Xbf9+5CFVghTAp+XtIpGmG4zU/HoZdenoVve8AjhUi +VBcAkCaTvA5JaJG/+EfTnZVCwQ5N328mz8MYIWJmQ3DW1cAH4QIDAQABo0IwQDAOBgNVHQ8BAf8E +BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUVeSB0RGAvtiJuQijMfmhJAkWuXAwDQYJ +KoZIhvcNAQEFBQADggEBADubj1abMOdTmXx6eadNl9cZlZD7Bh/KM3xGY4+WZiT6QBshJ8rmcnPy +T/4xmf3IDExoU8aAghOY+rat2l098c5u9hURlIIM7j+VrxGrD9cv3h8Dj1csHsm7mhpElesYT6Yf +zX1XEC+bBAlahLVu2B064dae0Wx5XnkcFMXj0EyTO2U87d89vqbllRrDtRnDvV5bu/8j72gZyxKT +J1wDLW8w0B62GqzeWvfRqqgnpv55gcR5mTNXuhKwqeBCbJPKVt7+bYQLCIt+jerXmCHG8+c8eS9e +nNFMFY3h7CI3zJpDC5fcgJCNs2ebb0gIFVbPv/ErfF6adulZkMV8gzURZVE= +-----END CERTIFICATE----- + +Baltimore CyberTrust Root +========================= +-----BEGIN CERTIFICATE----- +MIIDdzCCAl+gAwIBAgIEAgAAuTANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJJRTESMBAGA1UE +ChMJQmFsdGltb3JlMRMwEQYDVQQLEwpDeWJlclRydXN0MSIwIAYDVQQDExlCYWx0aW1vcmUgQ3li +ZXJUcnVzdCBSb290MB4XDTAwMDUxMjE4NDYwMFoXDTI1MDUxMjIzNTkwMFowWjELMAkGA1UEBhMC +SUUxEjAQBgNVBAoTCUJhbHRpbW9yZTETMBEGA1UECxMKQ3liZXJUcnVzdDEiMCAGA1UEAxMZQmFs +dGltb3JlIEN5YmVyVHJ1c3QgUm9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKME +uyKrmD1X6CZymrV51Cni4eiVgLGw41uOKymaZN+hXe2wCQVt2yguzmKiYv60iNoS6zjrIZ3AQSsB +UnuId9Mcj8e6uYi1agnnc+gRQKfRzMpijS3ljwumUNKoUMMo6vWrJYeKmpYcqWe4PwzV9/lSEy/C +G9VwcPCPwBLKBsua4dnKM3p31vjsufFoREJIE9LAwqSuXmD+tqYF/LTdB1kC1FkYmGP1pWPgkAx9 +XbIGevOF6uvUA65ehD5f/xXtabz5OTZydc93Uk3zyZAsuT3lySNTPx8kmCFcB5kpvcY67Oduhjpr +l3RjM71oGDHweI12v/yejl0qhqdNkNwnGjkCAwEAAaNFMEMwHQYDVR0OBBYEFOWdWTCCR1jMrPoI +VDaGezq1BE3wMBIGA1UdEwEB/wQIMAYBAf8CAQMwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEB +BQUAA4IBAQCFDF2O5G9RaEIFoN27TyclhAO992T9Ldcw46QQF+vaKSm2eT929hkTI7gQCvlYpNRh +cL0EYWoSihfVCr3FvDB81ukMJY2GQE/szKN+OMY3EU/t3WgxjkzSswF07r51XgdIGn9w/xZchMB5 +hbgF/X++ZRGjD8ACtPhSNzkE1akxehi/oCr0Epn3o0WC4zxe9Z2etciefC7IpJ5OCBRLbf1wbWsa +Y71k5h+3zvDyny67G7fyUIhzksLi4xaNmjICq44Y3ekQEe5+NauQrz4wlHrQMz2nZQ/1/I6eYs9H +RCwBXbsdtTLSR9I4LtD+gdwyah617jzV/OeBHRnDJELqYzmp +-----END CERTIFICATE----- + +Equifax Secure Global eBusiness CA +================================== +-----BEGIN CERTIFICATE----- +MIICkDCCAfmgAwIBAgIBATANBgkqhkiG9w0BAQQFADBaMQswCQYDVQQGEwJVUzEcMBoGA1UEChMT +RXF1aWZheCBTZWN1cmUgSW5jLjEtMCsGA1UEAxMkRXF1aWZheCBTZWN1cmUgR2xvYmFsIGVCdXNp +bmVzcyBDQS0xMB4XDTk5MDYyMTA0MDAwMFoXDTIwMDYyMTA0MDAwMFowWjELMAkGA1UEBhMCVVMx +HDAaBgNVBAoTE0VxdWlmYXggU2VjdXJlIEluYy4xLTArBgNVBAMTJEVxdWlmYXggU2VjdXJlIEds +b2JhbCBlQnVzaW5lc3MgQ0EtMTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAuucXkAJlsTRV +PEnCUdXfp9E3j9HngXNBUmCbnaEXJnitx7HoJpQytd4zjTov2/KaelpzmKNc6fuKcxtc58O/gGzN +qfTWK8D3+ZmqY6KxRwIP1ORROhI8bIpaVIRw28HFkM9yRcuoWcDNM50/o5brhTMhHD4ePmBudpxn +hcXIw2ECAwEAAaNmMGQwEQYJYIZIAYb4QgEBBAQDAgAHMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0j +BBgwFoAUvqigdHJQa0S3ySPY+6j/s1draGwwHQYDVR0OBBYEFL6ooHRyUGtEt8kj2Puo/7NXa2hs +MA0GCSqGSIb3DQEBBAUAA4GBADDiAVGqx+pf2rnQZQ8w1j7aDRRJbpGTJxQx78T3LUX47Me/okEN +I7SS+RkAZ70Br83gcfxaz2TE4JaY0KNA4gGK7ycH8WUBikQtBmV1UsCGECAhX2xrD2yuCRyv8qIY +NMR1pHMc8Y3c7635s3a0kr/clRAevsvIO1qEYBlWlKlV +-----END CERTIFICATE----- + +Equifax Secure eBusiness CA 1 +============================= +-----BEGIN CERTIFICATE----- +MIICgjCCAeugAwIBAgIBBDANBgkqhkiG9w0BAQQFADBTMQswCQYDVQQGEwJVUzEcMBoGA1UEChMT +RXF1aWZheCBTZWN1cmUgSW5jLjEmMCQGA1UEAxMdRXF1aWZheCBTZWN1cmUgZUJ1c2luZXNzIENB +LTEwHhcNOTkwNjIxMDQwMDAwWhcNMjAwNjIxMDQwMDAwWjBTMQswCQYDVQQGEwJVUzEcMBoGA1UE +ChMTRXF1aWZheCBTZWN1cmUgSW5jLjEmMCQGA1UEAxMdRXF1aWZheCBTZWN1cmUgZUJ1c2luZXNz +IENBLTEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAM4vGbwXt3fek6lfWg0XTzQaDJj0ItlZ +1MRoRvC0NcWFAyDGr0WlIVFFQesWWDYyb+JQYmT5/VGcqiTZ9J2DKocKIdMSODRsjQBuWqDZQu4a +IZX5UkxVWsUPOE9G+m34LjXWHXzr4vCwdYDIqROsvojvOm6rXyo4YgKwEnv+j6YDAgMBAAGjZjBk +MBEGCWCGSAGG+EIBAQQEAwIABzAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFEp4MlIR21kW +Nl7fwRQ2QGpHfEyhMB0GA1UdDgQWBBRKeDJSEdtZFjZe38EUNkBqR3xMoTANBgkqhkiG9w0BAQQF +AAOBgQB1W6ibAxHm6VZMzfmpTMANmvPMZWnmJXbMWbfWVMMdzZmsGd20hdXgPfxiIKeES1hl8eL5 +lSE/9dR+WB5Hh1Q+WKG1tfgq73HnvMP2sUlG4tega+VWeponmHxGYhTnyfxuAxJ5gDgdSIKN/Bf+ +KpYrtWKmpj29f5JZzVoqgrI3eQ== +-----END CERTIFICATE----- + +AddTrust Low-Value Services Root +================================ +-----BEGIN CERTIFICATE----- +MIIEGDCCAwCgAwIBAgIBATANBgkqhkiG9w0BAQUFADBlMQswCQYDVQQGEwJTRTEUMBIGA1UEChML +QWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3b3JrMSEwHwYDVQQDExhBZGRU +cnVzdCBDbGFzcyAxIENBIFJvb3QwHhcNMDAwNTMwMTAzODMxWhcNMjAwNTMwMTAzODMxWjBlMQsw +CQYDVQQGEwJTRTEUMBIGA1UEChMLQWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBO +ZXR3b3JrMSEwHwYDVQQDExhBZGRUcnVzdCBDbGFzcyAxIENBIFJvb3QwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQCWltQhSWDia+hBBwzexODcEyPNwTXH+9ZOEQpnXvUGW2ulCDtbKRY6 +54eyNAbFvAWlA3yCyykQruGIgb3WntP+LVbBFc7jJp0VLhD7Bo8wBN6ntGO0/7Gcrjyvd7ZWxbWr +oulpOj0OM3kyP3CCkplhbY0wCI9xP6ZIVxn4JdxLZlyldI+Yrsj5wAYi56xz36Uu+1LcsRVlIPo1 +Zmne3yzxbrww2ywkEtvrNTVokMsAsJchPXQhI2U0K7t4WaPW4XY5mqRJjox0r26kmqPZm9I4XJui +GMx1I4S+6+JNM3GOGvDC+Mcdoq0Dlyz4zyXG9rgkMbFjXZJ/Y/AlyVMuH79NAgMBAAGjgdIwgc8w +HQYDVR0OBBYEFJWxtPCUtr3H2tERCSG+wa9J/RB7MAsGA1UdDwQEAwIBBjAPBgNVHRMBAf8EBTAD +AQH/MIGPBgNVHSMEgYcwgYSAFJWxtPCUtr3H2tERCSG+wa9J/RB7oWmkZzBlMQswCQYDVQQGEwJT +RTEUMBIGA1UEChMLQWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3b3JrMSEw +HwYDVQQDExhBZGRUcnVzdCBDbGFzcyAxIENBIFJvb3SCAQEwDQYJKoZIhvcNAQEFBQADggEBACxt +ZBsfzQ3duQH6lmM0MkhHma6X7f1yFqZzR1r0693p9db7RcwpiURdv0Y5PejuvE1Uhh4dbOMXJ0Ph +iVYrqW9yTkkz43J8KiOavD7/KCrto/8cI7pDVwlnTUtiBi34/2ydYB7YHEt9tTEv2dB8Xfjea4MY +eDdXL+gzB2ffHsdrKpV2ro9Xo/D0UrSpUwjP4E/TelOL/bscVjby/rK25Xa71SJlpz/+0WatC7xr +mYbvP33zGDLKe8bjq2RGlfgmadlVg3sslgf/WSxEo8bl6ancoWOAWiFeIc9TVPC6b4nbqKqVz4vj +ccweGyBECMB6tkD9xOQ14R0WHNC8K47Wcdk= +-----END CERTIFICATE----- + +AddTrust External Root +====================== +-----BEGIN CERTIFICATE----- +MIIENjCCAx6gAwIBAgIBATANBgkqhkiG9w0BAQUFADBvMQswCQYDVQQGEwJTRTEUMBIGA1UEChML +QWRkVHJ1c3QgQUIxJjAkBgNVBAsTHUFkZFRydXN0IEV4dGVybmFsIFRUUCBOZXR3b3JrMSIwIAYD +VQQDExlBZGRUcnVzdCBFeHRlcm5hbCBDQSBSb290MB4XDTAwMDUzMDEwNDgzOFoXDTIwMDUzMDEw +NDgzOFowbzELMAkGA1UEBhMCU0UxFDASBgNVBAoTC0FkZFRydXN0IEFCMSYwJAYDVQQLEx1BZGRU +cnVzdCBFeHRlcm5hbCBUVFAgTmV0d29yazEiMCAGA1UEAxMZQWRkVHJ1c3QgRXh0ZXJuYWwgQ0Eg +Um9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALf3GjPm8gAELTngTlvtH7xsD821 ++iO2zt6bETOXpClMfZOfvUq8k+0DGuOPz+VtUFrWlymUWoCwSXrbLpX9uMq/NzgtHj6RQa1wVsfw +Tz/oMp50ysiQVOnGXw94nZpAPA6sYapeFI+eh6FqUNzXmk6vBbOmcZSccbNQYArHE504B4YCqOmo +aSYYkKtMsE8jqzpPhNjfzp/haW+710LXa0Tkx63ubUFfclpxCDezeWWkWaCUN/cALw3CknLa0Dhy +2xSoRcRdKn23tNbE7qzNE0S3ySvdQwAl+mG5aWpYIxG3pzOPVnVZ9c0p10a3CitlttNCbxWyuHv7 +7+ldU9U0WicCAwEAAaOB3DCB2TAdBgNVHQ4EFgQUrb2YejS0Jvf6xCZU7wO94CTLVBowCwYDVR0P +BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wgZkGA1UdIwSBkTCBjoAUrb2YejS0Jvf6xCZU7wO94CTL +VBqhc6RxMG8xCzAJBgNVBAYTAlNFMRQwEgYDVQQKEwtBZGRUcnVzdCBBQjEmMCQGA1UECxMdQWRk +VHJ1c3QgRXh0ZXJuYWwgVFRQIE5ldHdvcmsxIjAgBgNVBAMTGUFkZFRydXN0IEV4dGVybmFsIENB +IFJvb3SCAQEwDQYJKoZIhvcNAQEFBQADggEBALCb4IUlwtYj4g+WBpKdQZic2YR5gdkeWxQHIzZl +j7DYd7usQWxHYINRsPkyPef89iYTx4AWpb9a/IfPeHmJIZriTAcKhjW88t5RxNKWt9x+Tu5w/Rw5 +6wwCURQtjr0W4MHfRnXnJK3s9EK0hZNwEGe6nQY1ShjTK3rMUUKhemPR5ruhxSvCNr4TDea9Y355 +e6cJDUCrat2PisP29owaQgVR1EX1n6diIWgVIEM8med8vSTYqZEXc4g/VhsxOBi0cQ+azcgOno4u +G+GMmIPLHzHxREzGBHNJdmAPx/i9F4BrLunMTA5amnkPIAou1Z5jJh5VkpTYghdae9C8x49OhgQ= +-----END CERTIFICATE----- + +AddTrust Public Services Root +============================= +-----BEGIN CERTIFICATE----- +MIIEFTCCAv2gAwIBAgIBATANBgkqhkiG9w0BAQUFADBkMQswCQYDVQQGEwJTRTEUMBIGA1UEChML +QWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3b3JrMSAwHgYDVQQDExdBZGRU +cnVzdCBQdWJsaWMgQ0EgUm9vdDAeFw0wMDA1MzAxMDQxNTBaFw0yMDA1MzAxMDQxNTBaMGQxCzAJ +BgNVBAYTAlNFMRQwEgYDVQQKEwtBZGRUcnVzdCBBQjEdMBsGA1UECxMUQWRkVHJ1c3QgVFRQIE5l +dHdvcmsxIDAeBgNVBAMTF0FkZFRydXN0IFB1YmxpYyBDQSBSb290MIIBIjANBgkqhkiG9w0BAQEF +AAOCAQ8AMIIBCgKCAQEA6Rowj4OIFMEg2Dybjxt+A3S72mnTRqX4jsIMEZBRpS9mVEBV6tsfSlbu +nyNu9DnLoblv8n75XYcmYZ4c+OLspoH4IcUkzBEMP9smcnrHAZcHF/nXGCwwfQ56HmIexkvA/X1i +d9NEHif2P0tEs7c42TkfYNVRknMDtABp4/MUTu7R3AnPdzRGULD4EfL+OHn3Bzn+UZKXC1sIXzSG +Aa2Il+tmzV7R/9x98oTaunet3IAIx6eH1lWfl2royBFkuucZKT8Rs3iQhCBSWxHveNCD9tVIkNAw +HM+A+WD+eeSI8t0A65RF62WUaUC6wNW0uLp9BBGo6zEFlpROWCGOn9Bg/QIDAQABo4HRMIHOMB0G +A1UdDgQWBBSBPjfYkrAfd59ctKtzquf2NGAv+jALBgNVHQ8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB +/zCBjgYDVR0jBIGGMIGDgBSBPjfYkrAfd59ctKtzquf2NGAv+qFopGYwZDELMAkGA1UEBhMCU0Ux +FDASBgNVBAoTC0FkZFRydXN0IEFCMR0wGwYDVQQLExRBZGRUcnVzdCBUVFAgTmV0d29yazEgMB4G +A1UEAxMXQWRkVHJ1c3QgUHVibGljIENBIFJvb3SCAQEwDQYJKoZIhvcNAQEFBQADggEBAAP3FUr4 +JNojVhaTdt02KLmuG7jD8WS6IBh4lSknVwW8fCr0uVFV2ocC3g8WFzH4qnkuCRO7r7IgGRLlk/lL ++YPoRNWyQSW/iHVv/xD8SlTQX/D67zZzfRs2RcYhbbQVuE7PnFylPVoAjgbjPGsye/Kf8Lb93/Ao +GEjwxrzQvzSAlsJKsW2Ox5BF3i9nrEUEo3rcVZLJR2bYGozH7ZxOmuASu7VqTITh4SINhwBk/ox9 +Yjllpu9CtoAlEmEBqCQTcAARJl/6NVDFSMwGR+gn2HCNX2TmoUQmXiLsks3/QppEIW1cxeMiHV9H +EufOX1362KqxMy3ZdvJOOjMMK7MtkAY= +-----END CERTIFICATE----- + +AddTrust Qualified Certificates Root +==================================== +-----BEGIN CERTIFICATE----- +MIIEHjCCAwagAwIBAgIBATANBgkqhkiG9w0BAQUFADBnMQswCQYDVQQGEwJTRTEUMBIGA1UEChML +QWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3b3JrMSMwIQYDVQQDExpBZGRU +cnVzdCBRdWFsaWZpZWQgQ0EgUm9vdDAeFw0wMDA1MzAxMDQ0NTBaFw0yMDA1MzAxMDQ0NTBaMGcx +CzAJBgNVBAYTAlNFMRQwEgYDVQQKEwtBZGRUcnVzdCBBQjEdMBsGA1UECxMUQWRkVHJ1c3QgVFRQ +IE5ldHdvcmsxIzAhBgNVBAMTGkFkZFRydXN0IFF1YWxpZmllZCBDQSBSb290MIIBIjANBgkqhkiG +9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5B6a/twJWoekn0e+EV+vhDTbYjx5eLfpMLXsDBwqxBb/4Oxx +64r1EW7tTw2R0hIYLUkVAcKkIhPHEWT/IhKauY5cLwjPcWqzZwFZ8V1G87B4pfYOQnrjfxvM0PC3 +KP0q6p6zsLkEqv32x7SxuCqg+1jxGaBvcCV+PmlKfw8i2O+tCBGaKZnhqkRFmhJePp1tUvznoD1o +L/BLcHwTOK28FSXx1s6rosAx1i+f4P8UWfyEk9mHfExUE+uf0S0R+Bg6Ot4l2ffTQO2kBhLEO+GR +wVY18BTcZTYJbqukB8c10cIDMzZbdSZtQvESa0NvS3GU+jQd7RNuyoB/mC9suWXY6QIDAQABo4HU +MIHRMB0GA1UdDgQWBBQ5lYtii1zJ1IC6WA+XPxUIQ8yYpzALBgNVHQ8EBAMCAQYwDwYDVR0TAQH/ +BAUwAwEB/zCBkQYDVR0jBIGJMIGGgBQ5lYtii1zJ1IC6WA+XPxUIQ8yYp6FrpGkwZzELMAkGA1UE +BhMCU0UxFDASBgNVBAoTC0FkZFRydXN0IEFCMR0wGwYDVQQLExRBZGRUcnVzdCBUVFAgTmV0d29y +azEjMCEGA1UEAxMaQWRkVHJ1c3QgUXVhbGlmaWVkIENBIFJvb3SCAQEwDQYJKoZIhvcNAQEFBQAD +ggEBABmrder4i2VhlRO6aQTvhsoToMeqT2QbPxj2qC0sVY8FtzDqQmodwCVRLae/DLPt7wh/bDxG +GuoYQ992zPlmhpwsaPXpF/gxsxjE1kh9I0xowX67ARRvxdlu3rsEQmr49lx95dr6h+sNNVJn0J6X +dgWTP5XHAeZpVTh/EGGZyeNfpso+gmNIquIISD6q8rKFYqa0p9m9N5xotS1WfbC3P6CxB9bpT9ze +RXEwMn8bLgn5v1Kh7sKAPgZcLlVAwRv1cEWw3F369nJad9Jjzc9YiQBCYz95OdBEsIJuQRno3eDB +iFrRHnGTHyQwdOUeqN48Jzd/g66ed8/wMLH/S5noxqE= +-----END CERTIFICATE----- + +Entrust Root Certification Authority +==================================== +-----BEGIN CERTIFICATE----- +MIIEkTCCA3mgAwIBAgIERWtQVDANBgkqhkiG9w0BAQUFADCBsDELMAkGA1UEBhMCVVMxFjAUBgNV +BAoTDUVudHJ1c3QsIEluYy4xOTA3BgNVBAsTMHd3dy5lbnRydXN0Lm5ldC9DUFMgaXMgaW5jb3Jw +b3JhdGVkIGJ5IHJlZmVyZW5jZTEfMB0GA1UECxMWKGMpIDIwMDYgRW50cnVzdCwgSW5jLjEtMCsG +A1UEAxMkRW50cnVzdCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA2MTEyNzIwMjM0 +MloXDTI2MTEyNzIwNTM0MlowgbAxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1FbnRydXN0LCBJbmMu +MTkwNwYDVQQLEzB3d3cuZW50cnVzdC5uZXQvQ1BTIGlzIGluY29ycG9yYXRlZCBieSByZWZlcmVu +Y2UxHzAdBgNVBAsTFihjKSAyMDA2IEVudHJ1c3QsIEluYy4xLTArBgNVBAMTJEVudHJ1c3QgUm9v +dCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +ALaVtkNC+sZtKm9I35RMOVcF7sN5EUFoNu3s/poBj6E4KPz3EEZmLk0eGrEaTsbRwJWIsMn/MYsz +A9u3g3s+IIRe7bJWKKf44LlAcTfFy0cOlypowCKVYhXbR9n10Cv/gkvJrT7eTNuQgFA/CYqEAOww +Cj0Yzfv9KlmaI5UXLEWeH25DeW0MXJj+SKfFI0dcXv1u5x609mhF0YaDW6KKjbHjKYD+JXGIrb68 +j6xSlkuqUY3kEzEZ6E5Nn9uss2rVvDlUccp6en+Q3X0dgNmBu1kmwhH+5pPi94DkZfs0Nw4pgHBN +rziGLp5/V6+eF67rHMsoIV+2HNjnogQi+dPa2MsCAwEAAaOBsDCBrTAOBgNVHQ8BAf8EBAMCAQYw +DwYDVR0TAQH/BAUwAwEB/zArBgNVHRAEJDAigA8yMDA2MTEyNzIwMjM0MlqBDzIwMjYxMTI3MjA1 +MzQyWjAfBgNVHSMEGDAWgBRokORnpKZTgMeGZqTx90tD+4S9bTAdBgNVHQ4EFgQUaJDkZ6SmU4DH +hmak8fdLQ/uEvW0wHQYJKoZIhvZ9B0EABBAwDhsIVjcuMTo0LjADAgSQMA0GCSqGSIb3DQEBBQUA +A4IBAQCT1DCw1wMgKtD5Y+iRDAUgqV8ZyntyTtSx29CW+1RaGSwMCPeyvIWonX9tO1KzKtvn1ISM +Y/YPyyYBkVBs9F8U4pN0wBOeMDpQ47RgxRzwIkSNcUesyBrJ6ZuaAGAT/3B+XxFNSRuzFVJ7yVTa +v52Vr2ua2J7p8eRDjeIRRDq/r72DQnNSi6q7pynP9WQcCk3RvKqsnyrQ/39/2n3qse0wJcGE2jTS +W3iDVuycNsMm4hH2Z0kdkquM++v/eu6FSqdQgPCnXEqULl8FmTxSQeDNtGPPAUO6nIPcj2A781q0 +tHuu2guQOHXvgR1m0vdXcDazv/wor3ElhVsT/h5/WrQ8 +-----END CERTIFICATE----- + +RSA Security 2048 v3 +==================== +-----BEGIN CERTIFICATE----- +MIIDYTCCAkmgAwIBAgIQCgEBAQAAAnwAAAAKAAAAAjANBgkqhkiG9w0BAQUFADA6MRkwFwYDVQQK +ExBSU0EgU2VjdXJpdHkgSW5jMR0wGwYDVQQLExRSU0EgU2VjdXJpdHkgMjA0OCBWMzAeFw0wMTAy +MjIyMDM5MjNaFw0yNjAyMjIyMDM5MjNaMDoxGTAXBgNVBAoTEFJTQSBTZWN1cml0eSBJbmMxHTAb +BgNVBAsTFFJTQSBTZWN1cml0eSAyMDQ4IFYzMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC +AQEAt49VcdKA3XtpeafwGFAyPGJn9gqVB93mG/Oe2dJBVGutn3y+Gc37RqtBaB4Y6lXIL5F4iSj7 +Jylg/9+PjDvJSZu1pJTOAeo+tWN7fyb9Gd3AIb2E0S1PRsNO3Ng3OTsor8udGuorryGlwSMiuLgb +WhOHV4PR8CDn6E8jQrAApX2J6elhc5SYcSa8LWrg903w8bYqODGBDSnhAMFRD0xS+ARaqn1y07iH +KrtjEAMqs6FPDVpeRrc9DvV07Jmf+T0kgYim3WBU6JU2PcYJk5qjEoAAVZkZR73QpXzDuvsf9/UP ++Ky5tfQ3mBMY3oVbtwyCO4dvlTlYMNpuAWgXIszACwIDAQABo2MwYTAPBgNVHRMBAf8EBTADAQH/ +MA4GA1UdDwEB/wQEAwIBBjAfBgNVHSMEGDAWgBQHw1EwpKrpRa41JPr/JCwz0LGdjDAdBgNVHQ4E +FgQUB8NRMKSq6UWuNST6/yQsM9CxnYwwDQYJKoZIhvcNAQEFBQADggEBAF8+hnZuuDU8TjYcHnmY +v/3VEhF5Ug7uMYm83X/50cYVIeiKAVQNOvtUudZj1LGqlk2iQk3UUx+LEN5/Zb5gEydxiKRz44Rj +0aRV4VCT5hsOedBnvEbIvz8XDZXmxpBp3ue0L96VfdASPz0+f00/FGj1EVDVwfSQpQgdMWD/YIwj +VAqv/qFuxdF6Kmh4zx6CCiC0H63lhbJqaHVOrSU3lIW+vaHU6rcMSzyd6BIA8F+sDeGscGNz9395 +nzIlQnQFgCi/vcEkllgVsRch6YlL2weIZ/QVrXA+L02FO8K32/6YaCOJ4XQP3vTFhGMpG8zLB8kA +pKnXwiJPZ9d37CAFYd4= +-----END CERTIFICATE----- + +GeoTrust Global CA +================== +-----BEGIN CERTIFICATE----- +MIIDVDCCAjygAwIBAgIDAjRWMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVTMRYwFAYDVQQK +Ew1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9iYWwgQ0EwHhcNMDIwNTIxMDQw +MDAwWhcNMjIwNTIxMDQwMDAwWjBCMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5j +LjEbMBkGA1UEAxMSR2VvVHJ1c3QgR2xvYmFsIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB +CgKCAQEA2swYYzD99BcjGlZ+W988bDjkcbd4kdS8odhM+KhDtgPpTSEHCIjaWC9mOSm9BXiLnTjo +BbdqfnGk5sRgprDvgOSJKA+eJdbtg/OtppHHmMlCGDUUna2YRpIuT8rxh0PBFpVXLVDviS2Aelet +8u5fa9IAjbkU+BQVNdnARqN7csiRv8lVK83Qlz6cJmTM386DGXHKTubU1XupGc1V3sjs0l44U+Vc +T4wt/lAjNvxm5suOpDkZALeVAjmRCw7+OC7RHQWa9k0+bw8HHa8sHo9gOeL6NlMTOdReJivbPagU +vTLrGAMoUgRx5aszPeE4uwc2hGKceeoWMPRfwCvocWvk+QIDAQABo1MwUTAPBgNVHRMBAf8EBTAD +AQH/MB0GA1UdDgQWBBTAephojYn7qwVkDBF9qn1luMrMTjAfBgNVHSMEGDAWgBTAephojYn7qwVk +DBF9qn1luMrMTjANBgkqhkiG9w0BAQUFAAOCAQEANeMpauUvXVSOKVCUn5kaFOSPeCpilKInZ57Q +zxpeR+nBsqTP3UEaBU6bS+5Kb1VSsyShNwrrZHYqLizz/Tt1kL/6cdjHPTfStQWVYrmm3ok9Nns4 +d0iXrKYgjy6myQzCsplFAMfOEVEiIuCl6rYVSAlk6l5PdPcFPseKUgzbFbS9bZvlxrFUaKnjaZC2 +mqUPuLk/IH2uSrW4nOQdtqvmlKXBx4Ot2/Unhw4EbNX/3aBd7YdStysVAq45pmp06drE57xNNB6p +XE0zX5IJL4hmXXeXxx12E6nV5fEWCRE11azbJHFwLJhWC9kXtNHjUStedejV0NxPNO3CBWaAocvm +Mw== +-----END CERTIFICATE----- + +GeoTrust Global CA 2 +==================== +-----BEGIN CERTIFICATE----- +MIIDZjCCAk6gAwIBAgIBATANBgkqhkiG9w0BAQUFADBEMQswCQYDVQQGEwJVUzEWMBQGA1UEChMN +R2VvVHJ1c3QgSW5jLjEdMBsGA1UEAxMUR2VvVHJ1c3QgR2xvYmFsIENBIDIwHhcNMDQwMzA0MDUw +MDAwWhcNMTkwMzA0MDUwMDAwWjBEMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5j +LjEdMBsGA1UEAxMUR2VvVHJ1c3QgR2xvYmFsIENBIDIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw +ggEKAoIBAQDvPE1APRDfO1MA4Wf+lGAVPoWI8YkNkMgoI5kF6CsgncbzYEbYwbLVjDHZ3CB5JIG/ +NTL8Y2nbsSpr7iFY8gjpeMtvy/wWUsiRxP89c96xPqfCfWbB9X5SJBri1WeR0IIQ13hLTytCOb1k +LUCgsBDTOEhGiKEMuzozKmKY+wCdE1l/bztyqu6mD4b5BWHqZ38MN5aL5mkWRxHCJ1kDs6ZgwiFA +Vvqgx306E+PsV8ez1q6diYD3Aecs9pYrEw15LNnA5IZ7S4wMcoKK+xfNAGw6EzywhIdLFnopsk/b +HdQL82Y3vdj2V7teJHq4PIu5+pIaGoSe2HSPqht/XvT+RSIhAgMBAAGjYzBhMA8GA1UdEwEB/wQF +MAMBAf8wHQYDVR0OBBYEFHE4NvICMVNHK266ZUapEBVYIAUJMB8GA1UdIwQYMBaAFHE4NvICMVNH +K266ZUapEBVYIAUJMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQUFAAOCAQEAA/e1K6tdEPx7 +srJerJsOflN4WT5CBP51o62sgU7XAotexC3IUnbHLB/8gTKY0UvGkpMzNTEv/NgdRN3ggX+d6Yvh +ZJFiCzkIjKx0nVnZellSlxG5FntvRdOW2TF9AjYPnDtuzywNA0ZF66D0f0hExghAzN4bcLUprbqL +OzRldRtxIR0sFAqwlpW41uryZfspuk/qkZN0abby/+Ea0AzRdoXLiiW9l14sbxWZJue2Kf8i7MkC +x1YAzUm5s2x7UwQa4qjJqhIFI8LO57sEAszAR6LkxCkvW0VXiVHuPOtSCP8HNR6fNWpHSlaY0VqF +H4z1Ir+rzoPz4iIprn2DQKi6bA== +-----END CERTIFICATE----- + +GeoTrust Universal CA +===================== +-----BEGIN CERTIFICATE----- +MIIFaDCCA1CgAwIBAgIBATANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJVUzEWMBQGA1UEChMN +R2VvVHJ1c3QgSW5jLjEeMBwGA1UEAxMVR2VvVHJ1c3QgVW5pdmVyc2FsIENBMB4XDTA0MDMwNDA1 +MDAwMFoXDTI5MDMwNDA1MDAwMFowRTELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IElu +Yy4xHjAcBgNVBAMTFUdlb1RydXN0IFVuaXZlcnNhbCBDQTCCAiIwDQYJKoZIhvcNAQEBBQADggIP +ADCCAgoCggIBAKYVVaCjxuAfjJ0hUNfBvitbtaSeodlyWL0AG0y/YckUHUWCq8YdgNY96xCcOq9t +JPi8cQGeBvV8Xx7BDlXKg5pZMK4ZyzBIle0iN430SppyZj6tlcDgFgDgEB8rMQ7XlFTTQjOgNB0e +RXbdT8oYN+yFFXoZCPzVx5zw8qkuEKmS5j1YPakWaDwvdSEYfyh3peFhF7em6fgemdtzbvQKoiFs +7tqqhZJmr/Z6a4LauiIINQ/PQvE1+mrufislzDoR5G2vc7J2Ha3QsnhnGqQ5HFELZ1aD/ThdDc7d +8Lsrlh/eezJS/R27tQahsiFepdaVaH/wmZ7cRQg+59IJDTWU3YBOU5fXtQlEIGQWFwMCTFMNaN7V +qnJNk22CDtucvc+081xdVHppCZbW2xHBjXWotM85yM48vCR85mLK4b19p71XZQvk/iXttmkQ3Cga +Rr0BHdCXteGYO8A3ZNY9lO4L4fUorgtWv3GLIylBjobFS1J72HGrH4oVpjuDWtdYAVHGTEHZf9hB +Z3KiKN9gg6meyHv8U3NyWfWTehd2Ds735VzZC1U0oqpbtWpU5xPKV+yXbfReBi9Fi1jUIxaS5BZu +KGNZMN9QAZxjiRqf2xeUgnA3wySemkfWWspOqGmJch+RbNt+nhutxx9z3SxPGWX9f5NAEC7S8O08 +ni4oPmkmM8V7AgMBAAGjYzBhMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFNq7LqqwDLiIJlF0 +XG0D08DYj3rWMB8GA1UdIwQYMBaAFNq7LqqwDLiIJlF0XG0D08DYj3rWMA4GA1UdDwEB/wQEAwIB +hjANBgkqhkiG9w0BAQUFAAOCAgEAMXjmx7XfuJRAyXHEqDXsRh3ChfMoWIawC/yOsjmPRFWrZIRc +aanQmjg8+uUfNeVE44B5lGiku8SfPeE0zTBGi1QrlaXv9z+ZhP015s8xxtxqv6fXIwjhmF7DWgh2 +qaavdy+3YL1ERmrvl/9zlcGO6JP7/TG37FcREUWbMPEaiDnBTzynANXH/KttgCJwpQzgXQQpAvvL +oJHRfNbDflDVnVi+QTjruXU8FdmbyUqDWcDaU/0zuzYYm4UPFd3uLax2k7nZAY1IEKj79TiG8dsK +xr2EoyNB3tZ3b4XUhRxQ4K5RirqNPnbiucon8l+f725ZDQbYKxek0nxru18UGkiPGkzns0ccjkxF +KyDuSN/n3QmOGKjaQI2SJhFTYXNd673nxE0pN2HrrDktZy4W1vUAg4WhzH92xH3kt0tm7wNFYGm2 +DFKWkoRepqO1pD4r2czYG0eq8kTaT/kD6PAUyz/zg97QwVTjt+gKN02LIFkDMBmhLMi9ER/frslK +xfMnZmaGrGiR/9nmUxwPi1xpZQomyB40w11Re9epnAahNt3ViZS82eQtDF4JbAiXfKM9fJP/P6EU +p8+1Xevb2xzEdt+Iub1FBZUbrvxGakyvSOPOrg/SfuvmbJxPgWp6ZKy7PtXny3YuxadIwVyQD8vI +P/rmMuGNG2+k5o7Y+SlIis5z/iw= +-----END CERTIFICATE----- + +GeoTrust Universal CA 2 +======================= +-----BEGIN CERTIFICATE----- +MIIFbDCCA1SgAwIBAgIBATANBgkqhkiG9w0BAQUFADBHMQswCQYDVQQGEwJVUzEWMBQGA1UEChMN +R2VvVHJ1c3QgSW5jLjEgMB4GA1UEAxMXR2VvVHJ1c3QgVW5pdmVyc2FsIENBIDIwHhcNMDQwMzA0 +MDUwMDAwWhcNMjkwMzA0MDUwMDAwWjBHMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3Qg +SW5jLjEgMB4GA1UEAxMXR2VvVHJ1c3QgVW5pdmVyc2FsIENBIDIwggIiMA0GCSqGSIb3DQEBAQUA +A4ICDwAwggIKAoICAQCzVFLByT7y2dyxUxpZKeexw0Uo5dfR7cXFS6GqdHtXr0om/Nj1XqduGdt0 +DE81WzILAePb63p3NeqqWuDW6KFXlPCQo3RWlEQwAx5cTiuFJnSCegx2oG9NzkEtoBUGFF+3Qs17 +j1hhNNwqCPkuwwGmIkQcTAeC5lvO0Ep8BNMZcyfwqph/Lq9O64ceJHdqXbboW0W63MOhBW9Wjo8Q +JqVJwy7XQYci4E+GymC16qFjwAGXEHm9ADwSbSsVsaxLse4YuU6W3Nx2/zu+z18DwPw76L5GG//a +QMJS9/7jOvdqdzXQ2o3rXhhqMcceujwbKNZrVMaqW9eiLBsZzKIC9ptZvTdrhrVtgrrY6slWvKk2 +WP0+GfPtDCapkzj4T8FdIgbQl+rhrcZV4IErKIM6+vR7IVEAvlI4zs1meaj0gVbi0IMJR1FbUGrP +20gaXT73y/Zl92zxlfgCOzJWgjl6W70viRu/obTo/3+NjN8D8WBOWBFM66M/ECuDmgFz2ZRthAAn +ZqzwcEAJQpKtT5MNYQlRJNiS1QuUYbKHsu3/mjX/hVTK7URDrBs8FmtISgocQIgfksILAAX/8sgC +SqSqqcyZlpwvWOB94b67B9xfBHJcMTTD7F8t4D1kkCLm0ey4Lt1ZrtmhN79UNdxzMk+MBB4zsslG +8dhcyFVQyWi9qLo2CQIDAQABo2MwYTAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR281Xh+qQ2 ++/CfXGJx7Tz0RzgQKzAfBgNVHSMEGDAWgBR281Xh+qQ2+/CfXGJx7Tz0RzgQKzAOBgNVHQ8BAf8E +BAMCAYYwDQYJKoZIhvcNAQEFBQADggIBAGbBxiPz2eAubl/oz66wsCVNK/g7WJtAJDday6sWSf+z +dXkzoS9tcBc0kf5nfo/sm+VegqlVHy/c1FEHEv6sFj4sNcZj/NwQ6w2jqtB8zNHQL1EuxBRa3ugZ +4T7GzKQp5y6EqgYweHZUcyiYWTjgAA1i00J9IZ+uPTqM1fp3DRgrFg5fNuH8KrUwJM/gYwx7WBr+ +mbpCErGR9Hxo4sjoryzqyX6uuyo9DRXcNJW2GHSoag/HtPQTxORb7QrSpJdMKu0vbBKJPfEncKpq +A1Ihn0CoZ1Dy81of398j9tx4TuaYT1U6U+Pv8vSfx3zYWK8pIpe44L2RLrB27FcRz+8pRPPphXpg +Y+RdM4kX2TGq2tbzGDVyz4crL2MjhF2EjD9XoIj8mZEoJmmZ1I+XRL6O1UixpCgp8RW04eWe3fiP +pm8m1wk8OhwRDqZsN/etRIcsKMfYdIKz0G9KV7s1KSegi+ghp4dkNl3M2Basx7InQJJVOCiNUW7d +FGdTbHFcJoRNdVq2fmBWqU2t+5sel/MN2dKXVHfaPRK34B7vCAas+YWH6aLcr34YEoP9VhdBLtUp +gn2Z9DH2canPLAEnpQW5qrJITirvn5NSUZU8UnOOVkwXQMAJKOSLakhT2+zNVVXxxvjpoixMptEm +X36vWkzaH6byHCx+rgIW0lbQL1dTR+iS +-----END CERTIFICATE----- + +America Online Root Certification Authority 1 +============================================= +-----BEGIN CERTIFICATE----- +MIIDpDCCAoygAwIBAgIBATANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEcMBoGA1UEChMT +QW1lcmljYSBPbmxpbmUgSW5jLjE2MDQGA1UEAxMtQW1lcmljYSBPbmxpbmUgUm9vdCBDZXJ0aWZp +Y2F0aW9uIEF1dGhvcml0eSAxMB4XDTAyMDUyODA2MDAwMFoXDTM3MTExOTIwNDMwMFowYzELMAkG +A1UEBhMCVVMxHDAaBgNVBAoTE0FtZXJpY2EgT25saW5lIEluYy4xNjA0BgNVBAMTLUFtZXJpY2Eg +T25saW5lIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgMTCCASIwDQYJKoZIhvcNAQEBBQAD +ggEPADCCAQoCggEBAKgv6KRpBgNHw+kqmP8ZonCaxlCyfqXfaE0bfA+2l2h9LaaLl+lkhsmj76CG +v2BlnEtUiMJIxUo5vxTjWVXlGbR0yLQFOVwWpeKVBeASrlmLojNoWBym1BW32J/X3HGrfpq/m44z +DyL9Hy7nBzbvYjnF3cu6JRQj3gzGPTzOggjmZj7aUTsWOqMFf6Dch9Wc/HKpoH145LcxVR5lu9Rh +sCFg7RAycsWSJR74kEoYeEfffjA3PlAb2xzTa5qGUwew76wGePiEmf4hjUyAtgyC9mZweRrTT6PP +8c9GsEsPPt2IYriMqQkoO3rHl+Ee5fSfwMCuJKDIodkP1nsmgmkyPacCAwEAAaNjMGEwDwYDVR0T +AQH/BAUwAwEB/zAdBgNVHQ4EFgQUAK3Zo/Z59m50qX8zPYEX10zPM94wHwYDVR0jBBgwFoAUAK3Z +o/Z59m50qX8zPYEX10zPM94wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBBQUAA4IBAQB8itEf +GDeC4Liwo+1WlchiYZwFos3CYiZhzRAW18y0ZTTQEYqtqKkFZu90821fnZmv9ov761KyBZiibyrF +VL0lvV+uyIbqRizBs73B6UlwGBaXCBOMIOAbLjpHyx7kADCVW/RFo8AasAFOq73AI25jP4BKxQft +3OJvx8Fi8eNy1gTIdGcL+oiroQHIb/AUr9KZzVGTfu0uOMe9zkZQPXLjeSWdm4grECDdpbgyn43g +Kd8hdIaC2y+CMMbHNYaz+ZZfRtsMRf3zUMNvxsNIrUam4SdHCh0Om7bCd39j8uB9Gr784N/Xx6ds +sPmuujz9dLQR6FgNgLzTqIA6me11zEZ7 +-----END CERTIFICATE----- + +America Online Root Certification Authority 2 +============================================= +-----BEGIN CERTIFICATE----- +MIIFpDCCA4ygAwIBAgIBATANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEcMBoGA1UEChMT +QW1lcmljYSBPbmxpbmUgSW5jLjE2MDQGA1UEAxMtQW1lcmljYSBPbmxpbmUgUm9vdCBDZXJ0aWZp +Y2F0aW9uIEF1dGhvcml0eSAyMB4XDTAyMDUyODA2MDAwMFoXDTM3MDkyOTE0MDgwMFowYzELMAkG +A1UEBhMCVVMxHDAaBgNVBAoTE0FtZXJpY2EgT25saW5lIEluYy4xNjA0BgNVBAMTLUFtZXJpY2Eg +T25saW5lIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgMjCCAiIwDQYJKoZIhvcNAQEBBQAD +ggIPADCCAgoCggIBAMxBRR3pPU0Q9oyxQcngXssNt79Hc9PwVU3dxgz6sWYFas14tNwC206B89en +fHG8dWOgXeMHDEjsJcQDIPT/DjsS/5uN4cbVG7RtIuOx238hZK+GvFciKtZHgVdEglZTvYYUAQv8 +f3SkWq7xuhG1m1hagLQ3eAkzfDJHA1zEpYNI9FdWboE2JxhP7JsowtS013wMPgwr38oE18aO6lhO +qKSlGBxsRZijQdEt0sdtjRnxrXm3gT+9BoInLRBYBbV4Bbkv2wxrkJB+FFk4u5QkE+XRnRTf04JN +RvCAOVIyD+OEsnpD8l7eXz8d3eOyG6ChKiMDbi4BFYdcpnV1x5dhvt6G3NRI270qv0pV2uh9UPu0 +gBe4lL8BPeraunzgWGcXuVjgiIZGZ2ydEEdYMtA1fHkqkKJaEBEjNa0vzORKW6fIJ/KD3l67Xnfn +6KVuY8INXWHQjNJsWiEOyiijzirplcdIz5ZvHZIlyMbGwcEMBawmxNJ10uEqZ8A9W6Wa6897Gqid +FEXlD6CaZd4vKL3Ob5Rmg0gp2OpljK+T2WSfVVcmv2/LNzGZo2C7HK2JNDJiuEMhBnIMoVxtRsX6 +Kc8w3onccVvdtjc+31D1uAclJuW8tf48ArO3+L5DwYcRlJ4jbBeKuIonDFRH8KmzwICMoCfrHRnj +B453cMor9H124HhnAgMBAAGjYzBhMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFE1FwWg4u3Op +aaEg5+31IqEjFNeeMB8GA1UdIwQYMBaAFE1FwWg4u3OpaaEg5+31IqEjFNeeMA4GA1UdDwEB/wQE +AwIBhjANBgkqhkiG9w0BAQUFAAOCAgEAZ2sGuV9FOypLM7PmG2tZTiLMubekJcmnxPBUlgtk87FY +T15R/LKXeydlwuXK5w0MJXti4/qftIe3RUavg6WXSIylvfEWK5t2LHo1YGwRgJfMqZJS5ivmae2p ++DYtLHe/YUjRYwu5W1LtGLBDQiKmsXeu3mnFzcccobGlHBD7GL4acN3Bkku+KVqdPzW+5X1R+FXg +JXUjhx5c3LqdsKyzadsXg8n33gy8CNyRnqjQ1xU3c6U1uPx+xURABsPr+CKAXEfOAuMRn0T//Zoy +zH1kUQ7rVyZ2OuMeIjzCpjbdGe+n/BLzJsBZMYVMnNjP36TMzCmT/5RtdlwTCJfy7aULTd3oyWgO +ZtMADjMSW7yV5TKQqLPGbIOtd+6Lfn6xqavT4fG2wLHqiMDn05DpKJKUe2h7lyoKZy2FAjgQ5ANh +1NolNscIWC2hp1GvMApJ9aZphwctREZ2jirlmjvXGKL8nDgQzMY70rUXOm/9riW99XJZZLF0Kjhf +GEzfz3EEWjbUvy+ZnOjZurGV5gJLIaFb1cFPj65pbVPbAZO1XB4Y3WRayhgoPmMEEf0cjQAPuDff +Z4qdZqkCapH/E8ovXYO8h5Ns3CRRFgQlZvqz2cK6Kb6aSDiCmfS/O0oxGfm/jiEzFMpPVF/7zvuP +cX/9XhmgD0uRuMRUvAawRY8mkaKO/qk= +-----END CERTIFICATE----- + +Visa eCommerce Root +=================== +-----BEGIN CERTIFICATE----- +MIIDojCCAoqgAwIBAgIQE4Y1TR0/BvLB+WUF1ZAcYjANBgkqhkiG9w0BAQUFADBrMQswCQYDVQQG +EwJVUzENMAsGA1UEChMEVklTQTEvMC0GA1UECxMmVmlzYSBJbnRlcm5hdGlvbmFsIFNlcnZpY2Ug +QXNzb2NpYXRpb24xHDAaBgNVBAMTE1Zpc2EgZUNvbW1lcmNlIFJvb3QwHhcNMDIwNjI2MDIxODM2 +WhcNMjIwNjI0MDAxNjEyWjBrMQswCQYDVQQGEwJVUzENMAsGA1UEChMEVklTQTEvMC0GA1UECxMm +VmlzYSBJbnRlcm5hdGlvbmFsIFNlcnZpY2UgQXNzb2NpYXRpb24xHDAaBgNVBAMTE1Zpc2EgZUNv +bW1lcmNlIFJvb3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvV95WHm6h2mCxlCfL +F9sHP4CFT8icttD0b0/Pmdjh28JIXDqsOTPHH2qLJj0rNfVIsZHBAk4ElpF7sDPwsRROEW+1QK8b +RaVK7362rPKgH1g/EkZgPI2h4H3PVz4zHvtH8aoVlwdVZqW1LS7YgFmypw23RuwhY/81q6UCzyr0 +TP579ZRdhE2o8mCP2w4lPJ9zcc+U30rq299yOIzzlr3xF7zSujtFWsan9sYXiwGd/BmoKoMWuDpI +/k4+oKsGGelT84ATB+0tvz8KPFUgOSwsAGl0lUq8ILKpeeUYiZGo3BxN77t+Nwtd/jmliFKMAGzs +GHxBvfaLdXe6YJ2E5/4tAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEG +MB0GA1UdDgQWBBQVOIMPPyw/cDMezUb+B4wg4NfDtzANBgkqhkiG9w0BAQUFAAOCAQEAX/FBfXxc +CLkr4NWSR/pnXKUTwwMhmytMiUbPWU3J/qVAtmPN3XEolWcRzCSs00Rsca4BIGsDoo8Ytyk6feUW +YFN4PMCvFYP3j1IzJL1kk5fui/fbGKhtcbP3LBfQdCVp9/5rPJS+TUtBjE7ic9DjkCJzQ83z7+pz +zkWKsKZJ/0x9nXGIxHYdkFsd7v3M9+79YKWxehZx0RbQfBI8bGmX265fOZpwLwU8GUYEmSA20GBu +YQa7FkKMcPcw++DbZqMAAb3mLNqRX6BGi01qnD093QVG/na/oAo85ADmJ7f/hC3euiInlhBx6yLt +398znM/jra6O1I7mT1GvFpLgXPYHDw== +-----END CERTIFICATE----- + +Certum Root CA +============== +-----BEGIN CERTIFICATE----- +MIIDDDCCAfSgAwIBAgIDAQAgMA0GCSqGSIb3DQEBBQUAMD4xCzAJBgNVBAYTAlBMMRswGQYDVQQK +ExJVbml6ZXRvIFNwLiB6IG8uby4xEjAQBgNVBAMTCUNlcnR1bSBDQTAeFw0wMjA2MTExMDQ2Mzla +Fw0yNzA2MTExMDQ2MzlaMD4xCzAJBgNVBAYTAlBMMRswGQYDVQQKExJVbml6ZXRvIFNwLiB6IG8u +by4xEjAQBgNVBAMTCUNlcnR1bSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAM6x +wS7TT3zNJc4YPk/EjG+AanPIW1H4m9LcuwBcsaD8dQPugfCI7iNS6eYVM42sLQnFdvkrOYCJ5JdL +kKWoePhzQ3ukYbDYWMzhbGZ+nPMJXlVjhNWo7/OxLjBos8Q82KxujZlakE403Daaj4GIULdtlkIJ +89eVgw1BS7Bqa/j8D35in2fE7SZfECYPCE/wpFcozo+47UX2bu4lXapuOb7kky/ZR6By6/qmW6/K +Uz/iDsaWVhFu9+lmqSbYf5VT7QqFiLpPKaVCjF62/IUgAKpoC6EahQGcxEZjgoi2IrHu/qpGWX7P +NSzVttpd90gzFFS269lvzs2I1qsb2pY7HVkCAwEAAaMTMBEwDwYDVR0TAQH/BAUwAwEB/zANBgkq +hkiG9w0BAQUFAAOCAQEAuI3O7+cUus/usESSbLQ5PqKEbq24IXfS1HeCh+YgQYHu4vgRt2PRFze+ +GXYkHAQaTOs9qmdvLdTN/mUxcMUbpgIKumB7bVjCmkn+YzILa+M6wKyrO7Do0wlRjBCDxjTgxSvg +GrZgFCdsMneMvLJymM/NzD+5yCRCFNZX/OYmQ6kd5YCQzgNUKD73P9P4Te1qCjqTE5s7FCMTY5w/ +0YcneeVMUeMBrYVdGjux1XMQpNPyvG5k9VpWkKjHDkx0Dy5xO/fIR/RpbxXyEV6DHpx8Uq79AtoS +qFlnGNu8cN2bsWntgM6JQEhqDjXKKWYVIZQs6GAqm4VKQPNriiTsBhYscw== +-----END CERTIFICATE----- + +Comodo AAA Services root +======================== +-----BEGIN CERTIFICATE----- +MIIEMjCCAxqgAwIBAgIBATANBgkqhkiG9w0BAQUFADB7MQswCQYDVQQGEwJHQjEbMBkGA1UECAwS +R3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRowGAYDVQQKDBFDb21vZG8gQ0Eg +TGltaXRlZDEhMB8GA1UEAwwYQUFBIENlcnRpZmljYXRlIFNlcnZpY2VzMB4XDTA0MDEwMTAwMDAw +MFoXDTI4MTIzMTIzNTk1OVowezELMAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFuY2hl +c3RlcjEQMA4GA1UEBwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxITAfBgNV +BAMMGEFBQSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC +ggEBAL5AnfRu4ep2hxxNRUSOvkbIgwadwSr+GB+O5AL686tdUIoWMQuaBtDFcCLNSS1UY8y2bmhG +C1Pqy0wkwLxyTurxFa70VJoSCsN6sjNg4tqJVfMiWPPe3M/vg4aijJRPn2jymJBGhCfHdr/jzDUs +i14HZGWCwEiwqJH5YZ92IFCokcdmtet4YgNW8IoaE+oxox6gmf049vYnMlhvB/VruPsUK6+3qszW +Y19zjNoFmag4qMsXeDZRrOme9Hg6jc8P2ULimAyrL58OAd7vn5lJ8S3frHRNG5i1R8XlKdH5kBjH +Ypy+g8cmez6KJcfA3Z3mNWgQIJ2P2N7Sw4ScDV7oL8kCAwEAAaOBwDCBvTAdBgNVHQ4EFgQUoBEK +Iz6W8Qfs4q8p74Klf9AwpLQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wewYDVR0f +BHQwcjA4oDagNIYyaHR0cDovL2NybC5jb21vZG9jYS5jb20vQUFBQ2VydGlmaWNhdGVTZXJ2aWNl +cy5jcmwwNqA0oDKGMGh0dHA6Ly9jcmwuY29tb2RvLm5ldC9BQUFDZXJ0aWZpY2F0ZVNlcnZpY2Vz +LmNybDANBgkqhkiG9w0BAQUFAAOCAQEACFb8AvCb6P+k+tZ7xkSAzk/ExfYAWMymtrwUSWgEdujm +7l3sAg9g1o1QGE8mTgHj5rCl7r+8dFRBv/38ErjHT1r0iWAFf2C3BUrz9vHCv8S5dIa2LX1rzNLz +Rt0vxuBqw8M0Ayx9lt1awg6nCpnBBYurDC/zXDrPbDdVCYfeU0BsWO/8tqtlbgT2G9w84FoVxp7Z +8VlIMCFlA2zs6SFz7JsDoeA3raAVGI/6ugLOpyypEBMs1OUIJqsil2D4kF501KKaU73yqWjgom7C +12yxow+ev+to51byrvLjKzg6CYG1a4XXvi3tPxq3smPi9WIsgtRqAEFQ8TmDn5XpNpaYbg== +-----END CERTIFICATE----- + +Comodo Secure Services root +=========================== +-----BEGIN CERTIFICATE----- +MIIEPzCCAyegAwIBAgIBATANBgkqhkiG9w0BAQUFADB+MQswCQYDVQQGEwJHQjEbMBkGA1UECAwS +R3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRowGAYDVQQKDBFDb21vZG8gQ0Eg +TGltaXRlZDEkMCIGA1UEAwwbU2VjdXJlIENlcnRpZmljYXRlIFNlcnZpY2VzMB4XDTA0MDEwMTAw +MDAwMFoXDTI4MTIzMTIzNTk1OVowfjELMAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFu +Y2hlc3RlcjEQMA4GA1UEBwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxJDAi +BgNVBAMMG1NlY3VyZSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczCCASIwDQYJKoZIhvcNAQEBBQADggEP +ADCCAQoCggEBAMBxM4KK0HDrc4eCQNUd5MvJDkKQ+d40uaG6EfQlhfPMcm3ye5drswfxdySRXyWP +9nQ95IDC+DwN879A6vfIUtFyb+/Iq0G4bi4XKpVpDM3SHpR7LZQdqnXXs5jLrLxkU0C8j6ysNstc +rbvd4JQX7NFc0L/vpZXJkMWwrPsbQ996CF23uPJAGysnnlDOXmWCiIxe004MeuoIkbY2qitC++rC +oznl2yY4rYsK7hljxxwk3wN42ubqwUcaCwtGCd0C/N7Lh1/XMGNooa7cMqG6vv5Eq2i2pRcV/b3V +p6ea5EQz6YiO/O1R65NxTq0B50SOqy3LqP4BSUjwwN3HaNiS/j0CAwEAAaOBxzCBxDAdBgNVHQ4E +FgQUPNiTiMLAggnMAZkGkyDpnnAJY08wDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8w +gYEGA1UdHwR6MHgwO6A5oDeGNWh0dHA6Ly9jcmwuY29tb2RvY2EuY29tL1NlY3VyZUNlcnRpZmlj +YXRlU2VydmljZXMuY3JsMDmgN6A1hjNodHRwOi8vY3JsLmNvbW9kby5uZXQvU2VjdXJlQ2VydGlm +aWNhdGVTZXJ2aWNlcy5jcmwwDQYJKoZIhvcNAQEFBQADggEBAIcBbSMdflsXfcFhMs+P5/OKlFlm +4J4oqF7Tt/Q05qo5spcWxYJvMqTpjOev/e/C6LlLqqP05tqNZSH7uoDrJiiFGv45jN5bBAS0VPmj +Z55B+glSzAVIqMk/IQQezkhr/IXownuvf7fM+F86/TXGDe+X3EyrEeFryzHRbPtIgKvcnDe4IRRL +DXE97IMzbtFuMhbsmMcWi1mmNKsFVy2T96oTy9IT4rcuO81rUBcJaD61JlfutuC23bkpgHl9j6Pw +pCikFcSF9CfUa7/lXORlAnZUtOM3ZiTTGWHIUhDlizeauan5Hb/qmZJhlv8BzaFfDbxxvA6sCx1H +RR3B7Hzs/Sk= +-----END CERTIFICATE----- + +Comodo Trusted Services root +============================ +-----BEGIN CERTIFICATE----- +MIIEQzCCAyugAwIBAgIBATANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJHQjEbMBkGA1UECAwS +R3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRowGAYDVQQKDBFDb21vZG8gQ0Eg +TGltaXRlZDElMCMGA1UEAwwcVHJ1c3RlZCBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczAeFw0wNDAxMDEw +MDAwMDBaFw0yODEyMzEyMzU5NTlaMH8xCzAJBgNVBAYTAkdCMRswGQYDVQQIDBJHcmVhdGVyIE1h +bmNoZXN0ZXIxEDAOBgNVBAcMB1NhbGZvcmQxGjAYBgNVBAoMEUNvbW9kbyBDQSBMaW1pdGVkMSUw +IwYDVQQDDBxUcnVzdGVkIENlcnRpZmljYXRlIFNlcnZpY2VzMIIBIjANBgkqhkiG9w0BAQEFAAOC +AQ8AMIIBCgKCAQEA33FvNlhTWvI2VFeAxHQIIO0Yfyod5jWaHiWsnOWWfnJSoBVC21ndZHoa0Lh7 +3TkVvFVIxO06AOoxEbrycXQaZ7jPM8yoMa+j49d/vzMtTGo87IvDktJTdyR0nAducPy9C1t2ul/y +/9c3S0pgePfw+spwtOpZqqPOSC+pw7ILfhdyFgymBwwbOM/JYrc/oJOlh0Hyt3BAd9i+FHzjqMB6 +juljatEPmsbS9Is6FARW1O24zG71++IsWL1/T2sr92AkWCTOJu80kTrV44HQsvAEAtdbtz6SrGsS +ivnkBbA7kUlcsutT6vifR4buv5XAwAaf0lteERv0xwQ1KdJVXOTt6wIDAQABo4HJMIHGMB0GA1Ud +DgQWBBTFe1i97doladL3WRaoszLAeydb9DAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB +/zCBgwYDVR0fBHwwejA8oDqgOIY2aHR0cDovL2NybC5jb21vZG9jYS5jb20vVHJ1c3RlZENlcnRp +ZmljYXRlU2VydmljZXMuY3JsMDqgOKA2hjRodHRwOi8vY3JsLmNvbW9kby5uZXQvVHJ1c3RlZENl +cnRpZmljYXRlU2VydmljZXMuY3JsMA0GCSqGSIb3DQEBBQUAA4IBAQDIk4E7ibSvuIQSTI3S8Ntw +uleGFTQQuS9/HrCoiWChisJ3DFBKmwCL2Iv0QeLQg4pKHBQGsKNoBXAxMKdTmw7pSqBYaWcOrp32 +pSxBvzwGa+RZzG0Q8ZZvH9/0BAKkn0U+yNj6NkZEUD+Cl5EfKNsYEYwq5GWDVxISjBc/lDb+XbDA +BHcTuPQV1T84zJQ6VdCsmPW6AF/ghhmBeC8owH7TzEIK9a5QoNE+xqFx7D+gIIxmOom0jtTYsU0l +R+4viMi14QVFwL4Ucd56/Y57fU0IlqUSc/AtyjcndBInTMu2l+nZrghtWjlA3QVHdWpaIbOjGM9O +9y5Xt5hwXsjEeLBi +-----END CERTIFICATE----- + +QuoVadis Root CA +================ +-----BEGIN CERTIFICATE----- +MIIF0DCCBLigAwIBAgIEOrZQizANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJCTTEZMBcGA1UE +ChMQUXVvVmFkaXMgTGltaXRlZDElMCMGA1UECxMcUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0 +eTEuMCwGA1UEAxMlUXVvVmFkaXMgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wMTAz +MTkxODMzMzNaFw0yMTAzMTcxODMzMzNaMH8xCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRp +cyBMaW1pdGVkMSUwIwYDVQQLExxSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MS4wLAYDVQQD +EyVRdW9WYWRpcyBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEF +AAOCAQ8AMIIBCgKCAQEAv2G1lVO6V/z68mcLOhrfEYBklbTRvM16z/Ypli4kVEAkOPcahdxYTMuk +J0KX0J+DisPkBgNbAKVRHnAEdOLB1Dqr1607BxgFjv2DrOpm2RgbaIr1VxqYuvXtdj182d6UajtL +F8HVj71lODqV0D1VNk7feVcxKh7YWWVJWCCYfqtffp/p1k3sg3Spx2zY7ilKhSoGFPlU5tPaZQeL +YzcS19Dsw3sgQUSj7cugF+FxZc4dZjH3dgEZyH0DWLaVSR2mEiboxgx24ONmy+pdpibu5cxfvWen +AScOospUxbF6lR1xHkopigPcakXBpBlebzbNw6Kwt/5cOOJSvPhEQ+aQuwIDAQABo4ICUjCCAk4w +PQYIKwYBBQUHAQEEMTAvMC0GCCsGAQUFBzABhiFodHRwczovL29jc3AucXVvdmFkaXNvZmZzaG9y +ZS5jb20wDwYDVR0TAQH/BAUwAwEB/zCCARoGA1UdIASCAREwggENMIIBCQYJKwYBBAG+WAABMIH7 +MIHUBggrBgEFBQcCAjCBxxqBxFJlbGlhbmNlIG9uIHRoZSBRdW9WYWRpcyBSb290IENlcnRpZmlj +YXRlIGJ5IGFueSBwYXJ0eSBhc3N1bWVzIGFjY2VwdGFuY2Ugb2YgdGhlIHRoZW4gYXBwbGljYWJs +ZSBzdGFuZGFyZCB0ZXJtcyBhbmQgY29uZGl0aW9ucyBvZiB1c2UsIGNlcnRpZmljYXRpb24gcHJh +Y3RpY2VzLCBhbmQgdGhlIFF1b1ZhZGlzIENlcnRpZmljYXRlIFBvbGljeS4wIgYIKwYBBQUHAgEW +Fmh0dHA6Ly93d3cucXVvdmFkaXMuYm0wHQYDVR0OBBYEFItLbe3TKbkGGew5Oanwl4Rqy+/fMIGu +BgNVHSMEgaYwgaOAFItLbe3TKbkGGew5Oanwl4Rqy+/foYGEpIGBMH8xCzAJBgNVBAYTAkJNMRkw +FwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMSUwIwYDVQQLExxSb290IENlcnRpZmljYXRpb24gQXV0 +aG9yaXR5MS4wLAYDVQQDEyVRdW9WYWRpcyBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggQ6 +tlCLMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQUFAAOCAQEAitQUtf70mpKnGdSkfnIYj9lo +fFIk3WdvOXrEql494liwTXCYhGHoG+NpGA7O+0dQoE7/8CQfvbLO9Sf87C9TqnN7Az10buYWnuul +LsS/VidQK2K6vkscPFVcQR0kvoIgR13VRH56FmjffU1RcHhXHTMe/QKZnAzNCgVPx7uOpHX6Sm2x +gI4JVrmcGmD+XcHXetwReNDWXcG31a0ymQM6isxUJTkxgXsTIlG6Rmyhu576BGxJJnSP0nPrzDCi +5upZIof4l/UO/erMkqQWxFIY6iHOsfHmhIHluqmGKPJDWl0Snawe2ajlCmqnf6CHKc/yiU3U7MXi +5nrQNiOKSnQ2+Q== +-----END CERTIFICATE----- + +QuoVadis Root CA 2 +================== +-----BEGIN CERTIFICATE----- +MIIFtzCCA5+gAwIBAgICBQkwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQk0xGTAXBgNVBAoT +EFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMTElF1b1ZhZGlzIFJvb3QgQ0EgMjAeFw0wNjExMjQx +ODI3MDBaFw0zMTExMjQxODIzMzNaMEUxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM +aW1pdGVkMRswGQYDVQQDExJRdW9WYWRpcyBSb290IENBIDIwggIiMA0GCSqGSIb3DQEBAQUAA4IC +DwAwggIKAoICAQCaGMpLlA0ALa8DKYrwD4HIrkwZhR0In6spRIXzL4GtMh6QRr+jhiYaHv5+HBg6 +XJxgFyo6dIMzMH1hVBHL7avg5tKifvVrbxi3Cgst/ek+7wrGsxDp3MJGF/hd/aTa/55JWpzmM+Yk +lvc/ulsrHHo1wtZn/qtmUIttKGAr79dgw8eTvI02kfN/+NsRE8Scd3bBrrcCaoF6qUWD4gXmuVbB +lDePSHFjIuwXZQeVikvfj8ZaCuWw419eaxGrDPmF60Tp+ARz8un+XJiM9XOva7R+zdRcAitMOeGy +lZUtQofX1bOQQ7dsE/He3fbE+Ik/0XX1ksOR1YqI0JDs3G3eicJlcZaLDQP9nL9bFqyS2+r+eXyt +66/3FsvbzSUr5R/7mp/iUcw6UwxI5g69ybR2BlLmEROFcmMDBOAENisgGQLodKcftslWZvB1Jdxn +wQ5hYIizPtGo/KPaHbDRsSNU30R2be1B2MGyIrZTHN81Hdyhdyox5C315eXbyOD/5YDXC2Og/zOh +D7osFRXql7PSorW+8oyWHhqPHWykYTe5hnMz15eWniN9gqRMgeKh0bpnX5UHoycR7hYQe7xFSkyy +BNKr79X9DFHOUGoIMfmR2gyPZFwDwzqLID9ujWc9Otb+fVuIyV77zGHcizN300QyNQliBJIWENie +J0f7OyHj+OsdWwIDAQABo4GwMIGtMA8GA1UdEwEB/wQFMAMBAf8wCwYDVR0PBAQDAgEGMB0GA1Ud +DgQWBBQahGK8SEwzJQTU7tD2A8QZRtGUazBuBgNVHSMEZzBlgBQahGK8SEwzJQTU7tD2A8QZRtGU +a6FJpEcwRTELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMT +ElF1b1ZhZGlzIFJvb3QgQ0EgMoICBQkwDQYJKoZIhvcNAQEFBQADggIBAD4KFk2fBluornFdLwUv +Z+YTRYPENvbzwCYMDbVHZF34tHLJRqUDGCdViXh9duqWNIAXINzng/iN/Ae42l9NLmeyhP3ZRPx3 +UIHmfLTJDQtyU/h2BwdBR5YM++CCJpNVjP4iH2BlfF/nJrP3MpCYUNQ3cVX2kiF495V5+vgtJodm +VjB3pjd4M1IQWK4/YY7yarHvGH5KWWPKjaJW1acvvFYfzznB4vsKqBUsfU16Y8Zsl0Q80m/DShcK ++JDSV6IZUaUtl0HaB0+pUNqQjZRG4T7wlP0QADj1O+hA4bRuVhogzG9Yje0uRY/W6ZM/57Es3zrW +IozchLsib9D45MY56QSIPMO661V6bYCZJPVsAfv4l7CUW+v90m/xd2gNNWQjrLhVoQPRTUIZ3Ph1 +WVaj+ahJefivDrkRoHy3au000LYmYjgahwz46P0u05B/B5EqHdZ+XIWDmbA4CD/pXvk1B+TJYm5X +f6dQlfe6yJvmjqIBxdZmv3lh8zwc4bmCXF2gw+nYSL0ZohEUGW6yhhtoPkg3Goi3XZZenMfvJ2II +4pEZXNLxId26F0KCl3GBUzGpn/Z9Yr9y4aOTHcyKJloJONDO1w2AFrR4pTqHTI2KpdVGl/IsELm8 +VCLAAVBpQ570su9t+Oza8eOx79+Rj1QqCyXBJhnEUhAFZdWCEOrCMc0u +-----END CERTIFICATE----- + +QuoVadis Root CA 3 +================== +-----BEGIN CERTIFICATE----- +MIIGnTCCBIWgAwIBAgICBcYwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQk0xGTAXBgNVBAoT +EFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMTElF1b1ZhZGlzIFJvb3QgQ0EgMzAeFw0wNjExMjQx +OTExMjNaFw0zMTExMjQxOTA2NDRaMEUxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM +aW1pdGVkMRswGQYDVQQDExJRdW9WYWRpcyBSb290IENBIDMwggIiMA0GCSqGSIb3DQEBAQUAA4IC +DwAwggIKAoICAQDMV0IWVJzmmNPTTe7+7cefQzlKZbPoFog02w1ZkXTPkrgEQK0CSzGrvI2RaNgg +DhoB4hp7Thdd4oq3P5kazethq8Jlph+3t723j/z9cI8LoGe+AaJZz3HmDyl2/7FWeUUrH556VOij +KTVopAFPD6QuN+8bv+OPEKhyq1hX51SGyMnzW9os2l2ObjyjPtr7guXd8lyyBTNvijbO0BNO/79K +DDRMpsMhvVAEVeuxu537RR5kFd5VAYwCdrXLoT9CabwvvWhDFlaJKjdhkf2mrk7AyxRllDdLkgbv +BNDInIjbC3uBr7E9KsRlOni27tyAsdLTmZw67mtaa7ONt9XOnMK+pUsvFrGeaDsGb659n/je7Mwp +p5ijJUMv7/FfJuGITfhebtfZFG4ZM2mnO4SJk8RTVROhUXhA+LjJou57ulJCg54U7QVSWllWp5f8 +nT8KKdjcT5EOE7zelaTfi5m+rJsziO+1ga8bxiJTyPbH7pcUsMV8eFLI8M5ud2CEpukqdiDtWAEX +MJPpGovgc2PZapKUSU60rUqFxKMiMPwJ7Wgic6aIDFUhWMXhOp8q3crhkODZc6tsgLjoC2SToJyM +Gf+z0gzskSaHirOi4XCPLArlzW1oUevaPwV/izLmE1xr/l9A4iLItLRkT9a6fUg+qGkM17uGcclz +uD87nSVL2v9A6wIDAQABo4IBlTCCAZEwDwYDVR0TAQH/BAUwAwEB/zCB4QYDVR0gBIHZMIHWMIHT +BgkrBgEEAb5YAAMwgcUwgZMGCCsGAQUFBwICMIGGGoGDQW55IHVzZSBvZiB0aGlzIENlcnRpZmlj +YXRlIGNvbnN0aXR1dGVzIGFjY2VwdGFuY2Ugb2YgdGhlIFF1b1ZhZGlzIFJvb3QgQ0EgMyBDZXJ0 +aWZpY2F0ZSBQb2xpY3kgLyBDZXJ0aWZpY2F0aW9uIFByYWN0aWNlIFN0YXRlbWVudC4wLQYIKwYB +BQUHAgEWIWh0dHA6Ly93d3cucXVvdmFkaXNnbG9iYWwuY29tL2NwczALBgNVHQ8EBAMCAQYwHQYD +VR0OBBYEFPLAE+CCQz777i9nMpY1XNu4ywLQMG4GA1UdIwRnMGWAFPLAE+CCQz777i9nMpY1XNu4 +ywLQoUmkRzBFMQswCQYDVQQGEwJCTTEZMBcGA1UEChMQUXVvVmFkaXMgTGltaXRlZDEbMBkGA1UE +AxMSUXVvVmFkaXMgUm9vdCBDQSAzggIFxjANBgkqhkiG9w0BAQUFAAOCAgEAT62gLEz6wPJv92ZV +qyM07ucp2sNbtrCD2dDQ4iH782CnO11gUyeim/YIIirnv6By5ZwkajGxkHon24QRiSemd1o417+s +hvzuXYO8BsbRd2sPbSQvS3pspweWyuOEn62Iix2rFo1bZhfZFvSLgNLd+LJ2w/w4E6oM3kJpK27z +POuAJ9v1pkQNn1pVWQvVDVJIxa6f8i+AxeoyUDUSly7B4f/xI4hROJ/yZlZ25w9Rl6VSDE1JUZU2 +Pb+iSwwQHYaZTKrzchGT5Or2m9qoXadNt54CrnMAyNojA+j56hl0YgCUyyIgvpSnWbWCar6ZeXqp +8kokUvd0/bpO5qgdAm6xDYBEwa7TIzdfu4V8K5Iu6H6li92Z4b8nby1dqnuH/grdS/yO9SbkbnBC +bjPsMZ57k8HkyWkaPcBrTiJt7qtYTcbQQcEr6k8Sh17rRdhs9ZgC06DYVYoGmRmioHfRMJ6szHXu +g/WwYjnPbFfiTNKRCw51KBuav/0aQ/HKd/s7j2G4aSgWQgRecCocIdiP4b0jWy10QJLZYxkNc91p +vGJHvOB0K7Lrfb5BG7XARsWhIstfTsEokt4YutUqKLsRixeTmJlglFwjz1onl14LBQaTNx47aTbr +qZ5hHY8y2o4M1nQ+ewkk2gF3R8Q7zTSMmfXK4SVhM7JZG+Ju1zdXtg2pEto= +-----END CERTIFICATE----- + +Security Communication Root CA +============================== +-----BEGIN CERTIFICATE----- +MIIDWjCCAkKgAwIBAgIBADANBgkqhkiG9w0BAQUFADBQMQswCQYDVQQGEwJKUDEYMBYGA1UEChMP +U0VDT00gVHJ1c3QubmV0MScwJQYDVQQLEx5TZWN1cml0eSBDb21tdW5pY2F0aW9uIFJvb3RDQTEw +HhcNMDMwOTMwMDQyMDQ5WhcNMjMwOTMwMDQyMDQ5WjBQMQswCQYDVQQGEwJKUDEYMBYGA1UEChMP +U0VDT00gVHJ1c3QubmV0MScwJQYDVQQLEx5TZWN1cml0eSBDb21tdW5pY2F0aW9uIFJvb3RDQTEw +ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCzs/5/022x7xZ8V6UMbXaKL0u/ZPtM7orw +8yl89f/uKuDp6bpbZCKamm8sOiZpUQWZJtzVHGpxxpp9Hp3dfGzGjGdnSj74cbAZJ6kJDKaVv0uM +DPpVmDvY6CKhS3E4eayXkmmziX7qIWgGmBSWh9JhNrxtJ1aeV+7AwFb9Ms+k2Y7CI9eNqPPYJayX +5HA49LY6tJ07lyZDo6G8SVlyTCMwhwFY9k6+HGhWZq/NQV3Is00qVUarH9oe4kA92819uZKAnDfd +DJZkndwi92SL32HeFZRSFaB9UslLqCHJxrHty8OVYNEP8Ktw+N/LTX7s1vqr2b1/VPKl6Xn62dZ2 +JChzAgMBAAGjPzA9MB0GA1UdDgQWBBSgc0mZaNyFW2XjmygvV5+9M7wHSDALBgNVHQ8EBAMCAQYw +DwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAaECpqLvkT115swW1F7NgE+vGkl3g +0dNq/vu+m22/xwVtWSDEHPC32oRYAmP6SBbvT6UL90qY8j+eG61Ha2POCEfrUj94nK9NrvjVT8+a +mCoQQTlSxN3Zmw7vkwGusi7KaEIkQmywszo+zenaSMQVy+n5Bw+SUEmK3TGXX8npN6o7WWWXlDLJ +s58+OmJYxUmtYg5xpTKqL8aJdkNAExNnPaJUJRDL8Try2frbSVa7pv6nQTXD4IhhyYjH3zYQIphZ +6rBK+1YWc26sTfcioU+tHXotRSflMMFe8toTyyVCUZVHA4xsIcx0Qu1T/zOLjw9XARYvz6buyXAi +FL39vmwLAw== +-----END CERTIFICATE----- + +Sonera Class 2 Root CA +====================== +-----BEGIN CERTIFICATE----- +MIIDIDCCAgigAwIBAgIBHTANBgkqhkiG9w0BAQUFADA5MQswCQYDVQQGEwJGSTEPMA0GA1UEChMG +U29uZXJhMRkwFwYDVQQDExBTb25lcmEgQ2xhc3MyIENBMB4XDTAxMDQwNjA3Mjk0MFoXDTIxMDQw +NjA3Mjk0MFowOTELMAkGA1UEBhMCRkkxDzANBgNVBAoTBlNvbmVyYTEZMBcGA1UEAxMQU29uZXJh +IENsYXNzMiBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJAXSjWdyvANlsdE+hY3 +/Ei9vX+ALTU74W+oZ6m/AxxNjG8yR9VBaKQTBME1DJqEQ/xcHf+Js+gXGM2RX/uJ4+q/Tl18GybT +dXnt5oTjV+WtKcT0OijnpXuENmmz/V52vaMtmdOQTiMofRhj8VQ7Jp12W5dCsv+u8E7s3TmVToMG +f+dJQMjFAbJUWmYdPfz56TwKnoG4cPABi+QjVHzIrviQHgCWctRUz2EjvOr7nQKV0ba5cTppCD8P +tOFCx4j1P5iop7oc4HFx71hXgVB6XGt0Rg6DA5jDjqhu8nYybieDwnPz3BjotJPqdURrBGAgcVeH +nfO+oJAjPYok4doh28MCAwEAAaMzMDEwDwYDVR0TAQH/BAUwAwEB/zARBgNVHQ4ECgQISqCqWITT +XjwwCwYDVR0PBAQDAgEGMA0GCSqGSIb3DQEBBQUAA4IBAQBazof5FnIVV0sd2ZvnoiYw7JNn39Yt +0jSv9zilzqsWuasvfDXLrNAPtEwr/IDva4yRXzZ299uzGxnq9LIR/WFxRL8oszodv7ND6J+/3DEI +cbCdjdY0RzKQxmUk96BKfARzjzlvF4xytb1LyHr4e4PDKE6cCepnP7JnBBvDFNr450kkkdAdavph +Oe9r5yF1BgfYErQhIHBCcYHaPJo2vqZbDWpsmh+Re/n570K6Tk6ezAyNlNzZRZxe7EJQY670XcSx +EtzKO6gunRRaBXW37Ndj4ro1tgQIkejanZz2ZrUYrAqmVCY0M9IbwdR/GjqOC6oybtv8TyWf2TLH +llpwrN9M +-----END CERTIFICATE----- + +Staat der Nederlanden Root CA +============================= +-----BEGIN CERTIFICATE----- +MIIDujCCAqKgAwIBAgIEAJiWijANBgkqhkiG9w0BAQUFADBVMQswCQYDVQQGEwJOTDEeMBwGA1UE +ChMVU3RhYXQgZGVyIE5lZGVybGFuZGVuMSYwJAYDVQQDEx1TdGFhdCBkZXIgTmVkZXJsYW5kZW4g +Um9vdCBDQTAeFw0wMjEyMTcwOTIzNDlaFw0xNTEyMTYwOTE1MzhaMFUxCzAJBgNVBAYTAk5MMR4w +HAYDVQQKExVTdGFhdCBkZXIgTmVkZXJsYW5kZW4xJjAkBgNVBAMTHVN0YWF0IGRlciBOZWRlcmxh +bmRlbiBSb290IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmNK1URF6gaYUmHFt +vsznExvWJw56s2oYHLZhWtVhCb/ekBPHZ+7d89rFDBKeNVU+LCeIQGv33N0iYfXCxw719tV2U02P +jLwYdjeFnejKScfST5gTCaI+Ioicf9byEGW07l8Y1Rfj+MX94p2i71MOhXeiD+EwR+4A5zN9RGca +C1Hoi6CeUJhoNFIfLm0B8mBF8jHrqTFoKbt6QZ7GGX+UtFE5A3+y3qcym7RHjm+0Sq7lr7HcsBth +vJly3uSJt3omXdozSVtSnA71iq3DuD3oBmrC1SoLbHuEvVYFy4ZlkuxEK7COudxwC0barbxjiDn6 +22r+I/q85Ej0ZytqERAhSQIDAQABo4GRMIGOMAwGA1UdEwQFMAMBAf8wTwYDVR0gBEgwRjBEBgRV +HSAAMDwwOgYIKwYBBQUHAgEWLmh0dHA6Ly93d3cucGtpb3ZlcmhlaWQubmwvcG9saWNpZXMvcm9v +dC1wb2xpY3kwDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBSofeu8Y6R0E3QA7Jbg0zTBLL9s+DAN +BgkqhkiG9w0BAQUFAAOCAQEABYSHVXQ2YcG70dTGFagTtJ+k/rvuFbQvBgwp8qiSpGEN/KtcCFtR +EytNwiphyPgJWPwtArI5fZlmgb9uXJVFIGzmeafR2Bwp/MIgJ1HI8XxdNGdphREwxgDS1/PTfLbw +MVcoEoJz6TMvplW0C5GUR5z6u3pCMuiufi3IvKwUv9kP2Vv8wfl6leF9fpb8cbDCTMjfRTTJzg3y +nGQI0DvDKcWy7ZAEwbEpkcUwb8GpcjPM/l0WFywRaed+/sWDCN+83CI6LiBpIzlWYGeQiy52OfsR +iJf2fL1LuCAWZwWN4jvBcj+UlTfHXbme2JOhF4//DGYVwSR8MnwDHTuhWEUykw== +-----END CERTIFICATE----- + +TDC Internet Root CA +==================== +-----BEGIN CERTIFICATE----- +MIIEKzCCAxOgAwIBAgIEOsylTDANBgkqhkiG9w0BAQUFADBDMQswCQYDVQQGEwJESzEVMBMGA1UE +ChMMVERDIEludGVybmV0MR0wGwYDVQQLExRUREMgSW50ZXJuZXQgUm9vdCBDQTAeFw0wMTA0MDUx +NjMzMTdaFw0yMTA0MDUxNzAzMTdaMEMxCzAJBgNVBAYTAkRLMRUwEwYDVQQKEwxUREMgSW50ZXJu +ZXQxHTAbBgNVBAsTFFREQyBJbnRlcm5ldCBSb290IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A +MIIBCgKCAQEAxLhAvJHVYx/XmaCLDEAedLdInUaMArLgJF/wGROnN4NrXceO+YQwzho7+vvOi20j +xsNuZp+Jpd/gQlBn+h9sHvTQBda/ytZO5GhgbEaqHF1j4QeGDmUApy6mcca8uYGoOn0a0vnRrEvL +znWv3Hv6gXPU/Lq9QYjUdLP5Xjg6PEOo0pVOd20TDJ2PeAG3WiAfAzc14izbSysseLlJ28TQx5yc +5IogCSEWVmb/Bexb4/DPqyQkXsN/cHoSxNK1EKC2IeGNeGlVRGn1ypYcNIUXJXfi9i8nmHj9eQY6 +otZaQ8H/7AQ77hPv01ha/5Lr7K7a8jcDR0G2l8ktCkEiu7vmpwIDAQABo4IBJTCCASEwEQYJYIZI +AYb4QgEBBAQDAgAHMGUGA1UdHwReMFwwWqBYoFakVDBSMQswCQYDVQQGEwJESzEVMBMGA1UEChMM +VERDIEludGVybmV0MR0wGwYDVQQLExRUREMgSW50ZXJuZXQgUm9vdCBDQTENMAsGA1UEAxMEQ1JM +MTArBgNVHRAEJDAigA8yMDAxMDQwNTE2MzMxN1qBDzIwMjEwNDA1MTcwMzE3WjALBgNVHQ8EBAMC +AQYwHwYDVR0jBBgwFoAUbGQBx/2FbazI2p5QCIUItTxWqFAwHQYDVR0OBBYEFGxkAcf9hW2syNqe +UAiFCLU8VqhQMAwGA1UdEwQFMAMBAf8wHQYJKoZIhvZ9B0EABBAwDhsIVjUuMDo0LjADAgSQMA0G +CSqGSIb3DQEBBQUAA4IBAQBOQ8zR3R0QGwZ/t6T609lN+yOfI1Rb5osvBCiLtSdtiaHsmGnc540m +gwV5dOy0uaOXwTUA/RXaOYE6lTGQ3pfphqiZdwzlWqCE/xIWrG64jcN7ksKsLtB9KOy282A4aW8+ +2ARVPp7MVdK6/rtHBNcK2RYKNCn1WBPVT8+PVkuzHu7TmHnaCB4Mb7j4Fifvwm899qNLPg7kbWzb +O0ESm70NRyN/PErQr8Cv9u8btRXE64PECV90i9kR+8JWsTz4cMo0jUNAE4z9mQNUecYu6oah9jrU +Cbz0vGbMPVjQV0kK7iXiQe4T+Zs4NNEA9X7nlB38aQNiuJkFBT1reBK9sG9l +-----END CERTIFICATE----- + +UTN DATACorp SGC Root CA +======================== +-----BEGIN CERTIFICATE----- +MIIEXjCCA0agAwIBAgIQRL4Mi1AAIbQR0ypoBqmtaTANBgkqhkiG9w0BAQUFADCBkzELMAkGA1UE +BhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2UgQ2l0eTEeMBwGA1UEChMVVGhl +IFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xGzAZ +BgNVBAMTElVUTiAtIERBVEFDb3JwIFNHQzAeFw05OTA2MjQxODU3MjFaFw0xOTA2MjQxOTA2MzBa +MIGTMQswCQYDVQQGEwJVUzELMAkGA1UECBMCVVQxFzAVBgNVBAcTDlNhbHQgTGFrZSBDaXR5MR4w +HAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxITAfBgNVBAsTGGh0dHA6Ly93d3cudXNlcnRy +dXN0LmNvbTEbMBkGA1UEAxMSVVROIC0gREFUQUNvcnAgU0dDMIIBIjANBgkqhkiG9w0BAQEFAAOC +AQ8AMIIBCgKCAQEA3+5YEKIrblXEjr8uRgnn4AgPLit6E5Qbvfa2gI5lBZMAHryv4g+OGQ0SR+ys +raP6LnD43m77VkIVni5c7yPeIbkFdicZD0/Ww5y0vpQZY/KmEQrrU0icvvIpOxboGqBMpsn0GFlo +wHDyUwDAXlCCpVZvNvlK4ESGoE1O1kduSUrLZ9emxAW5jh70/P/N5zbgnAVssjMiFdC04MwXwLLA +9P4yPykqlXvY8qdOD1R8oQ2AswkDwf9c3V6aPryuvEeKaq5xyh+xKrhfQgUL7EYw0XILyulWbfXv +33i+Ybqypa4ETLyorGkVl73v67SMvzX41MPRKA5cOp9wGDMgd8SirwIDAQABo4GrMIGoMAsGA1Ud +DwQEAwIBxjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRTMtGzz3/64PGgXYVOktKeRR20TzA9 +BgNVHR8ENjA0MDKgMKAuhixodHRwOi8vY3JsLnVzZXJ0cnVzdC5jb20vVVROLURBVEFDb3JwU0dD +LmNybDAqBgNVHSUEIzAhBggrBgEFBQcDAQYKKwYBBAGCNwoDAwYJYIZIAYb4QgQBMA0GCSqGSIb3 +DQEBBQUAA4IBAQAnNZcAiosovcYzMB4p/OL31ZjUQLtgyr+rFywJNn9Q+kHcrpY6CiM+iVnJowft +Gzet/Hy+UUla3joKVAgWRcKZsYfNjGjgaQPpxE6YsjuMFrMOoAyYUJuTqXAJyCyjj98C5OBxOvG0 +I3KgqgHf35g+FFCgMSa9KOlaMCZ1+XtgHI3zzVAmbQQnmt/VDUVHKWss5nbZqSl9Mt3JNjy9rjXx +EZ4du5A/EkdOjtd+D2JzHVImOBwYSf0wdJrE5SIv2MCN7ZF6TACPcn9d2t0bi0Vr591pl6jFVkwP +DPafepE39peC4N1xaf92P2BNPM/3mfnGV/TJVTl4uix5yaaIK/QI +-----END CERTIFICATE----- + +UTN USERFirst Hardware Root CA +============================== +-----BEGIN CERTIFICATE----- +MIIEdDCCA1ygAwIBAgIQRL4Mi1AAJLQR0zYq/mUK/TANBgkqhkiG9w0BAQUFADCBlzELMAkGA1UE +BhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2UgQ2l0eTEeMBwGA1UEChMVVGhl +IFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHzAd +BgNVBAMTFlVUTi1VU0VSRmlyc3QtSGFyZHdhcmUwHhcNOTkwNzA5MTgxMDQyWhcNMTkwNzA5MTgx +OTIyWjCBlzELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2UgQ2l0 +eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExhodHRwOi8vd3d3LnVz +ZXJ0cnVzdC5jb20xHzAdBgNVBAMTFlVUTi1VU0VSRmlyc3QtSGFyZHdhcmUwggEiMA0GCSqGSIb3 +DQEBAQUAA4IBDwAwggEKAoIBAQCx98M4P7Sof885glFn0G2f0v9Y8+efK+wNiVSZuTiZFvfgIXlI +wrthdBKWHTxqctU8EGc6Oe0rE81m65UJM6Rsl7HoxuzBdXmcRl6Nq9Bq/bkqVRcQVLMZ8Jr28bFd +tqdt++BxF2uiiPsA3/4aMXcMmgF6sTLjKwEHOG7DpV4jvEWbe1DByTCP2+UretNb+zNAHqDVmBe8 +i4fDidNdoI6yqqr2jmmIBsX6iSHzCJ1pLgkzmykNRg+MzEk0sGlRvfkGzWitZky8PqxhvQqIDsjf +Pe58BEydCl5rkdbux+0ojatNh4lz0G6k0B4WixThdkQDf2Os5M1JnMWS9KsyoUhbAgMBAAGjgbkw +gbYwCwYDVR0PBAQDAgHGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFKFyXyYbKJhDlV0HN9WF +lp1L0sNFMEQGA1UdHwQ9MDswOaA3oDWGM2h0dHA6Ly9jcmwudXNlcnRydXN0LmNvbS9VVE4tVVNF +UkZpcnN0LUhhcmR3YXJlLmNybDAxBgNVHSUEKjAoBggrBgEFBQcDAQYIKwYBBQUHAwUGCCsGAQUF +BwMGBggrBgEFBQcDBzANBgkqhkiG9w0BAQUFAAOCAQEARxkP3nTGmZev/K0oXnWO6y1n7k57K9cM +//bey1WiCuFMVGWTYGufEpytXoMs61quwOQt9ABjHbjAbPLPSbtNk28GpgoiskliCE7/yMgUsogW +XecB5BKV5UU0s4tpvc+0hY91UZ59Ojg6FEgSxvunOxqNDYJAB+gECJChicsZUN/KHAG8HQQZexB2 +lzvukJDKxA4fFm517zP4029bHpbj4HR3dHuKom4t3XbWOTCC8KucUvIqx69JXn7HaOWCgchqJ/kn +iCrVWFCVH/A7HFe7fRQ5YiuayZSSKqMiDP+JJn1fIytH1xUdqWqeUQ0qUZ6B+dQ7XnASfxAynB67 +nfhmqA== +-----END CERTIFICATE----- + +Camerfirma Chambers of Commerce Root +==================================== +-----BEGIN CERTIFICATE----- +MIIEvTCCA6WgAwIBAgIBADANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJFVTEnMCUGA1UEChMe +QUMgQ2FtZXJmaXJtYSBTQSBDSUYgQTgyNzQzMjg3MSMwIQYDVQQLExpodHRwOi8vd3d3LmNoYW1i +ZXJzaWduLm9yZzEiMCAGA1UEAxMZQ2hhbWJlcnMgb2YgQ29tbWVyY2UgUm9vdDAeFw0wMzA5MzAx +NjEzNDNaFw0zNzA5MzAxNjEzNDRaMH8xCzAJBgNVBAYTAkVVMScwJQYDVQQKEx5BQyBDYW1lcmZp +cm1hIFNBIENJRiBBODI3NDMyODcxIzAhBgNVBAsTGmh0dHA6Ly93d3cuY2hhbWJlcnNpZ24ub3Jn +MSIwIAYDVQQDExlDaGFtYmVycyBvZiBDb21tZXJjZSBSb290MIIBIDANBgkqhkiG9w0BAQEFAAOC +AQ0AMIIBCAKCAQEAtzZV5aVdGDDg2olUkfzIx1L4L1DZ77F1c2VHfRtbunXF/KGIJPov7coISjlU +xFF6tdpg6jg8gbLL8bvZkSM/SAFwdakFKq0fcfPJVD0dBmpAPrMMhe5cG3nCYsS4No41XQEMIwRH +NaqbYE6gZj3LJgqcQKH0XZi/caulAGgq7YN6D6IUtdQis4CwPAxaUWktWBiP7Zme8a7ileb2R6jW +DA+wWFjbw2Y3npuRVDM30pQcakjJyfKl2qUMI/cjDpwyVV5xnIQFUZot/eZOKjRa3spAN2cMVCFV +d9oKDMyXroDclDZK9D7ONhMeU+SsTjoF7Nuucpw4i9A5O4kKPnf+dQIBA6OCAUQwggFAMBIGA1Ud +EwEB/wQIMAYBAf8CAQwwPAYDVR0fBDUwMzAxoC+gLYYraHR0cDovL2NybC5jaGFtYmVyc2lnbi5v +cmcvY2hhbWJlcnNyb290LmNybDAdBgNVHQ4EFgQU45T1sU3p26EpW1eLTXYGduHRooowDgYDVR0P +AQH/BAQDAgEGMBEGCWCGSAGG+EIBAQQEAwIABzAnBgNVHREEIDAegRxjaGFtYmVyc3Jvb3RAY2hh +bWJlcnNpZ24ub3JnMCcGA1UdEgQgMB6BHGNoYW1iZXJzcm9vdEBjaGFtYmVyc2lnbi5vcmcwWAYD +VR0gBFEwTzBNBgsrBgEEAYGHLgoDATA+MDwGCCsGAQUFBwIBFjBodHRwOi8vY3BzLmNoYW1iZXJz +aWduLm9yZy9jcHMvY2hhbWJlcnNyb290Lmh0bWwwDQYJKoZIhvcNAQEFBQADggEBAAxBl8IahsAi +fJ/7kPMa0QOx7xP5IV8EnNrJpY0nbJaHkb5BkAFyk+cefV/2icZdp0AJPaxJRUXcLo0waLIJuvvD +L8y6C98/d3tGfToSJI6WjzwFCm/SlCgdbQzALogi1djPHRPH8EjX1wWnz8dHnjs8NMiAT9QUu/wN +UPf6s+xCX6ndbcj0dc97wXImsQEcXCz9ek60AcUFV7nnPKoF2YjpB0ZBzu9Bga5Y34OirsrXdx/n +ADydb47kMgkdTXg0eDQ8lJsm7U9xxhl6vSAiSFr+S30Dt+dYvsYyTnQeaN2oaFuzPu5ifdmA6Ap1 +erfutGWaIZDgqtCYvDi1czyL+Nw= +-----END CERTIFICATE----- + +Camerfirma Global Chambersign Root +================================== +-----BEGIN CERTIFICATE----- +MIIExTCCA62gAwIBAgIBADANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJFVTEnMCUGA1UEChMe +QUMgQ2FtZXJmaXJtYSBTQSBDSUYgQTgyNzQzMjg3MSMwIQYDVQQLExpodHRwOi8vd3d3LmNoYW1i +ZXJzaWduLm9yZzEgMB4GA1UEAxMXR2xvYmFsIENoYW1iZXJzaWduIFJvb3QwHhcNMDMwOTMwMTYx +NDE4WhcNMzcwOTMwMTYxNDE4WjB9MQswCQYDVQQGEwJFVTEnMCUGA1UEChMeQUMgQ2FtZXJmaXJt +YSBTQSBDSUYgQTgyNzQzMjg3MSMwIQYDVQQLExpodHRwOi8vd3d3LmNoYW1iZXJzaWduLm9yZzEg +MB4GA1UEAxMXR2xvYmFsIENoYW1iZXJzaWduIFJvb3QwggEgMA0GCSqGSIb3DQEBAQUAA4IBDQAw +ggEIAoIBAQCicKLQn0KuWxfH2H3PFIP8T8mhtxOviteePgQKkotgVvq0Mi+ITaFgCPS3CU6gSS9J +1tPfnZdan5QEcOw/Wdm3zGaLmFIoCQLfxS+EjXqXd7/sQJ0lcqu1PzKY+7e3/HKE5TWH+VX6ox8O +by4o3Wmg2UIQxvi1RMLQQ3/bvOSiPGpVeAp3qdjqGTK3L/5cPxvusZjsyq16aUXjlg9V9ubtdepl +6DJWk0aJqCWKZQbua795B9Dxt6/tLE2Su8CoX6dnfQTyFQhwrJLWfQTSM/tMtgsL+xrJxI0DqX5c +8lCrEqWhz0hQpe/SyBoT+rB/sYIcd2oPX9wLlY/vQ37mRQklAgEDo4IBUDCCAUwwEgYDVR0TAQH/ +BAgwBgEB/wIBDDA/BgNVHR8EODA2MDSgMqAwhi5odHRwOi8vY3JsLmNoYW1iZXJzaWduLm9yZy9j +aGFtYmVyc2lnbnJvb3QuY3JsMB0GA1UdDgQWBBRDnDafsJ4wTcbOX60Qq+UDpfqpFDAOBgNVHQ8B +Af8EBAMCAQYwEQYJYIZIAYb4QgEBBAQDAgAHMCoGA1UdEQQjMCGBH2NoYW1iZXJzaWducm9vdEBj +aGFtYmVyc2lnbi5vcmcwKgYDVR0SBCMwIYEfY2hhbWJlcnNpZ25yb290QGNoYW1iZXJzaWduLm9y +ZzBbBgNVHSAEVDBSMFAGCysGAQQBgYcuCgEBMEEwPwYIKwYBBQUHAgEWM2h0dHA6Ly9jcHMuY2hh +bWJlcnNpZ24ub3JnL2Nwcy9jaGFtYmVyc2lnbnJvb3QuaHRtbDANBgkqhkiG9w0BAQUFAAOCAQEA +PDtwkfkEVCeR4e3t/mh/YV3lQWVPMvEYBZRqHN4fcNs+ezICNLUMbKGKfKX0j//U2K0X1S0E0T9Y +gOKBWYi+wONGkyT+kL0mojAt6JcmVzWJdJYY9hXiryQZVgICsroPFOrGimbBhkVVi76SvpykBMdJ +PJ7oKXqJ1/6v/2j1pReQvayZzKWGVwlnRtvWFsJG8eSpUPWP0ZIV018+xgBJOm5YstHRJw0lyDL4 +IBHNfTIzSJRUTN3cecQwn+uOuFW114hcxWokPbLTBQNRxgfvzBRydD1ucs4YKIxKoHflCStFREes +t2d/AYoFWpO+ocH/+OcOZ6RHSXZddZAa9SaP8A== +-----END CERTIFICATE----- + +NetLock Notary (Class A) Root +============================= +-----BEGIN CERTIFICATE----- +MIIGfTCCBWWgAwIBAgICAQMwDQYJKoZIhvcNAQEEBQAwga8xCzAJBgNVBAYTAkhVMRAwDgYDVQQI +EwdIdW5nYXJ5MREwDwYDVQQHEwhCdWRhcGVzdDEnMCUGA1UEChMeTmV0TG9jayBIYWxvemF0Yml6 +dG9uc2FnaSBLZnQuMRowGAYDVQQLExFUYW51c2l0dmFueWtpYWRvazE2MDQGA1UEAxMtTmV0TG9j +ayBLb3pqZWd5em9pIChDbGFzcyBBKSBUYW51c2l0dmFueWtpYWRvMB4XDTk5MDIyNDIzMTQ0N1oX +DTE5MDIxOTIzMTQ0N1owga8xCzAJBgNVBAYTAkhVMRAwDgYDVQQIEwdIdW5nYXJ5MREwDwYDVQQH +EwhCdWRhcGVzdDEnMCUGA1UEChMeTmV0TG9jayBIYWxvemF0Yml6dG9uc2FnaSBLZnQuMRowGAYD +VQQLExFUYW51c2l0dmFueWtpYWRvazE2MDQGA1UEAxMtTmV0TG9jayBLb3pqZWd5em9pIChDbGFz +cyBBKSBUYW51c2l0dmFueWtpYWRvMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvHSM +D7tM9DceqQWC2ObhbHDqeLVu0ThEDaiDzl3S1tWBxdRL51uUcCbbO51qTGL3cfNk1mE7PetzozfZ +z+qMkjvN9wfcZnSX9EUi3fRc4L9t875lM+QVOr/bmJBVOMTtplVjC7B4BPTjbsE/jvxReB+SnoPC +/tmwqcm8WgD/qaiYdPv2LD4VOQ22BFWoDpggQrOxJa1+mm9dU7GrDPzr4PN6s6iz/0b2Y6LYOph7 +tqyF/7AlT3Rj5xMHpQqPBffAZG9+pyeAlt7ULoZgx2srXnN7F+eRP2QM2EsiNCubMvJIH5+hCoR6 +4sKtlz2O1cH5VqNQ6ca0+pii7pXmKgOM3wIDAQABo4ICnzCCApswDgYDVR0PAQH/BAQDAgAGMBIG +A1UdEwEB/wQIMAYBAf8CAQQwEQYJYIZIAYb4QgEBBAQDAgAHMIICYAYJYIZIAYb4QgENBIICURaC +Ak1GSUdZRUxFTSEgRXplbiB0YW51c2l0dmFueSBhIE5ldExvY2sgS2Z0LiBBbHRhbGFub3MgU3pv +bGdhbHRhdGFzaSBGZWx0ZXRlbGVpYmVuIGxlaXJ0IGVsamFyYXNvayBhbGFwamFuIGtlc3p1bHQu +IEEgaGl0ZWxlc2l0ZXMgZm9seWFtYXRhdCBhIE5ldExvY2sgS2Z0LiB0ZXJtZWtmZWxlbG9zc2Vn +LWJpenRvc2l0YXNhIHZlZGkuIEEgZGlnaXRhbGlzIGFsYWlyYXMgZWxmb2dhZGFzYW5hayBmZWx0 +ZXRlbGUgYXogZWxvaXJ0IGVsbGVub3J6ZXNpIGVsamFyYXMgbWVndGV0ZWxlLiBBeiBlbGphcmFz +IGxlaXJhc2EgbWVndGFsYWxoYXRvIGEgTmV0TG9jayBLZnQuIEludGVybmV0IGhvbmxhcGphbiBh +IGh0dHBzOi8vd3d3Lm5ldGxvY2submV0L2RvY3MgY2ltZW4gdmFneSBrZXJoZXRvIGF6IGVsbGVu +b3J6ZXNAbmV0bG9jay5uZXQgZS1tYWlsIGNpbWVuLiBJTVBPUlRBTlQhIFRoZSBpc3N1YW5jZSBh +bmQgdGhlIHVzZSBvZiB0aGlzIGNlcnRpZmljYXRlIGlzIHN1YmplY3QgdG8gdGhlIE5ldExvY2sg +Q1BTIGF2YWlsYWJsZSBhdCBodHRwczovL3d3dy5uZXRsb2NrLm5ldC9kb2NzIG9yIGJ5IGUtbWFp +bCBhdCBjcHNAbmV0bG9jay5uZXQuMA0GCSqGSIb3DQEBBAUAA4IBAQBIJEb3ulZv+sgoA0BO5TE5 +ayZrU3/b39/zcT0mwBQOxmd7I6gMc90Bu8bKbjc5VdXHjFYgDigKDtIqpLBJUsY4B/6+CgmM0ZjP +ytoUMaFP0jn8DxEsQ8Pdq5PHVT5HfBgaANzze9jyf1JsIPQLX2lS9O74silg6+NJMSEN1rUQQeJB +CWziGppWS3cC9qCbmieH6FUpccKQn0V4GuEVZD3QDtigdp+uxdAu6tYPVuxkf1qbFFgBJ34TUMdr +KuZoPL9coAob4Q566eKAw+np9v1sEZ7Q5SgnK1QyQhSCdeZK8CtmdWOMovsEPoMOmzbwGOQmIMOM +8CgHrTwXZoi1/baI +-----END CERTIFICATE----- + +NetLock Business (Class B) Root +=============================== +-----BEGIN CERTIFICATE----- +MIIFSzCCBLSgAwIBAgIBaTANBgkqhkiG9w0BAQQFADCBmTELMAkGA1UEBhMCSFUxETAPBgNVBAcT +CEJ1ZGFwZXN0MScwJQYDVQQKEx5OZXRMb2NrIEhhbG96YXRiaXp0b25zYWdpIEtmdC4xGjAYBgNV +BAsTEVRhbnVzaXR2YW55a2lhZG9rMTIwMAYDVQQDEylOZXRMb2NrIFV6bGV0aSAoQ2xhc3MgQikg +VGFudXNpdHZhbnlraWFkbzAeFw05OTAyMjUxNDEwMjJaFw0xOTAyMjAxNDEwMjJaMIGZMQswCQYD +VQQGEwJIVTERMA8GA1UEBxMIQnVkYXBlc3QxJzAlBgNVBAoTHk5ldExvY2sgSGFsb3phdGJpenRv +bnNhZ2kgS2Z0LjEaMBgGA1UECxMRVGFudXNpdHZhbnlraWFkb2sxMjAwBgNVBAMTKU5ldExvY2sg +VXpsZXRpIChDbGFzcyBCKSBUYW51c2l0dmFueWtpYWRvMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB +iQKBgQCx6gTsIKAjwo84YM/HRrPVG/77uZmeBNwcf4xKgZjupNTKihe5In+DCnVMm8Bp2GQ5o+2S +o/1bXHQawEfKOml2mrriRBf8TKPV/riXiK+IA4kfpPIEPsgHC+b5sy96YhQJRhTKZPWLgLViqNhr +1nGTLbO/CVRY7QbrqHvcQ7GhaQIDAQABo4ICnzCCApswEgYDVR0TAQH/BAgwBgEB/wIBBDAOBgNV +HQ8BAf8EBAMCAAYwEQYJYIZIAYb4QgEBBAQDAgAHMIICYAYJYIZIAYb4QgENBIICURaCAk1GSUdZ +RUxFTSEgRXplbiB0YW51c2l0dmFueSBhIE5ldExvY2sgS2Z0LiBBbHRhbGFub3MgU3pvbGdhbHRh +dGFzaSBGZWx0ZXRlbGVpYmVuIGxlaXJ0IGVsamFyYXNvayBhbGFwamFuIGtlc3p1bHQuIEEgaGl0 +ZWxlc2l0ZXMgZm9seWFtYXRhdCBhIE5ldExvY2sgS2Z0LiB0ZXJtZWtmZWxlbG9zc2VnLWJpenRv +c2l0YXNhIHZlZGkuIEEgZGlnaXRhbGlzIGFsYWlyYXMgZWxmb2dhZGFzYW5hayBmZWx0ZXRlbGUg +YXogZWxvaXJ0IGVsbGVub3J6ZXNpIGVsamFyYXMgbWVndGV0ZWxlLiBBeiBlbGphcmFzIGxlaXJh +c2EgbWVndGFsYWxoYXRvIGEgTmV0TG9jayBLZnQuIEludGVybmV0IGhvbmxhcGphbiBhIGh0dHBz +Oi8vd3d3Lm5ldGxvY2submV0L2RvY3MgY2ltZW4gdmFneSBrZXJoZXRvIGF6IGVsbGVub3J6ZXNA +bmV0bG9jay5uZXQgZS1tYWlsIGNpbWVuLiBJTVBPUlRBTlQhIFRoZSBpc3N1YW5jZSBhbmQgdGhl +IHVzZSBvZiB0aGlzIGNlcnRpZmljYXRlIGlzIHN1YmplY3QgdG8gdGhlIE5ldExvY2sgQ1BTIGF2 +YWlsYWJsZSBhdCBodHRwczovL3d3dy5uZXRsb2NrLm5ldC9kb2NzIG9yIGJ5IGUtbWFpbCBhdCBj +cHNAbmV0bG9jay5uZXQuMA0GCSqGSIb3DQEBBAUAA4GBAATbrowXr/gOkDFOzT4JwG06sPgzTEdM +43WIEJessDgVkcYplswhwG08pXTP2IKlOcNl40JwuyKQ433bNXbhoLXan3BukxowOR0w2y7jfLKR +stE3Kfq51hdcR0/jHTjrn9V7lagonhVK0dHQKwCXoOKSNitjrFgBazMpUIaD8QFI +-----END CERTIFICATE----- + +NetLock Express (Class C) Root +============================== +-----BEGIN CERTIFICATE----- +MIIFTzCCBLigAwIBAgIBaDANBgkqhkiG9w0BAQQFADCBmzELMAkGA1UEBhMCSFUxETAPBgNVBAcT +CEJ1ZGFwZXN0MScwJQYDVQQKEx5OZXRMb2NrIEhhbG96YXRiaXp0b25zYWdpIEtmdC4xGjAYBgNV +BAsTEVRhbnVzaXR2YW55a2lhZG9rMTQwMgYDVQQDEytOZXRMb2NrIEV4cHJlc3N6IChDbGFzcyBD +KSBUYW51c2l0dmFueWtpYWRvMB4XDTk5MDIyNTE0MDgxMVoXDTE5MDIyMDE0MDgxMVowgZsxCzAJ +BgNVBAYTAkhVMREwDwYDVQQHEwhCdWRhcGVzdDEnMCUGA1UEChMeTmV0TG9jayBIYWxvemF0Yml6 +dG9uc2FnaSBLZnQuMRowGAYDVQQLExFUYW51c2l0dmFueWtpYWRvazE0MDIGA1UEAxMrTmV0TG9j +ayBFeHByZXNzeiAoQ2xhc3MgQykgVGFudXNpdHZhbnlraWFkbzCBnzANBgkqhkiG9w0BAQEFAAOB +jQAwgYkCgYEA6+ywbGGKIyWvYCDj2Z/8kwvbXY2wobNAOoLO/XXgeDIDhlqGlZHtU/qdQPzm6N3Z +W3oDvV3zOwzDUXmbrVWg6dADEK8KuhRC2VImESLH0iDMgqSaqf64gXadarfSNnU+sYYJ9m5tfk63 +euyucYT2BDMIJTLrdKwWRMbkQJMdf60CAwEAAaOCAp8wggKbMBIGA1UdEwEB/wQIMAYBAf8CAQQw +DgYDVR0PAQH/BAQDAgAGMBEGCWCGSAGG+EIBAQQEAwIABzCCAmAGCWCGSAGG+EIBDQSCAlEWggJN +RklHWUVMRU0hIEV6ZW4gdGFudXNpdHZhbnkgYSBOZXRMb2NrIEtmdC4gQWx0YWxhbm9zIFN6b2xn +YWx0YXRhc2kgRmVsdGV0ZWxlaWJlbiBsZWlydCBlbGphcmFzb2sgYWxhcGphbiBrZXN6dWx0LiBB +IGhpdGVsZXNpdGVzIGZvbHlhbWF0YXQgYSBOZXRMb2NrIEtmdC4gdGVybWVrZmVsZWxvc3NlZy1i +aXp0b3NpdGFzYSB2ZWRpLiBBIGRpZ2l0YWxpcyBhbGFpcmFzIGVsZm9nYWRhc2FuYWsgZmVsdGV0 +ZWxlIGF6IGVsb2lydCBlbGxlbm9yemVzaSBlbGphcmFzIG1lZ3RldGVsZS4gQXogZWxqYXJhcyBs +ZWlyYXNhIG1lZ3RhbGFsaGF0byBhIE5ldExvY2sgS2Z0LiBJbnRlcm5ldCBob25sYXBqYW4gYSBo +dHRwczovL3d3dy5uZXRsb2NrLm5ldC9kb2NzIGNpbWVuIHZhZ3kga2VyaGV0byBheiBlbGxlbm9y +emVzQG5ldGxvY2submV0IGUtbWFpbCBjaW1lbi4gSU1QT1JUQU5UISBUaGUgaXNzdWFuY2UgYW5k +IHRoZSB1c2Ugb2YgdGhpcyBjZXJ0aWZpY2F0ZSBpcyBzdWJqZWN0IHRvIHRoZSBOZXRMb2NrIENQ +UyBhdmFpbGFibGUgYXQgaHR0cHM6Ly93d3cubmV0bG9jay5uZXQvZG9jcyBvciBieSBlLW1haWwg +YXQgY3BzQG5ldGxvY2submV0LjANBgkqhkiG9w0BAQQFAAOBgQAQrX/XDDKACtiG8XmYta3UzbM2 +xJZIwVzNmtkFLp++UOv0JhQQLdRmF/iewSf98e3ke0ugbLWrmldwpu2gpO0u9f38vf5NNwgMvOOW +gyL1SRt/Syu0VMGAfJlOHdCM7tCs5ZL6dVb+ZKATj7i4Fp1hBWeAyNDYpQcCNJgEjTME1A== +-----END CERTIFICATE----- + +XRamp Global CA Root +==================== +-----BEGIN CERTIFICATE----- +MIIEMDCCAxigAwIBAgIQUJRs7Bjq1ZxN1ZfvdY+grTANBgkqhkiG9w0BAQUFADCBgjELMAkGA1UE +BhMCVVMxHjAcBgNVBAsTFXd3dy54cmFtcHNlY3VyaXR5LmNvbTEkMCIGA1UEChMbWFJhbXAgU2Vj +dXJpdHkgU2VydmljZXMgSW5jMS0wKwYDVQQDEyRYUmFtcCBHbG9iYWwgQ2VydGlmaWNhdGlvbiBB +dXRob3JpdHkwHhcNMDQxMTAxMTcxNDA0WhcNMzUwMTAxMDUzNzE5WjCBgjELMAkGA1UEBhMCVVMx +HjAcBgNVBAsTFXd3dy54cmFtcHNlY3VyaXR5LmNvbTEkMCIGA1UEChMbWFJhbXAgU2VjdXJpdHkg +U2VydmljZXMgSW5jMS0wKwYDVQQDEyRYUmFtcCBHbG9iYWwgQ2VydGlmaWNhdGlvbiBBdXRob3Jp +dHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCYJB69FbS638eMpSe2OAtp87ZOqCwu +IR1cRN8hXX4jdP5efrRKt6atH67gBhbim1vZZ3RrXYCPKZ2GG9mcDZhtdhAoWORlsH9KmHmf4MMx +foArtYzAQDsRhtDLooY2YKTVMIJt2W7QDxIEM5dfT2Fa8OT5kavnHTu86M/0ay00fOJIYRyO82FE +zG+gSqmUsE3a56k0enI4qEHMPJQRfevIpoy3hsvKMzvZPTeL+3o+hiznc9cKV6xkmxnr9A8ECIqs +AxcZZPRaJSKNNCyy9mgdEm3Tih4U2sSPpuIjhdV6Db1q4Ons7Be7QhtnqiXtRYMh/MHJfNViPvry +xS3T/dRlAgMBAAGjgZ8wgZwwEwYJKwYBBAGCNxQCBAYeBABDAEEwCwYDVR0PBAQDAgGGMA8GA1Ud +EwEB/wQFMAMBAf8wHQYDVR0OBBYEFMZPoj0GY4QJnM5i5ASsjVy16bYbMDYGA1UdHwQvMC0wK6Ap +oCeGJWh0dHA6Ly9jcmwueHJhbXBzZWN1cml0eS5jb20vWEdDQS5jcmwwEAYJKwYBBAGCNxUBBAMC +AQEwDQYJKoZIhvcNAQEFBQADggEBAJEVOQMBG2f7Shz5CmBbodpNl2L5JFMn14JkTpAuw0kbK5rc +/Kh4ZzXxHfARvbdI4xD2Dd8/0sm2qlWkSLoC295ZLhVbO50WfUfXN+pfTXYSNrsf16GBBEYgoyxt +qZ4Bfj8pzgCT3/3JknOJiWSe5yvkHJEs0rnOfc5vMZnT5r7SHpDwCRR5XCOrTdLaIR9NmXmd4c8n +nxCbHIgNsIpkQTG4DmyQJKSbXHGPurt+HBvbaoAPIbzp26a3QPSyi6mx5O+aGtA9aZnuqCij4Tyz +8LIRnM98QObd50N9otg6tamN8jSZxNQQ4Qb9CYQQO+7ETPTsJ3xCwnR8gooJybQDJbw= +-----END CERTIFICATE----- + +Go Daddy Class 2 CA +=================== +-----BEGIN CERTIFICATE----- +MIIEADCCAuigAwIBAgIBADANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMY +VGhlIEdvIERhZGR5IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBEYWRkeSBDbGFzcyAyIENlcnRp +ZmljYXRpb24gQXV0aG9yaXR5MB4XDTA0MDYyOTE3MDYyMFoXDTM0MDYyOTE3MDYyMFowYzELMAkG +A1UEBhMCVVMxITAfBgNVBAoTGFRoZSBHbyBEYWRkeSBHcm91cCwgSW5jLjExMC8GA1UECxMoR28g +RGFkZHkgQ2xhc3MgMiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASAwDQYJKoZIhvcNAQEBBQAD +ggENADCCAQgCggEBAN6d1+pXGEmhW+vXX0iG6r7d/+TvZxz0ZWizV3GgXne77ZtJ6XCAPVYYYwhv +2vLM0D9/AlQiVBDYsoHUwHU9S3/Hd8M+eKsaA7Ugay9qK7HFiH7Eux6wwdhFJ2+qN1j3hybX2C32 +qRe3H3I2TqYXP2WYktsqbl2i/ojgC95/5Y0V4evLOtXiEqITLdiOr18SPaAIBQi2XKVlOARFmR6j +YGB0xUGlcmIbYsUfb18aQr4CUWWoriMYavx4A6lNf4DD+qta/KFApMoZFv6yyO9ecw3ud72a9nmY +vLEHZ6IVDd2gWMZEewo+YihfukEHU1jPEX44dMX4/7VpkI+EdOqXG68CAQOjgcAwgb0wHQYDVR0O +BBYEFNLEsNKR1EwRcbNhyz2h/t2oatTjMIGNBgNVHSMEgYUwgYKAFNLEsNKR1EwRcbNhyz2h/t2o +atTjoWekZTBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYVGhlIEdvIERhZGR5IEdyb3VwLCBJbmMu +MTEwLwYDVQQLEyhHbyBEYWRkeSBDbGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggEAMAwG +A1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBADJL87LKPpH8EsahB4yOd6AzBhRckB4Y9wim +PQoZ+YeAEW5p5JYXMP80kWNyOO7MHAGjHZQopDH2esRU1/blMVgDoszOYtuURXO1v0XJJLXVggKt +I3lpjbi2Tc7PTMozI+gciKqdi0FuFskg5YmezTvacPd+mSYgFFQlq25zheabIZ0KbIIOqPjCDPoQ +HmyW74cNxA9hi63ugyuV+I6ShHI56yDqg+2DzZduCLzrTia2cyvk0/ZM/iZx4mERdEr/VxqHD3VI +Ls9RaRegAhJhldXRQLIQTO7ErBBDpqWeCtWVYpoNz4iCxTIM5CufReYNnyicsbkqWletNw+vHX/b +vZ8= +-----END CERTIFICATE----- + +Starfield Class 2 CA +==================== +-----BEGIN CERTIFICATE----- +MIIEDzCCAvegAwIBAgIBADANBgkqhkiG9w0BAQUFADBoMQswCQYDVQQGEwJVUzElMCMGA1UEChMc +U3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMpU3RhcmZpZWxkIENsYXNzIDIg +Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDQwNjI5MTczOTE2WhcNMzQwNjI5MTczOTE2WjBo +MQswCQYDVQQGEwJVUzElMCMGA1UEChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAG +A1UECxMpU3RhcmZpZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggEgMA0GCSqG +SIb3DQEBAQUAA4IBDQAwggEIAoIBAQC3Msj+6XGmBIWtDBFk385N78gDGIc/oav7PKaf8MOh2tTY +bitTkPskpD6E8J7oX+zlJ0T1KKY/e97gKvDIr1MvnsoFAZMej2YcOadN+lq2cwQlZut3f+dZxkqZ +JRRU6ybH838Z1TBwj6+wRir/resp7defqgSHo9T5iaU0X9tDkYI22WY8sbi5gv2cOj4QyDvvBmVm +epsZGD3/cVE8MC5fvj13c7JdBmzDI1aaK4UmkhynArPkPw2vCHmCuDY96pzTNbO8acr1zJ3o/WSN +F4Azbl5KXZnJHoe0nRrA1W4TNSNe35tfPe/W93bC6j67eA0cQmdrBNj41tpvi/JEoAGrAgEDo4HF +MIHCMB0GA1UdDgQWBBS/X7fRzt0fhvRbVazc1xDCDqmI5zCBkgYDVR0jBIGKMIGHgBS/X7fRzt0f +hvRbVazc1xDCDqmI56FspGowaDELMAkGA1UEBhMCVVMxJTAjBgNVBAoTHFN0YXJmaWVsZCBUZWNo +bm9sb2dpZXMsIEluYy4xMjAwBgNVBAsTKVN0YXJmaWVsZCBDbGFzcyAyIENlcnRpZmljYXRpb24g +QXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAAWdP4id0ckaVaGs +afPzWdqbAYcaT1epoXkJKtv3L7IezMdeatiDh6GX70k1PncGQVhiv45YuApnP+yz3SFmH8lU+nLM +PUxA2IGvd56Deruix/U0F47ZEUD0/CwqTRV/p2JdLiXTAAsgGh1o+Re49L2L7ShZ3U0WixeDyLJl +xy16paq8U4Zt3VekyvggQQto8PT7dL5WXXp59fkdheMtlb71cZBDzI0fmgAKhynpVSJYACPq4xJD +KVtHCN2MQWplBqjlIapBtJUhlbl90TSrE9atvNziPTnNvT51cKEYWQPJIrSPnNVeKtelttQKbfi3 +QBFGmh95DmK/D5fs4C8fF5Q= +-----END CERTIFICATE----- + +StartCom Certification Authority +================================ +-----BEGIN CERTIFICATE----- +MIIHyTCCBbGgAwIBAgIBATANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJJTDEWMBQGA1UEChMN +U3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmlu +ZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDYwOTE3MTk0 +NjM2WhcNMzYwOTE3MTk0NjM2WjB9MQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRk +LjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMg +U3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAw +ggIKAoICAQDBiNsJvGxGfHiflXu1M5DycmLWwTYgIiRezul38kMKogZkpMyONvg45iPwbm2xPN1y +o4UcodM9tDMr0y+v/uqwQVlntsQGfQqedIXWeUyAN3rfOQVSWff0G0ZDpNKFhdLDcfN1YjS6LIp/ +Ho/u7TTQEceWzVI9ujPW3U3eCztKS5/CJi/6tRYccjV3yjxd5srhJosaNnZcAdt0FCX+7bWgiA/d +eMotHweXMAEtcnn6RtYTKqi5pquDSR3l8u/d5AGOGAqPY1MWhWKpDhk6zLVmpsJrdAfkK+F2PrRt +2PZE4XNiHzvEvqBTViVsUQn3qqvKv3b9bZvzndu/PWa8DFaqr5hIlTpL36dYUNk4dalb6kMMAv+Z +6+hsTXBbKWWc3apdzK8BMewM69KN6Oqce+Zu9ydmDBpI125C4z/eIT574Q1w+2OqqGwaVLRcJXrJ +osmLFqa7LH4XXgVNWG4SHQHuEhANxjJ/GP/89PrNbpHoNkm+Gkhpi8KWTRoSsmkXwQqQ1vp5Iki/ +untp+HDH+no32NgN0nZPV/+Qt+OR0t3vwmC3Zzrd/qqc8NSLf3Iizsafl7b4r4qgEKjZ+xjGtrVc +UjyJthkqcwEKDwOzEmDyei+B26Nu/yYwl/WL3YlXtq09s68rxbd2AvCl1iuahhQqcvbjM4xdCUsT +37uMdBNSSwIDAQABo4ICUjCCAk4wDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAa4wHQYDVR0OBBYE +FE4L7xqkQFulF2mHMMo0aEPQQa7yMGQGA1UdHwRdMFswLKAqoCiGJmh0dHA6Ly9jZXJ0LnN0YXJ0 +Y29tLm9yZy9zZnNjYS1jcmwuY3JsMCugKaAnhiVodHRwOi8vY3JsLnN0YXJ0Y29tLm9yZy9zZnNj +YS1jcmwuY3JsMIIBXQYDVR0gBIIBVDCCAVAwggFMBgsrBgEEAYG1NwEBATCCATswLwYIKwYBBQUH +AgEWI2h0dHA6Ly9jZXJ0LnN0YXJ0Y29tLm9yZy9wb2xpY3kucGRmMDUGCCsGAQUFBwIBFilodHRw +Oi8vY2VydC5zdGFydGNvbS5vcmcvaW50ZXJtZWRpYXRlLnBkZjCB0AYIKwYBBQUHAgIwgcMwJxYg +U3RhcnQgQ29tbWVyY2lhbCAoU3RhcnRDb20pIEx0ZC4wAwIBARqBl0xpbWl0ZWQgTGlhYmlsaXR5 +LCByZWFkIHRoZSBzZWN0aW9uICpMZWdhbCBMaW1pdGF0aW9ucyogb2YgdGhlIFN0YXJ0Q29tIENl +cnRpZmljYXRpb24gQXV0aG9yaXR5IFBvbGljeSBhdmFpbGFibGUgYXQgaHR0cDovL2NlcnQuc3Rh +cnRjb20ub3JnL3BvbGljeS5wZGYwEQYJYIZIAYb4QgEBBAQDAgAHMDgGCWCGSAGG+EIBDQQrFilT +dGFydENvbSBGcmVlIFNTTCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTANBgkqhkiG9w0BAQUFAAOC +AgEAFmyZ9GYMNPXQhV59CuzaEE44HF7fpiUFS5Eyweg78T3dRAlbB0mKKctmArexmvclmAk8jhvh +3TaHK0u7aNM5Zj2gJsfyOZEdUauCe37Vzlrk4gNXcGmXCPleWKYK34wGmkUWFjgKXlf2Ysd6AgXm +vB618p70qSmD+LIU424oh0TDkBreOKk8rENNZEXO3SipXPJzewT4F+irsfMuXGRuczE6Eri8sxHk +fY+BUZo7jYn0TZNmezwD7dOaHZrzZVD1oNB1ny+v8OqCQ5j4aZyJecRDjkZy42Q2Eq/3JR44iZB3 +fsNrarnDy0RLrHiQi+fHLB5LEUTINFInzQpdn4XBidUaePKVEFMy3YCEZnXZtWgo+2EuvoSoOMCZ +EoalHmdkrQYuL6lwhceWD3yJZfWOQ1QOq92lgDmUYMA0yZZwLKMS9R9Ie70cfmu3nZD0Ijuu+Pwq +yvqCUqDvr0tVk+vBtfAii6w0TiYiBKGHLHVKt+V9E9e4DGTANtLJL4YSjCMJwRuCO3NJo2pXh5Tl +1njFmUNj403gdy3hZZlyaQQaRwnmDwFWJPsfvw55qVguucQJAX6Vum0ABj6y6koQOdjQK/W/7HW/ +lwLFCRsI3FU34oH7N4RDYiDK51ZLZer+bMEkkyShNOsF/5oirpt9P/FlUQqmMGqz9IgcgA38coro +g14= +-----END CERTIFICATE----- + +Taiwan GRCA +=========== +-----BEGIN CERTIFICATE----- +MIIFcjCCA1qgAwIBAgIQH51ZWtcvwgZEpYAIaeNe9jANBgkqhkiG9w0BAQUFADA/MQswCQYDVQQG +EwJUVzEwMC4GA1UECgwnR292ZXJubWVudCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4X +DTAyMTIwNTEzMjMzM1oXDTMyMTIwNTEzMjMzM1owPzELMAkGA1UEBhMCVFcxMDAuBgNVBAoMJ0dv +dmVybm1lbnQgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCAiIwDQYJKoZIhvcNAQEBBQAD +ggIPADCCAgoCggIBAJoluOzMonWoe/fOW1mKydGGEghU7Jzy50b2iPN86aXfTEc2pBsBHH8eV4qN +w8XRIePaJD9IK/ufLqGU5ywck9G/GwGHU5nOp/UKIXZ3/6m3xnOUT0b3EEk3+qhZSV1qgQdW8or5 +BtD3cCJNtLdBuTK4sfCxw5w/cP1T3YGq2GN49thTbqGsaoQkclSGxtKyyhwOeYHWtXBiCAEuTk8O +1RGvqa/lmr/czIdtJuTJV6L7lvnM4T9TjGxMfptTCAtsF/tnyMKtsc2AtJfcdgEWFelq16TheEfO +htX7MfP6Mb40qij7cEwdScevLJ1tZqa2jWR+tSBqnTuBto9AAGdLiYa4zGX+FVPpBMHWXx1E1wov +J5pGfaENda1UhhXcSTvxls4Pm6Dso3pdvtUqdULle96ltqqvKKyskKw4t9VoNSZ63Pc78/1Fm9G7 +Q3hub/FCVGqY8A2tl+lSXunVanLeavcbYBT0peS2cWeqH+riTcFCQP5nRhc4L0c/cZyu5SHKYS1t +B6iEfC3uUSXxY5Ce/eFXiGvviiNtsea9P63RPZYLhY3Naye7twWb7LuRqQoHEgKXTiCQ8P8NHuJB +O9NAOueNXdpm5AKwB1KYXA6OM5zCppX7VRluTI6uSw+9wThNXo+EHWbNxWCWtFJaBYmOlXqYwZE8 +lSOyDvR5tMl8wUohAgMBAAGjajBoMB0GA1UdDgQWBBTMzO/MKWCkO7GStjz6MmKPrCUVOzAMBgNV +HRMEBTADAQH/MDkGBGcqBwAEMTAvMC0CAQAwCQYFKw4DAhoFADAHBgVnKgMAAAQUA5vwIhP/lSg2 +09yewDL7MTqKUWUwDQYJKoZIhvcNAQEFBQADggIBAECASvomyc5eMN1PhnR2WPWus4MzeKR6dBcZ +TulStbngCnRiqmjKeKBMmo4sIy7VahIkv9Ro04rQ2JyftB8M3jh+Vzj8jeJPXgyfqzvS/3WXy6Tj +Zwj/5cAWtUgBfen5Cv8b5Wppv3ghqMKnI6mGq3ZW6A4M9hPdKmaKZEk9GhiHkASfQlK3T8v+R0F2 +Ne//AHY2RTKbxkaFXeIksB7jSJaYV0eUVXoPQbFEJPPB/hprv4j9wabak2BegUqZIJxIZhm1AHlU +D7gsL0u8qV1bYH+Mh6XgUmMqvtg7hUAV/h62ZT/FS9p+tXo1KaMuephgIqP0fSdOLeq0dDzpD6Qz +DxARvBMB1uUO07+1EqLhRSPAzAhuYbeJq4PjJB7mXQfnHyA+z2fI56wwbSdLaG5LKlwCCDTb+Hbk +Z6MmnD+iMsJKxYEYMRBWqoTvLQr/uB930r+lWKBi5NdLkXWNiYCYfm3LU05er/ayl4WXudpVBrkk +7tfGOB5jGxI7leFYrPLfhNVfmS8NVVvmONsuP3LpSIXLuykTjx44VbnzssQwmSNOXfJIoRIM3BKQ +CZBUkQM8R+XVyWXgt0t97EfTsws+rZ7QdAAO671RrcDeLMDDav7v3Aun+kbfYNucpllQdSNpc5Oy ++fwC00fmcc4QAu4njIT/rEUNE1yDMuAlpYYsfPQS +-----END CERTIFICATE----- + +Swisscom Root CA 1 +================== +-----BEGIN CERTIFICATE----- +MIIF2TCCA8GgAwIBAgIQXAuFXAvnWUHfV8w/f52oNjANBgkqhkiG9w0BAQUFADBkMQswCQYDVQQG +EwJjaDERMA8GA1UEChMIU3dpc3Njb20xJTAjBgNVBAsTHERpZ2l0YWwgQ2VydGlmaWNhdGUgU2Vy +dmljZXMxGzAZBgNVBAMTElN3aXNzY29tIFJvb3QgQ0EgMTAeFw0wNTA4MTgxMjA2MjBaFw0yNTA4 +MTgyMjA2MjBaMGQxCzAJBgNVBAYTAmNoMREwDwYDVQQKEwhTd2lzc2NvbTElMCMGA1UECxMcRGln +aXRhbCBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczEbMBkGA1UEAxMSU3dpc3Njb20gUm9vdCBDQSAxMIIC +IjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA0LmwqAzZuz8h+BvVM5OAFmUgdbI9m2BtRsiM +MW8Xw/qabFbtPMWRV8PNq5ZJkCoZSx6jbVfd8StiKHVFXqrWW/oLJdihFvkcxC7mlSpnzNApbjyF +NDhhSbEAn9Y6cV9Nbc5fuankiX9qUvrKm/LcqfmdmUc/TilftKaNXXsLmREDA/7n29uj/x2lzZAe +AR81sH8A25Bvxn570e56eqeqDFdvpG3FEzuwpdntMhy0XmeLVNxzh+XTF3xmUHJd1BpYwdnP2IkC +b6dJtDZd0KTeByy2dbcokdaXvij1mB7qWybJvbCXc9qukSbraMH5ORXWZ0sKbU/Lz7DkQnGMU3nn +7uHbHaBuHYwadzVcFh4rUx80i9Fs/PJnB3r1re3WmquhsUvhzDdf/X/NTa64H5xD+SpYVUNFvJbN +cA78yeNmuk6NO4HLFWR7uZToXTNShXEuT46iBhFRyePLoW4xCGQMwtI89Tbo19AOeCMgkckkKmUp +WyL3Ic6DXqTz3kvTaI9GdVyDCW4pa8RwjPWd1yAv/0bSKzjCL3UcPX7ape8eYIVpQtPM+GP+HkM5 +haa2Y0EQs3MevNP6yn0WR+Kn1dCjigoIlmJWbjTb2QK5MHXjBNLnj8KwEUAKrNVxAmKLMb7dxiNY +MUJDLXT5xp6mig/p/r+D5kNXJLrvRjSq1xIBOO0CAwEAAaOBhjCBgzAOBgNVHQ8BAf8EBAMCAYYw +HQYDVR0hBBYwFDASBgdghXQBUwABBgdghXQBUwABMBIGA1UdEwEB/wQIMAYBAf8CAQcwHwYDVR0j +BBgwFoAUAyUv3m+CATpcLNwroWm1Z9SM0/0wHQYDVR0OBBYEFAMlL95vggE6XCzcK6FptWfUjNP9 +MA0GCSqGSIb3DQEBBQUAA4ICAQA1EMvspgQNDQ/NwNurqPKIlwzfky9NfEBWMXrrpA9gzXrzvsMn +jgM+pN0S734edAY8PzHyHHuRMSG08NBsl9Tpl7IkVh5WwzW9iAUPWxAaZOHHgjD5Mq2eUCzneAXQ +MbFamIp1TpBcahQq4FJHgmDmHtqBsfsUC1rxn9KVuj7QG9YVHaO+htXbD8BJZLsuUBlL0iT43R4H +VtA4oJVwIHaM190e3p9xxCPvgxNcoyQVTSlAPGrEqdi3pkSlDfTgnXceQHAm/NrZNuR55LU/vJtl +vrsRls/bxig5OgjOR1tTWsWZ/l2p3e9M1MalrQLmjAcSHm8D0W+go/MpvRLHUKKwf4ipmXeascCl +OS5cfGniLLDqN2qk4Vrh9VDlg++luyqI54zb/W1elxmofmZ1a3Hqv7HHb6D0jqTsNFFbjCYDcKF3 +1QESVwA12yPeDooomf2xEG9L/zgtYE4snOtnta1J7ksfrK/7DZBaZmBwXarNeNQk7shBoJMBkpxq +nvy5JMWzFYJ+vq6VK+uxwNrjAWALXmmshFZhvnEX/h0TD/7Gh0Xp/jKgGg0TpJRVcaUWi7rKibCy +x/yP2FS1k2Kdzs9Z+z0YzirLNRWCXf9UIltxUvu3yf5gmwBBZPCqKuy2QkPOiWaByIufOVQDJdMW +NY6E0F/6MBr1mmz0DlP5OlvRHA== +-----END CERTIFICATE----- + +DigiCert Assured ID Root CA +=========================== +-----BEGIN CERTIFICATE----- +MIIDtzCCAp+gAwIBAgIQDOfg5RfYRv6P5WD8G/AwOTANBgkqhkiG9w0BAQUFADBlMQswCQYDVQQG +EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSQw +IgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwHhcNMDYxMTEwMDAwMDAwWhcNMzEx +MTEwMDAwMDAwWjBlMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQL +ExB3d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0Ew +ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtDhXO5EOAXLGH87dg+XESpa7cJpSIqvTO +9SA5KFhgDPiA2qkVlTJhPLWxKISKityfCgyDF3qPkKyK53lTXDGEKvYPmDI2dsze3Tyoou9q+yHy +UmHfnyDXH+Kx2f4YZNISW1/5WBg1vEfNoTb5a3/UsDg+wRvDjDPZ2C8Y/igPs6eD1sNuRMBhNZYW +/lmci3Zt1/GiSw0r/wty2p5g0I6QNcZ4VYcgoc/lbQrISXwxmDNsIumH0DJaoroTghHtORedmTpy +oeb6pNnVFzF1roV9Iq4/AUaG9ih5yLHa5FcXxH4cDrC0kqZWs72yl+2qp/C3xag/lRbQ/6GW6whf +GHdPAgMBAAGjYzBhMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRF +66Kv9JLLgjEtUYunpyGd823IDzAfBgNVHSMEGDAWgBRF66Kv9JLLgjEtUYunpyGd823IDzANBgkq +hkiG9w0BAQUFAAOCAQEAog683+Lt8ONyc3pklL/3cmbYMuRCdWKuh+vy1dneVrOfzM4UKLkNl2Bc +EkxY5NM9g0lFWJc1aRqoR+pWxnmrEthngYTffwk8lOa4JiwgvT2zKIn3X/8i4peEH+ll74fg38Fn +SbNd67IJKusm7Xi+fT8r87cmNW1fiQG2SVufAQWbqz0lwcy2f8Lxb4bG+mRo64EtlOtCt/qMHt1i +8b5QZ7dsvfPxH2sMNgcWfzd8qVttevESRmCD1ycEvkvOl77DZypoEd+A5wwzZr8TDRRu838fYxAe ++o0bJW1sj6W3YQGx0qMmoRBxna3iw/nDmVG3KwcIzi7mULKn+gpFL6Lw8g== +-----END CERTIFICATE----- + +DigiCert Global Root CA +======================= +-----BEGIN CERTIFICATE----- +MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBhMQswCQYDVQQG +EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSAw +HgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBDQTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAw +MDAwMDBaMGExCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3 +dy5kaWdpY2VydC5jb20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkq +hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsBCSDMAZOn +TjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97nh6Vfe63SKMI2tavegw5 +BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt43C/dxC//AH2hdmoRBBYMql1GNXRor5H +4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7PT19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y +7vrTC0LUq7dBMtoM1O/4gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQAB +o2MwYTAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbRTLtm +8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUwDQYJKoZIhvcNAQEF +BQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/EsrhMAtudXH/vTBH1jLuG2cenTnmCmr +EbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIt +tep3Sp+dWOIrWcBAI+0tKIJFPnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886 +UAb3LujEV0lsYSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk +CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4= +-----END CERTIFICATE----- + +DigiCert High Assurance EV Root CA +================================== +-----BEGIN CERTIFICATE----- +MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBsMQswCQYDVQQG +EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSsw +KQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5jZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAw +MFoXDTMxMTExMDAwMDAwMFowbDELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZ +MBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFu +Y2UgRVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm+9S75S0t +Mqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTWPNt0OKRKzE0lgvdKpVMS +OO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEMxChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3 +MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFBIk5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQ +NAQTXKFx01p8VdteZOE3hzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUe +h10aUAsgEsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQFMAMB +Af8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaAFLE+w2kD+L9HAdSY +JhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3NecnzyIZgYIVyHbIUf4KmeqvxgydkAQ +V8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6zeM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFp +myPInngiK3BD41VHMWEZ71jFhS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkK +mNEVX58Svnw2Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe +vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep+OkuE6N36B9K +-----END CERTIFICATE----- + +Certplus Class 2 Primary CA +=========================== +-----BEGIN CERTIFICATE----- +MIIDkjCCAnqgAwIBAgIRAIW9S/PY2uNp9pTXX8OlRCMwDQYJKoZIhvcNAQEFBQAwPTELMAkGA1UE +BhMCRlIxETAPBgNVBAoTCENlcnRwbHVzMRswGQYDVQQDExJDbGFzcyAyIFByaW1hcnkgQ0EwHhcN +OTkwNzA3MTcwNTAwWhcNMTkwNzA2MjM1OTU5WjA9MQswCQYDVQQGEwJGUjERMA8GA1UEChMIQ2Vy +dHBsdXMxGzAZBgNVBAMTEkNsYXNzIDIgUHJpbWFyeSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEP +ADCCAQoCggEBANxQltAS+DXSCHh6tlJw/W/uz7kRy1134ezpfgSN1sxvc0NXYKwzCkTsA18cgCSR +5aiRVhKC9+Ar9NuuYS6JEI1rbLqzAr3VNsVINyPi8Fo3UjMXEuLRYE2+L0ER4/YXJQyLkcAbmXuZ +Vg2v7tK8R1fjeUl7NIknJITesezpWE7+Tt9avkGtrAjFGA7v0lPubNCdEgETjdyAYveVqUSISnFO +YFWe2yMZeVYHDD9jC1yw4r5+FfyUM1hBOHTE4Y+L3yasH7WLO7dDWWuwJKZtkIvEcupdM5i3y95e +e++U8Rs+yskhwcWYAqqi9lt3m/V+llU0HGdpwPFC40es/CgcZlUCAwEAAaOBjDCBiTAPBgNVHRME +CDAGAQH/AgEKMAsGA1UdDwQEAwIBBjAdBgNVHQ4EFgQU43Mt38sOKAze3bOkynm4jrvoMIkwEQYJ +YIZIAYb4QgEBBAQDAgEGMDcGA1UdHwQwMC4wLKAqoCiGJmh0dHA6Ly93d3cuY2VydHBsdXMuY29t +L0NSTC9jbGFzczIuY3JsMA0GCSqGSIb3DQEBBQUAA4IBAQCnVM+IRBnL39R/AN9WM2K191EBkOvD +P9GIROkkXe/nFL0gt5o8AP5tn9uQ3Nf0YtaLcF3n5QRIqWh8yfFC82x/xXp8HVGIutIKPidd3i1R +TtMTZGnkLuPT55sJmabglZvOGtd/vjzOUrMRFcEPF80Du5wlFbqidon8BvEY0JNLDnyCt6X09l/+ +7UCmnYR0ObncHoUW2ikbhiMAybuJfm6AiB4vFLQDJKgybwOaRywwvlbGp0ICcBvqQNi6BQNwB6SW +//1IMwrh3KWBkJtN3X3n57LNXMhqlfil9o3EXXgIvnsG1knPGTZQIy4I5p4FTUcY1Rbpsda2ENW7 +l7+ijrRU +-----END CERTIFICATE----- + +DST Root CA X3 +============== +-----BEGIN CERTIFICATE----- +MIIDSjCCAjKgAwIBAgIQRK+wgNajJ7qJMDmGLvhAazANBgkqhkiG9w0BAQUFADA/MSQwIgYDVQQK +ExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMTDkRTVCBSb290IENBIFgzMB4X +DTAwMDkzMDIxMTIxOVoXDTIxMDkzMDE0MDExNVowPzEkMCIGA1UEChMbRGlnaXRhbCBTaWduYXR1 +cmUgVHJ1c3QgQ28uMRcwFQYDVQQDEw5EU1QgUm9vdCBDQSBYMzCCASIwDQYJKoZIhvcNAQEBBQAD +ggEPADCCAQoCggEBAN+v6ZdQCINXtMxiZfaQguzH0yxrMMpb7NnDfcdAwRgUi+DoM3ZJKuM/IUmT +rE4Orz5Iy2Xu/NMhD2XSKtkyj4zl93ewEnu1lcCJo6m67XMuegwGMoOifooUMM0RoOEqOLl5CjH9 +UL2AZd+3UWODyOKIYepLYYHsUmu5ouJLGiifSKOeDNoJjj4XLh7dIN9bxiqKqy69cK3FCxolkHRy +xXtqqzTWMIn/5WgTe1QLyNau7Fqckh49ZLOMxt+/yUFw7BZy1SbsOFU5Q9D8/RhcQPGX69Wam40d +utolucbY38EVAjqr2m7xPi71XAicPNaDaeQQmxkqtilX4+U9m5/wAl0CAwEAAaNCMEAwDwYDVR0T +AQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFMSnsaR7LHH62+FLkHX/xBVghYkQ +MA0GCSqGSIb3DQEBBQUAA4IBAQCjGiybFwBcqR7uKGY3Or+Dxz9LwwmglSBd49lZRNI+DT69ikug +dB/OEIKcdBodfpga3csTS7MgROSR6cz8faXbauX+5v3gTt23ADq1cEmv8uXrAvHRAosZy5Q6XkjE +GB5YGV8eAlrwDPGxrancWYaLbumR9YbK+rlmM6pZW87ipxZzR8srzJmwN0jP41ZL9c8PDHIyh8bw +RLtTcm1D9SZImlJnt1ir/md2cXjbDaJWFBM5JDGFoqgCWjBH4d1QB7wCCZAA62RjYJsWvIjJEubS +fZGL+T0yjWW06XyxV3bqxbYoOb8VZRzI9neWagqNdwvYkQsEjgfbKbYK7p2CNTUQ +-----END CERTIFICATE----- + +DST ACES CA X6 +============== +-----BEGIN CERTIFICATE----- +MIIECTCCAvGgAwIBAgIQDV6ZCtadt3js2AdWO4YV2TANBgkqhkiG9w0BAQUFADBbMQswCQYDVQQG +EwJVUzEgMB4GA1UEChMXRGlnaXRhbCBTaWduYXR1cmUgVHJ1c3QxETAPBgNVBAsTCERTVCBBQ0VT +MRcwFQYDVQQDEw5EU1QgQUNFUyBDQSBYNjAeFw0wMzExMjAyMTE5NThaFw0xNzExMjAyMTE5NTha +MFsxCzAJBgNVBAYTAlVTMSAwHgYDVQQKExdEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdDERMA8GA1UE +CxMIRFNUIEFDRVMxFzAVBgNVBAMTDkRTVCBBQ0VTIENBIFg2MIIBIjANBgkqhkiG9w0BAQEFAAOC +AQ8AMIIBCgKCAQEAuT31LMmU3HWKlV1j6IR3dma5WZFcRt2SPp/5DgO0PWGSvSMmtWPuktKe1jzI +DZBfZIGxqAgNTNj50wUoUrQBJcWVHAx+PhCEdc/BGZFjz+iokYi5Q1K7gLFViYsx+tC3dr5BPTCa +pCIlF3PoHuLTrCq9Wzgh1SpL11V94zpVvddtawJXa+ZHfAjIgrrep4c9oW24MFbCswKBXy314pow +GCi4ZtPLAZZv6opFVdbgnf9nKxcCpk4aahELfrd755jWjHZvwTvbUJN+5dCOHze4vbrGn2zpfDPy +MjwmR/onJALJfh1biEITajV8fTXpLmaRcpPVMibEdPVTo7NdmvYJywIDAQABo4HIMIHFMA8GA1Ud +EwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgHGMB8GA1UdEQQYMBaBFHBraS1vcHNAdHJ1c3Rkc3Qu +Y29tMGIGA1UdIARbMFkwVwYKYIZIAWUDAgEBATBJMEcGCCsGAQUFBwIBFjtodHRwOi8vd3d3LnRy +dXN0ZHN0LmNvbS9jZXJ0aWZpY2F0ZXMvcG9saWN5L0FDRVMtaW5kZXguaHRtbDAdBgNVHQ4EFgQU +CXIGThhDD+XWzMNqizF7eI+og7gwDQYJKoZIhvcNAQEFBQADggEBAKPYjtay284F5zLNAdMEA+V2 +5FYrnJmQ6AgwbN99Pe7lv7UkQIRJ4dEorsTCOlMwiPH1d25Ryvr/ma8kXxug/fKshMrfqfBfBC6t +Fr8hlxCBPeP/h40y3JTlR4peahPJlJU90u7INJXQgNStMgiAVDzgvVJT11J8smk/f3rPanTK+gQq +nExaBqXpIK1FZg9p8d2/6eMyi/rgwYZNcjwu2JN4Cir42NInPRmJX1p7ijvMDNpRrscL9yuwNwXs +vFcj4jjSm2jzVhKIT0J8uDHEtdvkyCE06UgRNe76x5JXxZ805Mf29w4LTJxoeHtxMcfrHuBnQfO3 +oKfN5XozNmr6mis= +-----END CERTIFICATE----- + +TURKTRUST Certificate Services Provider Root 1 +============================================== +-----BEGIN CERTIFICATE----- +MIID+zCCAuOgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBtzE/MD0GA1UEAww2VMOcUktUUlVTVCBF +bGVrdHJvbmlrIFNlcnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxMQswCQYDVQQGDAJUUjEP +MA0GA1UEBwwGQU5LQVJBMVYwVAYDVQQKDE0oYykgMjAwNSBUw5xSS1RSVVNUIEJpbGdpIMSwbGV0 +acWfaW0gdmUgQmlsacWfaW0gR8O8dmVubGnEn2kgSGl6bWV0bGVyaSBBLsWeLjAeFw0wNTA1MTMx +MDI3MTdaFw0xNTAzMjIxMDI3MTdaMIG3MT8wPQYDVQQDDDZUw5xSS1RSVVNUIEVsZWt0cm9uaWsg +U2VydGlmaWthIEhpem1ldCBTYcSfbGF5xLFjxLFzxLExCzAJBgNVBAYMAlRSMQ8wDQYDVQQHDAZB +TktBUkExVjBUBgNVBAoMTShjKSAyMDA1IFTDnFJLVFJVU1QgQmlsZ2kgxLBsZXRpxZ9pbSB2ZSBC +aWxpxZ9pbSBHw7x2ZW5sacSfaSBIaXptZXRsZXJpIEEuxZ4uMIIBIjANBgkqhkiG9w0BAQEFAAOC +AQ8AMIIBCgKCAQEAylIF1mMD2Bxf3dJ7XfIMYGFbazt0K3gNfUW9InTojAPBxhEqPZW8qZSwu5GX +yGl8hMW0kWxsE2qkVa2kheiVfrMArwDCBRj1cJ02i67L5BuBf5OI+2pVu32Fks66WJ/bMsW9Xe8i +Si9BB35JYbOG7E6mQW6EvAPs9TscyB/C7qju6hJKjRTP8wrgUDn5CDX4EVmt5yLqS8oUBt5CurKZ +8y1UiBAG6uEaPj1nH/vO+3yC6BFdSsG5FOpU2WabfIl9BJpiyelSPJ6c79L1JuTm5Rh8i27fbMx4 +W09ysstcP4wFjdFMjK2Sx+F4f2VsSQZQLJ4ywtdKxnWKWU51b0dewQIDAQABoxAwDjAMBgNVHRME +BTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQAV9VX/N5aAWSGk/KEVTCD21F/aAyT8z5Aa9CEKmu46 +sWrv7/hg0Uw2ZkUd82YCdAR7kjCo3gp2D++Vbr3JN+YaDayJSFvMgzbC9UZcWYJWtNX+I7TYVBxE +q8Sn5RTOPEFhfEPmzcSBCYsk+1Ql1haolgxnB2+zUEfjHCQo3SqYpGH+2+oSN7wBGjSFvW5P55Fy +B0SFHljKVETd96y5y4khctuPwGkplyqjrhgjlxxBKot8KsF8kOipKMDTkcatKIdAaLX/7KfS0zgY +nNN9aV3wxqUeJBujR/xpB2jn5Jq07Q+hh4cCzofSSE7hvP/L8XKSRGQDJereW26fyfJOrN3H +-----END CERTIFICATE----- + +TURKTRUST Certificate Services Provider Root 2 +============================================== +-----BEGIN CERTIFICATE----- +MIIEPDCCAySgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBvjE/MD0GA1UEAww2VMOcUktUUlVTVCBF +bGVrdHJvbmlrIFNlcnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxMQswCQYDVQQGEwJUUjEP +MA0GA1UEBwwGQW5rYXJhMV0wWwYDVQQKDFRUw5xSS1RSVVNUIEJpbGdpIMSwbGV0acWfaW0gdmUg +QmlsacWfaW0gR8O8dmVubGnEn2kgSGl6bWV0bGVyaSBBLsWeLiAoYykgS2FzxLFtIDIwMDUwHhcN +MDUxMTA3MTAwNzU3WhcNMTUwOTE2MTAwNzU3WjCBvjE/MD0GA1UEAww2VMOcUktUUlVTVCBFbGVr +dHJvbmlrIFNlcnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxMQswCQYDVQQGEwJUUjEPMA0G +A1UEBwwGQW5rYXJhMV0wWwYDVQQKDFRUw5xSS1RSVVNUIEJpbGdpIMSwbGV0acWfaW0gdmUgQmls +acWfaW0gR8O8dmVubGnEn2kgSGl6bWV0bGVyaSBBLsWeLiAoYykgS2FzxLFtIDIwMDUwggEiMA0G +CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCpNn7DkUNMwxmYCMjHWHtPFoylzkkBH3MOrHUTpvqe +LCDe2JAOCtFp0if7qnefJ1Il4std2NiDUBd9irWCPwSOtNXwSadktx4uXyCcUHVPr+G1QRT0mJKI +x+XlZEdhR3n9wFHxwZnn3M5q+6+1ATDcRhzviuyV79z/rxAc653YsKpqhRgNF8k+v/Gb0AmJQv2g +QrSdiVFVKc8bcLyEVK3BEx+Y9C52YItdP5qtygy/p1Zbj3e41Z55SZI/4PGXJHpsmxcPbe9TmJEr +5A++WXkHeLuXlfSfadRYhwqp48y2WBmfJiGxxFmNskF1wK1pzpwACPI2/z7woQ8arBT9pmAPAgMB +AAGjQzBBMB0GA1UdDgQWBBTZN7NOBf3Zz58SFq62iS/rJTqIHDAPBgNVHQ8BAf8EBQMDBwYAMA8G +A1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAHJglrfJ3NgpXiOFX7KzLXb7iNcX/ntt +Rbj2hWyfIvwqECLsqrkw9qtY1jkQMZkpAL2JZkH7dN6RwRgLn7Vhy506vvWolKMiVW4XSf/SKfE4 +Jl3vpao6+XF75tpYHdN0wgH6PmlYX63LaL4ULptswLbcoCb6dxriJNoaN+BnrdFzgw2lGh1uEpJ+ +hGIAF728JRhX8tepb1mIvDS3LoV4nZbcFMMsilKbloxSZj2GFotHuFEJjOp9zYhys2AzsfAKRO8P +9Qk3iCQOLGsgOqL6EfJANZxEaGM7rDNvY7wsu/LSy3Z9fYjYHcgFHW68lKlmjHdxx/qR+i9Rnuk5 +UrbnBEI= +-----END CERTIFICATE----- + +SwissSign Gold CA - G2 +====================== +-----BEGIN CERTIFICATE----- +MIIFujCCA6KgAwIBAgIJALtAHEP1Xk+wMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNVBAYTAkNIMRUw +EwYDVQQKEwxTd2lzc1NpZ24gQUcxHzAdBgNVBAMTFlN3aXNzU2lnbiBHb2xkIENBIC0gRzIwHhcN +MDYxMDI1MDgzMDM1WhcNMzYxMDI1MDgzMDM1WjBFMQswCQYDVQQGEwJDSDEVMBMGA1UEChMMU3dp +c3NTaWduIEFHMR8wHQYDVQQDExZTd2lzc1NpZ24gR29sZCBDQSAtIEcyMIICIjANBgkqhkiG9w0B +AQEFAAOCAg8AMIICCgKCAgEAr+TufoskDhJuqVAtFkQ7kpJcyrhdhJJCEyq8ZVeCQD5XJM1QiyUq +t2/876LQwB8CJEoTlo8jE+YoWACjR8cGp4QjK7u9lit/VcyLwVcfDmJlD909Vopz2q5+bbqBHH5C +jCA12UNNhPqE21Is8w4ndwtrvxEvcnifLtg+5hg3Wipy+dpikJKVyh+c6bM8K8vzARO/Ws/BtQpg +vd21mWRTuKCWs2/iJneRjOBiEAKfNA+k1ZIzUd6+jbqEemA8atufK+ze3gE/bk3lUIbLtK/tREDF +ylqM2tIrfKjuvqblCqoOpd8FUrdVxyJdMmqXl2MT28nbeTZ7hTpKxVKJ+STnnXepgv9VHKVxaSvR +AiTysybUa9oEVeXBCsdtMDeQKuSeFDNeFhdVxVu1yzSJkvGdJo+hB9TGsnhQ2wwMC3wLjEHXuend +jIj3o02yMszYF9rNt85mndT9Xv+9lz4pded+p2JYryU0pUHHPbwNUMoDAw8IWh+Vc3hiv69yFGkO +peUDDniOJihC8AcLYiAQZzlG+qkDzAQ4embvIIO1jEpWjpEA/I5cgt6IoMPiaG59je883WX0XaxR +7ySArqpWl2/5rX3aYT+YdzylkbYcjCbaZaIJbcHiVOO5ykxMgI93e2CaHt+28kgeDrpOVG2Y4OGi +GqJ3UM/EY5LsRxmd6+ZrzsECAwEAAaOBrDCBqTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUw +AwEB/zAdBgNVHQ4EFgQUWyV7lqRlUX64OfPAeGZe6Drn8O4wHwYDVR0jBBgwFoAUWyV7lqRlUX64 +OfPAeGZe6Drn8O4wRgYDVR0gBD8wPTA7BglghXQBWQECAQEwLjAsBggrBgEFBQcCARYgaHR0cDov +L3JlcG9zaXRvcnkuc3dpc3NzaWduLmNvbS8wDQYJKoZIhvcNAQEFBQADggIBACe645R88a7A3hfm +5djV9VSwg/S7zV4Fe0+fdWavPOhWfvxyeDgD2StiGwC5+OlgzczOUYrHUDFu4Up+GC9pWbY9ZIEr +44OE5iKHjn3g7gKZYbge9LgriBIWhMIxkziWMaa5O1M/wySTVltpkuzFwbs4AOPsF6m43Md8AYOf +Mke6UiI0HTJ6CVanfCU2qT1L2sCCbwq7EsiHSycR+R4tx5M/nttfJmtS2S6K8RTGRI0Vqbe/vd6m +Gu6uLftIdxf+u+yvGPUqUfA5hJeVbG4bwyvEdGB5JbAKJ9/fXtI5z0V9QkvfsywexcZdylU6oJxp +mo/a77KwPJ+HbBIrZXAVUjEaJM9vMSNQH4xPjyPDdEFjHFWoFN0+4FFQz/EbMFYOkrCChdiDyyJk +vC24JdVUorgG6q2SpCSgwYa1ShNqR88uC1aVVMvOmttqtKay20EIhid392qgQmwLOM7XdVAyksLf +KzAiSNDVQTglXaTpXZ/GlHXQRf0wl0OPkKsKx4ZzYEppLd6leNcG2mqeSz53OiATIgHQv2ieY2Br +NU0LbbqhPcCT4H8js1WtciVORvnSFu+wZMEBnunKoGqYDs/YYPIvSbjkQuE4NRb0yG5P94FW6Lqj +viOvrv1vA+ACOzB2+httQc8Bsem4yWb02ybzOqR08kkkW8mw0FfB+j564ZfJ +-----END CERTIFICATE----- + +SwissSign Silver CA - G2 +======================== +-----BEGIN CERTIFICATE----- +MIIFvTCCA6WgAwIBAgIITxvUL1S7L0swDQYJKoZIhvcNAQEFBQAwRzELMAkGA1UEBhMCQ0gxFTAT +BgNVBAoTDFN3aXNzU2lnbiBBRzEhMB8GA1UEAxMYU3dpc3NTaWduIFNpbHZlciBDQSAtIEcyMB4X +DTA2MTAyNTA4MzI0NloXDTM2MTAyNTA4MzI0NlowRzELMAkGA1UEBhMCQ0gxFTATBgNVBAoTDFN3 +aXNzU2lnbiBBRzEhMB8GA1UEAxMYU3dpc3NTaWduIFNpbHZlciBDQSAtIEcyMIICIjANBgkqhkiG +9w0BAQEFAAOCAg8AMIICCgKCAgEAxPGHf9N4Mfc4yfjDmUO8x/e8N+dOcbpLj6VzHVxumK4DV644 +N0MvFz0fyM5oEMF4rhkDKxD6LHmD9ui5aLlV8gREpzn5/ASLHvGiTSf5YXu6t+WiE7brYT7QbNHm ++/pe7R20nqA1W6GSy/BJkv6FCgU+5tkL4k+73JU3/JHpMjUi0R86TieFnbAVlDLaYQ1HTWBCrpJH +6INaUFjpiou5XaHc3ZlKHzZnu0jkg7Y360g6rw9njxcH6ATK72oxh9TAtvmUcXtnZLi2kUpCe2Uu +MGoM9ZDulebyzYLs2aFK7PayS+VFheZteJMELpyCbTapxDFkH4aDCyr0NQp4yVXPQbBH6TCfmb5h +qAaEuSh6XzjZG6k4sIN/c8HDO0gqgg8hm7jMqDXDhBuDsz6+pJVpATqJAHgE2cn0mRmrVn5bi4Y5 +FZGkECwJMoBgs5PAKrYYC51+jUnyEEp/+dVGLxmSo5mnJqy7jDzmDrxHB9xzUfFwZC8I+bRHHTBs +ROopN4WSaGa8gzj+ezku01DwH/teYLappvonQfGbGHLy9YR0SslnxFSuSGTfjNFusB3hB48IHpmc +celM2KX3RxIfdNFRnobzwqIjQAtz20um53MGjMGg6cFZrEb65i/4z3GcRm25xBWNOHkDRUjvxF3X +CO6HOSKGsg0PWEP3calILv3q1h8CAwEAAaOBrDCBqTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/ +BAUwAwEB/zAdBgNVHQ4EFgQUF6DNweRBtjpbO8tFnb0cwpj6hlgwHwYDVR0jBBgwFoAUF6DNweRB +tjpbO8tFnb0cwpj6hlgwRgYDVR0gBD8wPTA7BglghXQBWQEDAQEwLjAsBggrBgEFBQcCARYgaHR0 +cDovL3JlcG9zaXRvcnkuc3dpc3NzaWduLmNvbS8wDQYJKoZIhvcNAQEFBQADggIBAHPGgeAn0i0P +4JUw4ppBf1AsX19iYamGamkYDHRJ1l2E6kFSGG9YrVBWIGrGvShpWJHckRE1qTodvBqlYJ7YH39F +kWnZfrt4csEGDyrOj4VwYaygzQu4OSlWhDJOhrs9xCrZ1x9y7v5RoSJBsXECYxqCsGKrXlcSH9/L +3XWgwF15kIwb4FDm3jH+mHtwX6WQ2K34ArZv02DdQEsixT2tOnqfGhpHkXkzuoLcMmkDlm4fS/Bx +/uNncqCxv1yL5PqZIseEuRuNI5c/7SXgz2W79WEE790eslpBIlqhn10s6FvJbakMDHiqYMZWjwFa +DGi8aRl5xB9+lwW/xekkUV7U1UtT7dkjWjYDZaPBA61BMPNGG4WQr2W11bHkFlt4dR2Xem1ZqSqP +e97Dh4kQmUlzeMg9vVE1dCrV8X5pGyq7O70luJpaPXJhkGaH7gzWTdQRdAtq/gsD/KNVV4n+Ssuu +WxcFyPKNIzFTONItaj+CuY0IavdeQXRuwxF+B6wpYJE/OMpXEA29MC/HpeZBoNquBYeaoKRlbEwJ +DIm6uNO5wJOKMPqN5ZprFQFOZ6raYlY+hAhm0sQ2fac+EPyI4NSA5QC9qvNOBqN6avlicuMJT+ub +DgEj8Z+7fNzcbBGXJbLytGMU0gYqZ4yD9c7qB9iaah7s5Aq7KkzrCWA5zspi2C5u +-----END CERTIFICATE----- + +GeoTrust Primary Certification Authority +======================================== +-----BEGIN CERTIFICATE----- +MIIDfDCCAmSgAwIBAgIQGKy1av1pthU6Y2yv2vrEoTANBgkqhkiG9w0BAQUFADBYMQswCQYDVQQG +EwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjExMC8GA1UEAxMoR2VvVHJ1c3QgUHJpbWFyeSBD +ZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNjExMjcwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMFgx +CzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTEwLwYDVQQDEyhHZW9UcnVzdCBQ +cmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB +CgKCAQEAvrgVe//UfH1nrYNke8hCUy3f9oQIIGHWAVlqnEQRr+92/ZV+zmEwu3qDXwK9AWbK7hWN +b6EwnL2hhZ6UOvNWiAAxz9juapYC2e0DjPt1befquFUWBRaa9OBesYjAZIVcFU2Ix7e64HXprQU9 +nceJSOC7KMgD4TCTZF5SwFlwIjVXiIrxlQqD17wxcwE07e9GceBrAqg1cmuXm2bgyxx5X9gaBGge +RwLmnWDiNpcB3841kt++Z8dtd1k7j53WkBWUvEI0EME5+bEnPn7WinXFsq+W06Lem+SYvn3h6YGt +tm/81w7a4DSwDRp35+MImO9Y+pyEtzavwt+s0vQQBnBxNQIDAQABo0IwQDAPBgNVHRMBAf8EBTAD +AQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQULNVQQZcVi/CPNmFbSvtr2ZnJM5IwDQYJKoZI +hvcNAQEFBQADggEBAFpwfyzdtzRP9YZRqSa+S7iq8XEN3GHHoOo0Hnp3DwQ16CePbJC/kRYkRj5K +Ts4rFtULUh38H2eiAkUxT87z+gOneZ1TatnaYzr4gNfTmeGl4b7UVXGYNTq+k+qurUKykG/g/CFN +NWMziUnWm07Kx+dOCQD32sfvmWKZd7aVIl6KoKv0uHiYyjgZmclynnjNS6yvGaBzEi38wkG6gZHa +Floxt/m0cYASSJlyc1pZU8FjUjPtp8nSOQJw+uCxQmYpqptR7TBUIhRf2asdweSU8Pj1K/fqynhG +1riR/aYNKxoUAT6A8EKglQdebc3MS6RFjasS6LPeWuWgfOgPIh1a6Vk= +-----END CERTIFICATE----- + +thawte Primary Root CA +====================== +-----BEGIN CERTIFICATE----- +MIIEIDCCAwigAwIBAgIQNE7VVyDV7exJ9C/ON9srbTANBgkqhkiG9w0BAQUFADCBqTELMAkGA1UE +BhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2 +aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMvKGMpIDIwMDYgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhv +cml6ZWQgdXNlIG9ubHkxHzAdBgNVBAMTFnRoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EwHhcNMDYxMTE3 +MDAwMDAwWhcNMzYwNzE2MjM1OTU5WjCBqTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwg +SW5jLjEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMv +KGMpIDIwMDYgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxHzAdBgNVBAMT +FnRoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCs +oPD7gFnUnMekz52hWXMJEEUMDSxuaPFsW0hoSVk3/AszGcJ3f8wQLZU0HObrTQmnHNK4yZc2AreJ +1CRfBsDMRJSUjQJib+ta3RGNKJpchJAQeg29dGYvajig4tVUROsdB58Hum/u6f1OCyn1PoSgAfGc +q/gcfomk6KHYcWUNo1F77rzSImANuVud37r8UVsLr5iy6S7pBOhih94ryNdOwUxkHt3Ph1i6Sk/K +aAcdHJ1KxtUvkcx8cXIcxcBn6zL9yZJclNqFwJu/U30rCfSMnZEfl2pSy94JNqR32HuHUETVPm4p +afs5SSYeCaWAe0At6+gnhcn+Yf1+5nyXHdWdAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYD +VR0PAQH/BAQDAgEGMB0GA1UdDgQWBBR7W0XPr87Lev0xkhpqtvNG61dIUDANBgkqhkiG9w0BAQUF +AAOCAQEAeRHAS7ORtvzw6WfUDW5FvlXok9LOAz/t2iWwHVfLHjp2oEzsUHboZHIMpKnxuIvW1oeE +uzLlQRHAd9mzYJ3rG9XRbkREqaYB7FViHXe4XI5ISXycO1cRrK1zN44veFyQaEfZYGDm/Ac9IiAX +xPcW6cTYcvnIc3zfFi8VqT79aie2oetaupgf1eNNZAqdE8hhuvU5HIe6uL17In/2/qxAeeWsEG89 +jxt5dovEN7MhGITlNgDrYyCZuen+MwS7QcjBAvlEYyCegc5C09Y/LHbTY5xZ3Y+m4Q6gLkH3LpVH +z7z9M/P2C2F+fpErgUfCJzDupxBdN49cOSvkBPB7jVaMaA== +-----END CERTIFICATE----- + +VeriSign Class 3 Public Primary Certification Authority - G5 +============================================================ +-----BEGIN CERTIFICATE----- +MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCByjELMAkGA1UE +BhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBO +ZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVk +IHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRp +ZmljYXRpb24gQXV0aG9yaXR5IC0gRzUwHhcNMDYxMTA4MDAwMDAwWhcNMzYwNzE2MjM1OTU5WjCB +yjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2ln +biBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2lnbiwgSW5jLiAtIEZvciBh +dXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmlt +YXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw +ggEKAoIBAQCvJAgIKXo1nmAMqudLO07cfLw8RRy7K+D+KQL5VwijZIUVJ/XxrcgxiV0i6CqqpkKz +j/i5Vbext0uz/o9+B1fs70PbZmIVYc9gDaTY3vjgw2IIPVQT60nKWVSFJuUrjxuf6/WhkcIzSdhD +Y2pSS9KP6HBRTdGJaXvHcPaz3BJ023tdS1bTlr8Vd6Gw9KIl8q8ckmcY5fQGBO+QueQA5N06tRn/ +Arr0PO7gi+s3i+z016zy9vA9r911kTMZHRxAy3QkGSGT2RT+rCpSx4/VBEnkjWNHiDxpg8v+R70r +fk/Fla4OndTRQ8Bnc+MUCH7lP59zuDMKz10/NIeWiu5T6CUVAgMBAAGjgbIwga8wDwYDVR0TAQH/ +BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2Uv +Z2lmMCEwHzAHBgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVy +aXNpZ24uY29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFH/TZafC3ey78DAJ80M5+gKvMzEzMA0GCSqG +SIb3DQEBBQUAA4IBAQCTJEowX2LP2BqYLz3q3JktvXf2pXkiOOzEp6B4Eq1iDkVwZMXnl2YtmAl+ +X6/WzChl8gGqCBpH3vn5fJJaCGkgDdk+bW48DW7Y5gaRQBi5+MHt39tBquCWIMnNZBU4gcmU7qKE +KQsTb47bDN0lAtukixlE0kF6BWlKWE9gyn6CagsCqiUXObXbf+eEZSqVir2G3l6BFoMtEMze/aiC +Km0oHw0LxOXnGiYZ4fQRbxC1lfznQgUy286dUV4otp6F01vvpX1FQHKOtw5rDgb7MzVIcbidJ4vE +ZV8NhnacRHr2lVz2XTIIM6RUthg/aFzyQkqFOFSDX9HoLPKsEdao7WNq +-----END CERTIFICATE----- + +SecureTrust CA +============== +-----BEGIN CERTIFICATE----- +MIIDuDCCAqCgAwIBAgIQDPCOXAgWpa1Cf/DrJxhZ0DANBgkqhkiG9w0BAQUFADBIMQswCQYDVQQG +EwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24xFzAVBgNVBAMTDlNlY3VyZVRy +dXN0IENBMB4XDTA2MTEwNzE5MzExOFoXDTI5MTIzMTE5NDA1NVowSDELMAkGA1UEBhMCVVMxIDAe +BgNVBAoTF1NlY3VyZVRydXN0IENvcnBvcmF0aW9uMRcwFQYDVQQDEw5TZWN1cmVUcnVzdCBDQTCC +ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKukgeWVzfX2FI7CT8rU4niVWJxB4Q2ZQCQX +OZEzZum+4YOvYlyJ0fwkW2Gz4BERQRwdbvC4u/jep4G6pkjGnx29vo6pQT64lO0pGtSO0gMdA+9t +DWccV9cGrcrI9f4Or2YlSASWC12juhbDCE/RRvgUXPLIXgGZbf2IzIaowW8xQmxSPmjL8xk037uH +GFaAJsTQ3MBv396gwpEWoGQRS0S8Hvbn+mPeZqx2pHGj7DaUaHp3pLHnDi+BeuK1cobvomuL8A/b +01k/unK8RCSc43Oz969XL0Imnal0ugBS8kvNU3xHCzaFDmapCJcWNFfBZveA4+1wVMeT4C4oFVmH +ursCAwEAAaOBnTCBmjATBgkrBgEEAYI3FAIEBh4EAEMAQTALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/ +BAUwAwEB/zAdBgNVHQ4EFgQUQjK2FvoE/f5dS3rD/fdMQB1aQ68wNAYDVR0fBC0wKzApoCegJYYj +aHR0cDovL2NybC5zZWN1cmV0cnVzdC5jb20vU1RDQS5jcmwwEAYJKwYBBAGCNxUBBAMCAQAwDQYJ +KoZIhvcNAQEFBQADggEBADDtT0rhWDpSclu1pqNlGKa7UTt36Z3q059c4EVlew3KW+JwULKUBRSu +SceNQQcSc5R+DCMh/bwQf2AQWnL1mA6s7Ll/3XpvXdMc9P+IBWlCqQVxyLesJugutIxq/3HcuLHf +mbx8IVQr5Fiiu1cprp6poxkmD5kuCLDv/WnPmRoJjeOnnyvJNjR7JLN4TJUXpAYmHrZkUjZfYGfZ +nMUFdAvnZyPSCPyI6a6Lf+Ew9Dd+/cYy2i2eRDAwbO4H3tI0/NL/QPZL9GZGBlSm8jIKYyYwa5vR +3ItHuuG51WLQoqD0ZwV4KWMabwTW+MZMo5qxN7SN5ShLHZ4swrhovO0C7jE= +-----END CERTIFICATE----- + +Secure Global CA +================ +-----BEGIN CERTIFICATE----- +MIIDvDCCAqSgAwIBAgIQB1YipOjUiolN9BPI8PjqpTANBgkqhkiG9w0BAQUFADBKMQswCQYDVQQG +EwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24xGTAXBgNVBAMTEFNlY3VyZSBH +bG9iYWwgQ0EwHhcNMDYxMTA3MTk0MjI4WhcNMjkxMjMxMTk1MjA2WjBKMQswCQYDVQQGEwJVUzEg +MB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24xGTAXBgNVBAMTEFNlY3VyZSBHbG9iYWwg +Q0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvNS7YrGxVaQZx5RNoJLNP2MwhR/jx +YDiJiQPpvepeRlMJ3Fz1Wuj3RSoC6zFh1ykzTM7HfAo3fg+6MpjhHZevj8fcyTiW89sa/FHtaMbQ +bqR8JNGuQsiWUGMu4P51/pinX0kuleM5M2SOHqRfkNJnPLLZ/kG5VacJjnIFHovdRIWCQtBJwB1g +8NEXLJXr9qXBkqPFwqcIYA1gBBCWeZ4WNOaptvolRTnIHmX5k/Wq8VLcmZg9pYYaDDUz+kulBAYV +HDGA76oYa8J719rO+TMg1fW9ajMtgQT7sFzUnKPiXB3jqUJ1XnvUd+85VLrJChgbEplJL4hL/VBi +0XPnj3pDAgMBAAGjgZ0wgZowEwYJKwYBBAGCNxQCBAYeBABDAEEwCwYDVR0PBAQDAgGGMA8GA1Ud +EwEB/wQFMAMBAf8wHQYDVR0OBBYEFK9EBMJBfkiD2045AuzshHrmzsmkMDQGA1UdHwQtMCswKaAn +oCWGI2h0dHA6Ly9jcmwuc2VjdXJldHJ1c3QuY29tL1NHQ0EuY3JsMBAGCSsGAQQBgjcVAQQDAgEA +MA0GCSqGSIb3DQEBBQUAA4IBAQBjGghAfaReUw132HquHw0LURYD7xh8yOOvaliTFGCRsoTciE6+ +OYo68+aCiV0BN7OrJKQVDpI1WkpEXk5X+nXOH0jOZvQ8QCaSmGwb7iRGDBezUqXbpZGRzzfTb+cn +CDpOGR86p1hcF895P4vkp9MmI50mD1hp/Ed+stCNi5O/KU9DaXR2Z0vPB4zmAve14bRDtUstFJ/5 +3CYNv6ZHdAbYiNE6KTCEztI5gGIbqMdXSbxqVVFnFUq+NQfk1XWYN3kwFNspnWzFacxHVaIw98xc +f8LDmBxrThaA63p4ZUWiABqvDA1VZDRIuJK58bRQKfJPIx/abKwfROHdI3hRW8cW +-----END CERTIFICATE----- + +COMODO Certification Authority +============================== +-----BEGIN CERTIFICATE----- +MIIEHTCCAwWgAwIBAgIQToEtioJl4AsC7j41AkblPTANBgkqhkiG9w0BAQUFADCBgTELMAkGA1UE +BhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgG +A1UEChMRQ09NT0RPIENBIExpbWl0ZWQxJzAlBgNVBAMTHkNPTU9ETyBDZXJ0aWZpY2F0aW9uIEF1 +dGhvcml0eTAeFw0wNjEyMDEwMDAwMDBaFw0yOTEyMzEyMzU5NTlaMIGBMQswCQYDVQQGEwJHQjEb +MBkGA1UECBMSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHEwdTYWxmb3JkMRowGAYDVQQKExFD +T01PRE8gQ0EgTGltaXRlZDEnMCUGA1UEAxMeQ09NT0RPIENlcnRpZmljYXRpb24gQXV0aG9yaXR5 +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0ECLi3LjkRv3UcEbVASY06m/weaKXTuH ++7uIzg3jLz8GlvCiKVCZrts7oVewdFFxze1CkU1B/qnI2GqGd0S7WWaXUF601CxwRM/aN5VCaTww +xHGzUvAhTaHYujl8HJ6jJJ3ygxaYqhZ8Q5sVW7euNJH+1GImGEaaP+vB+fGQV+useg2L23IwambV +4EajcNxo2f8ESIl33rXp+2dtQem8Ob0y2WIC8bGoPW43nOIv4tOiJovGuFVDiOEjPqXSJDlqR6sA +1KGzqSX+DT+nHbrTUcELpNqsOO9VUCQFZUaTNE8tja3G1CEZ0o7KBWFxB3NH5YoZEr0ETc5OnKVI +rLsm9wIDAQABo4GOMIGLMB0GA1UdDgQWBBQLWOWLxkwVN6RAqTCpIb5HNlpW/zAOBgNVHQ8BAf8E +BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zBJBgNVHR8EQjBAMD6gPKA6hjhodHRwOi8vY3JsLmNvbW9k +b2NhLmNvbS9DT01PRE9DZXJ0aWZpY2F0aW9uQXV0aG9yaXR5LmNybDANBgkqhkiG9w0BAQUFAAOC +AQEAPpiem/Yb6dc5t3iuHXIYSdOH5EOC6z/JqvWote9VfCFSZfnVDeFs9D6Mk3ORLgLETgdxb8CP +OGEIqB6BCsAvIC9Bi5HcSEW88cbeunZrM8gALTFGTO3nnc+IlP8zwFboJIYmuNg4ON8qa90SzMc/ +RxdMosIGlgnW2/4/PEZB31jiVg88O8EckzXZOFKs7sjsLjBOlDW0JB9LeGna8gI4zJVSk/BwJVmc +IGfE7vmLV2H0knZ9P4SNVbfo5azV8fUZVqZa+5Acr5Pr5RzUZ5ddBA6+C4OmF4O5MBKgxTMVBbkN ++8cFduPYSo38NBejxiEovjBFMR7HeL5YYTisO+IBZQ== +-----END CERTIFICATE----- + +Network Solutions Certificate Authority +======================================= +-----BEGIN CERTIFICATE----- +MIID5jCCAs6gAwIBAgIQV8szb8JcFuZHFhfjkDFo4DANBgkqhkiG9w0BAQUFADBiMQswCQYDVQQG +EwJVUzEhMB8GA1UEChMYTmV0d29yayBTb2x1dGlvbnMgTC5MLkMuMTAwLgYDVQQDEydOZXR3b3Jr +IFNvbHV0aW9ucyBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwHhcNMDYxMjAxMDAwMDAwWhcNMjkxMjMx +MjM1OTU5WjBiMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYTmV0d29yayBTb2x1dGlvbnMgTC5MLkMu +MTAwLgYDVQQDEydOZXR3b3JrIFNvbHV0aW9ucyBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwggEiMA0G +CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDkvH6SMG3G2I4rC7xGzuAnlt7e+foS0zwzc7MEL7xx +jOWftiJgPl9dzgn/ggwbmlFQGiaJ3dVhXRncEg8tCqJDXRfQNJIg6nPPOCwGJgl6cvf6UDL4wpPT +aaIjzkGxzOTVHzbRijr4jGPiFFlp7Q3Tf2vouAPlT2rlmGNpSAW+Lv8ztumXWWn4Zxmuk2GWRBXT +crA/vGp97Eh/jcOrqnErU2lBUzS1sLnFBgrEsEX1QV1uiUV7PTsmjHTC5dLRfbIR1PtYMiKagMnc +/Qzpf14Dl847ABSHJ3A4qY5usyd2mFHgBeMhqxrVhSI8KbWaFsWAqPS7azCPL0YCorEMIuDTAgMB +AAGjgZcwgZQwHQYDVR0OBBYEFCEwyfsA106Y2oeqKtCnLrFAMadMMA4GA1UdDwEB/wQEAwIBBjAP +BgNVHRMBAf8EBTADAQH/MFIGA1UdHwRLMEkwR6BFoEOGQWh0dHA6Ly9jcmwubmV0c29sc3NsLmNv +bS9OZXR3b3JrU29sdXRpb25zQ2VydGlmaWNhdGVBdXRob3JpdHkuY3JsMA0GCSqGSIb3DQEBBQUA +A4IBAQC7rkvnt1frf6ott3NHhWrB5KUd5Oc86fRZZXe1eltajSU24HqXLjjAV2CDmAaDn7l2em5Q +4LqILPxFzBiwmZVRDuwduIj/h1AcgsLj4DKAv6ALR8jDMe+ZZzKATxcheQxpXN5eNK4CtSbqUN9/ +GGUsyfJj4akH/nxxH2szJGoeBfcFaMBqEssuXmHLrijTfsK0ZpEmXzwuJF/LWA/rKOyvEZbz3Htv +wKeI8lN3s2Berq4o2jUsbzRF0ybh3uxbTydrFny9RAQYgrOJeRcQcT16ohZO9QHNpGxlaKFJdlxD +ydi8NmdspZS11My5vWo1ViHe2MPr+8ukYEywVaCge1ey +-----END CERTIFICATE----- + +WellsSecure Public Root Certificate Authority +============================================= +-----BEGIN CERTIFICATE----- +MIIEvTCCA6WgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBhTELMAkGA1UEBhMCVVMxIDAeBgNVBAoM +F1dlbGxzIEZhcmdvIFdlbGxzU2VjdXJlMRwwGgYDVQQLDBNXZWxscyBGYXJnbyBCYW5rIE5BMTYw +NAYDVQQDDC1XZWxsc1NlY3VyZSBQdWJsaWMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwHhcN +MDcxMjEzMTcwNzU0WhcNMjIxMjE0MDAwNzU0WjCBhTELMAkGA1UEBhMCVVMxIDAeBgNVBAoMF1dl +bGxzIEZhcmdvIFdlbGxzU2VjdXJlMRwwGgYDVQQLDBNXZWxscyBGYXJnbyBCYW5rIE5BMTYwNAYD +VQQDDC1XZWxsc1NlY3VyZSBQdWJsaWMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwggEiMA0G +CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDub7S9eeKPCCGeOARBJe+rWxxTkqxtnt3CxC5FlAM1 +iGd0V+PfjLindo8796jE2yljDpFoNoqXjopxaAkH5OjUDk/41itMpBb570OYj7OeUt9tkTmPOL13 +i0Nj67eT/DBMHAGTthP796EfvyXhdDcsHqRePGj4S78NuR4uNuip5Kf4D8uCdXw1LSLWwr8L87T8 +bJVhHlfXBIEyg1J55oNjz7fLY4sR4r1e6/aN7ZVyKLSsEmLpSjPmgzKuBXWVvYSV2ypcm44uDLiB +K0HmOFafSZtsdvqKXfcBeYF8wYNABf5x/Qw/zE5gCQ5lRxAvAcAFP4/4s0HvWkJ+We/SlwxlAgMB +AAGjggE0MIIBMDAPBgNVHRMBAf8EBTADAQH/MDkGA1UdHwQyMDAwLqAsoCqGKGh0dHA6Ly9jcmwu +cGtpLndlbGxzZmFyZ28uY29tL3dzcHJjYS5jcmwwDgYDVR0PAQH/BAQDAgHGMB0GA1UdDgQWBBQm +lRkQ2eihl5H/3BnZtQQ+0nMKajCBsgYDVR0jBIGqMIGngBQmlRkQ2eihl5H/3BnZtQQ+0nMKaqGB +i6SBiDCBhTELMAkGA1UEBhMCVVMxIDAeBgNVBAoMF1dlbGxzIEZhcmdvIFdlbGxzU2VjdXJlMRww +GgYDVQQLDBNXZWxscyBGYXJnbyBCYW5rIE5BMTYwNAYDVQQDDC1XZWxsc1NlY3VyZSBQdWJsaWMg +Um9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHmCAQEwDQYJKoZIhvcNAQEFBQADggEBALkVsUSRzCPI +K0134/iaeycNzXK7mQDKfGYZUMbVmO2rvwNa5U3lHshPcZeG1eMd/ZDJPHV3V3p9+N701NX3leZ0 +bh08rnyd2wIDBSxxSyU+B+NemvVmFymIGjifz6pBA4SXa5M4esowRBskRDPQ5NHcKDj0E0M1NSlj +qHyita04pO2t/caaH/+Xc/77szWnk4bGdpEA5qxRFsQnMlzbc9qlk1eOPm01JghZ1edE13YgY+es +E2fDbbFwRnzVlhE9iW9dqKHrjQrawx0zbKPqZxmamX9LPYNRKh3KL4YMon4QLSvUFpULB6ouFJJJ +tylv2G0xffX8oRAHh84vWdw+WNs= +-----END CERTIFICATE----- + +COMODO ECC Certification Authority +================================== +-----BEGIN CERTIFICATE----- +MIICiTCCAg+gAwIBAgIQH0evqmIAcFBUTAGem2OZKjAKBggqhkjOPQQDAzCBhTELMAkGA1UEBhMC +R0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UE +ChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlvbiBB +dXRob3JpdHkwHhcNMDgwMzA2MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0Ix +GzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMR +Q09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRo +b3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQDR3svdcmCFYX7deSRFtSrYpn1PlILBs5BAH+X +4QokPB0BBO490o0JlwzgdeT6+3eKKvUDYEs2ixYjFq0JcfRK9ChQtP6IHG4/bC8vCVlbpVsLM5ni +wz2J+Wos77LTBumjQjBAMB0GA1UdDgQWBBR1cacZSBm8nZ3qQUfflMRId5nTeTAOBgNVHQ8BAf8E +BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjEA7wNbeqy3eApyt4jf/7VG +FAkK+qDmfQjGGoe9GKhzvSbKYAydzpmfz1wPMOG+FDHqAjAU9JM8SaczepBGR7NjfRObTrdvGDeA +U/7dIOA1mjbRxwG55tzd8/8dLDoWV9mSOdY= +-----END CERTIFICATE----- + +IGC/A +===== +-----BEGIN CERTIFICATE----- +MIIEAjCCAuqgAwIBAgIFORFFEJQwDQYJKoZIhvcNAQEFBQAwgYUxCzAJBgNVBAYTAkZSMQ8wDQYD +VQQIEwZGcmFuY2UxDjAMBgNVBAcTBVBhcmlzMRAwDgYDVQQKEwdQTS9TR0ROMQ4wDAYDVQQLEwVE +Q1NTSTEOMAwGA1UEAxMFSUdDL0ExIzAhBgkqhkiG9w0BCQEWFGlnY2FAc2dkbi5wbS5nb3V2LmZy +MB4XDTAyMTIxMzE0MjkyM1oXDTIwMTAxNzE0MjkyMlowgYUxCzAJBgNVBAYTAkZSMQ8wDQYDVQQI +EwZGcmFuY2UxDjAMBgNVBAcTBVBhcmlzMRAwDgYDVQQKEwdQTS9TR0ROMQ4wDAYDVQQLEwVEQ1NT +STEOMAwGA1UEAxMFSUdDL0ExIzAhBgkqhkiG9w0BCQEWFGlnY2FAc2dkbi5wbS5nb3V2LmZyMIIB +IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsh/R0GLFMzvABIaIs9z4iPf930Pfeo2aSVz2 +TqrMHLmh6yeJ8kbpO0px1R2OLc/mratjUMdUC24SyZA2xtgv2pGqaMVy/hcKshd+ebUyiHDKcMCW +So7kVc0dJ5S/znIq7Fz5cyD+vfcuiWe4u0dzEvfRNWk68gq5rv9GQkaiv6GFGvm/5P9JhfejcIYy +HF2fYPepraX/z9E0+X1bF8bc1g4oa8Ld8fUzaJ1O/Id8NhLWo4DoQw1VYZTqZDdH6nfK0LJYBcNd +frGoRpAxVs5wKpayMLh35nnAvSk7/ZR3TL0gzUEl4C7HG7vupARB0l2tEmqKm0f7yd1GQOGdPDPQ +tQIDAQABo3cwdTAPBgNVHRMBAf8EBTADAQH/MAsGA1UdDwQEAwIBRjAVBgNVHSAEDjAMMAoGCCqB +egF5AQEBMB0GA1UdDgQWBBSjBS8YYFDCiQrdKyFP/45OqDAxNjAfBgNVHSMEGDAWgBSjBS8YYFDC +iQrdKyFP/45OqDAxNjANBgkqhkiG9w0BAQUFAAOCAQEABdwm2Pp3FURo/C9mOnTgXeQp/wYHE4RK +q89toB9RlPhJy3Q2FLwV3duJL92PoF189RLrn544pEfMs5bZvpwlqwN+Mw+VgQ39FuCIvjfwbF3Q +MZsyK10XZZOYYLxuj7GoPB7ZHPOpJkL5ZB3C55L29B5aqhlSXa/oovdgoPaN8In1buAKBQGVyYsg +Crpa/JosPL3Dt8ldeCUFP1YUmwza+zpI/pdpXsoQhvdOlgQITeywvl3cO45Pwf2aNjSaTFR+FwNI +lQgRHAdvhQh+XU3Endv7rs6y0bO4g2wdsrN58dhwmX7wEwLOXt1R0982gaEbeC9xs/FZTEYYKKuF +0mBWWg== +-----END CERTIFICATE----- + +Security Communication EV RootCA1 +================================= +-----BEGIN CERTIFICATE----- +MIIDfTCCAmWgAwIBAgIBADANBgkqhkiG9w0BAQUFADBgMQswCQYDVQQGEwJKUDElMCMGA1UEChMc +U0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEqMCgGA1UECxMhU2VjdXJpdHkgQ29tbXVuaWNh +dGlvbiBFViBSb290Q0ExMB4XDTA3MDYwNjAyMTIzMloXDTM3MDYwNjAyMTIzMlowYDELMAkGA1UE +BhMCSlAxJTAjBgNVBAoTHFNFQ09NIFRydXN0IFN5c3RlbXMgQ08uLExURC4xKjAoBgNVBAsTIVNl +Y3VyaXR5IENvbW11bmljYXRpb24gRVYgUm9vdENBMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC +AQoCggEBALx/7FebJOD+nLpCeamIivqA4PUHKUPqjgo0No0c+qe1OXj/l3X3L+SqawSERMqm4miO +/VVQYg+kcQ7OBzgtQoVQrTyWb4vVog7P3kmJPdZkLjjlHmy1V4qe70gOzXppFodEtZDkBp2uoQSX +WHnvIEqCa4wiv+wfD+mEce3xDuS4GBPMVjZd0ZoeUWs5bmB2iDQL87PRsJ3KYeJkHcFGB7hj3R4z +ZbOOCVVSPbW9/wfrrWFVGCypaZhKqkDFMxRldAD5kd6vA0jFQFTcD4SQaCDFkpbcLuUCRarAX1T4 +bepJz11sS6/vmsJWXMY1VkJqMF/Cq/biPT+zyRGPMUzXn0kCAwEAAaNCMEAwHQYDVR0OBBYEFDVK +9U2vP9eCOKyrcWUXdYydVZPmMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MA0GCSqG +SIb3DQEBBQUAA4IBAQCoh+ns+EBnXcPBZsdAS5f8hxOQWsTvoMpfi7ent/HWtWS3irO4G8za+6xm +iEHO6Pzk2x6Ipu0nUBsCMCRGef4Eh3CXQHPRwMFXGZpppSeZq51ihPZRwSzJIxXYKLerJRO1RuGG +Av8mjMSIkh1W/hln8lXkgKNrnKt34VFxDSDbEJrbvXZ5B3eZKK2aXtqxT0QsNY6llsf9g/BYxnnW +mHyojf6GPgcWkuF75x3sM3Z+Qi5KhfmRiWiEA4Glm5q+4zfFVKtWOxgtQaQM+ELbmaDgcm+7XeEW +T1MKZPlO9L9OVL14bIjqv5wTJMJwaaJ/D8g8rQjJsJhAoyrniIPtd490 +-----END CERTIFICATE----- + +OISTE WISeKey Global Root GA CA +=============================== +-----BEGIN CERTIFICATE----- +MIID8TCCAtmgAwIBAgIQQT1yx/RrH4FDffHSKFTfmjANBgkqhkiG9w0BAQUFADCBijELMAkGA1UE +BhMCQ0gxEDAOBgNVBAoTB1dJU2VLZXkxGzAZBgNVBAsTEkNvcHlyaWdodCAoYykgMjAwNTEiMCAG +A1UECxMZT0lTVEUgRm91bmRhdGlvbiBFbmRvcnNlZDEoMCYGA1UEAxMfT0lTVEUgV0lTZUtleSBH +bG9iYWwgUm9vdCBHQSBDQTAeFw0wNTEyMTExNjAzNDRaFw0zNzEyMTExNjA5NTFaMIGKMQswCQYD +VQQGEwJDSDEQMA4GA1UEChMHV0lTZUtleTEbMBkGA1UECxMSQ29weXJpZ2h0IChjKSAyMDA1MSIw +IAYDVQQLExlPSVNURSBGb3VuZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5 +IEdsb2JhbCBSb290IEdBIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAy0+zAJs9 +Nt350UlqaxBJH+zYK7LG+DKBKUOVTJoZIyEVRd7jyBxRVVuuk+g3/ytr6dTqvirdqFEr12bDYVxg +Asj1znJ7O7jyTmUIms2kahnBAbtzptf2w93NvKSLtZlhuAGio9RN1AU9ka34tAhxZK9w8RxrfvbD +d50kc3vkDIzh2TbhmYsFmQvtRTEJysIA2/dyoJaqlYfQjse2YXMNdmaM3Bu0Y6Kff5MTMPGhJ9vZ +/yxViJGg4E8HsChWjBgbl0SOid3gF27nKu+POQoxhILYQBRJLnpB5Kf+42TMwVlxSywhp1t94B3R +LoGbw9ho972WG6xwsRYUC9tguSYBBQIDAQABo1EwTzALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/BAUw +AwEB/zAdBgNVHQ4EFgQUswN+rja8sHnR3JQmthG+IbJphpQwEAYJKwYBBAGCNxUBBAMCAQAwDQYJ +KoZIhvcNAQEFBQADggEBAEuh/wuHbrP5wUOxSPMowB0uyQlB+pQAHKSkq0lPjz0e701vvbyk9vIm +MMkQyh2I+3QZH4VFvbBsUfk2ftv1TDI6QU9bR8/oCy22xBmddMVHxjtqD6wU2zz0c5ypBd8A3HR4 ++vg1YFkCExh8vPtNsCBtQ7tgMHpnM1zFmdH4LTlSc/uMqpclXHLZCB6rTjzjgTGfA6b7wP4piFXa +hNVQA7bihKOmNqoROgHhGEvWRGizPflTdISzRpFGlgC3gCy24eMQ4tui5yiPAZZiFj4A4xylNoEY +okxSdsARo27mHbrjWr42U8U+dY+GaSlYU7Wcu2+fXMUY7N0v4ZjJ/L7fCg0= +-----END CERTIFICATE----- + +Microsec e-Szigno Root CA +========================= +-----BEGIN CERTIFICATE----- +MIIHqDCCBpCgAwIBAgIRAMy4579OKRr9otxmpRwsDxEwDQYJKoZIhvcNAQEFBQAwcjELMAkGA1UE +BhMCSFUxETAPBgNVBAcTCEJ1ZGFwZXN0MRYwFAYDVQQKEw1NaWNyb3NlYyBMdGQuMRQwEgYDVQQL +EwtlLVN6aWdubyBDQTEiMCAGA1UEAxMZTWljcm9zZWMgZS1Temlnbm8gUm9vdCBDQTAeFw0wNTA0 +MDYxMjI4NDRaFw0xNzA0MDYxMjI4NDRaMHIxCzAJBgNVBAYTAkhVMREwDwYDVQQHEwhCdWRhcGVz +dDEWMBQGA1UEChMNTWljcm9zZWMgTHRkLjEUMBIGA1UECxMLZS1Temlnbm8gQ0ExIjAgBgNVBAMT +GU1pY3Jvc2VjIGUtU3ppZ25vIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB +AQDtyADVgXvNOABHzNuEwSFpLHSQDCHZU4ftPkNEU6+r+ICbPHiN1I2uuO/TEdyB5s87lozWbxXG +d36hL+BfkrYn13aaHUM86tnsL+4582pnS4uCzyL4ZVX+LMsvfUh6PXX5qqAnu3jCBspRwn5mS6/N +oqdNAoI/gqyFxuEPkEeZlApxcpMqyabAvjxWTHOSJ/FrtfX9/DAFYJLG65Z+AZHCabEeHXtTRbjc +QR/Ji3HWVBTji1R4P770Yjtb9aPs1ZJ04nQw7wHb4dSrmZsqa/i9phyGI0Jf7Enemotb9HI6QMVJ +PqW+jqpx62z69Rrkav17fVVA71hu5tnVvCSrwe+3AgMBAAGjggQ3MIIEMzBnBggrBgEFBQcBAQRb +MFkwKAYIKwYBBQUHMAGGHGh0dHBzOi8vcmNhLmUtc3ppZ25vLmh1L29jc3AwLQYIKwYBBQUHMAKG +IWh0dHA6Ly93d3cuZS1zemlnbm8uaHUvUm9vdENBLmNydDAPBgNVHRMBAf8EBTADAQH/MIIBcwYD +VR0gBIIBajCCAWYwggFiBgwrBgEEAYGoGAIBAQEwggFQMCgGCCsGAQUFBwIBFhxodHRwOi8vd3d3 +LmUtc3ppZ25vLmh1L1NaU1ovMIIBIgYIKwYBBQUHAgIwggEUHoIBEABBACAAdABhAG4A+gBzAO0A +dAB2AOEAbgB5ACAA6QByAHQAZQBsAG0AZQB6AOkAcwDpAGgAZQB6ACAA6QBzACAAZQBsAGYAbwBn +AGEAZADhAHMA4QBoAG8AegAgAGEAIABTAHoAbwBsAGcA4QBsAHQAYQB0APMAIABTAHoAbwBsAGcA +4QBsAHQAYQB0AOEAcwBpACAAUwB6AGEAYgDhAGwAeQB6AGEAdABhACAAcwB6AGUAcgBpAG4AdAAg +AGsAZQBsAGwAIABlAGwAagDhAHIAbgBpADoAIABoAHQAdABwADoALwAvAHcAdwB3AC4AZQAtAHMA +egBpAGcAbgBvAC4AaAB1AC8AUwBaAFMAWgAvMIHIBgNVHR8EgcAwgb0wgbqggbeggbSGIWh0dHA6 +Ly93d3cuZS1zemlnbm8uaHUvUm9vdENBLmNybIaBjmxkYXA6Ly9sZGFwLmUtc3ppZ25vLmh1L0NO +PU1pY3Jvc2VjJTIwZS1Temlnbm8lMjBSb290JTIwQ0EsT1U9ZS1Temlnbm8lMjBDQSxPPU1pY3Jv +c2VjJTIwTHRkLixMPUJ1ZGFwZXN0LEM9SFU/Y2VydGlmaWNhdGVSZXZvY2F0aW9uTGlzdDtiaW5h +cnkwDgYDVR0PAQH/BAQDAgEGMIGWBgNVHREEgY4wgYuBEGluZm9AZS1zemlnbm8uaHWkdzB1MSMw +IQYDVQQDDBpNaWNyb3NlYyBlLVN6aWduw7MgUm9vdCBDQTEWMBQGA1UECwwNZS1TemlnbsOzIEhT +WjEWMBQGA1UEChMNTWljcm9zZWMgS2Z0LjERMA8GA1UEBxMIQnVkYXBlc3QxCzAJBgNVBAYTAkhV +MIGsBgNVHSMEgaQwgaGAFMegSXUWYYTbMUuE0vE3QJDvTtz3oXakdDByMQswCQYDVQQGEwJIVTER +MA8GA1UEBxMIQnVkYXBlc3QxFjAUBgNVBAoTDU1pY3Jvc2VjIEx0ZC4xFDASBgNVBAsTC2UtU3pp +Z25vIENBMSIwIAYDVQQDExlNaWNyb3NlYyBlLVN6aWdubyBSb290IENBghEAzLjnv04pGv2i3Gal +HCwPETAdBgNVHQ4EFgQUx6BJdRZhhNsxS4TS8TdAkO9O3PcwDQYJKoZIhvcNAQEFBQADggEBANMT +nGZjWS7KXHAM/IO8VbH0jgdsZifOwTsgqRy7RlRw7lrMoHfqaEQn6/Ip3Xep1fvj1KcExJW4C+FE +aGAHQzAxQmHl7tnlJNUb3+FKG6qfx1/4ehHqE5MAyopYse7tDk2016g2JnzgOsHVV4Lxdbb9iV/a +86g4nzUGCM4ilb7N1fy+W955a9x6qWVmvrElWl/tftOsRm1M9DKHtCAE4Gx4sHfRhUZLphK3dehK +yVZs15KrnfVJONJPU+NVkBHbmJbGSfI+9J8b4PeI3CVimUTYc78/MPMMNz7UwiiAc7EBt51alhQB +S6kRnSlqLtBdgcDPsiBDxwPgN05dCtxZICU= +-----END CERTIFICATE----- + +Certigna +======== +-----BEGIN CERTIFICATE----- +MIIDqDCCApCgAwIBAgIJAP7c4wEPyUj/MA0GCSqGSIb3DQEBBQUAMDQxCzAJBgNVBAYTAkZSMRIw +EAYDVQQKDAlEaGlteW90aXMxETAPBgNVBAMMCENlcnRpZ25hMB4XDTA3MDYyOTE1MTMwNVoXDTI3 +MDYyOTE1MTMwNVowNDELMAkGA1UEBhMCRlIxEjAQBgNVBAoMCURoaW15b3RpczERMA8GA1UEAwwI +Q2VydGlnbmEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDIaPHJ1tazNHUmgh7stL7q +XOEm7RFHYeGifBZ4QCHkYJ5ayGPhxLGWkv8YbWkj4Sti993iNi+RB7lIzw7sebYs5zRLcAglozyH +GxnygQcPOJAZ0xH+hrTy0V4eHpbNgGzOOzGTtvKg0KmVEn2lmsxryIRWijOp5yIVUxbwzBfsV1/p +ogqYCd7jX5xv3EjjhQsVWqa6n6xI4wmy9/Qy3l40vhx4XUJbzg4ij02Q130yGLMLLGq/jj8UEYkg +DncUtT2UCIf3JR7VsmAA7G8qKCVuKj4YYxclPz5EIBb2JsglrgVKtOdjLPOMFlN+XPsRGgjBRmKf +Irjxwo1p3Po6WAbfAgMBAAGjgbwwgbkwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUGu3+QTmQ +tCRZvgHyUtVF9lo53BEwZAYDVR0jBF0wW4AUGu3+QTmQtCRZvgHyUtVF9lo53BGhOKQ2MDQxCzAJ +BgNVBAYTAkZSMRIwEAYDVQQKDAlEaGlteW90aXMxETAPBgNVBAMMCENlcnRpZ25hggkA/tzjAQ/J +SP8wDgYDVR0PAQH/BAQDAgEGMBEGCWCGSAGG+EIBAQQEAwIABzANBgkqhkiG9w0BAQUFAAOCAQEA +hQMeknH2Qq/ho2Ge6/PAD/Kl1NqV5ta+aDY9fm4fTIrv0Q8hbV6lUmPOEvjvKtpv6zf+EwLHyzs+ +ImvaYS5/1HI93TDhHkxAGYwP15zRgzB7mFncfca5DClMoTOi62c6ZYTTluLtdkVwj7Ur3vkj1klu +PBS1xp81HlDQwY9qcEQCYsuuHWhBp6pX6FOqB9IG9tUUBguRA3UsbHK1YZWaDYu5Def131TN3ubY +1gkIl2PlwS6wt0QmwCbAr1UwnjvVNioZBPRcHv/PLLf/0P2HQBHVESO7SMAhqaQoLf0V+LBOK/Qw +WyH8EZE0vkHve52Xdf+XlcCWWC/qu0bXu+TZLg== +-----END CERTIFICATE----- + +AC Ra\xC3\xADz Certic\xC3\xA1mara S.A. +====================================== +-----BEGIN CERTIFICATE----- +MIIGZjCCBE6gAwIBAgIPB35Sk3vgFeNX8GmMy+wMMA0GCSqGSIb3DQEBBQUAMHsxCzAJBgNVBAYT +AkNPMUcwRQYDVQQKDD5Tb2NpZWRhZCBDYW1lcmFsIGRlIENlcnRpZmljYWNpw7NuIERpZ2l0YWwg +LSBDZXJ0aWPDoW1hcmEgUy5BLjEjMCEGA1UEAwwaQUMgUmHDrXogQ2VydGljw6FtYXJhIFMuQS4w +HhcNMDYxMTI3MjA0NjI5WhcNMzAwNDAyMjE0MjAyWjB7MQswCQYDVQQGEwJDTzFHMEUGA1UECgw+ +U29jaWVkYWQgQ2FtZXJhbCBkZSBDZXJ0aWZpY2FjacOzbiBEaWdpdGFsIC0gQ2VydGljw6FtYXJh +IFMuQS4xIzAhBgNVBAMMGkFDIFJhw616IENlcnRpY8OhbWFyYSBTLkEuMIICIjANBgkqhkiG9w0B +AQEFAAOCAg8AMIICCgKCAgEAq2uJo1PMSCMI+8PPUZYILrgIem08kBeGqentLhM0R7LQcNzJPNCN +yu5LF6vQhbCnIwTLqKL85XXbQMpiiY9QngE9JlsYhBzLfDe3fezTf3MZsGqy2IiKLUV0qPezuMDU +2s0iiXRNWhU5cxh0T7XrmafBHoi0wpOQY5fzp6cSsgkiBzPZkc0OnB8OIMfuuzONj8LSWKdf/WU3 +4ojC2I+GdV75LaeHM/J4Ny+LvB2GNzmxlPLYvEqcgxhaBvzz1NS6jBUJJfD5to0EfhcSM2tXSExP +2yYe68yQ54v5aHxwD6Mq0Do43zeX4lvegGHTgNiRg0JaTASJaBE8rF9ogEHMYELODVoqDA+bMMCm +8Ibbq0nXl21Ii/kDwFJnmxL3wvIumGVC2daa49AZMQyth9VXAnow6IYm+48jilSH5L887uvDdUhf +HjlvgWJsxS3EF1QZtzeNnDeRyPYL1epjb4OsOMLzP96a++EjYfDIJss2yKHzMI+ko6Kh3VOz3vCa +Mh+DkXkwwakfU5tTohVTP92dsxA7SH2JD/ztA/X7JWR1DhcZDY8AFmd5ekD8LVkH2ZD6mq093ICK +5lw1omdMEWux+IBkAC1vImHFrEsm5VoQgpukg3s0956JkSCXjrdCx2bD0Omk1vUgjcTDlaxECp1b +czwmPS9KvqfJpxAe+59QafMCAwEAAaOB5jCB4zAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQE +AwIBBjAdBgNVHQ4EFgQU0QnQ6dfOeXRU+Tows/RtLAMDG2gwgaAGA1UdIASBmDCBlTCBkgYEVR0g +ADCBiTArBggrBgEFBQcCARYfaHR0cDovL3d3dy5jZXJ0aWNhbWFyYS5jb20vZHBjLzBaBggrBgEF +BQcCAjBOGkxMaW1pdGFjaW9uZXMgZGUgZ2FyYW507WFzIGRlIGVzdGUgY2VydGlmaWNhZG8gc2Ug +cHVlZGVuIGVuY29udHJhciBlbiBsYSBEUEMuMA0GCSqGSIb3DQEBBQUAA4ICAQBclLW4RZFNjmEf +AygPU3zmpFmps4p6xbD/CHwso3EcIRNnoZUSQDWDg4902zNc8El2CoFS3UnUmjIz75uny3XlesuX +EpBcunvFm9+7OSPI/5jOCk0iAUgHforA1SBClETvv3eiiWdIG0ADBaGJ7M9i4z0ldma/Jre7Ir5v +/zlXdLp6yQGVwZVR6Kss+LGGIOk/yzVb0hfpKv6DExdA7ohiZVvVO2Dpezy4ydV/NgIlqmjCMRW3 +MGXrfx1IebHPOeJCgBbT9ZMj/EyXyVo3bHwi2ErN0o42gzmRkBDI8ck1fj+404HGIGQatlDCIaR4 +3NAvO2STdPCWkPHv+wlaNECW8DYSwaN0jJN+Qd53i+yG2dIPPy3RzECiiWZIHiCznCNZc6lEc7wk +eZBWN7PGKX6jD/EpOe9+XCgycDWs2rjIdWb8m0w5R44bb5tNAlQiM+9hup4phO9OSzNHdpdqy35f +/RWmnkJDW2ZaiogN9xa5P1FlK2Zqi9E4UqLWRhH6/JocdJ6PlwsCT2TG9WjTSy3/pDceiz+/RL5h +RqGEPQgnTIEgd4kI6mdAXmwIUV80WoyWaM3X94nCHNMyAK9Sy9NgWyo6R35rMDOhYil/SrnhLecU +Iw4OGEfhefwVVdCx/CVxY3UzHCMrr1zZ7Ud3YA47Dx7SwNxkBYn8eNZcLCZDqQ== +-----END CERTIFICATE----- + +TC TrustCenter Class 2 CA II +============================ +-----BEGIN CERTIFICATE----- +MIIEqjCCA5KgAwIBAgIOLmoAAQACH9dSISwRXDswDQYJKoZIhvcNAQEFBQAwdjELMAkGA1UEBhMC +REUxHDAaBgNVBAoTE1RDIFRydXN0Q2VudGVyIEdtYkgxIjAgBgNVBAsTGVRDIFRydXN0Q2VudGVy +IENsYXNzIDIgQ0ExJTAjBgNVBAMTHFRDIFRydXN0Q2VudGVyIENsYXNzIDIgQ0EgSUkwHhcNMDYw +MTEyMTQzODQzWhcNMjUxMjMxMjI1OTU5WjB2MQswCQYDVQQGEwJERTEcMBoGA1UEChMTVEMgVHJ1 +c3RDZW50ZXIgR21iSDEiMCAGA1UECxMZVEMgVHJ1c3RDZW50ZXIgQ2xhc3MgMiBDQTElMCMGA1UE +AxMcVEMgVHJ1c3RDZW50ZXIgQ2xhc3MgMiBDQSBJSTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC +AQoCggEBAKuAh5uO8MN8h9foJIIRszzdQ2Lu+MNF2ujhoF/RKrLqk2jftMjWQ+nEdVl//OEd+DFw +IxuInie5e/060smp6RQvkL4DUsFJzfb95AhmC1eKokKguNV/aVyQMrKXDcpK3EY+AlWJU+MaWss2 +xgdW94zPEfRMuzBwBJWl9jmM/XOBCH2JXjIeIqkiRUuwZi4wzJ9l/fzLganx4Duvo4bRierERXlQ +Xa7pIXSSTYtZgo+U4+lK8edJsBTj9WLL1XK9H7nSn6DNqPoByNkN39r8R52zyFTfSUrxIan+GE7u +SNQZu+995OKdy1u2bv/jzVrndIIFuoAlOMvkaZ6vQaoahPUCAwEAAaOCATQwggEwMA8GA1UdEwEB +/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTjq1RMgKHbVkO3kUrL84J6E1wIqzCB +7QYDVR0fBIHlMIHiMIHfoIHcoIHZhjVodHRwOi8vd3d3LnRydXN0Y2VudGVyLmRlL2NybC92Mi90 +Y19jbGFzc18yX2NhX0lJLmNybIaBn2xkYXA6Ly93d3cudHJ1c3RjZW50ZXIuZGUvQ049VEMlMjBU +cnVzdENlbnRlciUyMENsYXNzJTIwMiUyMENBJTIwSUksTz1UQyUyMFRydXN0Q2VudGVyJTIwR21i +SCxPVT1yb290Y2VydHMsREM9dHJ1c3RjZW50ZXIsREM9ZGU/Y2VydGlmaWNhdGVSZXZvY2F0aW9u +TGlzdD9iYXNlPzANBgkqhkiG9w0BAQUFAAOCAQEAjNfffu4bgBCzg/XbEeprS6iSGNn3Bzn1LL4G +dXpoUxUc6krtXvwjshOg0wn/9vYua0Fxec3ibf2uWWuFHbhOIprtZjluS5TmVfwLG4t3wVMTZonZ +KNaL80VKY7f9ewthXbhtvsPcW3nS7Yblok2+XnR8au0WOB9/WIFaGusyiC2y8zl3gK9etmF1Kdsj +TYjKUCjLhdLTEKJZbtOTVAB6okaVhgWcqRmY5TFyDADiZ9lA4CQze28suVyrZZ0srHbqNZn1l7kP +JOzHdiEoZa5X6AeIdUpWoNIFOqTmjZKILPPy4cHGYdtBxceb9w4aUUXCYWvcZCcXjFq32nQozZfk +vQ== +-----END CERTIFICATE----- + +TC TrustCenter Class 3 CA II +============================ +-----BEGIN CERTIFICATE----- +MIIEqjCCA5KgAwIBAgIOSkcAAQAC5aBd1j8AUb8wDQYJKoZIhvcNAQEFBQAwdjELMAkGA1UEBhMC +REUxHDAaBgNVBAoTE1RDIFRydXN0Q2VudGVyIEdtYkgxIjAgBgNVBAsTGVRDIFRydXN0Q2VudGVy +IENsYXNzIDMgQ0ExJTAjBgNVBAMTHFRDIFRydXN0Q2VudGVyIENsYXNzIDMgQ0EgSUkwHhcNMDYw +MTEyMTQ0MTU3WhcNMjUxMjMxMjI1OTU5WjB2MQswCQYDVQQGEwJERTEcMBoGA1UEChMTVEMgVHJ1 +c3RDZW50ZXIgR21iSDEiMCAGA1UECxMZVEMgVHJ1c3RDZW50ZXIgQ2xhc3MgMyBDQTElMCMGA1UE +AxMcVEMgVHJ1c3RDZW50ZXIgQ2xhc3MgMyBDQSBJSTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC +AQoCggEBALTgu1G7OVyLBMVMeRwjhjEQY0NVJz/GRcekPewJDRoeIMJWHt4bNwcwIi9v8Qbxq63W +yKthoy9DxLCyLfzDlml7forkzMA5EpBCYMnMNWju2l+QVl/NHE1bWEnrDgFPZPosPIlY2C8u4rBo +6SI7dYnWRBpl8huXJh0obazovVkdKyT21oQDZogkAHhg8fir/gKya/si+zXmFtGt9i4S5Po1auUZ +uV3bOx4a+9P/FRQI2AlqukWdFHlgfa9Aigdzs5OW03Q0jTo3Kd5c7PXuLjHCINy+8U9/I1LZW+Jk +2ZyqBwi1Rb3R0DHBq1SfqdLDYmAD8bs5SpJKPQq5ncWg/jcCAwEAAaOCATQwggEwMA8GA1UdEwEB +/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTUovyfs8PYA9NXXAek0CSnwPIA1DCB +7QYDVR0fBIHlMIHiMIHfoIHcoIHZhjVodHRwOi8vd3d3LnRydXN0Y2VudGVyLmRlL2NybC92Mi90 +Y19jbGFzc18zX2NhX0lJLmNybIaBn2xkYXA6Ly93d3cudHJ1c3RjZW50ZXIuZGUvQ049VEMlMjBU +cnVzdENlbnRlciUyMENsYXNzJTIwMyUyMENBJTIwSUksTz1UQyUyMFRydXN0Q2VudGVyJTIwR21i +SCxPVT1yb290Y2VydHMsREM9dHJ1c3RjZW50ZXIsREM9ZGU/Y2VydGlmaWNhdGVSZXZvY2F0aW9u +TGlzdD9iYXNlPzANBgkqhkiG9w0BAQUFAAOCAQEANmDkcPcGIEPZIxpC8vijsrlNirTzwppVMXzE +O2eatN9NDoqTSheLG43KieHPOh6sHfGcMrSOWXaiQYUlN6AT0PV8TtXqluJucsG7Kv5sbviRmEb8 +yRtXW+rIGjs/sFGYPAfaLFkB2otE6OF0/ado3VS6g0bsyEa1+K+XwDsJHI/OcpY9M1ZwvJbL2NV9 +IJqDnxrcOfHFcqMRA/07QlIp2+gB95tejNaNhk4Z+rwcvsUhpYeeeC422wlxo3I0+GzjBgnyXlal +092Y+tTmBvTwtiBjS+opvaqCZh77gaqnN60TGOaSw4HBM7uIHqHn4rS9MWwOUT1v+5ZWgOI2F9Hc +5A== +-----END CERTIFICATE----- + +TC TrustCenter Universal CA I +============================= +-----BEGIN CERTIFICATE----- +MIID3TCCAsWgAwIBAgIOHaIAAQAC7LdggHiNtgYwDQYJKoZIhvcNAQEFBQAweTELMAkGA1UEBhMC +REUxHDAaBgNVBAoTE1RDIFRydXN0Q2VudGVyIEdtYkgxJDAiBgNVBAsTG1RDIFRydXN0Q2VudGVy +IFVuaXZlcnNhbCBDQTEmMCQGA1UEAxMdVEMgVHJ1c3RDZW50ZXIgVW5pdmVyc2FsIENBIEkwHhcN +MDYwMzIyMTU1NDI4WhcNMjUxMjMxMjI1OTU5WjB5MQswCQYDVQQGEwJERTEcMBoGA1UEChMTVEMg +VHJ1c3RDZW50ZXIgR21iSDEkMCIGA1UECxMbVEMgVHJ1c3RDZW50ZXIgVW5pdmVyc2FsIENBMSYw +JAYDVQQDEx1UQyBUcnVzdENlbnRlciBVbml2ZXJzYWwgQ0EgSTCCASIwDQYJKoZIhvcNAQEBBQAD +ggEPADCCAQoCggEBAKR3I5ZEr5D0MacQ9CaHnPM42Q9e3s9B6DGtxnSRJJZ4Hgmgm5qVSkr1YnwC +qMqs+1oEdjneX/H5s7/zA1hV0qq34wQi0fiU2iIIAI3TfCZdzHd55yx4Oagmcw6iXSVphU9VDprv +xrlE4Vc93x9UIuVvZaozhDrzznq+VZeujRIPFDPiUHDDSYcTvFHe15gSWu86gzOSBnWLknwSaHtw +ag+1m7Z3W0hZneTvWq3zwZ7U10VOylY0Ibw+F1tvdwxIAUMpsN0/lm7mlaoMwCC2/T42J5zjXM9O +gdwZu5GQfezmlwQek8wiSdeXhrYTCjxDI3d+8NzmzSQfO4ObNDqDNOMCAwEAAaNjMGEwHwYDVR0j +BBgwFoAUkqR1LKSevoFE63n8isWVpesQdXMwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC +AYYwHQYDVR0OBBYEFJKkdSyknr6BROt5/IrFlaXrEHVzMA0GCSqGSIb3DQEBBQUAA4IBAQAo0uCG +1eb4e/CX3CJrO5UUVg8RMKWaTzqwOuAGy2X17caXJ/4l8lfmXpWMPmRgFVp/Lw0BxbFg/UU1z/Cy +vwbZ71q+s2IhtNerNXxTPqYn8aEt2hojnczd7Dwtnic0XQ/CNnm8yUpiLe1r2X1BQ3y2qsrtYbE3 +ghUJGooWMNjsydZHcnhLEEYUjl8Or+zHL6sQ17bxbuyGssLoDZJz3KL0Dzq/YSMQiZxIQG5wALPT +ujdEWBF6AmqI8Dc08BnprNRlc/ZpjGSUOnmFKbAWKwyCPwacx/0QK54PLLae4xW/2TYcuiUaUj0a +7CIMHOCkoj3w6DnPgcB77V0fb8XQC9eY +-----END CERTIFICATE----- + +Deutsche Telekom Root CA 2 +========================== +-----BEGIN CERTIFICATE----- +MIIDnzCCAoegAwIBAgIBJjANBgkqhkiG9w0BAQUFADBxMQswCQYDVQQGEwJERTEcMBoGA1UEChMT +RGV1dHNjaGUgVGVsZWtvbSBBRzEfMB0GA1UECxMWVC1UZWxlU2VjIFRydXN0IENlbnRlcjEjMCEG +A1UEAxMaRGV1dHNjaGUgVGVsZWtvbSBSb290IENBIDIwHhcNOTkwNzA5MTIxMTAwWhcNMTkwNzA5 +MjM1OTAwWjBxMQswCQYDVQQGEwJERTEcMBoGA1UEChMTRGV1dHNjaGUgVGVsZWtvbSBBRzEfMB0G +A1UECxMWVC1UZWxlU2VjIFRydXN0IENlbnRlcjEjMCEGA1UEAxMaRGV1dHNjaGUgVGVsZWtvbSBS +b290IENBIDIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCrC6M14IspFLEUha88EOQ5 +bzVdSq7d6mGNlUn0b2SjGmBmpKlAIoTZ1KXleJMOaAGtuU1cOs7TuKhCQN/Po7qCWWqSG6wcmtoI +KyUn+WkjR/Hg6yx6m/UTAtB+NHzCnjwAWav12gz1MjwrrFDa1sPeg5TKqAyZMg4ISFZbavva4VhY +AUlfckE8FQYBjl2tqriTtM2e66foai1SNNs671x1Udrb8zH57nGYMsRUFUQM+ZtV7a3fGAigo4aK +Se5TBY8ZTNXeWHmb0mocQqvF1afPaA+W5OFhmHZhyJF81j4A4pFQh+GdCuatl9Idxjp9y7zaAzTV +jlsB9WoHtxa2bkp/AgMBAAGjQjBAMB0GA1UdDgQWBBQxw3kbuvVT1xfgiXotF2wKsyudMzAPBgNV +HRMECDAGAQH/AgEFMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQUFAAOCAQEAlGRZrTlk5ynr +E/5aw4sTV8gEJPB0d8Bg42f76Ymmg7+Wgnxu1MM9756AbrsptJh6sTtU6zkXR34ajgv8HzFZMQSy +zhfzLMdiNlXiItiJVbSYSKpk+tYcNthEeFpaIzpXl/V6ME+un2pMSyuOoAPjPuCp1NJ70rOo4nI8 +rZ7/gFnkm0W09juwzTkZmDLl6iFhkOQxIY40sfcvNUqFENrnijchvllj4PKFiDFT1FQUhXB59C4G +dyd1Lx+4ivn+xbrYNuSD7Odlt79jWvNGr4GUN9RBjNYj1h7P9WgbRGOiWrqnNVmh5XAFmw4jV5mU +Cm26OWMohpLzGITY+9HPBVZkVw== +-----END CERTIFICATE----- + +ComSign Secured CA +================== +-----BEGIN CERTIFICATE----- +MIIDqzCCApOgAwIBAgIRAMcoRwmzuGxFjB36JPU2TukwDQYJKoZIhvcNAQEFBQAwPDEbMBkGA1UE +AxMSQ29tU2lnbiBTZWN1cmVkIENBMRAwDgYDVQQKEwdDb21TaWduMQswCQYDVQQGEwJJTDAeFw0w +NDAzMjQxMTM3MjBaFw0yOTAzMTYxNTA0NTZaMDwxGzAZBgNVBAMTEkNvbVNpZ24gU2VjdXJlZCBD +QTEQMA4GA1UEChMHQ29tU2lnbjELMAkGA1UEBhMCSUwwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw +ggEKAoIBAQDGtWhfHZQVw6QIVS3joFd67+l0Kru5fFdJGhFeTymHDEjWaueP1H5XJLkGieQcPOqs +49ohgHMhCu95mGwfCP+hUH3ymBvJVG8+pSjsIQQPRbsHPaHA+iqYHU4Gk/v1iDurX8sWv+bznkqH +7Rnqwp9D5PGBpX8QTz7RSmKtUxvLg/8HZaWSLWapW7ha9B20IZFKF3ueMv5WJDmyVIRD9YTC2LxB +kMyd1mja6YJQqTtoz7VdApRgFrFD2UNd3V2Hbuq7s8lr9gOUCXDeFhF6K+h2j0kQmHe5Y1yLM5d1 +9guMsqtb3nQgJT/j8xH5h2iGNXHDHYwt6+UarA9z1YJZQIDTAgMBAAGjgacwgaQwDAYDVR0TBAUw +AwEB/zBEBgNVHR8EPTA7MDmgN6A1hjNodHRwOi8vZmVkaXIuY29tc2lnbi5jby5pbC9jcmwvQ29t +U2lnblNlY3VyZWRDQS5jcmwwDgYDVR0PAQH/BAQDAgGGMB8GA1UdIwQYMBaAFMFL7XC29z58ADsA +j8c+DkWfHl3sMB0GA1UdDgQWBBTBS+1wtvc+fAA7AI/HPg5Fnx5d7DANBgkqhkiG9w0BAQUFAAOC +AQEAFs/ukhNQq3sUnjO2QiBq1BW9Cav8cujvR3qQrFHBZE7piL1DRYHjZiM/EoZNGeQFsOY3wo3a +BijJD4mkU6l1P7CW+6tMM1X5eCZGbxs2mPtCdsGCuY7e+0X5YxtiOzkGynd6qDwJz2w2PQ8KRUtp +FhpFfTMDZflScZAmlaxMDPWLkz/MdXSFmLr/YnpNH4n+rr2UAJm/EaXc4HnFFgt9AmEd6oX5AhVP +51qJThRv4zdLhfXBPGHg/QVBspJ/wx2g0K5SZGBrGMYmnNj1ZOQ2GmKfig8+/21OGVZOIJFsnzQz +OjRXUDpvgV4GxvU+fE6OK85lBi5d0ipTdF7Tbieejw== +-----END CERTIFICATE----- + +Cybertrust Global Root +====================== +-----BEGIN CERTIFICATE----- +MIIDoTCCAomgAwIBAgILBAAAAAABD4WqLUgwDQYJKoZIhvcNAQEFBQAwOzEYMBYGA1UEChMPQ3li +ZXJ0cnVzdCwgSW5jMR8wHQYDVQQDExZDeWJlcnRydXN0IEdsb2JhbCBSb290MB4XDTA2MTIxNTA4 +MDAwMFoXDTIxMTIxNTA4MDAwMFowOzEYMBYGA1UEChMPQ3liZXJ0cnVzdCwgSW5jMR8wHQYDVQQD +ExZDeWJlcnRydXN0IEdsb2JhbCBSb290MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA ++Mi8vRRQZhP/8NN57CPytxrHjoXxEnOmGaoQ25yiZXRadz5RfVb23CO21O1fWLE3TdVJDm71aofW +0ozSJ8bi/zafmGWgE07GKmSb1ZASzxQG9Dvj1Ci+6A74q05IlG2OlTEQXO2iLb3VOm2yHLtgwEZL +AfVJrn5GitB0jaEMAs7u/OePuGtm839EAL9mJRQr3RAwHQeWP032a7iPt3sMpTjr3kfb1V05/Iin +89cqdPHoWqI7n1C6poxFNcJQZZXcY4Lv3b93TZxiyWNzFtApD0mpSPCzqrdsxacwOUBdrsTiXSZT +8M4cIwhhqJQZugRiQOwfOHB3EgZxpzAYXSUnpQIDAQABo4GlMIGiMA4GA1UdDwEB/wQEAwIBBjAP +BgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBS2CHsNesysIEyGVjJez6tuhS1wVzA/BgNVHR8EODA2 +MDSgMqAwhi5odHRwOi8vd3d3Mi5wdWJsaWMtdHJ1c3QuY29tL2NybC9jdC9jdHJvb3QuY3JsMB8G +A1UdIwQYMBaAFLYIew16zKwgTIZWMl7Pq26FLXBXMA0GCSqGSIb3DQEBBQUAA4IBAQBW7wojoFRO +lZfJ+InaRcHUowAl9B8Tq7ejhVhpwjCt2BWKLePJzYFa+HMjWqd8BfP9IjsO0QbE2zZMcwSO5bAi +5MXzLqXZI+O4Tkogp24CJJ8iYGd7ix1yCcUxXOl5n4BHPa2hCwcUPUf/A2kaDAtE52Mlp3+yybh2 +hO0j9n0Hq0V+09+zv+mKts2oomcrUtW3ZfA5TGOgkXmTUg9U3YO7n9GPp1Nzw8v/MOx8BLjYRB+T +X3EJIrduPuocA06dGiBh+4E37F78CkWr1+cXVdCg6mCbpvbjjFspwgZgFJ0tl0ypkxWdYcQBX0jW +WL1WMRJOEcgh4LMRkWXbtKaIOM5V +-----END CERTIFICATE----- + +ePKI Root Certification Authority +================================= +-----BEGIN CERTIFICATE----- +MIIFsDCCA5igAwIBAgIQFci9ZUdcr7iXAF7kBtK8nTANBgkqhkiG9w0BAQUFADBeMQswCQYDVQQG +EwJUVzEjMCEGA1UECgwaQ2h1bmdod2EgVGVsZWNvbSBDby4sIEx0ZC4xKjAoBgNVBAsMIWVQS0kg +Um9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNDEyMjAwMjMxMjdaFw0zNDEyMjAwMjMx +MjdaMF4xCzAJBgNVBAYTAlRXMSMwIQYDVQQKDBpDaHVuZ2h3YSBUZWxlY29tIENvLiwgTHRkLjEq +MCgGA1UECwwhZVBLSSBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIICIjANBgkqhkiG9w0B +AQEFAAOCAg8AMIICCgKCAgEA4SUP7o3biDN1Z82tH306Tm2d0y8U82N0ywEhajfqhFAHSyZbCUNs +IZ5qyNUD9WBpj8zwIuQf5/dqIjG3LBXy4P4AakP/h2XGtRrBp0xtInAhijHyl3SJCRImHJ7K2RKi +lTza6We/CKBk49ZCt0Xvl/T29de1ShUCWH2YWEtgvM3XDZoTM1PRYfl61dd4s5oz9wCGzh1NlDiv +qOx4UXCKXBCDUSH3ET00hl7lSM2XgYI1TBnsZfZrxQWh7kcT1rMhJ5QQCtkkO7q+RBNGMD+XPNjX +12ruOzjjK9SXDrkb5wdJfzcq+Xd4z1TtW0ado4AOkUPB1ltfFLqfpo0kR0BZv3I4sjZsN/+Z0V0O +WQqraffAsgRFelQArr5T9rXn4fg8ozHSqf4hUmTFpmfwdQcGlBSBVcYn5AGPF8Fqcde+S/uUWH1+ +ETOxQvdibBjWzwloPn9s9h6PYq2lY9sJpx8iQkEeb5mKPtf5P0B6ebClAZLSnT0IFaUQAS2zMnao +lQ2zepr7BxB4EW/hj8e6DyUadCrlHJhBmd8hh+iVBmoKs2pHdmX2Os+PYhcZewoozRrSgx4hxyy/ +vv9haLdnG7t4TY3OZ+XkwY63I2binZB1NJipNiuKmpS5nezMirH4JYlcWrYvjB9teSSnUmjDhDXi +Zo1jDiVN1Rmy5nk3pyKdVDECAwEAAaNqMGgwHQYDVR0OBBYEFB4M97Zn8uGSJglFwFU5Lnc/Qkqi +MAwGA1UdEwQFMAMBAf8wOQYEZyoHAAQxMC8wLQIBADAJBgUrDgMCGgUAMAcGBWcqAwAABBRFsMLH +ClZ87lt4DJX5GFPBphzYEDANBgkqhkiG9w0BAQUFAAOCAgEACbODU1kBPpVJufGBuvl2ICO1J2B0 +1GqZNF5sAFPZn/KmsSQHRGoqxqWOeBLoR9lYGxMqXnmbnwoqZ6YlPwZpVnPDimZI+ymBV3QGypzq +KOg4ZyYr8dW1P2WT+DZdjo2NQCCHGervJ8A9tDkPJXtoUHRVnAxZfVo9QZQlUgjgRywVMRnVvwdV +xrsStZf0X4OFunHB2WyBEXYKCrC/gpf36j36+uwtqSiUO1bd0lEursC9CBWMd1I0ltabrNMdjmEP +NXubrjlpC2JgQCA2j6/7Nu4tCEoduL+bXPjqpRugc6bY+G7gMwRfaKonh+3ZwZCc7b3jajWvY9+r +GNm65ulK6lCKD2GTHuItGeIwlDWSXQ62B68ZgI9HkFFLLk3dheLSClIKF5r8GrBQAuUBo2M3IUxE +xJtRmREOc5wGj1QupyheRDmHVi03vYVElOEMSyycw5KFNGHLD7ibSkNS/jQ6fbjpKdx2qcgw+BRx +gMYeNkh0IkFch4LoGHGLQYlE535YW6i4jRPpp2zDR+2zGp1iro2C6pSe3VkQw63d4k3jMdXH7Ojy +sP6SHhYKGvzZ8/gntsm+HbRsZJB/9OTEW9c3rkIO3aQab3yIVMUWbuF6aC74Or8NpDyJO3inTmOD +BCEIZ43ygknQW/2xzQ+DhNQ+IIX3Sj0rnP0qCglN6oH4EZw= +-----END CERTIFICATE----- + +T\xc3\x9c\x42\xC4\xB0TAK UEKAE K\xC3\xB6k Sertifika Hizmet Sa\xC4\x9Flay\xc4\xb1\x63\xc4\xb1s\xc4\xb1 - S\xC3\xBCr\xC3\xBCm 3 +============================================================================================================================= +-----BEGIN CERTIFICATE----- +MIIFFzCCA/+gAwIBAgIBETANBgkqhkiG9w0BAQUFADCCASsxCzAJBgNVBAYTAlRSMRgwFgYDVQQH +DA9HZWJ6ZSAtIEtvY2FlbGkxRzBFBgNVBAoMPlTDvHJraXllIEJpbGltc2VsIHZlIFRla25vbG9q +aWsgQXJhxZ90xLFybWEgS3VydW11IC0gVMOcQsSwVEFLMUgwRgYDVQQLDD9VbHVzYWwgRWxla3Ry +b25payB2ZSBLcmlwdG9sb2ppIEFyYcWfdMSxcm1hIEVuc3RpdMO8c8O8IC0gVUVLQUUxIzAhBgNV +BAsMGkthbXUgU2VydGlmaWthc3lvbiBNZXJrZXppMUowSAYDVQQDDEFUw5xCxLBUQUsgVUVLQUUg +S8O2ayBTZXJ0aWZpa2EgSGl6bWV0IFNhxJ9sYXnEsWPEsXPEsSAtIFPDvHLDvG0gMzAeFw0wNzA4 +MjQxMTM3MDdaFw0xNzA4MjExMTM3MDdaMIIBKzELMAkGA1UEBhMCVFIxGDAWBgNVBAcMD0dlYnpl +IC0gS29jYWVsaTFHMEUGA1UECgw+VMO8cmtpeWUgQmlsaW1zZWwgdmUgVGVrbm9sb2ppayBBcmHF +n3TEsXJtYSBLdXJ1bXUgLSBUw5xCxLBUQUsxSDBGBgNVBAsMP1VsdXNhbCBFbGVrdHJvbmlrIHZl +IEtyaXB0b2xvamkgQXJhxZ90xLFybWEgRW5zdGl0w7xzw7wgLSBVRUtBRTEjMCEGA1UECwwaS2Ft +dSBTZXJ0aWZpa2FzeW9uIE1lcmtlemkxSjBIBgNVBAMMQVTDnELEsFRBSyBVRUtBRSBLw7ZrIFNl +cnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxIC0gU8O8csO8bSAzMIIBIjANBgkqhkiG9w0B +AQEFAAOCAQ8AMIIBCgKCAQEAim1L/xCIOsP2fpTo6iBkcK4hgb46ezzb8R1Sf1n68yJMlaCQvEhO +Eav7t7WNeoMojCZG2E6VQIdhn8WebYGHV2yKO7Rm6sxA/OOqbLLLAdsyv9Lrhc+hDVXDWzhXcLh1 +xnnRFDDtG1hba+818qEhTsXOfJlfbLm4IpNQp81McGq+agV/E5wrHur+R84EpW+sky58K5+eeROR +6Oqeyjh1jmKwlZMq5d/pXpduIF9fhHpEORlAHLpVK/swsoHvhOPc7Jg4OQOFCKlUAwUp8MmPi+oL +hmUZEdPpCSPeaJMDyTYcIW7OjGbxmTDY17PDHfiBLqi9ggtm/oLL4eAagsNAgQIDAQABo0IwQDAd +BgNVHQ4EFgQUvYiHyY/2pAoLquvF/pEjnatKijIwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQF +MAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAB18+kmPNOm3JpIWmgV050vQbTlswyb2zrgxvMTfvCr4 +N5EY3ATIZJkrGG2AA1nJrvhY0D7twyOfaTyGOBye79oneNGEN3GKPEs5z35FBtYt2IpNeBLWrcLT +y9LQQfMmNkqblWwM7uXRQydmwYj3erMgbOqwaSvHIOgMA8RBBZniP+Rr+KCGgceExh/VS4ESshYh +LBOhgLJeDEoTniDYYkCrkOpkSi+sDQESeUWoL4cZaMjihccwsnX5OD+ywJO0a+IDRM5noN+J1q2M +dqMTw5RhK2vZbMEHCiIHhWyFJEapvj+LeISCfiQMnf2BN+MlqO02TpUsyZyQ2uypQjyttgI= +-----END CERTIFICATE----- + +Buypass Class 2 CA 1 +==================== +-----BEGIN CERTIFICATE----- +MIIDUzCCAjugAwIBAgIBATANBgkqhkiG9w0BAQUFADBLMQswCQYDVQQGEwJOTzEdMBsGA1UECgwU +QnV5cGFzcyBBUy05ODMxNjMzMjcxHTAbBgNVBAMMFEJ1eXBhc3MgQ2xhc3MgMiBDQSAxMB4XDTA2 +MTAxMzEwMjUwOVoXDTE2MTAxMzEwMjUwOVowSzELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1eXBh +c3MgQVMtOTgzMTYzMzI3MR0wGwYDVQQDDBRCdXlwYXNzIENsYXNzIDIgQ0EgMTCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAIs8B0XY9t/mx8q6jUPFR42wWsE425KEHK8T1A9vNkYgxC7M +cXA0ojTTNy7Y3Tp3L8DrKehc0rWpkTSHIln+zNvnma+WwajHQN2lFYxuyHyXA8vmIPLXl18xoS83 +0r7uvqmtqEyeIWZDO6i88wmjONVZJMHCR3axiFyCO7srpgTXjAePzdVBHfCuuCkslFJgNJQ72uA4 +0Z0zPhX0kzLFANq1KWYOOngPIVJfAuWSeyXTkh4vFZ2B5J2O6O+JzhRMVB0cgRJNcKi+EAUXfh/R +uFdV7c27UsKwHnjCTTZoy1YmwVLBvXb3WNVyfh9EdrsAiR0WnVE1703CVu9r4Iw7DekCAwEAAaNC +MEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUP42aWYv8e3uco684sDntkHGA1sgwDgYDVR0P +AQH/BAQDAgEGMA0GCSqGSIb3DQEBBQUAA4IBAQAVGn4TirnoB6NLJzKyQJHyIdFkhb5jatLPgcIV +1Xp+DCmsNx4cfHZSldq1fyOhKXdlyTKdqC5Wq2B2zha0jX94wNWZUYN/Xtm+DKhQ7SLHrQVMdvvt +7h5HZPb3J31cKA9FxVxiXqaakZG3Uxcu3K1gnZZkOb1naLKuBctN518fV4bVIJwo+28TOPX2EZL2 +fZleHwzoq0QkKXJAPTZSr4xYkHPB7GEseaHsh7U/2k3ZIQAw3pDaDtMaSKk+hQsUi4y8QZ5q9w5w +wDX3OaJdZtB7WZ+oRxKaJyOkLY4ng5IgodcVf/EuGO70SH8vf/GhGLWhC5SgYiAynB321O+/TIho +-----END CERTIFICATE----- + +Buypass Class 3 CA 1 +==================== +-----BEGIN CERTIFICATE----- +MIIDUzCCAjugAwIBAgIBAjANBgkqhkiG9w0BAQUFADBLMQswCQYDVQQGEwJOTzEdMBsGA1UECgwU +QnV5cGFzcyBBUy05ODMxNjMzMjcxHTAbBgNVBAMMFEJ1eXBhc3MgQ2xhc3MgMyBDQSAxMB4XDTA1 +MDUwOTE0MTMwM1oXDTE1MDUwOTE0MTMwM1owSzELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1eXBh +c3MgQVMtOTgzMTYzMzI3MR0wGwYDVQQDDBRCdXlwYXNzIENsYXNzIDMgQ0EgMTCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAKSO13TZKWTeXx+HgJHqTjnmGcZEC4DVC69TB4sSveZn8AKx +ifZgisRbsELRwCGoy+Gb72RRtqfPFfV0gGgEkKBYouZ0plNTVUhjP5JW3SROjvi6K//zNIqeKNc0 +n6wv1g/xpC+9UrJJhW05NfBEMJNGJPO251P7vGGvqaMU+8IXF4Rs4HyI+MkcVyzwPX6UvCWThOia +AJpFBUJXgPROztmuOfbIUxAMZTpHe2DC1vqRycZxbL2RhzyRhkmr8w+gbCZ2Xhysm3HljbybIR6c +1jh+JIAVMYKWsUnTYjdbiAwKYjT+p0h+mbEwi5A3lRyoH6UsjfRVyNvdWQrCrXig9IsCAwEAAaNC +MEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUOBTmyPCppAP0Tj4io1vy1uCtQHQwDgYDVR0P +AQH/BAQDAgEGMA0GCSqGSIb3DQEBBQUAA4IBAQABZ6OMySU9E2NdFm/soT4JXJEVKirZgCFPBdy7 +pYmrEzMqnji3jG8CcmPHc3ceCQa6Oyh7pEfJYWsICCD8igWKH7y6xsL+z27sEzNxZy5p+qksP2bA +EllNC1QCkoS72xLvg3BweMhT+t/Gxv/ciC8HwEmdMldg0/L2mSlf56oBzKwzqBwKu5HEA6BvtjT5 +htOzdlSY9EqBs1OdTUDs5XcTRa9bqh/YL0yCe/4qxFi7T/ye/QNlGioOw6UgFpRreaaiErS7GqQj +el/wroQk5PMr+4okoyeYZdowdXb8GZHo2+ubPzK/QJcHJrrM85SFSnonk8+QQtS4Wxam58tAA915 +-----END CERTIFICATE----- + +EBG Elektronik Sertifika Hizmet Sa\xC4\x9Flay\xc4\xb1\x63\xc4\xb1s\xc4\xb1 +========================================================================== +-----BEGIN CERTIFICATE----- +MIIF5zCCA8+gAwIBAgIITK9zQhyOdAIwDQYJKoZIhvcNAQEFBQAwgYAxODA2BgNVBAMML0VCRyBF +bGVrdHJvbmlrIFNlcnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxMTcwNQYDVQQKDC5FQkcg +QmlsacWfaW0gVGVrbm9sb2ppbGVyaSB2ZSBIaXptZXRsZXJpIEEuxZ4uMQswCQYDVQQGEwJUUjAe +Fw0wNjA4MTcwMDIxMDlaFw0xNjA4MTQwMDMxMDlaMIGAMTgwNgYDVQQDDC9FQkcgRWxla3Ryb25p +ayBTZXJ0aWZpa2EgSGl6bWV0IFNhxJ9sYXnEsWPEsXPEsTE3MDUGA1UECgwuRUJHIEJpbGnFn2lt +IFRla25vbG9qaWxlcmkgdmUgSGl6bWV0bGVyaSBBLsWeLjELMAkGA1UEBhMCVFIwggIiMA0GCSqG +SIb3DQEBAQUAA4ICDwAwggIKAoICAQDuoIRh0DpqZhAy2DE4f6en5f2h4fuXd7hxlugTlkaDT7by +X3JWbhNgpQGR4lvFzVcfd2NR/y8927k/qqk153nQ9dAktiHq6yOU/im/+4mRDGSaBUorzAzu8T2b +gmmkTPiab+ci2hC6X5L8GCcKqKpE+i4stPtGmggDg3KriORqcsnlZR9uKg+ds+g75AxuetpX/dfr +eYteIAbTdgtsApWjluTLdlHRKJ2hGvxEok3MenaoDT2/F08iiFD9rrbskFBKW5+VQarKD7JK/oCZ +TqNGFav4c0JqwmZ2sQomFd2TkuzbqV9UIlKRcF0T6kjsbgNs2d1s/OsNA/+mgxKb8amTD8UmTDGy +Y5lhcucqZJnSuOl14nypqZoaqsNW2xCaPINStnuWt6yHd6i58mcLlEOzrz5z+kI2sSXFCjEmN1Zn +uqMLfdb3ic1nobc6HmZP9qBVFCVMLDMNpkGMvQQxahByCp0OLna9XvNRiYuoP1Vzv9s6xiQFlpJI +qkuNKgPlV5EQ9GooFW5Hd4RcUXSfGenmHmMWOeMRFeNYGkS9y8RsZteEBt8w9DeiQyJ50hBs37vm +ExH8nYQKE3vwO9D8owrXieqWfo1IhR5kX9tUoqzVegJ5a9KK8GfaZXINFHDk6Y54jzJ0fFfy1tb0 +Nokb+Clsi7n2l9GkLqq+CxnCRelwXQIDAJ3Zo2MwYTAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB +/wQEAwIBBjAdBgNVHQ4EFgQU587GT/wWZ5b6SqMHwQSny2re2kcwHwYDVR0jBBgwFoAU587GT/wW +Z5b6SqMHwQSny2re2kcwDQYJKoZIhvcNAQEFBQADggIBAJuYml2+8ygjdsZs93/mQJ7ANtyVDR2t +FcU22NU57/IeIl6zgrRdu0waypIN30ckHrMk2pGI6YNw3ZPX6bqz3xZaPt7gyPvT/Wwp+BVGoGgm +zJNSroIBk5DKd8pNSe/iWtkqvTDOTLKBtjDOWU/aWR1qeqRFsIImgYZ29fUQALjuswnoT4cCB64k +XPBfrAowzIpAoHMEwfuJJPaaHFy3PApnNgUIMbOv2AFoKuB4j3TeuFGkjGwgPaL7s9QJ/XvCgKqT +bCmYIai7FvOpEl90tYeY8pUm3zTvilORiF0alKM/fCL414i6poyWqD1SNGKfAB5UVUJnxk1Gj7sU +RT0KlhaOEKGXmdXTMIXM3rRyt7yKPBgpaP3ccQfuJDlq+u2lrDgv+R4QDgZxGhBM/nV+/x5XOULK +1+EVoVZVWRvRo68R2E7DpSvvkL/A7IITW43WciyTTo9qKd+FPNMN4KIYEsxVL0e3p5sC/kH2iExt +2qkBR4NkJ2IQgtYSe14DHzSpyZH+r11thie3I6p1GMog57AP14kOpmciY/SDQSsGS7tY1dHXt7kQ +Y9iJSrSq3RZj9W6+YKH47ejWkE8axsWgKdOnIaj1Wjz3x0miIZpKlVIglnKaZsv30oZDfCK+lvm9 +AahH3eU7QPl1K5srRmSGjR70j/sHd9DqSaIcjVIUpgqT +-----END CERTIFICATE----- + +certSIGN ROOT CA +================ +-----BEGIN CERTIFICATE----- +MIIDODCCAiCgAwIBAgIGIAYFFnACMA0GCSqGSIb3DQEBBQUAMDsxCzAJBgNVBAYTAlJPMREwDwYD +VQQKEwhjZXJ0U0lHTjEZMBcGA1UECxMQY2VydFNJR04gUk9PVCBDQTAeFw0wNjA3MDQxNzIwMDRa +Fw0zMTA3MDQxNzIwMDRaMDsxCzAJBgNVBAYTAlJPMREwDwYDVQQKEwhjZXJ0U0lHTjEZMBcGA1UE +CxMQY2VydFNJR04gUk9PVCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALczuX7I +JUqOtdu0KBuqV5Do0SLTZLrTk+jUrIZhQGpgV2hUhE28alQCBf/fm5oqrl0Hj0rDKH/v+yv6efHH +rfAQUySQi2bJqIirr1qjAOm+ukbuW3N7LBeCgV5iLKECZbO9xSsAfsT8AzNXDe3i+s5dRdY4zTW2 +ssHQnIFKquSyAVwdj1+ZxLGt24gh65AIgoDzMKND5pCCrlUoSe1b16kQOA7+j0xbm0bqQfWwCHTD +0IgztnzXdN/chNFDDnU5oSVAKOp4yw4sLjmdjItuFhwvJoIQ4uNllAoEwF73XVv4EOLQunpL+943 +AAAaWyjj0pxzPjKHmKHJUS/X3qwzs08CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8B +Af8EBAMCAcYwHQYDVR0OBBYEFOCMm9slSbPxfIbWskKHC9BroNnkMA0GCSqGSIb3DQEBBQUAA4IB +AQA+0hyJLjX8+HXd5n9liPRyTMks1zJO890ZeUe9jjtbkw9QSSQTaxQGcu8J06Gh40CEyecYMnQ8 +SG4Pn0vU9x7Tk4ZkVJdjclDVVc/6IJMCopvDI5NOFlV2oHB5bc0hH88vLbwZ44gx+FkagQnIl6Z0 +x2DEW8xXjrJ1/RsCCdtZb3KTafcxQdaIOL+Hsr0Wefmq5L6IJd1hJyMctTEHBDa0GpC9oHRxUIlt +vBTjD4au8as+x6AJzKNI0eDbZOeStc+vckNwi/nDhDwTqn6Sm1dTk/pwwpEOMfmbZ13pljheX7Nz +TogVZ96edhBiIL5VaZVDADlN9u6wWk5JRFRYX0KD +-----END CERTIFICATE----- + +CNNIC ROOT +========== +-----BEGIN CERTIFICATE----- +MIIDVTCCAj2gAwIBAgIESTMAATANBgkqhkiG9w0BAQUFADAyMQswCQYDVQQGEwJDTjEOMAwGA1UE +ChMFQ05OSUMxEzARBgNVBAMTCkNOTklDIFJPT1QwHhcNMDcwNDE2MDcwOTE0WhcNMjcwNDE2MDcw +OTE0WjAyMQswCQYDVQQGEwJDTjEOMAwGA1UEChMFQ05OSUMxEzARBgNVBAMTCkNOTklDIFJPT1Qw +ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDTNfc/c3et6FtzF8LRb+1VvG7q6KR5smzD +o+/hn7E7SIX1mlwhIhAsxYLO2uOabjfhhyzcuQxauohV3/2q2x8x6gHx3zkBwRP9SFIhxFXf2tiz +VHa6dLG3fdfA6PZZxU3Iva0fFNrfWEQlMhkqx35+jq44sDB7R3IJMfAw28Mbdim7aXZOV/kbZKKT +VrdvmW7bCgScEeOAH8tjlBAKqeFkgjH5jCftppkA9nCTGPihNIaj3XrCGHn2emU1z5DrvTOTn1Or +czvmmzQgLx3vqR1jGqCA2wMv+SYahtKNu6m+UjqHZ0gNv7Sg2Ca+I19zN38m5pIEo3/PIKe38zrK +y5nLAgMBAAGjczBxMBEGCWCGSAGG+EIBAQQEAwIABzAfBgNVHSMEGDAWgBRl8jGtKvf33VKWCscC +wQ7vptU7ETAPBgNVHRMBAf8EBTADAQH/MAsGA1UdDwQEAwIB/jAdBgNVHQ4EFgQUZfIxrSr3991S +lgrHAsEO76bVOxEwDQYJKoZIhvcNAQEFBQADggEBAEs17szkrr/Dbq2flTtLP1se31cpolnKOOK5 +Gv+e5m4y3R6u6jW39ZORTtpC4cMXYFDy0VwmuYK36m3knITnA3kXr5g9lNvHugDnuL8BV8F3RTIM +O/G0HAiw/VGgod2aHRM2mm23xzy54cXZF/qD1T0VoDy7HgviyJA/qIYM/PmLXoXLT1tLYhFHxUV8 +BS9BsZ4QaRuZluBVeftOhpm4lNqGOGqTo+fLbuXf6iFViZx9fX+Y9QCJ7uOEwFyWtcVG6kbghVW2 +G8kS1sHNzYDzAgE8yGnLRUhj2JTQ7IUOO04RZfSCjKY9ri4ilAnIXOo8gV0WKgOXFlUJ24pBgp5m +mxE= +-----END CERTIFICATE----- + +ApplicationCA - Japanese Government +=================================== +-----BEGIN CERTIFICATE----- +MIIDoDCCAoigAwIBAgIBMTANBgkqhkiG9w0BAQUFADBDMQswCQYDVQQGEwJKUDEcMBoGA1UEChMT +SmFwYW5lc2UgR292ZXJubWVudDEWMBQGA1UECxMNQXBwbGljYXRpb25DQTAeFw0wNzEyMTIxNTAw +MDBaFw0xNzEyMTIxNTAwMDBaMEMxCzAJBgNVBAYTAkpQMRwwGgYDVQQKExNKYXBhbmVzZSBHb3Zl +cm5tZW50MRYwFAYDVQQLEw1BcHBsaWNhdGlvbkNBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB +CgKCAQEAp23gdE6Hj6UG3mii24aZS2QNcfAKBZuOquHMLtJqO8F6tJdhjYq+xpqcBrSGUeQ3DnR4 +fl+Kf5Sk10cI/VBaVuRorChzoHvpfxiSQE8tnfWuREhzNgaeZCw7NCPbXCbkcXmP1G55IrmTwcrN +wVbtiGrXoDkhBFcsovW8R0FPXjQilbUfKW1eSvNNcr5BViCH/OlQR9cwFO5cjFW6WY2H/CPek9AE +jP3vbb3QesmlOmpyM8ZKDQUXKi17safY1vC+9D/qDihtQWEjdnjDuGWk81quzMKq2edY3rZ+nYVu +nyoKb58DKTCXKB28t89UKU5RMfkntigm/qJj5kEW8DOYRwIDAQABo4GeMIGbMB0GA1UdDgQWBBRU +WssmP3HMlEYNllPqa0jQk/5CdTAOBgNVHQ8BAf8EBAMCAQYwWQYDVR0RBFIwUKROMEwxCzAJBgNV +BAYTAkpQMRgwFgYDVQQKDA/ml6XmnKzlm73mlL/lupwxIzAhBgNVBAsMGuOCouODl+ODquOCseOD +vOOCt+ODp+ODs0NBMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBADlqRHZ3ODrs +o2dGD/mLBqj7apAxzn7s2tGJfHrrLgy9mTLnsCTWw//1sogJhyzjVOGjprIIC8CFqMjSnHH2HZ9g +/DgzE+Ge3Atf2hZQKXsvcJEPmbo0NI2VdMV+eKlmXb3KIXdCEKxmJj3ekav9FfBv7WxfEPjzFvYD +io+nEhEMy/0/ecGc/WLuo89UDNErXxc+4z6/wCs+CZv+iKZ+tJIX/COUgb1up8WMwusRRdv4QcmW +dupwX3kSa+SjB1oF7ydJzyGfikwJcGapJsErEU4z0g781mzSDjJkaP+tBXhfAx2o45CsJOAPQKdL +rosot4LKGAfmt1t06SAZf7IbiVQ= +-----END CERTIFICATE----- + +GeoTrust Primary Certification Authority - G3 +============================================= +-----BEGIN CERTIFICATE----- +MIID/jCCAuagAwIBAgIQFaxulBmyeUtB9iepwxgPHzANBgkqhkiG9w0BAQsFADCBmDELMAkGA1UE +BhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xOTA3BgNVBAsTMChjKSAyMDA4IEdlb1RydXN0 +IEluYy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25seTE2MDQGA1UEAxMtR2VvVHJ1c3QgUHJpbWFy +eSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEczMB4XDTA4MDQwMjAwMDAwMFoXDTM3MTIwMTIz +NTk1OVowgZgxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTkwNwYDVQQLEzAo +YykgMjAwOCBHZW9UcnVzdCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxNjA0BgNVBAMT +LUdlb1RydXN0IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHMzCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBANziXmJYHTNXOTIz+uvLh4yn1ErdBojqZI4xmKU4kB6Yzy5j +K/BGvESyiaHAKAxJcCGVn2TAppMSAmUmhsalifD614SgcK9PGpc/BkTVyetyEH3kMSj7HGHmKAdE +c5IiaacDiGydY8hS2pgn5whMcD60yRLBxWeDXTPzAxHsatBT4tG6NmCUgLthY2xbF37fQJQeqw3C +IShwiP/WJmxsYAQlTlV+fe+/lEjetx3dcI0FX4ilm/LC7urRQEFtYjgdVgbFA0dRIBn8exALDmKu +dlW/X3e+PkkBUz2YJQN2JFodtNuJ6nnltrM7P7pMKEF/BqxqjsHQ9gUdfeZChuOl1UcCAwEAAaNC +MEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFMR5yo6hTgMdHNxr +2zFblD4/MH8tMA0GCSqGSIb3DQEBCwUAA4IBAQAtxRPPVoB7eni9n64smefv2t+UXglpp+duaIy9 +cr5HqQ6XErhK8WTTOd8lNNTBzU6B8A8ExCSzNJbGpqow32hhc9f5joWJ7w5elShKKiePEI4ufIbE +Ap7aDHdlDkQNkv39sxY2+hENHYwOB4lqKVb3cvTdFZx3NWZXqxNT2I7BQMXXExZacse3aQHEerGD +AWh9jUGhlBjBJVz88P6DAod8DQ3PLghcSkANPuyBYeYk28rgDi0Hsj5W3I31QYUHSJsMC8tJP33s +t/3LjWeJGqvtux6jAAgIFyqCXDFdRootD4abdNlF+9RAsXqqaC2Gspki4cErx5z481+oghLrGREt +-----END CERTIFICATE----- + +thawte Primary Root CA - G2 +=========================== +-----BEGIN CERTIFICATE----- +MIICiDCCAg2gAwIBAgIQNfwmXNmET8k9Jj1Xm67XVjAKBggqhkjOPQQDAzCBhDELMAkGA1UEBhMC +VVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjE4MDYGA1UECxMvKGMpIDIwMDcgdGhhd3RlLCBJbmMu +IC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxJDAiBgNVBAMTG3RoYXd0ZSBQcmltYXJ5IFJvb3Qg +Q0EgLSBHMjAeFw0wNzExMDUwMDAwMDBaFw0zODAxMTgyMzU5NTlaMIGEMQswCQYDVQQGEwJVUzEV +MBMGA1UEChMMdGhhd3RlLCBJbmMuMTgwNgYDVQQLEy8oYykgMjAwNyB0aGF3dGUsIEluYy4gLSBG +b3IgYXV0aG9yaXplZCB1c2Ugb25seTEkMCIGA1UEAxMbdGhhd3RlIFByaW1hcnkgUm9vdCBDQSAt +IEcyMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEotWcgnuVnfFSeIf+iha/BebfowJPDQfGAFG6DAJS +LSKkQjnE/o/qycG+1E3/n3qe4rF8mq2nhglzh9HnmuN6papu+7qzcMBniKI11KOasf2twu8x+qi5 +8/sIxpHR+ymVo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQU +mtgAMADna3+FGO6Lts6KDPgR4bswCgYIKoZIzj0EAwMDaQAwZgIxAN344FdHW6fmCsO99YCKlzUN +G4k8VIZ3KMqh9HneteY4sPBlcIx/AlTCv//YoT7ZzwIxAMSNlPzcU9LcnXgWHxUzI1NS41oxXZ3K +rr0TKUQNJ1uo52icEvdYPy5yAlejj6EULg== +-----END CERTIFICATE----- + +thawte Primary Root CA - G3 +=========================== +-----BEGIN CERTIFICATE----- +MIIEKjCCAxKgAwIBAgIQYAGXt0an6rS0mtZLL/eQ+zANBgkqhkiG9w0BAQsFADCBrjELMAkGA1UE +BhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2 +aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMvKGMpIDIwMDggdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhv +cml6ZWQgdXNlIG9ubHkxJDAiBgNVBAMTG3RoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EgLSBHMzAeFw0w +ODA0MDIwMDAwMDBaFw0zNzEyMDEyMzU5NTlaMIGuMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMdGhh +d3RlLCBJbmMuMSgwJgYDVQQLEx9DZXJ0aWZpY2F0aW9uIFNlcnZpY2VzIERpdmlzaW9uMTgwNgYD +VQQLEy8oYykgMjAwOCB0aGF3dGUsIEluYy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25seTEkMCIG +A1UEAxMbdGhhd3RlIFByaW1hcnkgUm9vdCBDQSAtIEczMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A +MIIBCgKCAQEAsr8nLPvb2FvdeHsbnndmgcs+vHyu86YnmjSjaDFxODNi5PNxZnmxqWWjpYvVj2At +P0LMqmsywCPLLEHd5N/8YZzic7IilRFDGF/Eth9XbAoFWCLINkw6fKXRz4aviKdEAhN0cXMKQlkC ++BsUa0Lfb1+6a4KinVvnSr0eAXLbS3ToO39/fR8EtCab4LRarEc9VbjXsCZSKAExQGbY2SS99irY +7CFJXJv2eul/VTV+lmuNk5Mny5K76qxAwJ/C+IDPXfRa3M50hqY+bAtTyr2SzhkGcuYMXDhpxwTW +vGzOW/b3aJzcJRVIiKHpqfiYnODz1TEoYRFsZ5aNOZnLwkUkOQIDAQABo0IwQDAPBgNVHRMBAf8E +BTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUrWyqlGCc7eT/+j4KdCtjA/e2Wb8wDQYJ +KoZIhvcNAQELBQADggEBABpA2JVlrAmSicY59BDlqQ5mU1143vokkbvnRFHfxhY0Cu9qRFHqKweK +A3rD6z8KLFIWoCtDuSWQP3CpMyVtRRooOyfPqsMpQhvfO0zAMzRbQYi/aytlryjvsvXDqmbOe1bu +t8jLZ8HJnBoYuMTDSQPxYA5QzUbF83d597YV4Djbxy8ooAw/dyZ02SUS2jHaGh7cKUGRIjxpp7sC +8rZcJwOJ9Abqm+RyguOhCcHpABnTPtRwa7pxpqpYrvS76Wy274fMm7v/OeZWYdMKp8RcTGB7BXcm +er/YB1IsYvdwY9k5vG8cwnncdimvzsUsZAReiDZuMdRAGmI0Nj81Aa6sY6A= +-----END CERTIFICATE----- + +GeoTrust Primary Certification Authority - G2 +============================================= +-----BEGIN CERTIFICATE----- +MIICrjCCAjWgAwIBAgIQPLL0SAoA4v7rJDteYD7DazAKBggqhkjOPQQDAzCBmDELMAkGA1UEBhMC +VVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xOTA3BgNVBAsTMChjKSAyMDA3IEdlb1RydXN0IElu +Yy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25seTE2MDQGA1UEAxMtR2VvVHJ1c3QgUHJpbWFyeSBD +ZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEcyMB4XDTA3MTEwNTAwMDAwMFoXDTM4MDExODIzNTk1 +OVowgZgxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTkwNwYDVQQLEzAoYykg +MjAwNyBHZW9UcnVzdCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxNjA0BgNVBAMTLUdl +b1RydXN0IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHMjB2MBAGByqGSM49AgEG +BSuBBAAiA2IABBWx6P0DFUPlrOuHNxFi79KDNlJ9RVcLSo17VDs6bl8VAsBQps8lL33KSLjHUGMc +KiEIfJo22Av+0SbFWDEwKCXzXV2juLaltJLtbCyf691DiaI8S0iRHVDsJt/WYC69IaNCMEAwDwYD +VR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFBVfNVdRVfslsq0DafwBo/q+ +EVXVMAoGCCqGSM49BAMDA2cAMGQCMGSWWaboCd6LuvpaiIjwH5HTRqjySkwCY/tsXzjbLkGTqQ7m +ndwxHLKgpxgceeHHNgIwOlavmnRs9vuD4DPTCF+hnMJbn0bWtsuRBmOiBuczrD6ogRLQy7rQkgu2 +npaqBA+K +-----END CERTIFICATE----- + +VeriSign Universal Root Certification Authority +=============================================== +-----BEGIN CERTIFICATE----- +MIIEuTCCA6GgAwIBAgIQQBrEZCGzEyEDDrvkEhrFHTANBgkqhkiG9w0BAQsFADCBvTELMAkGA1UE +BhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBO +ZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwOCBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVk +IHVzZSBvbmx5MTgwNgYDVQQDEy9WZXJpU2lnbiBVbml2ZXJzYWwgUm9vdCBDZXJ0aWZpY2F0aW9u +IEF1dGhvcml0eTAeFw0wODA0MDIwMDAwMDBaFw0zNzEyMDEyMzU5NTlaMIG9MQswCQYDVQQGEwJV +UzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdv +cmsxOjA4BgNVBAsTMShjKSAyMDA4IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl +IG9ubHkxODA2BgNVBAMTL1ZlcmlTaWduIFVuaXZlcnNhbCBSb290IENlcnRpZmljYXRpb24gQXV0 +aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx2E3XrEBNNti1xWb/1hajCMj +1mCOkdeQmIN65lgZOIzF9uVkhbSicfvtvbnazU0AtMgtc6XHaXGVHzk8skQHnOgO+k1KxCHfKWGP +MiJhgsWHH26MfF8WIFFE0XBPV+rjHOPMee5Y2A7Cs0WTwCznmhcrewA3ekEzeOEz4vMQGn+HLL72 +9fdC4uW/h2KJXwBL38Xd5HVEMkE6HnFuacsLdUYI0crSK5XQz/u5QGtkjFdN/BMReYTtXlT2NJ8I +AfMQJQYXStrxHXpma5hgZqTZ79IugvHw7wnqRMkVauIDbjPTrJ9VAMf2CGqUuV/c4DPxhGD5WycR +tPwW8rtWaoAljQIDAQABo4GyMIGvMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMG0G +CCsGAQUFBwEMBGEwX6FdoFswWTBXMFUWCWltYWdlL2dpZjAhMB8wBwYFKw4DAhoEFI/l0xqGrI2O +a8PPgGrUSBgsexkuMCUWI2h0dHA6Ly9sb2dvLnZlcmlzaWduLmNvbS92c2xvZ28uZ2lmMB0GA1Ud +DgQWBBS2d/ppSEefUxLVwuoHMnYH0ZcHGTANBgkqhkiG9w0BAQsFAAOCAQEASvj4sAPmLGd75JR3 +Y8xuTPl9Dg3cyLk1uXBPY/ok+myDjEedO2Pzmvl2MpWRsXe8rJq+seQxIcaBlVZaDrHC1LGmWazx +Y8u4TB1ZkErvkBYoH1quEPuBUDgMbMzxPcP1Y+Oz4yHJJDnp/RVmRvQbEdBNc6N9Rvk97ahfYtTx +P/jgdFcrGJ2BtMQo2pSXpXDrrB2+BxHw1dvd5Yzw1TKwg+ZX4o+/vqGqvz0dtdQ46tewXDpPaj+P +wGZsY6rp2aQW9IHRlRQOfc2VNNnSj3BzgXucfr2YYdhFh5iQxeuGMMY1v/D/w1WIg0vvBZIGcfK4 +mJO37M2CYfE45k+XmCpajQ== +-----END CERTIFICATE----- + +VeriSign Class 3 Public Primary Certification Authority - G4 +============================================================ +-----BEGIN CERTIFICATE----- +MIIDhDCCAwqgAwIBAgIQL4D+I4wOIg9IZxIokYesszAKBggqhkjOPQQDAzCByjELMAkGA1UEBhMC +VVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3 +b3JrMTowOAYDVQQLEzEoYykgMjAwNyBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVz +ZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmlj +YXRpb24gQXV0aG9yaXR5IC0gRzQwHhcNMDcxMTA1MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCByjEL +MAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBU +cnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNyBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRo +b3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5 +IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzQwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAASnVnp8 +Utpkmw4tXNherJI9/gHmGUo9FANL+mAnINmDiWn6VMaaGF5VKmTeBvaNSjutEDxlPZCIBIngMGGz +rl0Bp3vefLK+ymVhAIau2o970ImtTR1ZmkGxvEeA3J5iw/mjgbIwga8wDwYDVR0TAQH/BAUwAwEB +/zAOBgNVHQ8BAf8EBAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2UvZ2lmMCEw +HzAHBgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVyaXNpZ24u +Y29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFLMWkf3upm7ktS5Jj4d4gYDs5bG1MAoGCCqGSM49BAMD +A2gAMGUCMGYhDBgmYFo4e1ZC4Kf8NoRRkSAsdk1DPcQdhCPQrNZ8NQbOzWm9kA3bbEhCHQ6qQgIx +AJw9SDkjOVgaFRJZap7v1VmyHVIsmXHNxynfGyphe3HR3vPA5Q06Sqotp9iGKt0uEA== +-----END CERTIFICATE----- + +NetLock Arany (Class Gold) Főtanúsítvány +============================================ +-----BEGIN CERTIFICATE----- +MIIEFTCCAv2gAwIBAgIGSUEs5AAQMA0GCSqGSIb3DQEBCwUAMIGnMQswCQYDVQQGEwJIVTERMA8G +A1UEBwwIQnVkYXBlc3QxFTATBgNVBAoMDE5ldExvY2sgS2Z0LjE3MDUGA1UECwwuVGFuw7pzw610 +dsOhbnlraWFkw7NrIChDZXJ0aWZpY2F0aW9uIFNlcnZpY2VzKTE1MDMGA1UEAwwsTmV0TG9jayBB +cmFueSAoQ2xhc3MgR29sZCkgRsWRdGFuw7pzw610dsOhbnkwHhcNMDgxMjExMTUwODIxWhcNMjgx +MjA2MTUwODIxWjCBpzELMAkGA1UEBhMCSFUxETAPBgNVBAcMCEJ1ZGFwZXN0MRUwEwYDVQQKDAxO +ZXRMb2NrIEtmdC4xNzA1BgNVBAsMLlRhbsO6c8OtdHbDoW55a2lhZMOzayAoQ2VydGlmaWNhdGlv +biBTZXJ2aWNlcykxNTAzBgNVBAMMLE5ldExvY2sgQXJhbnkgKENsYXNzIEdvbGQpIEbFkXRhbsO6 +c8OtdHbDoW55MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxCRec75LbRTDofTjl5Bu +0jBFHjzuZ9lk4BqKf8owyoPjIMHj9DrTlF8afFttvzBPhCf2nx9JvMaZCpDyD/V/Q4Q3Y1GLeqVw +/HpYzY6b7cNGbIRwXdrzAZAj/E4wqX7hJ2Pn7WQ8oLjJM2P+FpD/sLj916jAwJRDC7bVWaaeVtAk +H3B5r9s5VA1lddkVQZQBr17s9o3x/61k/iCa11zr/qYfCGSji3ZVrR47KGAuhyXoqq8fxmRGILdw +fzzeSNuWU7c5d+Qa4scWhHaXWy+7GRWF+GmF9ZmnqfI0p6m2pgP8b4Y9VHx2BJtr+UBdADTHLpl1 +neWIA6pN+APSQnbAGwIDAKiLo0UwQzASBgNVHRMBAf8ECDAGAQH/AgEEMA4GA1UdDwEB/wQEAwIB +BjAdBgNVHQ4EFgQUzPpnk/C2uNClwB7zU/2MU9+D15YwDQYJKoZIhvcNAQELBQADggEBAKt/7hwW +qZw8UQCgwBEIBaeZ5m8BiFRhbvG5GK1Krf6BQCOUL/t1fC8oS2IkgYIL9WHxHG64YTjrgfpioTta +YtOUZcTh5m2C+C8lcLIhJsFyUR+MLMOEkMNaj7rP9KdlpeuY0fsFskZ1FSNqb4VjMIDw1Z4fKRzC +bLBQWV2QWzuoDTDPv31/zvGdg73JRm4gpvlhUbohL3u+pRVjodSVh/GeufOJ8z2FuLjbvrW5Kfna +NwUASZQDhETnv0Mxz3WLJdH0pmT1kvarBes96aULNmLazAZfNou2XjG4Kvte9nHfRCaexOYNkbQu +dZWAUWpLMKawYqGT8ZvYzsRjdT9ZR7E= +-----END CERTIFICATE----- + +Staat der Nederlanden Root CA - G2 +================================== +-----BEGIN CERTIFICATE----- +MIIFyjCCA7KgAwIBAgIEAJiWjDANBgkqhkiG9w0BAQsFADBaMQswCQYDVQQGEwJOTDEeMBwGA1UE +CgwVU3RhYXQgZGVyIE5lZGVybGFuZGVuMSswKQYDVQQDDCJTdGFhdCBkZXIgTmVkZXJsYW5kZW4g +Um9vdCBDQSAtIEcyMB4XDTA4MDMyNjExMTgxN1oXDTIwMDMyNTExMDMxMFowWjELMAkGA1UEBhMC +TkwxHjAcBgNVBAoMFVN0YWF0IGRlciBOZWRlcmxhbmRlbjErMCkGA1UEAwwiU3RhYXQgZGVyIE5l +ZGVybGFuZGVuIFJvb3QgQ0EgLSBHMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMVZ +5291qj5LnLW4rJ4L5PnZyqtdj7U5EILXr1HgO+EASGrP2uEGQxGZqhQlEq0i6ABtQ8SpuOUfiUtn +vWFI7/3S4GCI5bkYYCjDdyutsDeqN95kWSpGV+RLufg3fNU254DBtvPUZ5uW6M7XxgpT0GtJlvOj +CwV3SPcl5XCsMBQgJeN/dVrlSPhOewMHBPqCYYdu8DvEpMfQ9XQ+pV0aCPKbJdL2rAQmPlU6Yiil +e7Iwr/g3wtG61jj99O9JMDeZJiFIhQGp5Rbn3JBV3w/oOM2ZNyFPXfUib2rFEhZgF1XyZWampzCR +OME4HYYEhLoaJXhena/MUGDWE4dS7WMfbWV9whUYdMrhfmQpjHLYFhN9C0lK8SgbIHRrxT3dsKpI +CT0ugpTNGmXZK4iambwYfp/ufWZ8Pr2UuIHOzZgweMFvZ9C+X+Bo7d7iscksWXiSqt8rYGPy5V65 +48r6f1CGPqI0GAwJaCgRHOThuVw+R7oyPxjMW4T182t0xHJ04eOLoEq9jWYv6q012iDTiIJh8BIi +trzQ1aTsr1SIJSQ8p22xcik/Plemf1WvbibG/ufMQFxRRIEKeN5KzlW/HdXZt1bv8Hb/C3m1r737 +qWmRRpdogBQ2HbN/uymYNqUg+oJgYjOk7Na6B6duxc8UpufWkjTYgfX8HV2qXB72o007uPc5AgMB +AAGjgZcwgZQwDwYDVR0TAQH/BAUwAwEB/zBSBgNVHSAESzBJMEcGBFUdIAAwPzA9BggrBgEFBQcC +ARYxaHR0cDovL3d3dy5wa2lvdmVyaGVpZC5ubC9wb2xpY2llcy9yb290LXBvbGljeS1HMjAOBgNV +HQ8BAf8EBAMCAQYwHQYDVR0OBBYEFJFoMocVHYnitfGsNig0jQt8YojrMA0GCSqGSIb3DQEBCwUA +A4ICAQCoQUpnKpKBglBu4dfYszk78wIVCVBR7y29JHuIhjv5tLySCZa59sCrI2AGeYwRTlHSeYAz ++51IvuxBQ4EffkdAHOV6CMqqi3WtFMTC6GY8ggen5ieCWxjmD27ZUD6KQhgpxrRW/FYQoAUXvQwj +f/ST7ZwaUb7dRUG/kSS0H4zpX897IZmflZ85OkYcbPnNe5yQzSipx6lVu6xiNGI1E0sUOlWDuYaN +kqbG9AclVMwWVxJKgnjIFNkXgiYtXSAfea7+1HAWFpWD2DU5/1JddRwWxRNVz0fMdWVSSt7wsKfk +CpYL+63C4iWEst3kvX5ZbJvw8NjnyvLplzh+ib7M+zkXYT9y2zqR2GUBGR2tUKRXCnxLvJxxcypF +URmFzI79R6d0lR2o0a9OF7FpJsKqeFdbxU2n5Z4FF5TKsl+gSRiNNOkmbEgeqmiSBeGCc1qb3Adb +CG19ndeNIdn8FCCqwkXfP+cAslHkwvgFuXkajDTznlvkN1trSt8sV4pAWja63XVECDdCcAz+3F4h +oKOKwJCcaNpQ5kUQR3i2TtJlycM33+FCY7BXN0Ute4qcvwXqZVUz9zkQxSgqIXobisQk+T8VyJoV +IPVVYpbtbZNQvOSqeK3Zywplh6ZmwcSBo3c6WB4L7oOLnR7SUqTMHW+wmG2UMbX4cQrcufx9MmDm +66+KAQ== +-----END CERTIFICATE----- + +CA Disig +======== +-----BEGIN CERTIFICATE----- +MIIEDzCCAvegAwIBAgIBATANBgkqhkiG9w0BAQUFADBKMQswCQYDVQQGEwJTSzETMBEGA1UEBxMK +QnJhdGlzbGF2YTETMBEGA1UEChMKRGlzaWcgYS5zLjERMA8GA1UEAxMIQ0EgRGlzaWcwHhcNMDYw +MzIyMDEzOTM0WhcNMTYwMzIyMDEzOTM0WjBKMQswCQYDVQQGEwJTSzETMBEGA1UEBxMKQnJhdGlz +bGF2YTETMBEGA1UEChMKRGlzaWcgYS5zLjERMA8GA1UEAxMIQ0EgRGlzaWcwggEiMA0GCSqGSIb3 +DQEBAQUAA4IBDwAwggEKAoIBAQCS9jHBfYj9mQGp2HvycXXxMcbzdWb6UShGhJd4NLxs/LxFWYgm +GErENx+hSkS943EE9UQX4j/8SFhvXJ56CbpRNyIjZkMhsDxkovhqFQ4/61HhVKndBpnXmjxUizkD +Pw/Fzsbrg3ICqB9x8y34dQjbYkzo+s7552oftms1grrijxaSfQUMbEYDXcDtab86wYqg6I7ZuUUo +hwjstMoVvoLdtUSLLa2GDGhibYVW8qwUYzrG0ZmsNHhWS8+2rT+MitcE5eN4TPWGqvWP+j1scaMt +ymfraHtuM6kMgiioTGohQBUgDCZbg8KpFhXAJIJdKxatymP2dACw30PEEGBWZ2NFAgMBAAGjgf8w +gfwwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUjbJJaJ1yCCW5wCf1UJNWSEZx+Y8wDgYDVR0P +AQH/BAQDAgEGMDYGA1UdEQQvMC2BE2Nhb3BlcmF0b3JAZGlzaWcuc2uGFmh0dHA6Ly93d3cuZGlz +aWcuc2svY2EwZgYDVR0fBF8wXTAtoCugKYYnaHR0cDovL3d3dy5kaXNpZy5zay9jYS9jcmwvY2Ff +ZGlzaWcuY3JsMCygKqAohiZodHRwOi8vY2EuZGlzaWcuc2svY2EvY3JsL2NhX2Rpc2lnLmNybDAa +BgNVHSAEEzARMA8GDSuBHpGT5goAAAABAQEwDQYJKoZIhvcNAQEFBQADggEBAF00dGFMrzvY/59t +WDYcPQuBDRIrRhCA/ec8J9B6yKm2fnQwM6M6int0wHl5QpNt/7EpFIKrIYwvF/k/Ji/1WcbvgAa3 +mkkp7M5+cTxqEEHA9tOasnxakZzArFvITV734VP/Q3f8nktnbNfzg9Gg4H8l37iYC5oyOGwwoPP/ +CBUz91BKez6jPiCp3C9WgArtQVCwyfTssuMmRAAOb54GvCKWU3BlxFAKRmukLyeBEicTXxChds6K +ezfqwzlhA5WYOudsiCUI/HloDYd9Yvi0X/vF2Ey9WLw/Q1vUHgFNPGO+I++MzVpQuGhU+QqZMxEA +4Z7CRneC9VkGjCFMhwnN5ag= +-----END CERTIFICATE----- + +Juur-SK +======= +-----BEGIN CERTIFICATE----- +MIIE5jCCA86gAwIBAgIEO45L/DANBgkqhkiG9w0BAQUFADBdMRgwFgYJKoZIhvcNAQkBFglwa2lA +c2suZWUxCzAJBgNVBAYTAkVFMSIwIAYDVQQKExlBUyBTZXJ0aWZpdHNlZXJpbWlza2Vza3VzMRAw +DgYDVQQDEwdKdXVyLVNLMB4XDTAxMDgzMDE0MjMwMVoXDTE2MDgyNjE0MjMwMVowXTEYMBYGCSqG +SIb3DQEJARYJcGtpQHNrLmVlMQswCQYDVQQGEwJFRTEiMCAGA1UEChMZQVMgU2VydGlmaXRzZWVy +aW1pc2tlc2t1czEQMA4GA1UEAxMHSnV1ci1TSzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC +ggEBAIFxNj4zB9bjMI0TfncyRsvPGbJgMUaXhvSYRqTCZUXP00B841oiqBB4M8yIsdOBSvZiF3tf +TQou0M+LI+5PAk676w7KvRhj6IAcjeEcjT3g/1tf6mTll+g/mX8MCgkzABpTpyHhOEvWgxutr2TC ++Rx6jGZITWYfGAriPrsfB2WThbkasLnE+w0R9vXW+RvHLCu3GFH+4Hv2qEivbDtPL+/40UceJlfw +UR0zlv/vWT3aTdEVNMfqPxZIe5EcgEMPPbgFPtGzlc3Yyg/CQ2fbt5PgIoIuvvVoKIO5wTtpeyDa +Tpxt4brNj3pssAki14sL2xzVWiZbDcDq5WDQn/413z8CAwEAAaOCAawwggGoMA8GA1UdEwEB/wQF +MAMBAf8wggEWBgNVHSAEggENMIIBCTCCAQUGCisGAQQBzh8BAQEwgfYwgdAGCCsGAQUFBwICMIHD +HoHAAFMAZQBlACAAcwBlAHIAdABpAGYAaQBrAGEAYQB0ACAAbwBuACAAdgDkAGwAagBhAHMAdABh +AHQAdQBkACAAQQBTAC0AaQBzACAAUwBlAHIAdABpAGYAaQB0AHMAZQBlAHIAaQBtAGkAcwBrAGUA +cwBrAHUAcwAgAGEAbABhAG0ALQBTAEsAIABzAGUAcgB0AGkAZgBpAGsAYQBhAHQAaQBkAGUAIABr +AGkAbgBuAGkAdABhAG0AaQBzAGUAawBzMCEGCCsGAQUFBwIBFhVodHRwOi8vd3d3LnNrLmVlL2Nw +cy8wKwYDVR0fBCQwIjAgoB6gHIYaaHR0cDovL3d3dy5zay5lZS9qdXVyL2NybC8wHQYDVR0OBBYE +FASqekej5ImvGs8KQKcYP2/v6X2+MB8GA1UdIwQYMBaAFASqekej5ImvGs8KQKcYP2/v6X2+MA4G +A1UdDwEB/wQEAwIB5jANBgkqhkiG9w0BAQUFAAOCAQEAe8EYlFOiCfP+JmeaUOTDBS8rNXiRTHyo +ERF5TElZrMj3hWVcRrs7EKACr81Ptcw2Kuxd/u+gkcm2k298gFTsxwhwDY77guwqYHhpNjbRxZyL +abVAyJRld/JXIWY7zoVAtjNjGr95HvxcHdMdkxuLDF2FvZkwMhgJkVLpfKG6/2SSmuz+Ne6ML678 +IIbsSt4beDI3poHSna9aEhbKmVv8b20OxaAehsmR0FyYgl9jDIpaq9iVpszLita/ZEuOyoqysOkh +Mp6qqIWYNIE5ITuoOlIyPfZrN4YGWhWY3PARZv40ILcD9EEQfTmEeZZyY7aWAuVrua0ZTbvGRNs2 +yyqcjg== +-----END CERTIFICATE----- + +Hongkong Post Root CA 1 +======================= +-----BEGIN CERTIFICATE----- +MIIDMDCCAhigAwIBAgICA+gwDQYJKoZIhvcNAQEFBQAwRzELMAkGA1UEBhMCSEsxFjAUBgNVBAoT +DUhvbmdrb25nIFBvc3QxIDAeBgNVBAMTF0hvbmdrb25nIFBvc3QgUm9vdCBDQSAxMB4XDTAzMDUx +NTA1MTMxNFoXDTIzMDUxNTA0NTIyOVowRzELMAkGA1UEBhMCSEsxFjAUBgNVBAoTDUhvbmdrb25n +IFBvc3QxIDAeBgNVBAMTF0hvbmdrb25nIFBvc3QgUm9vdCBDQSAxMIIBIjANBgkqhkiG9w0BAQEF +AAOCAQ8AMIIBCgKCAQEArP84tulmAknjorThkPlAj3n54r15/gK97iSSHSL22oVyaf7XPwnU3ZG1 +ApzQjVrhVcNQhrkpJsLj2aDxaQMoIIBFIi1WpztUlVYiWR8o3x8gPW2iNr4joLFutbEnPzlTCeqr +auh0ssJlXI6/fMN4hM2eFvz1Lk8gKgifd/PFHsSaUmYeSF7jEAaPIpjhZY4bXSNmO7ilMlHIhqqh +qZ5/dpTCpmy3QfDVyAY45tQM4vM7TG1QjMSDJ8EThFk9nnV0ttgCXjqQesBCNnLsak3c78QA3xMY +V18meMjWCnl3v/evt3a5pQuEF10Q6m/hq5URX208o1xNg1vysxmKgIsLhwIDAQABoyYwJDASBgNV +HRMBAf8ECDAGAQH/AgEDMA4GA1UdDwEB/wQEAwIBxjANBgkqhkiG9w0BAQUFAAOCAQEADkbVPK7i +h9legYsCmEEIjEy82tvuJxuC52pF7BaLT4Wg87JwvVqWuspube5Gi27nKi6Wsxkz67SfqLI37pio +l7Yutmcn1KZJ/RyTZXaeQi/cImyaT/JaFTmxcdcrUehtHJjA2Sr0oYJ71clBoiMBdDhViw+5Lmei +IAQ32pwL0xch4I+XeTRvhEgCIDMb5jREn5Fw9IBehEPCKdJsEhTkYY2sEJCehFC78JZvRZ+K88ps +T/oROhUVRsPNH4NbLUES7VBnQRM9IauUiqpOfMGx+6fWtScvl6tu4B3i0RwsH0Ti/L6RoZz71ilT +c4afU9hDDl3WY4JxHYB0yvbiAmvZWg== +-----END CERTIFICATE----- + +SecureSign RootCA11 +=================== +-----BEGIN CERTIFICATE----- +MIIDbTCCAlWgAwIBAgIBATANBgkqhkiG9w0BAQUFADBYMQswCQYDVQQGEwJKUDErMCkGA1UEChMi +SmFwYW4gQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcywgSW5jLjEcMBoGA1UEAxMTU2VjdXJlU2lnbiBS +b290Q0ExMTAeFw0wOTA0MDgwNDU2NDdaFw0yOTA0MDgwNDU2NDdaMFgxCzAJBgNVBAYTAkpQMSsw +KQYDVQQKEyJKYXBhbiBDZXJ0aWZpY2F0aW9uIFNlcnZpY2VzLCBJbmMuMRwwGgYDVQQDExNTZWN1 +cmVTaWduIFJvb3RDQTExMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA/XeqpRyQBTvL +TJszi1oURaTnkBbR31fSIRCkF/3frNYfp+TbfPfs37gD2pRY/V1yfIw/XwFndBWW4wI8h9uuywGO +wvNmxoVF9ALGOrVisq/6nL+k5tSAMJjzDbaTj6nU2DbysPyKyiyhFTOVMdrAG/LuYpmGYz+/3ZMq +g6h2uRMft85OQoWPIucuGvKVCbIFtUROd6EgvanyTgp9UK31BQ1FT0Zx/Sg+U/sE2C3XZR1KG/rP +O7AxmjVuyIsG0wCR8pQIZUyxNAYAeoni8McDWc/V1uinMrPmmECGxc0nEovMe863ETxiYAcjPitA +bpSACW22s293bzUIUPsCh8U+iQIDAQABo0IwQDAdBgNVHQ4EFgQUW/hNT7KlhtQ60vFjmqC+CfZX +t94wDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAKCh +OBZmLqdWHyGcBvod7bkixTgm2E5P7KN/ed5GIaGHd48HCJqypMWvDzKYC3xmKbabfSVSSUOrTC4r +bnpwrxYO4wJs+0LmGJ1F2FXI6Dvd5+H0LgscNFxsWEr7jIhQX5Ucv+2rIrVls4W6ng+4reV6G4pQ +Oh29Dbx7VFALuUKvVaAYga1lme++5Jy/xIWrQbJUb9wlze144o4MjQlJ3WN7WmmWAiGovVJZ6X01 +y8hSyn+B/tlr0/cR7SXf+Of5pPpyl4RTDaXQMhhRdlkUbA/r7F+AjHVDg8OFmP9Mni0N5HeDk061 +lgeLKBObjBmNQSdJQO7e5iNEOdyhIta6A/I= +-----END CERTIFICATE----- + +ACEDICOM Root +============= +-----BEGIN CERTIFICATE----- +MIIFtTCCA52gAwIBAgIIYY3HhjsBggUwDQYJKoZIhvcNAQEFBQAwRDEWMBQGA1UEAwwNQUNFRElD +T00gUm9vdDEMMAoGA1UECwwDUEtJMQ8wDQYDVQQKDAZFRElDT00xCzAJBgNVBAYTAkVTMB4XDTA4 +MDQxODE2MjQyMloXDTI4MDQxMzE2MjQyMlowRDEWMBQGA1UEAwwNQUNFRElDT00gUm9vdDEMMAoG +A1UECwwDUEtJMQ8wDQYDVQQKDAZFRElDT00xCzAJBgNVBAYTAkVTMIICIjANBgkqhkiG9w0BAQEF +AAOCAg8AMIICCgKCAgEA/5KV4WgGdrQsyFhIyv2AVClVYyT/kGWbEHV7w2rbYgIB8hiGtXxaOLHk +WLn709gtn70yN78sFW2+tfQh0hOR2QetAQXW8713zl9CgQr5auODAKgrLlUTY4HKRxx7XBZXehuD +YAQ6PmXDzQHe3qTWDLqO3tkE7hdWIpuPY/1NFgu3e3eM+SW10W2ZEi5PGrjm6gSSrj0RuVFCPYew +MYWveVqc/udOXpJPQ/yrOq2lEiZmueIM15jO1FillUAKt0SdE3QrwqXrIhWYENiLxQSfHY9g5QYb +m8+5eaA9oiM/Qj9r+hwDezCNzmzAv+YbX79nuIQZ1RXve8uQNjFiybwCq0Zfm/4aaJQ0PZCOrfbk +HQl/Sog4P75n/TSW9R28MHTLOO7VbKvU/PQAtwBbhTIWdjPp2KOZnQUAqhbm84F9b32qhm2tFXTT +xKJxqvQUfecyuB+81fFOvW8XAjnXDpVCOscAPukmYxHqC9FK/xidstd7LzrZlvvoHpKuE1XI2Sf2 +3EgbsCTBheN3nZqk8wwRHQ3ItBTutYJXCb8gWH8vIiPYcMt5bMlL8qkqyPyHK9caUPgn6C9D4zq9 +2Fdx/c6mUlv53U3t5fZvie27k5x2IXXwkkwp9y+cAS7+UEaeZAwUswdbxcJzbPEHXEUkFDWug/Fq +TYl6+rPYLWbwNof1K1MCAwEAAaOBqjCBpzAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFKaz +4SsrSbbXc6GqlPUB53NlTKxQMA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUprPhKytJttdzoaqU +9QHnc2VMrFAwRAYDVR0gBD0wOzA5BgRVHSAAMDEwLwYIKwYBBQUHAgEWI2h0dHA6Ly9hY2VkaWNv +bS5lZGljb21ncm91cC5jb20vZG9jMA0GCSqGSIb3DQEBBQUAA4ICAQDOLAtSUWImfQwng4/F9tqg +aHtPkl7qpHMyEVNEskTLnewPeUKzEKbHDZ3Ltvo/Onzqv4hTGzz3gvoFNTPhNahXwOf9jU8/kzJP +eGYDdwdY6ZXIfj7QeQCM8htRM5u8lOk6e25SLTKeI6RF+7YuE7CLGLHdztUdp0J/Vb77W7tH1Pwk +zQSulgUV1qzOMPPKC8W64iLgpq0i5ALudBF/TP94HTXa5gI06xgSYXcGCRZj6hitoocf8seACQl1 +ThCojz2GuHURwCRiipZ7SkXp7FnFvmuD5uHorLUwHv4FB4D54SMNUI8FmP8sX+g7tq3PgbUhh8oI +KiMnMCArz+2UW6yyetLHKKGKC5tNSixthT8Jcjxn4tncB7rrZXtaAWPWkFtPF2Y9fwsZo5NjEFIq +nxQWWOLcpfShFosOkYuByptZ+thrkQdlVV9SH686+5DdaaVbnG0OLLb6zqylfDJKZ0DcMDQj3dcE +I2bw/FWAp/tmGYI1Z2JwOV5vx+qQQEQIHriy1tvuWacNGHk0vFQYXlPKNFHtRQrmjseCNj6nOGOp +MCwXEGCSn1WHElkQwg9naRHMTh5+Spqtr0CodaxWkHS4oJyleW/c6RrIaQXpuvoDs3zk4E7Czp3o +tkYNbn5XOmeUwssfnHdKZ05phkOTOPu220+DkdRgfks+KzgHVZhepA== +-----END CERTIFICATE----- + +Verisign Class 3 Public Primary Certification Authority +======================================================= +-----BEGIN CERTIFICATE----- +MIICPDCCAaUCEDyRMcsf9tAbDpq40ES/Er4wDQYJKoZIhvcNAQEFBQAwXzELMAkGA1UEBhMCVVMx +FzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAzIFB1YmxpYyBQcmltYXJ5 +IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTk2MDEyOTAwMDAwMFoXDTI4MDgwMjIzNTk1OVow +XzELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAz +IFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGfMA0GCSqGSIb3DQEBAQUA +A4GNADCBiQKBgQDJXFme8huKARS0EN8EQNvjV69qRUCPhAwL0TPZ2RHP7gJYHyX3KqhEBarsAx94 +f56TuZoAqiN91qyFomNFx3InzPRMxnVx0jnvT0Lwdd8KkMaOIG+YD/isI19wKTakyYbnsZogy1Ol +hec9vn2a/iRFM9x2Fe0PonFkTGUugWhFpwIDAQABMA0GCSqGSIb3DQEBBQUAA4GBABByUqkFFBky +CEHwxWsKzH4PIRnN5GfcX6kb5sroc50i2JhucwNhkcV8sEVAbkSdjbCxlnRhLQ2pRdKkkirWmnWX +bj9T/UWZYB2oK0z5XqcJ2HUw19JlYD1n1khVdWk/kfVIC0dpImmClr7JyDiGSnoscxlIaU5rfGW/ +D/xwzoiQ +-----END CERTIFICATE----- + +Microsec e-Szigno Root CA 2009 +============================== +-----BEGIN CERTIFICATE----- +MIIECjCCAvKgAwIBAgIJAMJ+QwRORz8ZMA0GCSqGSIb3DQEBCwUAMIGCMQswCQYDVQQGEwJIVTER +MA8GA1UEBwwIQnVkYXBlc3QxFjAUBgNVBAoMDU1pY3Jvc2VjIEx0ZC4xJzAlBgNVBAMMHk1pY3Jv +c2VjIGUtU3ppZ25vIFJvb3QgQ0EgMjAwOTEfMB0GCSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5o +dTAeFw0wOTA2MTYxMTMwMThaFw0yOTEyMzAxMTMwMThaMIGCMQswCQYDVQQGEwJIVTERMA8GA1UE +BwwIQnVkYXBlc3QxFjAUBgNVBAoMDU1pY3Jvc2VjIEx0ZC4xJzAlBgNVBAMMHk1pY3Jvc2VjIGUt +U3ppZ25vIFJvb3QgQ0EgMjAwOTEfMB0GCSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5odTCCASIw +DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOn4j/NjrdqG2KfgQvvPkd6mJviZpWNwrZuuyjNA +fW2WbqEORO7hE52UQlKavXWFdCyoDh2Tthi3jCyoz/tccbna7P7ofo/kLx2yqHWH2Leh5TvPmUpG +0IMZfcChEhyVbUr02MelTTMuhTlAdX4UfIASmFDHQWe4oIBhVKZsTh/gnQ4H6cm6M+f+wFUoLAKA +pxn1ntxVUwOXewdI/5n7N4okxFnMUBBjjqqpGrCEGob5X7uxUG6k0QrM1XF+H6cbfPVTbiJfyyvm +1HxdrtbCxkzlBQHZ7Vf8wSN5/PrIJIOV87VqUQHQd9bpEqH5GoP7ghu5sJf0dgYzQ0mg/wu1+rUC +AwEAAaOBgDB+MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTLD8bf +QkPMPcu1SCOhGnqmKrs0aDAfBgNVHSMEGDAWgBTLD8bfQkPMPcu1SCOhGnqmKrs0aDAbBgNVHREE +FDASgRBpbmZvQGUtc3ppZ25vLmh1MA0GCSqGSIb3DQEBCwUAA4IBAQDJ0Q5eLtXMs3w+y/w9/w0o +lZMEyL/azXm4Q5DwpL7v8u8hmLzU1F0G9u5C7DBsoKqpyvGvivo/C3NqPuouQH4frlRheesuCDfX +I/OMn74dseGkddug4lQUsbocKaQY9hK6ohQU4zE1yED/t+AFdlfBHFny+L/k7SViXITwfn4fs775 +tyERzAMBVnCnEJIeGzSBHq2cGsMEPO0CYdYeBvNfOofyK/FFh+U9rNHHV4S9a67c2Pm2G2JwCz02 +yULyMtd6YebS2z3PyKnJm9zbWETXbzivf3jTo60adbocwTZ8jx5tHMN1Rq41Bab2XD0h7lbwyYIi +LXpUq3DDfSJlgnCW +-----END CERTIFICATE----- + +E-Guven Kok Elektronik Sertifika Hizmet Saglayicisi +=================================================== +-----BEGIN CERTIFICATE----- +MIIDtjCCAp6gAwIBAgIQRJmNPMADJ72cdpW56tustTANBgkqhkiG9w0BAQUFADB1MQswCQYDVQQG +EwJUUjEoMCYGA1UEChMfRWxla3Ryb25payBCaWxnaSBHdXZlbmxpZ2kgQS5TLjE8MDoGA1UEAxMz +ZS1HdXZlbiBLb2sgRWxla3Ryb25payBTZXJ0aWZpa2EgSGl6bWV0IFNhZ2xheWljaXNpMB4XDTA3 +MDEwNDExMzI0OFoXDTE3MDEwNDExMzI0OFowdTELMAkGA1UEBhMCVFIxKDAmBgNVBAoTH0VsZWt0 +cm9uaWsgQmlsZ2kgR3V2ZW5saWdpIEEuUy4xPDA6BgNVBAMTM2UtR3V2ZW4gS29rIEVsZWt0cm9u +aWsgU2VydGlmaWthIEhpem1ldCBTYWdsYXlpY2lzaTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC +AQoCggEBAMMSIJ6wXgBljU5Gu4Bc6SwGl9XzcslwuedLZYDBS75+PNdUMZTe1RK6UxYC6lhj71vY +8+0qGqpxSKPcEC1fX+tcS5yWCEIlKBHMilpiAVDV6wlTL/jDj/6z/P2douNffb7tC+Bg62nsM+3Y +jfsSSYMAyYuXjDtzKjKzEve5TfL0TW3H5tYmNwjy2f1rXKPlSFxYvEK+A1qBuhw1DADT9SN+cTAI +JjjcJRFHLfO6IxClv7wC90Nex/6wN1CZew+TzuZDLMN+DfIcQ2Zgy2ExR4ejT669VmxMvLz4Bcpk +9Ok0oSy1c+HCPujIyTQlCFzz7abHlJ+tiEMl1+E5YP6sOVkCAwEAAaNCMEAwDgYDVR0PAQH/BAQD +AgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFJ/uRLOU1fqRTy7ZVZoEVtstxNulMA0GCSqG +SIb3DQEBBQUAA4IBAQB/X7lTW2M9dTLn+sR0GstG30ZpHFLPqk/CaOv/gKlR6D1id4k9CnU58W5d +F4dvaAXBlGzZXd/aslnLpRCKysw5zZ/rTt5S/wzw9JKp8mxTq5vSR6AfdPebmvEvFZ96ZDAYBzwq +D2fK/A+JYZ1lpTzlvBNbCNvj/+27BrtqBrF6T2XGgv0enIu1De5Iu7i9qgi0+6N8y5/NkHZchpZ4 +Vwpm+Vganf2XKWDeEaaQHBkc7gGWIjQ0LpH5t8Qn0Xvmv/uARFoW5evg1Ao4vOSR49XrXMGs3xtq +fJ7lddK2l4fbzIcrQzqECK+rPNv3PGYxhrCdU3nt+CPeQuMtgvEP5fqX +-----END CERTIFICATE----- + +GlobalSign Root CA - R3 +======================= +-----BEGIN CERTIFICATE----- +MIIDXzCCAkegAwIBAgILBAAAAAABIVhTCKIwDQYJKoZIhvcNAQELBQAwTDEgMB4GA1UECxMXR2xv +YmFsU2lnbiBSb290IENBIC0gUjMxEzARBgNVBAoTCkdsb2JhbFNpZ24xEzARBgNVBAMTCkdsb2Jh +bFNpZ24wHhcNMDkwMzE4MTAwMDAwWhcNMjkwMzE4MTAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxT +aWduIFJvb3QgQ0EgLSBSMzETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2ln +bjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMwldpB5BngiFvXAg7aEyiie/QV2EcWt +iHL8RgJDx7KKnQRfJMsuS+FggkbhUqsMgUdwbN1k0ev1LKMPgj0MK66X17YUhhB5uzsTgHeMCOFJ +0mpiLx9e+pZo34knlTifBtc+ycsmWQ1z3rDI6SYOgxXG71uL0gRgykmmKPZpO/bLyCiR5Z2KYVc3 +rHQU3HTgOu5yLy6c+9C7v/U9AOEGM+iCK65TpjoWc4zdQQ4gOsC0p6Hpsk+QLjJg6VfLuQSSaGjl +OCZgdbKfd/+RFO+uIEn8rUAVSNECMWEZXriX7613t2Saer9fwRPvm2L7DWzgVGkWqQPabumDk3F2 +xmmFghcCAwEAAaNCMEAwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYE +FI/wS3+oLkUkrk1Q+mOai97i3Ru8MA0GCSqGSIb3DQEBCwUAA4IBAQBLQNvAUKr+yAzv95ZURUm7 +lgAJQayzE4aGKAczymvmdLm6AC2upArT9fHxD4q/c2dKg8dEe3jgr25sbwMpjjM5RcOO5LlXbKr8 +EpbsU8Yt5CRsuZRj+9xTaGdWPoO4zzUhw8lo/s7awlOqzJCK6fBdRoyV3XpYKBovHd7NADdBj+1E +bddTKJd+82cEHhXXipa0095MJ6RMG3NzdvQXmcIfeg7jLQitChws/zyrVQ4PkX4268NXSb7hLi18 +YIvDQVETI53O9zJrlAGomecsMx86OyXShkDOOyyGeMlhLxS67ttVb9+E7gUJTb0o2HLO02JQZR7r +kpeDMdmztcpHWD9f +-----END CERTIFICATE----- + +Autoridad de Certificacion Firmaprofesional CIF A62634068 +========================================================= +-----BEGIN CERTIFICATE----- +MIIGFDCCA/ygAwIBAgIIU+w77vuySF8wDQYJKoZIhvcNAQEFBQAwUTELMAkGA1UEBhMCRVMxQjBA +BgNVBAMMOUF1dG9yaWRhZCBkZSBDZXJ0aWZpY2FjaW9uIEZpcm1hcHJvZmVzaW9uYWwgQ0lGIEE2 +MjYzNDA2ODAeFw0wOTA1MjAwODM4MTVaFw0zMDEyMzEwODM4MTVaMFExCzAJBgNVBAYTAkVTMUIw +QAYDVQQDDDlBdXRvcmlkYWQgZGUgQ2VydGlmaWNhY2lvbiBGaXJtYXByb2Zlc2lvbmFsIENJRiBB +NjI2MzQwNjgwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDKlmuO6vj78aI14H9M2uDD +Utd9thDIAl6zQyrET2qyyhxdKJp4ERppWVevtSBC5IsP5t9bpgOSL/UR5GLXMnE42QQMcas9UX4P +B99jBVzpv5RvwSmCwLTaUbDBPLutN0pcyvFLNg4kq7/DhHf9qFD0sefGL9ItWY16Ck6WaVICqjaY +7Pz6FIMMNx/Jkjd/14Et5cS54D40/mf0PmbR0/RAz15iNA9wBj4gGFrO93IbJWyTdBSTo3OxDqqH +ECNZXyAFGUftaI6SEspd/NYrspI8IM/hX68gvqB2f3bl7BqGYTM+53u0P6APjqK5am+5hyZvQWyI +plD9amML9ZMWGxmPsu2bm8mQ9QEM3xk9Dz44I8kvjwzRAv4bVdZO0I08r0+k8/6vKtMFnXkIoctX +MbScyJCyZ/QYFpM6/EfY0XiWMR+6KwxfXZmtY4laJCB22N/9q06mIqqdXuYnin1oKaPnirjaEbsX +LZmdEyRG98Xi2J+Of8ePdG1asuhy9azuJBCtLxTa/y2aRnFHvkLfuwHb9H/TKI8xWVvTyQKmtFLK +bpf7Q8UIJm+K9Lv9nyiqDdVF8xM6HdjAeI9BZzwelGSuewvF6NkBiDkal4ZkQdU7hwxu+g/GvUgU +vzlN1J5Bto+WHWOWk9mVBngxaJ43BjuAiUVhOSPHG0SjFeUc+JIwuwIDAQABo4HvMIHsMBIGA1Ud +EwEB/wQIMAYBAf8CAQEwDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBRlzeurNR4APn7VdMActHNH +DhpkLzCBpgYDVR0gBIGeMIGbMIGYBgRVHSAAMIGPMC8GCCsGAQUFBwIBFiNodHRwOi8vd3d3LmZp +cm1hcHJvZmVzaW9uYWwuY29tL2NwczBcBggrBgEFBQcCAjBQHk4AUABhAHMAZQBvACAAZABlACAA +bABhACAAQgBvAG4AYQBuAG8AdgBhACAANAA3ACAAQgBhAHIAYwBlAGwAbwBuAGEAIAAwADgAMAAx +ADcwDQYJKoZIhvcNAQEFBQADggIBABd9oPm03cXF661LJLWhAqvdpYhKsg9VSytXjDvlMd3+xDLx +51tkljYyGOylMnfX40S2wBEqgLk9am58m9Ot/MPWo+ZkKXzR4Tgegiv/J2Wv+xYVxC5xhOW1//qk +R71kMrv2JYSiJ0L1ILDCExARzRAVukKQKtJE4ZYm6zFIEv0q2skGz3QeqUvVhyj5eTSSPi5E6PaP +T481PyWzOdxjKpBrIF/EUhJOlywqrJ2X3kjyo2bbwtKDlaZmp54lD+kLM5FlClrD2VQS3a/DTg4f +Jl4N3LON7NWBcN7STyQF82xO9UxJZo3R/9ILJUFI/lGExkKvgATP0H5kSeTy36LssUzAKh3ntLFl +osS88Zj0qnAHY7S42jtM+kAiMFsRpvAFDsYCA0irhpuF3dvd6qJ2gHN99ZwExEWN57kci57q13XR +crHedUTnQn3iV2t93Jm8PYMo6oCTjcVMZcFwgbg4/EMxsvYDNEeyrPsiBsse3RdHHF9mudMaotoR +saS8I8nkvof/uZS2+F0gStRf571oe2XyFR7SOqkt6dhrJKyXWERHrVkY8SFlcN7ONGCoQPHzPKTD +KCOM/iczQ0CgFzzr6juwcqajuUpLXhZI9LK8yIySxZ2frHI2vDSANGupi5LAuBft7HZT9SQBjLMi +6Et8Vcad+qMUu2WFbm5PEn4KPJ2V +-----END CERTIFICATE----- + +Izenpe.com +========== +-----BEGIN CERTIFICATE----- +MIIF8TCCA9mgAwIBAgIQALC3WhZIX7/hy/WL1xnmfTANBgkqhkiG9w0BAQsFADA4MQswCQYDVQQG +EwJFUzEUMBIGA1UECgwLSVpFTlBFIFMuQS4xEzARBgNVBAMMCkl6ZW5wZS5jb20wHhcNMDcxMjEz +MTMwODI4WhcNMzcxMjEzMDgyNzI1WjA4MQswCQYDVQQGEwJFUzEUMBIGA1UECgwLSVpFTlBFIFMu +QS4xEzARBgNVBAMMCkl6ZW5wZS5jb20wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDJ +03rKDx6sp4boFmVqscIbRTJxldn+EFvMr+eleQGPicPK8lVx93e+d5TzcqQsRNiekpsUOqHnJJAK +ClaOxdgmlOHZSOEtPtoKct2jmRXagaKH9HtuJneJWK3W6wyyQXpzbm3benhB6QiIEn6HLmYRY2xU ++zydcsC8Lv/Ct90NduM61/e0aL6i9eOBbsFGb12N4E3GVFWJGjMxCrFXuaOKmMPsOzTFlUFpfnXC +PCDFYbpRR6AgkJOhkEvzTnyFRVSa0QUmQbC1TR0zvsQDyCV8wXDbO/QJLVQnSKwv4cSsPsjLkkxT +OTcj7NMB+eAJRE1NZMDhDVqHIrytG6P+JrUV86f8hBnp7KGItERphIPzidF0BqnMC9bC3ieFUCbK +F7jJeodWLBoBHmy+E60QrLUk9TiRodZL2vG70t5HtfG8gfZZa88ZU+mNFctKy6lvROUbQc/hhqfK +0GqfvEyNBjNaooXlkDWgYlwWTvDjovoDGrQscbNYLN57C9saD+veIR8GdwYDsMnvmfzAuU8Lhij+ +0rnq49qlw0dpEuDb8PYZi+17cNcC1u2HGCgsBCRMd+RIihrGO5rUD8r6ddIBQFqNeb+Lz0vPqhbB +leStTIo+F5HUsWLlguWABKQDfo2/2n+iD5dPDNMN+9fR5XJ+HMh3/1uaD7euBUbl8agW7EekFwID +AQABo4H2MIHzMIGwBgNVHREEgagwgaWBD2luZm9AaXplbnBlLmNvbaSBkTCBjjFHMEUGA1UECgw+ +SVpFTlBFIFMuQS4gLSBDSUYgQTAxMzM3MjYwLVJNZXJjLlZpdG9yaWEtR2FzdGVpeiBUMTA1NSBG +NjIgUzgxQzBBBgNVBAkMOkF2ZGEgZGVsIE1lZGl0ZXJyYW5lbyBFdG9yYmlkZWEgMTQgLSAwMTAx +MCBWaXRvcmlhLUdhc3RlaXowDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0O +BBYEFB0cZQ6o8iV7tJHP5LGx5r1VdGwFMA0GCSqGSIb3DQEBCwUAA4ICAQB4pgwWSp9MiDrAyw6l +Fn2fuUhfGI8NYjb2zRlrrKvV9pF9rnHzP7MOeIWblaQnIUdCSnxIOvVFfLMMjlF4rJUT3sb9fbga +kEyrkgPH7UIBzg/YsfqikuFgba56awmqxinuaElnMIAkejEWOVt+8Rwu3WwJrfIxwYJOubv5vr8q +hT/AQKM6WfxZSzwoJNu0FXWuDYi6LnPAvViH5ULy617uHjAimcs30cQhbIHsvm0m5hzkQiCeR7Cs +g1lwLDXWrzY0tM07+DKo7+N4ifuNRSzanLh+QBxh5z6ikixL8s36mLYp//Pye6kfLqCTVyvehQP5 +aTfLnnhqBbTFMXiJ7HqnheG5ezzevh55hM6fcA5ZwjUukCox2eRFekGkLhObNA5me0mrZJfQRsN5 +nXJQY6aYWwa9SG3YOYNw6DXwBdGqvOPbyALqfP2C2sJbUjWumDqtujWTI6cfSN01RpiyEGjkpTHC +ClguGYEQyVB1/OpaFs4R1+7vUIgtYf8/QnMFlEPVjjxOAToZpR9GTnfQXeWBIiGH/pR9hNiTrdZo +Q0iy2+tzJOeRf1SktoA+naM8THLCV8Sg1Mw4J87VBp6iSNnpn86CcDaTmjvfliHjWbcM2pE38P1Z +WrOZyGlsQyYBNWNgVYkDOnXYukrZVP/u3oDYLdE41V4tC5h9Pmzb/CaIxw== +-----END CERTIFICATE----- + +Chambers of Commerce Root - 2008 +================================ +-----BEGIN CERTIFICATE----- +MIIHTzCCBTegAwIBAgIJAKPaQn6ksa7aMA0GCSqGSIb3DQEBBQUAMIGuMQswCQYDVQQGEwJFVTFD +MEEGA1UEBxM6TWFkcmlkIChzZWUgY3VycmVudCBhZGRyZXNzIGF0IHd3dy5jYW1lcmZpcm1hLmNv +bS9hZGRyZXNzKTESMBAGA1UEBRMJQTgyNzQzMjg3MRswGQYDVQQKExJBQyBDYW1lcmZpcm1hIFMu +QS4xKTAnBgNVBAMTIENoYW1iZXJzIG9mIENvbW1lcmNlIFJvb3QgLSAyMDA4MB4XDTA4MDgwMTEy +Mjk1MFoXDTM4MDczMTEyMjk1MFowga4xCzAJBgNVBAYTAkVVMUMwQQYDVQQHEzpNYWRyaWQgKHNl +ZSBjdXJyZW50IGFkZHJlc3MgYXQgd3d3LmNhbWVyZmlybWEuY29tL2FkZHJlc3MpMRIwEAYDVQQF +EwlBODI3NDMyODcxGzAZBgNVBAoTEkFDIENhbWVyZmlybWEgUy5BLjEpMCcGA1UEAxMgQ2hhbWJl +cnMgb2YgQ29tbWVyY2UgUm9vdCAtIDIwMDgwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoIC +AQCvAMtwNyuAWko6bHiUfaN/Gh/2NdW928sNRHI+JrKQUrpjOyhYb6WzbZSm891kDFX29ufyIiKA +XuFixrYp4YFs8r/lfTJqVKAyGVn+H4vXPWCGhSRv4xGzdz4gljUha7MI2XAuZPeEklPWDrCQiorj +h40G072QDuKZoRuGDtqaCrsLYVAGUvGef3bsyw/QHg3PmTA9HMRFEFis1tPo1+XqxQEHd9ZR5gN/ +ikilTWh1uem8nk4ZcfUyS5xtYBkL+8ydddy/Js2Pk3g5eXNeJQ7KXOt3EgfLZEFHcpOrUMPrCXZk +NNI5t3YRCQ12RcSprj1qr7V9ZS+UWBDsXHyvfuK2GNnQm05aSd+pZgvMPMZ4fKecHePOjlO+Bd5g +D2vlGts/4+EhySnB8esHnFIbAURRPHsl18TlUlRdJQfKFiC4reRB7noI/plvg6aRArBsNlVq5331 +lubKgdaX8ZSD6e2wsWsSaR6s+12pxZjptFtYer49okQ6Y1nUCyXeG0+95QGezdIp1Z8XGQpvvwyQ +0wlf2eOKNcx5Wk0ZN5K3xMGtr/R5JJqyAQuxr1yW84Ay+1w9mPGgP0revq+ULtlVmhduYJ1jbLhj +ya6BXBg14JC7vjxPNyK5fuvPnnchpj04gftI2jE9K+OJ9dC1vX7gUMQSibMjmhAxhduub+84Mxh2 +EQIDAQABo4IBbDCCAWgwEgYDVR0TAQH/BAgwBgEB/wIBDDAdBgNVHQ4EFgQU+SSsD7K1+HnA+mCI +G8TZTQKeFxkwgeMGA1UdIwSB2zCB2IAU+SSsD7K1+HnA+mCIG8TZTQKeFxmhgbSkgbEwga4xCzAJ +BgNVBAYTAkVVMUMwQQYDVQQHEzpNYWRyaWQgKHNlZSBjdXJyZW50IGFkZHJlc3MgYXQgd3d3LmNh +bWVyZmlybWEuY29tL2FkZHJlc3MpMRIwEAYDVQQFEwlBODI3NDMyODcxGzAZBgNVBAoTEkFDIENh +bWVyZmlybWEgUy5BLjEpMCcGA1UEAxMgQ2hhbWJlcnMgb2YgQ29tbWVyY2UgUm9vdCAtIDIwMDiC +CQCj2kJ+pLGu2jAOBgNVHQ8BAf8EBAMCAQYwPQYDVR0gBDYwNDAyBgRVHSAAMCowKAYIKwYBBQUH +AgEWHGh0dHA6Ly9wb2xpY3kuY2FtZXJmaXJtYS5jb20wDQYJKoZIhvcNAQEFBQADggIBAJASryI1 +wqM58C7e6bXpeHxIvj99RZJe6dqxGfwWPJ+0W2aeaufDuV2I6A+tzyMP3iU6XsxPpcG1Lawk0lgH +3qLPaYRgM+gQDROpI9CF5Y57pp49chNyM/WqfcZjHwj0/gF/JM8rLFQJ3uIrbZLGOU8W6jx+ekbU +RWpGqOt1glanq6B8aBMz9p0w8G8nOSQjKpD9kCk18pPfNKXG9/jvjA9iSnyu0/VU+I22mlaHFoI6 +M6taIgj3grrqLuBHmrS1RaMFO9ncLkVAO+rcf+g769HsJtg1pDDFOqxXnrN2pSB7+R5KBWIBpih1 +YJeSDW4+TTdDDZIVnBgizVGZoCkaPF+KMjNbMMeJL0eYD6MDxvbxrN8y8NmBGuScvfaAFPDRLLmF +9dijscilIeUcE5fuDr3fKanvNFNb0+RqE4QGtjICxFKuItLcsiFCGtpA8CnJ7AoMXOLQusxI0zcK +zBIKinmwPQN/aUv0NCB9szTqjktk9T79syNnFQ0EuPAtwQlRPLJsFfClI9eDdOTlLsn+mCdCxqvG +nrDQWzilm1DefhiYtUU79nm06PcaewaD+9CL2rvHvRirCG88gGtAPxkZumWK5r7VXNM21+9AUiRg +OGcEMeyP84LG3rlV8zsxkVrctQgVrXYlCg17LofiDKYGvCYQbTed7N14jHyAxfDZd0jQ +-----END CERTIFICATE----- + +Global Chambersign Root - 2008 +============================== +-----BEGIN CERTIFICATE----- +MIIHSTCCBTGgAwIBAgIJAMnN0+nVfSPOMA0GCSqGSIb3DQEBBQUAMIGsMQswCQYDVQQGEwJFVTFD +MEEGA1UEBxM6TWFkcmlkIChzZWUgY3VycmVudCBhZGRyZXNzIGF0IHd3dy5jYW1lcmZpcm1hLmNv +bS9hZGRyZXNzKTESMBAGA1UEBRMJQTgyNzQzMjg3MRswGQYDVQQKExJBQyBDYW1lcmZpcm1hIFMu +QS4xJzAlBgNVBAMTHkdsb2JhbCBDaGFtYmVyc2lnbiBSb290IC0gMjAwODAeFw0wODA4MDExMjMx +NDBaFw0zODA3MzExMjMxNDBaMIGsMQswCQYDVQQGEwJFVTFDMEEGA1UEBxM6TWFkcmlkIChzZWUg +Y3VycmVudCBhZGRyZXNzIGF0IHd3dy5jYW1lcmZpcm1hLmNvbS9hZGRyZXNzKTESMBAGA1UEBRMJ +QTgyNzQzMjg3MRswGQYDVQQKExJBQyBDYW1lcmZpcm1hIFMuQS4xJzAlBgNVBAMTHkdsb2JhbCBD +aGFtYmVyc2lnbiBSb290IC0gMjAwODCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMDf +VtPkOpt2RbQT2//BthmLN0EYlVJH6xedKYiONWwGMi5HYvNJBL99RDaxccy9Wglz1dmFRP+RVyXf +XjaOcNFccUMd2drvXNL7G706tcuto8xEpw2uIRU/uXpbknXYpBI4iRmKt4DS4jJvVpyR1ogQC7N0 +ZJJ0YPP2zxhPYLIj0Mc7zmFLmY/CDNBAspjcDahOo7kKrmCgrUVSY7pmvWjg+b4aqIG7HkF4ddPB +/gBVsIdU6CeQNR1MM62X/JcumIS/LMmjv9GYERTtY/jKmIhYF5ntRQOXfjyGHoiMvvKRhI9lNNgA +TH23MRdaKXoKGCQwoze1eqkBfSbW+Q6OWfH9GzO1KTsXO0G2Id3UwD2ln58fQ1DJu7xsepeY7s2M +H/ucUa6LcL0nn3HAa6x9kGbo1106DbDVwo3VyJ2dwW3Q0L9R5OP4wzg2rtandeavhENdk5IMagfe +Ox2YItaswTXbo6Al/3K1dh3ebeksZixShNBFks4c5eUzHdwHU1SjqoI7mjcv3N2gZOnm3b2u/GSF +HTynyQbehP9r6GsaPMWis0L7iwk+XwhSx2LE1AVxv8Rk5Pihg+g+EpuoHtQ2TS9x9o0o9oOpE9Jh +wZG7SMA0j0GMS0zbaRL/UJScIINZc+18ofLx/d33SdNDWKBWY8o9PeU1VlnpDsogzCtLkykPAgMB +AAGjggFqMIIBZjASBgNVHRMBAf8ECDAGAQH/AgEMMB0GA1UdDgQWBBS5CcqcHtvTbDprru1U8VuT +BjUuXjCB4QYDVR0jBIHZMIHWgBS5CcqcHtvTbDprru1U8VuTBjUuXqGBsqSBrzCBrDELMAkGA1UE +BhMCRVUxQzBBBgNVBAcTOk1hZHJpZCAoc2VlIGN1cnJlbnQgYWRkcmVzcyBhdCB3d3cuY2FtZXJm +aXJtYS5jb20vYWRkcmVzcykxEjAQBgNVBAUTCUE4Mjc0MzI4NzEbMBkGA1UEChMSQUMgQ2FtZXJm +aXJtYSBTLkEuMScwJQYDVQQDEx5HbG9iYWwgQ2hhbWJlcnNpZ24gUm9vdCAtIDIwMDiCCQDJzdPp +1X0jzjAOBgNVHQ8BAf8EBAMCAQYwPQYDVR0gBDYwNDAyBgRVHSAAMCowKAYIKwYBBQUHAgEWHGh0 +dHA6Ly9wb2xpY3kuY2FtZXJmaXJtYS5jb20wDQYJKoZIhvcNAQEFBQADggIBAICIf3DekijZBZRG +/5BXqfEv3xoNa/p8DhxJJHkn2EaqbylZUohwEurdPfWbU1Rv4WCiqAm57OtZfMY18dwY6fFn5a+6 +ReAJ3spED8IXDneRRXozX1+WLGiLwUePmJs9wOzL9dWCkoQ10b42OFZyMVtHLaoXpGNR6woBrX/s +dZ7LoR/xfxKxueRkf2fWIyr0uDldmOghp+G9PUIadJpwr2hsUF1Jz//7Dl3mLEfXgTpZALVza2Mg +9jFFCDkO9HB+QHBaP9BrQql0PSgvAm11cpUJjUhjxsYjV5KTXjXBjfkK9yydYhz2rXzdpjEetrHH +foUm+qRqtdpjMNHvkzeyZi99Bffnt0uYlDXA2TopwZ2yUDMdSqlapskD7+3056huirRXhOukP9Du +qqqHW2Pok+JrqNS4cnhrG+055F3Lm6qH1U9OAP7Zap88MQ8oAgF9mOinsKJknnn4SPIVqczmyETr +P3iZ8ntxPjzxmKfFGBI/5rsoM0LpRQp8bfKGeS/Fghl9CYl8slR2iK7ewfPM4W7bMdaTrpmg7yVq +c5iJWzouE4gev8CSlDQb4ye3ix5vQv/n6TebUB0tovkC7stYWDpxvGjjqsGvHCgfotwjZT+B6q6Z +09gwzxMNTxXJhLynSC34MCN32EZLeW32jO06f2ARePTpm67VVMB0gNELQp/B +-----END CERTIFICATE----- + +Go Daddy Root Certificate Authority - G2 +======================================== +-----BEGIN CERTIFICATE----- +MIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMxEDAOBgNVBAgT +B0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoTEUdvRGFkZHkuY29tLCBJbmMu +MTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5 +MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgYMxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6 +b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjExMC8G +A1UEAxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3gElY6SKDE6bFIEMBO4Tx5oVJnyfq +9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH/PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD ++qK+ihVqf94Lw7YZFAXK6sOoBJQ7RnwyDfMAZiLIjWltNowRGLfTshxgtDj6AozO091GB94KPutd +fMh8+7ArU6SSYmlRJQVhGkSBjCypQ5Yj36w6gZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMl +NAJWJwGRtDtwKj9useiciAF9n9T521NtYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEAAaNC +MEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFDqahQcQZyi27/a9 +BUFuIMGU2g/eMA0GCSqGSIb3DQEBCwUAA4IBAQCZ21151fmXWWcDYfF+OwYxdS2hII5PZYe096ac +vNjpL9DbWu7PdIxztDhC2gV7+AJ1uP2lsdeu9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r +5N9ss4UXnT3ZJE95kTXWXwTrgIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYV +N8Gb5DKj7Tjo2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPO +LPAvTK33sefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI4uJEvlz36hz1 +-----END CERTIFICATE----- + +Starfield Root Certificate Authority - G2 +========================================= +-----BEGIN CERTIFICATE----- +MIID3TCCAsWgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBjzELMAkGA1UEBhMCVVMxEDAOBgNVBAgT +B0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoTHFN0YXJmaWVsZCBUZWNobm9s +b2dpZXMsIEluYy4xMjAwBgNVBAMTKVN0YXJmaWVsZCBSb290IENlcnRpZmljYXRlIEF1dGhvcml0 +eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgY8xCzAJBgNVBAYTAlVTMRAw +DgYDVQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFyZmllbGQg +VGVjaG5vbG9naWVzLCBJbmMuMTIwMAYDVQQDEylTdGFyZmllbGQgUm9vdCBDZXJ0aWZpY2F0ZSBB +dXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL3twQP89o/8ArFv +W59I2Z154qK3A2FWGMNHttfKPTUuiUP3oWmb3ooa/RMgnLRJdzIpVv257IzdIvpy3Cdhl+72WoTs +bhm5iSzchFvVdPtrX8WJpRBSiUZV9Lh1HOZ/5FSuS/hVclcCGfgXcVnrHigHdMWdSL5stPSksPNk +N3mSwOxGXn/hbVNMYq/NHwtjuzqd+/x5AJhhdM8mgkBj87JyahkNmcrUDnXMN/uLicFZ8WJ/X7Nf +ZTD4p7dNdloedl40wOiWVpmKs/B/pM293DIxfJHP4F8R+GuqSVzRmZTRouNjWwl2tVZi4Ut0HZbU +JtQIBFnQmA4O5t78w+wfkPECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC +AQYwHQYDVR0OBBYEFHwMMh+n2TB/xH1oo2Kooc6rB1snMA0GCSqGSIb3DQEBCwUAA4IBAQARWfol +TwNvlJk7mh+ChTnUdgWUXuEok21iXQnCoKjUsHU48TRqneSfioYmUeYs0cYtbpUgSpIB7LiKZ3sx +4mcujJUDJi5DnUox9g61DLu34jd/IroAow57UvtruzvE03lRTs2Q9GcHGcg8RnoNAX3FWOdt5oUw +F5okxBDgBPfg8n/Uqgr/Qh037ZTlZFkSIHc40zI+OIF1lnP6aI+xy84fxez6nH7PfrHxBy22/L/K +pL/QlwVKvOoYKAKQvVR4CSFx09F9HdkWsKlhPdAKACL8x3vLCWRFCztAgfd9fDL1mMpYjn0q7pBZ +c2T5NnReJaH1ZgUufzkVqSr7UIuOhWn0 +-----END CERTIFICATE----- + +Starfield Services Root Certificate Authority - G2 +================================================== +-----BEGIN CERTIFICATE----- +MIID7zCCAtegAwIBAgIBADANBgkqhkiG9w0BAQsFADCBmDELMAkGA1UEBhMCVVMxEDAOBgNVBAgT +B0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoTHFN0YXJmaWVsZCBUZWNobm9s +b2dpZXMsIEluYy4xOzA5BgNVBAMTMlN0YXJmaWVsZCBTZXJ2aWNlcyBSb290IENlcnRpZmljYXRl +IEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgZgxCzAJBgNV +BAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxT +dGFyZmllbGQgVGVjaG5vbG9naWVzLCBJbmMuMTswOQYDVQQDEzJTdGFyZmllbGQgU2VydmljZXMg +Um9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC +AQoCggEBANUMOsQq+U7i9b4Zl1+OiFOxHz/Lz58gE20pOsgPfTz3a3Y4Y9k2YKibXlwAgLIvWX/2 +h/klQ4bnaRtSmpDhcePYLQ1Ob/bISdm28xpWriu2dBTrz/sm4xq6HZYuajtYlIlHVv8loJNwU4Pa +hHQUw2eeBGg6345AWh1KTs9DkTvnVtYAcMtS7nt9rjrnvDH5RfbCYM8TWQIrgMw0R9+53pBlbQLP +LJGmpufehRhJfGZOozptqbXuNC66DQO4M99H67FrjSXZm86B0UVGMpZwh94CDklDhbZsc7tk6mFB +rMnUVN+HL8cisibMn1lUaJ/8viovxFUcdUBgF4UCVTmLfwUCAwEAAaNCMEAwDwYDVR0TAQH/BAUw +AwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFJxfAN+qAdcwKziIorhtSpzyEZGDMA0GCSqG +SIb3DQEBCwUAA4IBAQBLNqaEd2ndOxmfZyMIbw5hyf2E3F/YNoHN2BtBLZ9g3ccaaNnRbobhiCPP +E95Dz+I0swSdHynVv/heyNXBve6SbzJ08pGCL72CQnqtKrcgfU28elUSwhXqvfdqlS5sdJ/PHLTy +xQGjhdByPq1zqwubdQxtRbeOlKyWN7Wg0I8VRw7j6IPdj/3vQQF3zCepYoUz8jcI73HPdwbeyBkd +iEDPfUYd/x7H4c7/I9vG+o1VTqkC50cRRj70/b17KSa7qWFiNyi2LSr2EIZkyXCn0q23KXB56jza +YyWf/Wi3MOxw+3WKt21gZ7IeyLnp2KhvAotnDU0mV3HaIPzBSlCNsSi6 +-----END CERTIFICATE----- + +AffirmTrust Commercial +====================== +-----BEGIN CERTIFICATE----- +MIIDTDCCAjSgAwIBAgIId3cGJyapsXwwDQYJKoZIhvcNAQELBQAwRDELMAkGA1UEBhMCVVMxFDAS +BgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVzdCBDb21tZXJjaWFsMB4XDTEw +MDEyOTE0MDYwNloXDTMwMTIzMTE0MDYwNlowRDELMAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmly +bVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVzdCBDb21tZXJjaWFsMIIBIjANBgkqhkiG9w0BAQEF +AAOCAQ8AMIIBCgKCAQEA9htPZwcroRX1BiLLHwGy43NFBkRJLLtJJRTWzsO3qyxPxkEylFf6Eqdb +DuKPHx6GGaeqtS25Xw2Kwq+FNXkyLbscYjfysVtKPcrNcV/pQr6U6Mje+SJIZMblq8Yrba0F8PrV +C8+a5fBQpIs7R6UjW3p6+DM/uO+Zl+MgwdYoic+U+7lF7eNAFxHUdPALMeIrJmqbTFeurCA+ukV6 +BfO9m2kVrn1OIGPENXY6BwLJN/3HR+7o8XYdcxXyl6S1yHp52UKqK39c/s4mT6NmgTWvRLpUHhww +MmWd5jyTXlBOeuM61G7MGvv50jeuJCqrVwMiKA1JdX+3KNp1v47j3A55MQIDAQABo0IwQDAdBgNV +HQ4EFgQUnZPGU4teyq8/nx4P5ZmVvCT2lI8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC +AQYwDQYJKoZIhvcNAQELBQADggEBAFis9AQOzcAN/wr91LoWXym9e2iZWEnStB03TX8nfUYGXUPG +hi4+c7ImfU+TqbbEKpqrIZcUsd6M06uJFdhrJNTxFq7YpFzUf1GO7RgBsZNjvbz4YYCanrHOQnDi +qX0GJX0nof5v7LMeJNrjS1UaADs1tDvZ110w/YETifLCBivtZ8SOyUOyXGsViQK8YvxO8rUzqrJv +0wqiUOP2O+guRMLbZjipM1ZI8W0bM40NjD9gN53Tym1+NH4Nn3J2ixufcv1SNUFFApYvHLKac0kh +sUlHRUe072o0EclNmsxZt9YCnlpOZbWUrhvfKbAW8b8Angc6F2S1BLUjIZkKlTuXfO8= +-----END CERTIFICATE----- + +AffirmTrust Networking +====================== +-----BEGIN CERTIFICATE----- +MIIDTDCCAjSgAwIBAgIIfE8EORzUmS0wDQYJKoZIhvcNAQEFBQAwRDELMAkGA1UEBhMCVVMxFDAS +BgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVzdCBOZXR3b3JraW5nMB4XDTEw +MDEyOTE0MDgyNFoXDTMwMTIzMTE0MDgyNFowRDELMAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmly +bVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVzdCBOZXR3b3JraW5nMIIBIjANBgkqhkiG9w0BAQEF +AAOCAQ8AMIIBCgKCAQEAtITMMxcua5Rsa2FSoOujz3mUTOWUgJnLVWREZY9nZOIG41w3SfYvm4SE +Hi3yYJ0wTsyEheIszx6e/jarM3c1RNg1lho9Nuh6DtjVR6FqaYvZ/Ls6rnla1fTWcbuakCNrmreI +dIcMHl+5ni36q1Mr3Lt2PpNMCAiMHqIjHNRqrSK6mQEubWXLviRmVSRLQESxG9fhwoXA3hA/Pe24 +/PHxI1Pcv2WXb9n5QHGNfb2V1M6+oF4nI979ptAmDgAp6zxG8D1gvz9Q0twmQVGeFDdCBKNwV6gb +h+0t+nvujArjqWaJGctB+d1ENmHP4ndGyH329JKBNv3bNPFyfvMMFr20FQIDAQABo0IwQDAdBgNV +HQ4EFgQUBx/S55zawm6iQLSwelAQUHTEyL0wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC +AQYwDQYJKoZIhvcNAQEFBQADggEBAIlXshZ6qML91tmbmzTCnLQyFE2npN/svqe++EPbkTfOtDIu +UFUaNU52Q3Eg75N3ThVwLofDwR1t3Mu1J9QsVtFSUzpE0nPIxBsFZVpikpzuQY0x2+c06lkh1QF6 +12S4ZDnNye2v7UsDSKegmQGA3GWjNq5lWUhPgkvIZfFXHeVZLgo/bNjR9eUJtGxUAArgFU2HdW23 +WJZa3W3SAKD0m0i+wzekujbgfIeFlxoVot4uolu9rxj5kFDNcFn4J2dHy8egBzp90SxdbBk6ZrV9 +/ZFvgrG+CJPbFEfxojfHRZ48x3evZKiT3/Zpg4Jg8klCNO1aAFSFHBY2kgxc+qatv9s= +-----END CERTIFICATE----- + +AffirmTrust Premium +=================== +-----BEGIN CERTIFICATE----- +MIIFRjCCAy6gAwIBAgIIbYwURrGmCu4wDQYJKoZIhvcNAQEMBQAwQTELMAkGA1UEBhMCVVMxFDAS +BgNVBAoMC0FmZmlybVRydXN0MRwwGgYDVQQDDBNBZmZpcm1UcnVzdCBQcmVtaXVtMB4XDTEwMDEy +OTE0MTAzNloXDTQwMTIzMTE0MTAzNlowQTELMAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmlybVRy +dXN0MRwwGgYDVQQDDBNBZmZpcm1UcnVzdCBQcmVtaXVtMIICIjANBgkqhkiG9w0BAQEFAAOCAg8A +MIICCgKCAgEAxBLfqV/+Qd3d9Z+K4/as4Tx4mrzY8H96oDMq3I0gW64tb+eT2TZwamjPjlGjhVtn +BKAQJG9dKILBl1fYSCkTtuG+kU3fhQxTGJoeJKJPj/CihQvL9Cl/0qRY7iZNyaqoe5rZ+jjeRFcV +5fiMyNlI4g0WJx0eyIOFJbe6qlVBzAMiSy2RjYvmia9mx+n/K+k8rNrSs8PhaJyJ+HoAVt70VZVs ++7pk3WKL3wt3MutizCaam7uqYoNMtAZ6MMgpv+0GTZe5HMQxK9VfvFMSF5yZVylmd2EhMQcuJUmd +GPLu8ytxjLW6OQdJd/zvLpKQBY0tL3d770O/Nbua2Plzpyzy0FfuKE4mX4+QaAkvuPjcBukumj5R +p9EixAqnOEhss/n/fauGV+O61oV4d7pD6kh/9ti+I20ev9E2bFhc8e6kGVQa9QPSdubhjL08s9NI +S+LI+H+SqHZGnEJlPqQewQcDWkYtuJfzt9WyVSHvutxMAJf7FJUnM7/oQ0dG0giZFmA7mn7S5u04 +6uwBHjxIVkkJx0w3AJ6IDsBz4W9m6XJHMD4Q5QsDyZpCAGzFlH5hxIrff4IaC1nEWTJ3s7xgaVY5 +/bQGeyzWZDbZvUjthB9+pSKPKrhC9IK31FOQeE4tGv2Bb0TXOwF0lkLgAOIua+rF7nKsu7/+6qqo ++Nz2snmKtmcCAwEAAaNCMEAwHQYDVR0OBBYEFJ3AZ6YMItkm9UWrpmVSESfYRaxjMA8GA1UdEwEB +/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBDAUAA4ICAQCzV00QYk465KzquByv +MiPIs0laUZx2KI15qldGF9X1Uva3ROgIRL8YhNILgM3FEv0AVQVhh0HctSSePMTYyPtwni94loMg +Nt58D2kTiKV1NpgIpsbfrM7jWNa3Pt668+s0QNiigfV4Py/VpfzZotReBA4Xrf5B8OWycvpEgjNC +6C1Y91aMYj+6QrCcDFx+LmUmXFNPALJ4fqENmS2NuB2OosSw/WDQMKSOyARiqcTtNd56l+0OOF6S +L5Nwpamcb6d9Ex1+xghIsV5n61EIJenmJWtSKZGc0jlzCFfemQa0W50QBuHCAKi4HEoCChTQwUHK ++4w1IX2COPKpVJEZNZOUbWo6xbLQu4mGk+ibyQ86p3q4ofB4Rvr8Ny/lioTz3/4E2aFooC8k4gmV +BtWVyuEklut89pMFu+1z6S3RdTnX5yTb2E5fQ4+e0BQ5v1VwSJlXMbSc7kqYA5YwH2AG7hsj/oFg +IxpHYoWlzBk0gG+zrBrjn/B7SK3VAdlntqlyk+otZrWyuOQ9PLLvTIzq6we/qzWaVYa8GKa1qF60 +g2xraUDTn9zxw2lrueFtCfTxqlB2Cnp9ehehVZZCmTEJ3WARjQUwfuaORtGdFNrHF+QFlozEJLUb +zxQHskD4o55BhrwE0GuWyCqANP2/7waj3VjFhT0+j/6eKeC2uAloGRwYQw== +-----END CERTIFICATE----- + +AffirmTrust Premium ECC +======================= +-----BEGIN CERTIFICATE----- +MIIB/jCCAYWgAwIBAgIIdJclisc/elQwCgYIKoZIzj0EAwMwRTELMAkGA1UEBhMCVVMxFDASBgNV +BAoMC0FmZmlybVRydXN0MSAwHgYDVQQDDBdBZmZpcm1UcnVzdCBQcmVtaXVtIEVDQzAeFw0xMDAx +MjkxNDIwMjRaFw00MDEyMzExNDIwMjRaMEUxCzAJBgNVBAYTAlVTMRQwEgYDVQQKDAtBZmZpcm1U +cnVzdDEgMB4GA1UEAwwXQWZmaXJtVHJ1c3QgUHJlbWl1bSBFQ0MwdjAQBgcqhkjOPQIBBgUrgQQA +IgNiAAQNMF4bFZ0D0KF5Nbc6PJJ6yhUczWLznCZcBz3lVPqj1swS6vQUX+iOGasvLkjmrBhDeKzQ +N8O9ss0s5kfiGuZjuD0uL3jET9v0D6RoTFVya5UdThhClXjMNzyR4ptlKymjQjBAMB0GA1UdDgQW +BBSaryl6wBE1NSZRMADDav5A1a7WPDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAK +BggqhkjOPQQDAwNnADBkAjAXCfOHiFBar8jAQr9HX/VsaobgxCd05DhT1wV/GzTjxi+zygk8N53X +57hG8f2h4nECMEJZh0PUUd+60wkyWs6Iflc9nF9Ca/UHLbXwgpP5WW+uZPpY5Yse42O+tYHNbwKM +eQ== +-----END CERTIFICATE----- + +Certum Trusted Network CA +========================= +-----BEGIN CERTIFICATE----- +MIIDuzCCAqOgAwIBAgIDBETAMA0GCSqGSIb3DQEBBQUAMH4xCzAJBgNVBAYTAlBMMSIwIAYDVQQK +ExlVbml6ZXRvIFRlY2hub2xvZ2llcyBTLkEuMScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlv +biBBdXRob3JpdHkxIjAgBgNVBAMTGUNlcnR1bSBUcnVzdGVkIE5ldHdvcmsgQ0EwHhcNMDgxMDIy +MTIwNzM3WhcNMjkxMjMxMTIwNzM3WjB+MQswCQYDVQQGEwJQTDEiMCAGA1UEChMZVW5pemV0byBU +ZWNobm9sb2dpZXMgUy5BLjEnMCUGA1UECxMeQ2VydHVtIENlcnRpZmljYXRpb24gQXV0aG9yaXR5 +MSIwIAYDVQQDExlDZXJ0dW0gVHJ1c3RlZCBOZXR3b3JrIENBMIIBIjANBgkqhkiG9w0BAQEFAAOC +AQ8AMIIBCgKCAQEA4/t9o3K6wvDJFIf1awFO4W5AB7ptJ11/91sts1rHUV+rpDKmYYe2bg+G0jAC +l/jXaVehGDldamR5xgFZrDwxSjh80gTSSyjoIF87B6LMTXPb865Px1bVWqeWifrzq2jUI4ZZJ88J +J7ysbnKDHDBy3+Ci6dLhdHUZvSqeexVUBBvXQzmtVSjF4hq79MDkrjhJM8x2hZ85RdKknvISjFH4 +fOQtf/WsX+sWn7Et0brMkUJ3TCXJkDhv2/DM+44el1k+1WBO5gUo7Ul5E0u6SNsv+XLTOcr+H9g0 +cvW0QM8xAcPs3hEtF10fuFDRXhmnad4HMyjKUJX5p1TLVIZQRan5SQIDAQABo0IwQDAPBgNVHRMB +Af8EBTADAQH/MB0GA1UdDgQWBBQIds3LB/8k9sXN7buQvOKEN0Z19zAOBgNVHQ8BAf8EBAMCAQYw +DQYJKoZIhvcNAQEFBQADggEBAKaorSLOAT2mo/9i0Eidi15ysHhE49wcrwn9I0j6vSrEuVUEtRCj +jSfeC4Jj0O7eDDd5QVsisrCaQVymcODU0HfLI9MA4GxWL+FpDQ3Zqr8hgVDZBqWo/5U30Kr+4rP1 +mS1FhIrlQgnXdAIv94nYmem8J9RHjboNRhx3zxSkHLmkMcScKHQDNP8zGSal6Q10tz6XxnboJ5aj +Zt3hrvJBW8qYVoNzcOSGGtIxQbovvi0TWnZvTuhOgQ4/WwMioBK+ZlgRSssDxLQqKi2WF+A5VLxI +03YnnZotBqbJ7DnSq9ufmgsnAjUpsUCV5/nonFWIGUbWtzT1fs45mtk48VH3Tyw= +-----END CERTIFICATE----- + +Certinomis - Autorité Racine +============================= +-----BEGIN CERTIFICATE----- +MIIFnDCCA4SgAwIBAgIBATANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJGUjETMBEGA1UEChMK +Q2VydGlub21pczEXMBUGA1UECxMOMDAwMiA0MzM5OTg5MDMxJjAkBgNVBAMMHUNlcnRpbm9taXMg +LSBBdXRvcml0w6kgUmFjaW5lMB4XDTA4MDkxNzA4Mjg1OVoXDTI4MDkxNzA4Mjg1OVowYzELMAkG +A1UEBhMCRlIxEzARBgNVBAoTCkNlcnRpbm9taXMxFzAVBgNVBAsTDjAwMDIgNDMzOTk4OTAzMSYw +JAYDVQQDDB1DZXJ0aW5vbWlzIC0gQXV0b3JpdMOpIFJhY2luZTCCAiIwDQYJKoZIhvcNAQEBBQAD +ggIPADCCAgoCggIBAJ2Fn4bT46/HsmtuM+Cet0I0VZ35gb5j2CN2DpdUzZlMGvE5x4jYF1AMnmHa +wE5V3udauHpOd4cN5bjr+p5eex7Ezyh0x5P1FMYiKAT5kcOrJ3NqDi5N8y4oH3DfVS9O7cdxbwly +Lu3VMpfQ8Vh30WC8Tl7bmoT2R2FFK/ZQpn9qcSdIhDWerP5pqZ56XjUl+rSnSTV3lqc2W+HN3yNw +2F1MpQiD8aYkOBOo7C+ooWfHpi2GR+6K/OybDnT0K0kCe5B1jPyZOQE51kqJ5Z52qz6WKDgmi92N +jMD2AR5vpTESOH2VwnHu7XSu5DaiQ3XV8QCb4uTXzEIDS3h65X27uK4uIJPT5GHfceF2Z5c/tt9q +c1pkIuVC28+BA5PY9OMQ4HL2AHCs8MF6DwV/zzRpRbWT5BnbUhYjBYkOjUjkJW+zeL9i9Qf6lSTC +lrLooyPCXQP8w9PlfMl1I9f09bze5N/NgL+RiH2nE7Q5uiy6vdFrzPOlKO1Enn1So2+WLhl+HPNb +xxaOu2B9d2ZHVIIAEWBsMsGoOBvrbpgT1u449fCfDu/+MYHB0iSVL1N6aaLwD4ZFjliCK0wi1F6g +530mJ0jfJUaNSih8hp75mxpZuWW/Bd22Ql095gBIgl4g9xGC3srYn+Y3RyYe63j3YcNBZFgCQfna +4NH4+ej9Uji29YnfAgMBAAGjWzBZMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0G +A1UdDgQWBBQNjLZh2kS40RR9w759XkjwzspqsDAXBgNVHSAEEDAOMAwGCiqBegFWAgIAAQEwDQYJ +KoZIhvcNAQEFBQADggIBACQ+YAZ+He86PtvqrxyaLAEL9MW12Ukx9F1BjYkMTv9sov3/4gbIOZ/x +WqndIlgVqIrTseYyCYIDbNc/CMf4uboAbbnW/FIyXaR/pDGUu7ZMOH8oMDX/nyNTt7buFHAAQCva +R6s0fl6nVjBhK4tDrP22iCj1a7Y+YEq6QpA0Z43q619FVDsXrIvkxmUP7tCMXWY5zjKn2BCXwH40 +nJ+U8/aGH88bc62UeYdocMMzpXDn2NU4lG9jeeu/Cg4I58UvD0KgKxRA/yHgBcUn4YQRE7rWhh1B +CxMjidPJC+iKunqjo3M3NYB9Ergzd0A4wPpeMNLytqOx1qKVl4GbUu1pTP+A5FPbVFsDbVRfsbjv +JL1vnxHDx2TCDyhihWZeGnuyt++uNckZM6i4J9szVb9o4XVIRFb7zdNIu0eJOqxp9YDG5ERQL1TE +qkPFMTFYvZbF6nVsmnWxTfj3l/+WFvKXTej28xH5On2KOG4Ey+HTRRWqpdEdnV1j6CTmNhTih60b +WfVEm/vXd3wfAXBioSAaosUaKPQhA+4u2cGA6rnZgtZbdsLLO7XSAPCjDuGtbkD326C00EauFddE +wk01+dIL8hf2rGbVJLJP0RyZwG71fet0BLj5TXcJ17TPBzAJ8bgAVtkXFhYKK4bfjwEZGuW7gmP/ +vgt2Fl43N+bYdJeimUV5 +-----END CERTIFICATE----- + +Root CA Generalitat Valenciana +============================== +-----BEGIN CERTIFICATE----- +MIIGizCCBXOgAwIBAgIEO0XlaDANBgkqhkiG9w0BAQUFADBoMQswCQYDVQQGEwJFUzEfMB0GA1UE +ChMWR2VuZXJhbGl0YXQgVmFsZW5jaWFuYTEPMA0GA1UECxMGUEtJR1ZBMScwJQYDVQQDEx5Sb290 +IENBIEdlbmVyYWxpdGF0IFZhbGVuY2lhbmEwHhcNMDEwNzA2MTYyMjQ3WhcNMjEwNzAxMTUyMjQ3 +WjBoMQswCQYDVQQGEwJFUzEfMB0GA1UEChMWR2VuZXJhbGl0YXQgVmFsZW5jaWFuYTEPMA0GA1UE +CxMGUEtJR1ZBMScwJQYDVQQDEx5Sb290IENBIEdlbmVyYWxpdGF0IFZhbGVuY2lhbmEwggEiMA0G +CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDGKqtXETcvIorKA3Qdyu0togu8M1JAJke+WmmmO3I2 +F0zo37i7L3bhQEZ0ZQKQUgi0/6iMweDHiVYQOTPvaLRfX9ptI6GJXiKjSgbwJ/BXufjpTjJ3Cj9B +ZPPrZe52/lSqfR0grvPXdMIKX/UIKFIIzFVd0g/bmoGlu6GzwZTNVOAydTGRGmKy3nXiz0+J2ZGQ +D0EbtFpKd71ng+CT516nDOeB0/RSrFOyA8dEJvt55cs0YFAQexvba9dHq198aMpunUEDEO5rmXte +JajCq+TA81yc477OMUxkHl6AovWDfgzWyoxVjr7gvkkHD6MkQXpYHYTqWBLI4bft75PelAgxAgMB +AAGjggM7MIIDNzAyBggrBgEFBQcBAQQmMCQwIgYIKwYBBQUHMAGGFmh0dHA6Ly9vY3NwLnBraS5n +dmEuZXMwEgYDVR0TAQH/BAgwBgEB/wIBAjCCAjQGA1UdIASCAiswggInMIICIwYKKwYBBAG/VQIB +ADCCAhMwggHoBggrBgEFBQcCAjCCAdoeggHWAEEAdQB0AG8AcgBpAGQAYQBkACAAZABlACAAQwBl +AHIAdABpAGYAaQBjAGEAYwBpAPMAbgAgAFIAYQDtAHoAIABkAGUAIABsAGEAIABHAGUAbgBlAHIA +YQBsAGkAdABhAHQAIABWAGEAbABlAG4AYwBpAGEAbgBhAC4ADQAKAEwAYQAgAEQAZQBjAGwAYQBy +AGEAYwBpAPMAbgAgAGQAZQAgAFAAcgDhAGMAdABpAGMAYQBzACAAZABlACAAQwBlAHIAdABpAGYA +aQBjAGEAYwBpAPMAbgAgAHEAdQBlACAAcgBpAGcAZQAgAGUAbAAgAGYAdQBuAGMAaQBvAG4AYQBt +AGkAZQBuAHQAbwAgAGQAZQAgAGwAYQAgAHAAcgBlAHMAZQBuAHQAZQAgAEEAdQB0AG8AcgBpAGQA +YQBkACAAZABlACAAQwBlAHIAdABpAGYAaQBjAGEAYwBpAPMAbgAgAHMAZQAgAGUAbgBjAHUAZQBu +AHQAcgBhACAAZQBuACAAbABhACAAZABpAHIAZQBjAGMAaQDzAG4AIAB3AGUAYgAgAGgAdAB0AHAA +OgAvAC8AdwB3AHcALgBwAGsAaQAuAGcAdgBhAC4AZQBzAC8AYwBwAHMwJQYIKwYBBQUHAgEWGWh0 +dHA6Ly93d3cucGtpLmd2YS5lcy9jcHMwHQYDVR0OBBYEFHs100DSHHgZZu90ECjcPk+yeAT8MIGV +BgNVHSMEgY0wgYqAFHs100DSHHgZZu90ECjcPk+yeAT8oWykajBoMQswCQYDVQQGEwJFUzEfMB0G +A1UEChMWR2VuZXJhbGl0YXQgVmFsZW5jaWFuYTEPMA0GA1UECxMGUEtJR1ZBMScwJQYDVQQDEx5S +b290IENBIEdlbmVyYWxpdGF0IFZhbGVuY2lhbmGCBDtF5WgwDQYJKoZIhvcNAQEFBQADggEBACRh +TvW1yEICKrNcda3FbcrnlD+laJWIwVTAEGmiEi8YPyVQqHxK6sYJ2fR1xkDar1CdPaUWu20xxsdz +Ckj+IHLtb8zog2EWRpABlUt9jppSCS/2bxzkoXHPjCpaF3ODR00PNvsETUlR4hTJZGH71BTg9J63 +NI8KJr2XXPR5OkowGcytT6CYirQxlyric21+eLj4iIlPsSKRZEv1UN4D2+XFducTZnV+ZfsBn5OH +iJ35Rld8TWCvmHMTI6QgkYH60GFmuH3Rr9ZvHmw96RH9qfmCIoaZM3Fa6hlXPZHNqcCjbgcTpsnt ++GijnsNacgmHKNHEc8RzGF9QdRYxn7fofMM= +-----END CERTIFICATE----- + +A-Trust-nQual-03 +================ +-----BEGIN CERTIFICATE----- +MIIDzzCCAregAwIBAgIDAWweMA0GCSqGSIb3DQEBBQUAMIGNMQswCQYDVQQGEwJBVDFIMEYGA1UE +Cgw/QS1UcnVzdCBHZXMuIGYuIFNpY2hlcmhlaXRzc3lzdGVtZSBpbSBlbGVrdHIuIERhdGVudmVy +a2VociBHbWJIMRkwFwYDVQQLDBBBLVRydXN0LW5RdWFsLTAzMRkwFwYDVQQDDBBBLVRydXN0LW5R +dWFsLTAzMB4XDTA1MDgxNzIyMDAwMFoXDTE1MDgxNzIyMDAwMFowgY0xCzAJBgNVBAYTAkFUMUgw +RgYDVQQKDD9BLVRydXN0IEdlcy4gZi4gU2ljaGVyaGVpdHNzeXN0ZW1lIGltIGVsZWt0ci4gRGF0 +ZW52ZXJrZWhyIEdtYkgxGTAXBgNVBAsMEEEtVHJ1c3QtblF1YWwtMDMxGTAXBgNVBAMMEEEtVHJ1 +c3QtblF1YWwtMDMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtPWFuA/OQO8BBC4SA +zewqo51ru27CQoT3URThoKgtUaNR8t4j8DRE/5TrzAUjlUC5B3ilJfYKvUWG6Nm9wASOhURh73+n +yfrBJcyFLGM/BWBzSQXgYHiVEEvc+RFZznF/QJuKqiTfC0Li21a8StKlDJu3Qz7dg9MmEALP6iPE +SU7l0+m0iKsMrmKS1GWH2WrX9IWf5DMiJaXlyDO6w8dB3F/GaswADm0yqLaHNgBid5seHzTLkDx4 +iHQF63n1k3Flyp3HaxgtPVxO59X4PzF9j4fsCiIvI+n+u33J4PTs63zEsMMtYrWacdaxaujs2e3V +cuy+VwHOBVWf3tFgiBCzAgMBAAGjNjA0MA8GA1UdEwEB/wQFMAMBAf8wEQYDVR0OBAoECERqlWdV +eRFPMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQUFAAOCAQEAVdRU0VlIXLOThaq/Yy/kgM40 +ozRiPvbY7meIMQQDbwvUB/tOdQ/TLtPAF8fGKOwGDREkDg6lXb+MshOWcdzUzg4NCmgybLlBMRmr +sQd7TZjTXLDR8KdCoLXEjq/+8T/0709GAHbrAvv5ndJAlseIOrifEXnzgGWovR/TeIGgUUw3tKZd +JXDRZslo+S4RFGjxVJgIrCaSD96JntT6s3kr0qN51OyLrIdTaEJMUVF0HhsnLuP1Hyl0Te2v9+GS +mYHovjrHF1D2t8b8m7CKa9aIA5GPBnc6hQLdmNVDeD/GMBWsm2vLV7eJUYs66MmEDNuxUCAKGkq6 +ahq97BvIxYSazQ== +-----END CERTIFICATE----- + +TWCA Root Certification Authority +================================= +-----BEGIN CERTIFICATE----- +MIIDezCCAmOgAwIBAgIBATANBgkqhkiG9w0BAQUFADBfMQswCQYDVQQGEwJUVzESMBAGA1UECgwJ +VEFJV0FOLUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFUV0NBIFJvb3QgQ2VydGlmaWNh +dGlvbiBBdXRob3JpdHkwHhcNMDgwODI4MDcyNDMzWhcNMzAxMjMxMTU1OTU5WjBfMQswCQYDVQQG +EwJUVzESMBAGA1UECgwJVEFJV0FOLUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFUV0NB +IFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK +AoIBAQCwfnK4pAOU5qfeCTiRShFAh6d8WWQUe7UREN3+v9XAu1bihSX0NXIP+FPQQeFEAcK0HMMx +QhZHhTMidrIKbw/lJVBPhYa+v5guEGcevhEFhgWQxFnQfHgQsIBct+HHK3XLfJ+utdGdIzdjp9xC +oi2SBBtQwXu4PhvJVgSLL1KbralW6cH/ralYhzC2gfeXRfwZVzsrb+RH9JlF/h3x+JejiB03HFyP +4HYlmlD4oFT/RJB2I9IyxsOrBr/8+7/zrX2SYgJbKdM1o5OaQ2RgXbL6Mv87BK9NQGr5x+PvI/1r +y+UPizgN7gr8/g+YnzAx3WxSZfmLgb4i4RxYA7qRG4kHAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIB +BjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRqOFsmjd6LWvJPelSDGRjjCDWmujANBgkqhkiG +9w0BAQUFAAOCAQEAPNV3PdrfibqHDAhUaiBQkr6wQT25JmSDCi/oQMCXKCeCMErJk/9q56YAf4lC +mtYR5VPOL8zy2gXE/uJQxDqGfczafhAJO5I1KlOy/usrBdlsXebQ79NqZp4VKIV66IIArB6nCWlW +QtNoURi+VJq/REG6Sb4gumlc7rh3zc5sH62Dlhh9DrUUOYTxKOkto557HnpyWoOzeW/vtPzQCqVY +T0bf+215WfKEIlKuD8z7fDvnaspHYcN6+NOSBB+4IIThNlQWx0DeO4pz3N/GCUzf7Nr/1FNCocny +Yh0igzyXxfkZYiesZSLX0zzG5Y6yU8xJzrww/nsOM5D77dIUkR8Hrw== +-----END CERTIFICATE----- + +Security Communication RootCA2 +============================== +-----BEGIN CERTIFICATE----- +MIIDdzCCAl+gAwIBAgIBADANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJKUDElMCMGA1UEChMc +U0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEnMCUGA1UECxMeU2VjdXJpdHkgQ29tbXVuaWNh +dGlvbiBSb290Q0EyMB4XDTA5MDUyOTA1MDAzOVoXDTI5MDUyOTA1MDAzOVowXTELMAkGA1UEBhMC +SlAxJTAjBgNVBAoTHFNFQ09NIFRydXN0IFN5c3RlbXMgQ08uLExURC4xJzAlBgNVBAsTHlNlY3Vy +aXR5IENvbW11bmljYXRpb24gUm9vdENBMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +ANAVOVKxUrO6xVmCxF1SrjpDZYBLx/KWvNs2l9amZIyoXvDjChz335c9S672XewhtUGrzbl+dp++ ++T42NKA7wfYxEUV0kz1XgMX5iZnK5atq1LXaQZAQwdbWQonCv/Q4EpVMVAX3NuRFg3sUZdbcDE3R +3n4MqzvEFb46VqZab3ZpUql6ucjrappdUtAtCms1FgkQhNBqyjoGADdH5H5XTz+L62e4iKrFvlNV +spHEfbmwhRkGeC7bYRr6hfVKkaHnFtWOojnflLhwHyg/i/xAXmODPIMqGplrz95Zajv8bxbXH/1K +EOtOghY6rCcMU/Gt1SSwawNQwS08Ft1ENCcadfsCAwEAAaNCMEAwHQYDVR0OBBYEFAqFqXdlBZh8 +QIH4D5csOPEK7DzPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEB +CwUAA4IBAQBMOqNErLlFsceTfsgLCkLfZOoc7llsCLqJX2rKSpWeeo8HxdpFcoJxDjrSzG+ntKEj +u/Ykn8sX/oymzsLS28yN/HH8AynBbF0zX2S2ZTuJbxh2ePXcokgfGT+Ok+vx+hfuzU7jBBJV1uXk +3fs+BXziHV7Gp7yXT2g69ekuCkO2r1dcYmh8t/2jioSgrGK+KwmHNPBqAbubKVY8/gA3zyNs8U6q +tnRGEmyR7jTV7JqR50S+kDFy1UkC9gLl9B/rfNmWVan/7Ir5mUf/NVoCqgTLiluHcSmRvaS0eg29 +mvVXIwAHIRc/SjnRBUkLp7Y3gaVdjKozXoEofKd9J+sAro03 +-----END CERTIFICATE----- + +EC-ACC +====== +-----BEGIN CERTIFICATE----- +MIIFVjCCBD6gAwIBAgIQ7is969Qh3hSoYqwE893EATANBgkqhkiG9w0BAQUFADCB8zELMAkGA1UE +BhMCRVMxOzA5BgNVBAoTMkFnZW5jaWEgQ2F0YWxhbmEgZGUgQ2VydGlmaWNhY2lvIChOSUYgUS0w +ODAxMTc2LUkpMSgwJgYDVQQLEx9TZXJ2ZWlzIFB1YmxpY3MgZGUgQ2VydGlmaWNhY2lvMTUwMwYD +VQQLEyxWZWdldSBodHRwczovL3d3dy5jYXRjZXJ0Lm5ldC92ZXJhcnJlbCAoYykwMzE1MDMGA1UE +CxMsSmVyYXJxdWlhIEVudGl0YXRzIGRlIENlcnRpZmljYWNpbyBDYXRhbGFuZXMxDzANBgNVBAMT +BkVDLUFDQzAeFw0wMzAxMDcyMzAwMDBaFw0zMTAxMDcyMjU5NTlaMIHzMQswCQYDVQQGEwJFUzE7 +MDkGA1UEChMyQWdlbmNpYSBDYXRhbGFuYSBkZSBDZXJ0aWZpY2FjaW8gKE5JRiBRLTA4MDExNzYt +SSkxKDAmBgNVBAsTH1NlcnZlaXMgUHVibGljcyBkZSBDZXJ0aWZpY2FjaW8xNTAzBgNVBAsTLFZl +Z2V1IGh0dHBzOi8vd3d3LmNhdGNlcnQubmV0L3ZlcmFycmVsIChjKTAzMTUwMwYDVQQLEyxKZXJh +cnF1aWEgRW50aXRhdHMgZGUgQ2VydGlmaWNhY2lvIENhdGFsYW5lczEPMA0GA1UEAxMGRUMtQUND +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsyLHT+KXQpWIR4NA9h0X84NzJB5R85iK +w5K4/0CQBXCHYMkAqbWUZRkiFRfCQ2xmRJoNBD45b6VLeqpjt4pEndljkYRm4CgPukLjbo73FCeT +ae6RDqNfDrHrZqJyTxIThmV6PttPB/SnCWDaOkKZx7J/sxaVHMf5NLWUhdWZXqBIoH7nF2W4onW4 +HvPlQn2v7fOKSGRdghST2MDk/7NQcvJ29rNdQlB50JQ+awwAvthrDk4q7D7SzIKiGGUzE3eeml0a +E9jD2z3Il3rucO2n5nzbcc8tlGLfbdb1OL4/pYUKGbio2Al1QnDE6u/LDsg0qBIimAy4E5S2S+zw +0JDnJwIDAQABo4HjMIHgMB0GA1UdEQQWMBSBEmVjX2FjY0BjYXRjZXJ0Lm5ldDAPBgNVHRMBAf8E +BTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUoMOLRKo3pUW/l4Ba0fF4opvpXY0wfwYD +VR0gBHgwdjB0BgsrBgEEAfV4AQMBCjBlMCwGCCsGAQUFBwIBFiBodHRwczovL3d3dy5jYXRjZXJ0 +Lm5ldC92ZXJhcnJlbDA1BggrBgEFBQcCAjApGidWZWdldSBodHRwczovL3d3dy5jYXRjZXJ0Lm5l +dC92ZXJhcnJlbCAwDQYJKoZIhvcNAQEFBQADggEBAKBIW4IB9k1IuDlVNZyAelOZ1Vr/sXE7zDkJ +lF7W2u++AVtd0x7Y/X1PzaBB4DSTv8vihpw3kpBWHNzrKQXlxJ7HNd+KDM3FIUPpqojlNcAZQmNa +Al6kSBg6hW/cnbw/nZzBh7h6YQjpdwt/cKt63dmXLGQehb+8dJahw3oS7AwaboMMPOhyRp/7SNVe +l+axofjk70YllJyJ22k4vuxcDlbHZVHlUIiIv0LVKz3l+bqeLrPK9HOSAgu+TGbrIP65y7WZf+a2 +E/rKS03Z7lNGBjvGTq2TWoF+bCpLagVFjPIhpDGQh2xlnJ2lYJU6Un/10asIbvPuW/mIPX64b24D +5EI= +-----END CERTIFICATE----- + +Hellenic Academic and Research Institutions RootCA 2011 +======================================================= +-----BEGIN CERTIFICATE----- +MIIEMTCCAxmgAwIBAgIBADANBgkqhkiG9w0BAQUFADCBlTELMAkGA1UEBhMCR1IxRDBCBgNVBAoT +O0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgQ2VydC4gQXV0aG9y +aXR5MUAwPgYDVQQDEzdIZWxsZW5pYyBBY2FkZW1pYyBhbmQgUmVzZWFyY2ggSW5zdGl0dXRpb25z +IFJvb3RDQSAyMDExMB4XDTExMTIwNjEzNDk1MloXDTMxMTIwMTEzNDk1MlowgZUxCzAJBgNVBAYT +AkdSMUQwQgYDVQQKEztIZWxsZW5pYyBBY2FkZW1pYyBhbmQgUmVzZWFyY2ggSW5zdGl0dXRpb25z +IENlcnQuIEF1dGhvcml0eTFAMD4GA1UEAxM3SGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJlc2VhcmNo +IEluc3RpdHV0aW9ucyBSb290Q0EgMjAxMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +AKlTAOMupvaO+mDYLZU++CwqVE7NuYRhlFhPjz2L5EPzdYmNUeTDN9KKiE15HrcS3UN4SoqS5tdI +1Q+kOilENbgH9mgdVc04UfCMJDGFr4PJfel3r+0ae50X+bOdOFAPplp5kYCvN66m0zH7tSYJnTxa +71HFK9+WXesyHgLacEnsbgzImjeN9/E2YEsmLIKe0HjzDQ9jpFEw4fkrJxIH2Oq9GGKYsFk3fb7u +8yBRQlqD75O6aRXxYp2fmTmCobd0LovUxQt7L/DICto9eQqakxylKHJzkUOap9FNhYS5qXSPFEDH +3N6sQWRstBmbAmNtJGSPRLIl6s5ddAxjMlyNh+UCAwEAAaOBiTCBhjAPBgNVHRMBAf8EBTADAQH/ +MAsGA1UdDwQEAwIBBjAdBgNVHQ4EFgQUppFC/RNhSiOeCKQp5dgTBCPuQSUwRwYDVR0eBEAwPqA8 +MAWCAy5ncjAFggMuZXUwBoIELmVkdTAGggQub3JnMAWBAy5ncjAFgQMuZXUwBoEELmVkdTAGgQQu +b3JnMA0GCSqGSIb3DQEBBQUAA4IBAQAf73lB4XtuP7KMhjdCSk4cNx6NZrokgclPEg8hwAOXhiVt +XdMiKahsog2p6z0GW5k6x8zDmjR/qw7IThzh+uTczQ2+vyT+bOdrwg3IBp5OjWEopmr95fZi6hg8 +TqBTnbI6nOulnJEWtk2C4AwFSKls9cz4y51JtPACpf1wA+2KIaWuE4ZJwzNzvoc7dIsXRSZMFpGD +/md9zU1jZ/rzAxKWeAaNsWftjj++n08C9bMJL/NMh98qy5V8AcysNnq/onN694/BtZqhFLKPM58N +7yLcZnuEvUUXBj08yrl3NI/K6s8/MT7jiOOASSXIl7WdmplNsDz4SgCbZN2fOUvRJ9e4 +-----END CERTIFICATE----- + +Actalis Authentication Root CA +============================== +-----BEGIN CERTIFICATE----- +MIIFuzCCA6OgAwIBAgIIVwoRl0LE48wwDQYJKoZIhvcNAQELBQAwazELMAkGA1UEBhMCSVQxDjAM +BgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlzIFMucC5BLi8wMzM1ODUyMDk2NzEnMCUGA1UE +AwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290IENBMB4XDTExMDkyMjExMjIwMloXDTMwMDky +MjExMjIwMlowazELMAkGA1UEBhMCSVQxDjAMBgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlz +IFMucC5BLi8wMzM1ODUyMDk2NzEnMCUGA1UEAwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290 +IENBMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAp8bEpSmkLO/lGMWwUKNvUTufClrJ +wkg4CsIcoBh/kbWHuUA/3R1oHwiD1S0eiKD4j1aPbZkCkpAW1V8IbInX4ay8IMKx4INRimlNAJZa +by/ARH6jDuSRzVju3PvHHkVH3Se5CAGfpiEd9UEtL0z9KK3giq0itFZljoZUj5NDKd45RnijMCO6 +zfB9E1fAXdKDa0hMxKufgFpbOr3JpyI/gCczWw63igxdBzcIy2zSekciRDXFzMwujt0q7bd9Zg1f +YVEiVRvjRuPjPdA1YprbrxTIW6HMiRvhMCb8oJsfgadHHwTrozmSBp+Z07/T6k9QnBn+locePGX2 +oxgkg4YQ51Q+qDp2JE+BIcXjDwL4k5RHILv+1A7TaLndxHqEguNTVHnd25zS8gebLra8Pu2Fbe8l +EfKXGkJh90qX6IuxEAf6ZYGyojnP9zz/GPvG8VqLWeICrHuS0E4UT1lF9gxeKF+w6D9Fz8+vm2/7 +hNN3WpVvrJSEnu68wEqPSpP4RCHiMUVhUE4Q2OM1fEwZtN4Fv6MGn8i1zeQf1xcGDXqVdFUNaBr8 +EBtiZJ1t4JWgw5QHVw0U5r0F+7if5t+L4sbnfpb2U8WANFAoWPASUHEXMLrmeGO89LKtmyuy/uE5 +jF66CyCU3nuDuP/jVo23Eek7jPKxwV2dpAtMK9myGPW1n0sCAwEAAaNjMGEwHQYDVR0OBBYEFFLY +iDrIn3hm7YnzezhwlMkCAjbQMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUUtiIOsifeGbt +ifN7OHCUyQICNtAwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBCwUAA4ICAQALe3KHwGCmSUyI +WOYdiPcUZEim2FgKDk8TNd81HdTtBjHIgT5q1d07GjLukD0R0i70jsNjLiNmsGe+b7bAEzlgqqI0 +JZN1Ut6nna0Oh4lScWoWPBkdg/iaKWW+9D+a2fDzWochcYBNy+A4mz+7+uAwTc+G02UQGRjRlwKx +K3JCaKygvU5a2hi/a5iB0P2avl4VSM0RFbnAKVy06Ij3Pjaut2L9HmLecHgQHEhb2rykOLpn7VU+ +Xlff1ANATIGk0k9jpwlCCRT8AKnCgHNPLsBA2RF7SOp6AsDT6ygBJlh0wcBzIm2Tlf05fbsq4/aC +4yyXX04fkZT6/iyj2HYauE2yOE+b+h1IYHkm4vP9qdCa6HCPSXrW5b0KDtst842/6+OkfcvHlXHo +2qN8xcL4dJIEG4aspCJTQLas/kx2z/uUMsA1n3Y/buWQbqCmJqK4LL7RK4X9p2jIugErsWx0Hbhz +lefut8cl8ABMALJ+tguLHPPAUJ4lueAI3jZm/zel0btUZCzJJ7VLkn5l/9Mt4blOvH+kQSGQQXem +OR/qnuOf0GZvBeyqdn6/axag67XH/JJULysRJyU3eExRarDzzFhdFPFqSBX/wge2sY0PjlxQRrM9 +vwGYT7JZVEc+NHt4bVaTLnPqZih4zR0Uv6CPLy64Lo7yFIrM6bV8+2ydDKXhlg== +-----END CERTIFICATE----- + +Trustis FPS Root CA +=================== +-----BEGIN CERTIFICATE----- +MIIDZzCCAk+gAwIBAgIQGx+ttiD5JNM2a/fH8YygWTANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQG +EwJHQjEYMBYGA1UEChMPVHJ1c3RpcyBMaW1pdGVkMRwwGgYDVQQLExNUcnVzdGlzIEZQUyBSb290 +IENBMB4XDTAzMTIyMzEyMTQwNloXDTI0MDEyMTExMzY1NFowRTELMAkGA1UEBhMCR0IxGDAWBgNV +BAoTD1RydXN0aXMgTGltaXRlZDEcMBoGA1UECxMTVHJ1c3RpcyBGUFMgUm9vdCBDQTCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBAMVQe547NdDfxIzNjpvto8A2mfRC6qc+gIMPpqdZh8mQ +RUN+AOqGeSoDvT03mYlmt+WKVoaTnGhLaASMk5MCPjDSNzoiYYkchU59j9WvezX2fihHiTHcDnlk +H5nSW7r+f2C/revnPDgpai/lkQtV/+xvWNUtyd5MZnGPDNcE2gfmHhjjvSkCqPoc4Vu5g6hBSLwa +cY3nYuUtsuvffM/bq1rKMfFMIvMFE/eC+XN5DL7XSxzA0RU8k0Fk0ea+IxciAIleH2ulrG6nS4zt +o3Lmr2NNL4XSFDWaLk6M6jKYKIahkQlBOrTh4/L68MkKokHdqeMDx4gVOxzUGpTXn2RZEm0CAwEA +AaNTMFEwDwYDVR0TAQH/BAUwAwEB/zAfBgNVHSMEGDAWgBS6+nEleYtXQSUhhgtx67JkDoshZzAd +BgNVHQ4EFgQUuvpxJXmLV0ElIYYLceuyZA6LIWcwDQYJKoZIhvcNAQEFBQADggEBAH5Y//01GX2c +GE+esCu8jowU/yyg2kdbw++BLa8F6nRIW/M+TgfHbcWzk88iNVy2P3UnXwmWzaD+vkAMXBJV+JOC +yinpXj9WV4s4NvdFGkwozZ5BuO1WTISkQMi4sKUraXAEasP41BIy+Q7DsdwyhEQsb8tGD+pmQQ9P +8Vilpg0ND2HepZ5dfWWhPBfnqFVO76DH7cZEf1T1o+CP8HxVIo8ptoGj4W1OLBuAZ+ytIJ8MYmHV +l/9D7S3B2l0pKoU/rGXuhg8FjZBf3+6f9L/uHfuY5H+QK4R4EA5sSVPvFVtlRkpdr7r7OnIdzfYl +iB6XzCGcKQENZetX2fNXlrtIzYE= +-----END CERTIFICATE----- + +StartCom Certification Authority +================================ +-----BEGIN CERTIFICATE----- +MIIHhzCCBW+gAwIBAgIBLTANBgkqhkiG9w0BAQsFADB9MQswCQYDVQQGEwJJTDEWMBQGA1UEChMN +U3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmlu +ZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDYwOTE3MTk0 +NjM3WhcNMzYwOTE3MTk0NjM2WjB9MQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRk +LjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMg +U3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAw +ggIKAoICAQDBiNsJvGxGfHiflXu1M5DycmLWwTYgIiRezul38kMKogZkpMyONvg45iPwbm2xPN1y +o4UcodM9tDMr0y+v/uqwQVlntsQGfQqedIXWeUyAN3rfOQVSWff0G0ZDpNKFhdLDcfN1YjS6LIp/ +Ho/u7TTQEceWzVI9ujPW3U3eCztKS5/CJi/6tRYccjV3yjxd5srhJosaNnZcAdt0FCX+7bWgiA/d +eMotHweXMAEtcnn6RtYTKqi5pquDSR3l8u/d5AGOGAqPY1MWhWKpDhk6zLVmpsJrdAfkK+F2PrRt +2PZE4XNiHzvEvqBTViVsUQn3qqvKv3b9bZvzndu/PWa8DFaqr5hIlTpL36dYUNk4dalb6kMMAv+Z +6+hsTXBbKWWc3apdzK8BMewM69KN6Oqce+Zu9ydmDBpI125C4z/eIT574Q1w+2OqqGwaVLRcJXrJ +osmLFqa7LH4XXgVNWG4SHQHuEhANxjJ/GP/89PrNbpHoNkm+Gkhpi8KWTRoSsmkXwQqQ1vp5Iki/ +untp+HDH+no32NgN0nZPV/+Qt+OR0t3vwmC3Zzrd/qqc8NSLf3Iizsafl7b4r4qgEKjZ+xjGtrVc +UjyJthkqcwEKDwOzEmDyei+B26Nu/yYwl/WL3YlXtq09s68rxbd2AvCl1iuahhQqcvbjM4xdCUsT +37uMdBNSSwIDAQABo4ICEDCCAgwwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYD +VR0OBBYEFE4L7xqkQFulF2mHMMo0aEPQQa7yMB8GA1UdIwQYMBaAFE4L7xqkQFulF2mHMMo0aEPQ +Qa7yMIIBWgYDVR0gBIIBUTCCAU0wggFJBgsrBgEEAYG1NwEBATCCATgwLgYIKwYBBQUHAgEWImh0 +dHA6Ly93d3cuc3RhcnRzc2wuY29tL3BvbGljeS5wZGYwNAYIKwYBBQUHAgEWKGh0dHA6Ly93d3cu +c3RhcnRzc2wuY29tL2ludGVybWVkaWF0ZS5wZGYwgc8GCCsGAQUFBwICMIHCMCcWIFN0YXJ0IENv +bW1lcmNpYWwgKFN0YXJ0Q29tKSBMdGQuMAMCAQEagZZMaW1pdGVkIExpYWJpbGl0eSwgcmVhZCB0 +aGUgc2VjdGlvbiAqTGVnYWwgTGltaXRhdGlvbnMqIG9mIHRoZSBTdGFydENvbSBDZXJ0aWZpY2F0 +aW9uIEF1dGhvcml0eSBQb2xpY3kgYXZhaWxhYmxlIGF0IGh0dHA6Ly93d3cuc3RhcnRzc2wuY29t +L3BvbGljeS5wZGYwEQYJYIZIAYb4QgEBBAQDAgAHMDgGCWCGSAGG+EIBDQQrFilTdGFydENvbSBG +cmVlIFNTTCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTANBgkqhkiG9w0BAQsFAAOCAgEAjo/n3JR5 +fPGFf59Jb2vKXfuM/gTFwWLRfUKKvFO3lANmMD+x5wqnUCBVJX92ehQN6wQOQOY+2IirByeDqXWm +N3PH/UvSTa0XQMhGvjt/UfzDtgUx3M2FIk5xt/JxXrAaxrqTi3iSSoX4eA+D/i+tLPfkpLst0OcN +Org+zvZ49q5HJMqjNTbOx8aHmNrs++myziebiMMEofYLWWivydsQD032ZGNcpRJvkrKTlMeIFw6T +tn5ii5B/q06f/ON1FE8qMt9bDeD1e5MNq6HPh+GlBEXoPBKlCcWw0bdT82AUuoVpaiF8H3VhFyAX +e2w7QSlc4axa0c2Mm+tgHRns9+Ww2vl5GKVFP0lDV9LdJNUso/2RjSe15esUBppMeyG7Oq0wBhjA +2MFrLH9ZXF2RsXAiV+uKa0hK1Q8p7MZAwC+ITGgBF3f0JBlPvfrhsiAhS90a2Cl9qrjeVOwhVYBs +HvUwyKMQ5bLmKhQxw4UtjJixhlpPiVktucf3HMiKf8CdBUrmQk9io20ppB+Fq9vlgcitKj1MXVuE +JnHEhV5xJMqlG2zYYdMa4FTbzrqpMrUi9nNBCV24F10OD5mQ1kfabwo6YigUZ4LZ8dCAWZvLMdib +D4x3TrVoivJs9iQOLWxwxXPR3hTQcY+203sC9uO41Alua551hDnmfyWl8kgAwKQB2j8= +-----END CERTIFICATE----- + +StartCom Certification Authority G2 +=================================== +-----BEGIN CERTIFICATE----- +MIIFYzCCA0ugAwIBAgIBOzANBgkqhkiG9w0BAQsFADBTMQswCQYDVQQGEwJJTDEWMBQGA1UEChMN +U3RhcnRDb20gTHRkLjEsMCoGA1UEAxMjU3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkg +RzIwHhcNMTAwMTAxMDEwMDAxWhcNMzkxMjMxMjM1OTAxWjBTMQswCQYDVQQGEwJJTDEWMBQGA1UE +ChMNU3RhcnRDb20gTHRkLjEsMCoGA1UEAxMjU3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3Jp +dHkgRzIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC2iTZbB7cgNr2Cu+EWIAOVeq8O +o1XJJZlKxdBWQYeQTSFgpBSHO839sj60ZwNq7eEPS8CRhXBF4EKe3ikj1AENoBB5uNsDvfOpL9HG +4A/LnooUCri99lZi8cVytjIl2bLzvWXFDSxu1ZJvGIsAQRSCb0AgJnooD/Uefyf3lLE3PbfHkffi +Aez9lInhzG7TNtYKGXmu1zSCZf98Qru23QumNK9LYP5/Q0kGi4xDuFby2X8hQxfqp0iVAXV16iul +Q5XqFYSdCI0mblWbq9zSOdIxHWDirMxWRST1HFSr7obdljKF+ExP6JV2tgXdNiNnvP8V4so75qbs +O+wmETRIjfaAKxojAuuKHDp2KntWFhxyKrOq42ClAJ8Em+JvHhRYW6Vsi1g8w7pOOlz34ZYrPu8H +vKTlXcxNnw3h3Kq74W4a7I/htkxNeXJdFzULHdfBR9qWJODQcqhaX2YtENwvKhOuJv4KHBnM0D4L +nMgJLvlblnpHnOl68wVQdJVznjAJ85eCXuaPOQgeWeU1FEIT/wCc976qUM/iUUjXuG+v+E5+M5iS +FGI6dWPPe/regjupuznixL0sAA7IF6wT700ljtizkC+p2il9Ha90OrInwMEePnWjFqmveiJdnxMa +z6eg6+OGCtP95paV1yPIN93EfKo2rJgaErHgTuixO/XWb/Ew1wIDAQABo0IwQDAPBgNVHRMBAf8E +BTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUS8W0QGutHLOlHGVuRjaJhwUMDrYwDQYJ +KoZIhvcNAQELBQADggIBAHNXPyzVlTJ+N9uWkusZXn5T50HsEbZH77Xe7XRcxfGOSeD8bpkTzZ+K +2s06Ctg6Wgk/XzTQLwPSZh0avZyQN8gMjgdalEVGKua+etqhqaRpEpKwfTbURIfXUfEpY9Z1zRbk +J4kd+MIySP3bmdCPX1R0zKxnNBFi2QwKN4fRoxdIjtIXHfbX/dtl6/2o1PXWT6RbdejF0mCy2wl+ +JYt7ulKSnj7oxXehPOBKc2thz4bcQ///If4jXSRK9dNtD2IEBVeC2m6kMyV5Sy5UGYvMLD0w6dEG +/+gyRr61M3Z3qAFdlsHB1b6uJcDJHgoJIIihDsnzb02CVAAgp9KP5DlUFy6NHrgbuxu9mk47EDTc +nIhT76IxW1hPkWLIwpqazRVdOKnWvvgTtZ8SafJQYqz7Fzf07rh1Z2AQ+4NQ+US1dZxAF7L+/Xld +blhYXzD8AK6vM8EOTmy6p6ahfzLbOOCxchcKK5HsamMm7YnUeMx0HgX4a/6ManY5Ka5lIxKVCCIc +l85bBu4M4ru8H0ST9tg4RQUh7eStqxK2A6RCLi3ECToDZ2mEmuFZkIoohdVddLHRDiBYmxOlsGOm +7XtH/UVVMKTumtTm4ofvmMkyghEpIrwACjFeLQ/Ajulrso8uBtjRkcfGEvRM/TAXw8HaOFvjqerm +obp573PYtlNXLfbQ4ddI +-----END CERTIFICATE----- + +Buypass Class 2 Root CA +======================= +-----BEGIN CERTIFICATE----- +MIIFWTCCA0GgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJOTzEdMBsGA1UECgwU +QnV5cGFzcyBBUy05ODMxNjMzMjcxIDAeBgNVBAMMF0J1eXBhc3MgQ2xhc3MgMiBSb290IENBMB4X +DTEwMTAyNjA4MzgwM1oXDTQwMTAyNjA4MzgwM1owTjELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1 +eXBhc3MgQVMtOTgzMTYzMzI3MSAwHgYDVQQDDBdCdXlwYXNzIENsYXNzIDIgUm9vdCBDQTCCAiIw +DQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANfHXvfBB9R3+0Mh9PT1aeTuMgHbo4Yf5FkNuud1 +g1Lr6hxhFUi7HQfKjK6w3Jad6sNgkoaCKHOcVgb/S2TwDCo3SbXlzwx87vFKu3MwZfPVL4O2fuPn +9Z6rYPnT8Z2SdIrkHJasW4DptfQxh6NR/Md+oW+OU3fUl8FVM5I+GC911K2GScuVr1QGbNgGE41b +/+EmGVnAJLqBcXmQRFBoJJRfuLMR8SlBYaNByyM21cHxMlAQTn/0hpPshNOOvEu/XAFOBz3cFIqU +CqTqc/sLUegTBxj6DvEr0VQVfTzh97QZQmdiXnfgolXsttlpF9U6r0TtSsWe5HonfOV116rLJeff +awrbD02TTqigzXsu8lkBarcNuAeBfos4GzjmCleZPe4h6KP1DBbdi+w0jpwqHAAVF41og9JwnxgI +zRFo1clrUs3ERo/ctfPYV3Me6ZQ5BL/T3jjetFPsaRyifsSP5BtwrfKi+fv3FmRmaZ9JUaLiFRhn +Bkp/1Wy1TbMz4GHrXb7pmA8y1x1LPC5aAVKRCfLf6o3YBkBjqhHk/sM3nhRSP/TizPJhk9H9Z2vX +Uq6/aKtAQ6BXNVN48FP4YUIHZMbXb5tMOA1jrGKvNouicwoN9SG9dKpN6nIDSdvHXx1iY8f93ZHs +M+71bbRuMGjeyNYmsHVee7QHIJihdjK4TWxPAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYD +VR0OBBYEFMmAd+BikoL1RpzzuvdMw964o605MA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsF +AAOCAgEAU18h9bqwOlI5LJKwbADJ784g7wbylp7ppHR/ehb8t/W2+xUbP6umwHJdELFx7rxP462s +A20ucS6vxOOto70MEae0/0qyexAQH6dXQbLArvQsWdZHEIjzIVEpMMpghq9Gqx3tOluwlN5E40EI +osHsHdb9T7bWR9AUC8rmyrV7d35BH16Dx7aMOZawP5aBQW9gkOLo+fsicdl9sz1Gv7SEr5AcD48S +aq/v7h56rgJKihcrdv6sVIkkLE8/trKnToyokZf7KcZ7XC25y2a2t6hbElGFtQl+Ynhw/qlqYLYd +DnkM/crqJIByw5c/8nerQyIKx+u2DISCLIBrQYoIwOula9+ZEsuK1V6ADJHgJgg2SMX6OBE1/yWD +LfJ6v9r9jv6ly0UsH8SIU653DtmadsWOLB2jutXsMq7Aqqz30XpN69QH4kj3Io6wpJ9qzo6ysmD0 +oyLQI+uUWnpp3Q+/QFesa1lQ2aOZ4W7+jQF5JyMV3pKdewlNWudLSDBaGOYKbeaP4NK75t98biGC +wWg5TbSYWGZizEqQXsP6JwSxeRV0mcy+rSDeJmAc61ZRpqPq5KM/p/9h3PFaTWwyI0PurKju7koS +CTxdccK+efrCh2gdC/1cacwG0Jp9VJkqyTkaGa9LKkPzY11aWOIv4x3kqdbQCtCev9eBCfHJxyYN +rJgWVqA= +-----END CERTIFICATE----- + +Buypass Class 3 Root CA +======================= +-----BEGIN CERTIFICATE----- +MIIFWTCCA0GgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJOTzEdMBsGA1UECgwU +QnV5cGFzcyBBUy05ODMxNjMzMjcxIDAeBgNVBAMMF0J1eXBhc3MgQ2xhc3MgMyBSb290IENBMB4X +DTEwMTAyNjA4Mjg1OFoXDTQwMTAyNjA4Mjg1OFowTjELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1 +eXBhc3MgQVMtOTgzMTYzMzI3MSAwHgYDVQQDDBdCdXlwYXNzIENsYXNzIDMgUm9vdCBDQTCCAiIw +DQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAKXaCpUWUOOV8l6ddjEGMnqb8RB2uACatVI2zSRH +sJ8YZLya9vrVediQYkwiL944PdbgqOkcLNt4EemOaFEVcsfzM4fkoF0LXOBXByow9c3EN3coTRiR +5r/VUv1xLXA+58bEiuPwKAv0dpihi4dVsjoT/Lc+JzeOIuOoTyrvYLs9tznDDgFHmV0ST9tD+leh +7fmdvhFHJlsTmKtdFoqwNxxXnUX/iJY2v7vKB3tvh2PX0DJq1l1sDPGzbjniazEuOQAnFN44wOwZ +ZoYS6J1yFhNkUsepNxz9gjDthBgd9K5c/3ATAOux9TN6S9ZV+AWNS2mw9bMoNlwUxFFzTWsL8TQH +2xc519woe2v1n/MuwU8XKhDzzMro6/1rqy6any2CbgTUUgGTLT2G/H783+9CHaZr77kgxve9oKeV +/afmiSTYzIw0bOIjL9kSGiG5VZFvC5F5GQytQIgLcOJ60g7YaEi7ghM5EFjp2CoHxhLbWNvSO1UQ +RwUVZ2J+GGOmRj8JDlQyXr8NYnon74Do29lLBlo3WiXQCBJ31G8JUJc9yB3D34xFMFbG02SrZvPA +Xpacw8Tvw3xrizp5f7NJzz3iiZ+gMEuFuZyUJHmPfWupRWgPK9Dx2hzLabjKSWJtyNBjYt1gD1iq +j6G8BaVmos8bdrKEZLFMOVLAMLrwjEsCsLa3AgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYD +VR0OBBYEFEe4zf/lb+74suwvTg75JbCOPGvDMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsF +AAOCAgEAACAjQTUEkMJAYmDv4jVM1z+s4jSQuKFvdvoWFqRINyzpkMLyPPgKn9iB5btb2iUspKdV +cSQy9sgL8rxq+JOssgfCX5/bzMiKqr5qb+FJEMwx14C7u8jYog5kV+qi9cKpMRXSIGrs/CIBKM+G +uIAeqcwRpTzyFrNHnfzSgCHEy9BHcEGhyoMZCCxt8l13nIoUE9Q2HJLw5QY33KbmkJs4j1xrG0aG +Q0JfPgEHU1RdZX33inOhmlRaHylDFCfChQ+1iHsaO5S3HWCntZznKWlXWpuTekMwGwPXYshApqr8 +ZORK15FTAaggiG6cX0S5y2CBNOxv033aSF/rtJC8LakcC6wc1aJoIIAE1vyxjy+7SjENSoYc6+I2 +KSb12tjE8nVhz36udmNKekBlk4f4HoCMhuWG1o8O/FMsYOgWYRqiPkN7zTlgVGr18okmAWiDSKIz +6MkEkbIRNBE+6tBDGR8Dk5AM/1E9V/RBbuHLoL7ryWPNbczk+DaqaJ3tvV2XcEQNtg413OEMXbug +UZTLfhbrES+jkkXITHHZvMmZUldGL1DPvTVp9D0VzgalLA8+9oG6lLvDu79leNKGef9JOxqDDPDe +eOzI8k1MGt6CKfjBWtrt7uYnXuhF0J0cUahoq0Tj0Itq4/g7u9xN12TyUb7mqqta6THuBrxzvxNi +Cp/HuZc= +-----END CERTIFICATE----- + +T-TeleSec GlobalRoot Class 3 +============================ +-----BEGIN CERTIFICATE----- +MIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoM +IlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBU +cnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDMwHhcNMDgx +MDAxMTAyOTU2WhcNMzMxMDAxMjM1OTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lz +dGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBD +ZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDMwggEiMA0GCSqGSIb3 +DQEBAQUAA4IBDwAwggEKAoIBAQC9dZPwYiJvJK7genasfb3ZJNW4t/zN8ELg63iIVl6bmlQdTQyK +9tPPcPRStdiTBONGhnFBSivwKixVA9ZIw+A5OO3yXDw/RLyTPWGrTs0NvvAgJ1gORH8EGoel15YU +NpDQSXuhdfsaa3Ox+M6pCSzyU9XDFES4hqX2iys52qMzVNn6chr3IhUciJFrf2blw2qAsCTz34ZF +iP0Zf3WHHx+xGwpzJFu5ZeAsVMhg02YXP+HMVDNzkQI6pn97djmiH5a2OK61yJN0HZ65tOVgnS9W +0eDrXltMEnAMbEQgqxHY9Bn20pxSN+f6tsIxO0rUFJmtxxr1XV/6B7h8DR/Wgx6zAgMBAAGjQjBA +MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS1A/d2O2GCahKqGFPr +AyGUv/7OyjANBgkqhkiG9w0BAQsFAAOCAQEAVj3vlNW92nOyWL6ukK2YJ5f+AbGwUgC4TeQbIXQb +fsDuXmkqJa9c1h3a0nnJ85cp4IaH3gRZD/FZ1GSFS5mvJQQeyUapl96Cshtwn5z2r3Ex3XsFpSzT +ucpH9sry9uetuUg/vBa3wW306gmv7PO15wWeph6KU1HWk4HMdJP2udqmJQV0eVp+QD6CSyYRMG7h +P0HHRwA11fXT91Q+gT3aSWqas+8QPebrb9HIIkfLzM8BMZLZGOMivgkeGj5asuRrDFR6fUNOuIml +e9eiPZaGzPImNC1qkp2aGtAw4l1OBLBfiyB+d8E9lYLRRpo7PHi4b6HQDWSieB4pTpPDpFQUWw== +-----END CERTIFICATE----- + +EE Certification Centre Root CA +=============================== +-----BEGIN CERTIFICATE----- +MIIEAzCCAuugAwIBAgIQVID5oHPtPwBMyonY43HmSjANBgkqhkiG9w0BAQUFADB1MQswCQYDVQQG +EwJFRTEiMCAGA1UECgwZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1czEoMCYGA1UEAwwfRUUgQ2Vy +dGlmaWNhdGlvbiBDZW50cmUgUm9vdCBDQTEYMBYGCSqGSIb3DQEJARYJcGtpQHNrLmVlMCIYDzIw +MTAxMDMwMTAxMDMwWhgPMjAzMDEyMTcyMzU5NTlaMHUxCzAJBgNVBAYTAkVFMSIwIAYDVQQKDBlB +UyBTZXJ0aWZpdHNlZXJpbWlza2Vza3VzMSgwJgYDVQQDDB9FRSBDZXJ0aWZpY2F0aW9uIENlbnRy +ZSBSb290IENBMRgwFgYJKoZIhvcNAQkBFglwa2lAc2suZWUwggEiMA0GCSqGSIb3DQEBAQUAA4IB +DwAwggEKAoIBAQDIIMDs4MVLqwd4lfNE7vsLDP90jmG7sWLqI9iroWUyeuuOF0+W2Ap7kaJjbMeM +TC55v6kF/GlclY1i+blw7cNRfdCT5mzrMEvhvH2/UpvObntl8jixwKIy72KyaOBhU8E2lf/slLo2 +rpwcpzIP5Xy0xm90/XsY6KxX7QYgSzIwWFv9zajmofxwvI6Sc9uXp3whrj3B9UiHbCe9nyV0gVWw +93X2PaRka9ZP585ArQ/dMtO8ihJTmMmJ+xAdTX7Nfh9WDSFwhfYggx/2uh8Ej+p3iDXE/+pOoYtN +P2MbRMNE1CV2yreN1x5KZmTNXMWcg+HCCIia7E6j8T4cLNlsHaFLAgMBAAGjgYowgYcwDwYDVR0T +AQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFBLyWj7qVhy/zQas8fElyalL1BSZ +MEUGA1UdJQQ+MDwGCCsGAQUFBwMCBggrBgEFBQcDAQYIKwYBBQUHAwMGCCsGAQUFBwMEBggrBgEF +BQcDCAYIKwYBBQUHAwkwDQYJKoZIhvcNAQEFBQADggEBAHv25MANqhlHt01Xo/6tu7Fq1Q+e2+Rj +xY6hUFaTlrg4wCQiZrxTFGGVv9DHKpY5P30osxBAIWrEr7BSdxjhlthWXePdNl4dp1BUoMUq5KqM +lIpPnTX/dqQGE5Gion0ARD9V04I8GtVbvFZMIi5GQ4okQC3zErg7cBqklrkar4dBGmoYDQZPxz5u +uSlNDUmJEYcyW+ZLBMjkXOZ0c5RdFpgTlf7727FE5TpwrDdr5rMzcijJs1eg9gIWiAYLtqZLICjU +3j2LrTcFU3T+bsy8QxdxXvnFzBqpYe73dgzzcvRyrc9yAjYHR8/vGVCJYMzpJJUPwssd8m92kMfM +dcGWxZ0= +-----END CERTIFICATE----- + +TURKTRUST Certificate Services Provider Root 2007 +================================================= +-----BEGIN CERTIFICATE----- +MIIEPTCCAyWgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBvzE/MD0GA1UEAww2VMOcUktUUlVTVCBF +bGVrdHJvbmlrIFNlcnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxMQswCQYDVQQGEwJUUjEP +MA0GA1UEBwwGQW5rYXJhMV4wXAYDVQQKDFVUw5xSS1RSVVNUIEJpbGdpIMSwbGV0acWfaW0gdmUg +QmlsacWfaW0gR8O8dmVubGnEn2kgSGl6bWV0bGVyaSBBLsWeLiAoYykgQXJhbMSxayAyMDA3MB4X +DTA3MTIyNTE4MzcxOVoXDTE3MTIyMjE4MzcxOVowgb8xPzA9BgNVBAMMNlTDnFJLVFJVU1QgRWxl +a3Ryb25payBTZXJ0aWZpa2EgSGl6bWV0IFNhxJ9sYXnEsWPEsXPEsTELMAkGA1UEBhMCVFIxDzAN +BgNVBAcMBkFua2FyYTFeMFwGA1UECgxVVMOcUktUUlVTVCBCaWxnaSDEsGxldGnFn2ltIHZlIEJp +bGnFn2ltIEfDvHZlbmxpxJ9pIEhpem1ldGxlcmkgQS7Fni4gKGMpIEFyYWzEsWsgMjAwNzCCASIw +DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKu3PgqMyKVYFeaK7yc9SrToJdPNM8Ig3BnuiD9N +YvDdE3ePYakqtdTyuTFYKTsvP2qcb3N2Je40IIDu6rfwxArNK4aUyeNgsURSsloptJGXg9i3phQv +KUmi8wUG+7RP2qFsmmaf8EMJyupyj+sA1zU511YXRxcw9L6/P8JorzZAwan0qafoEGsIiveGHtya +KhUG9qPw9ODHFNRRf8+0222vR5YXm3dx2KdxnSQM9pQ/hTEST7ruToK4uT6PIzdezKKqdfcYbwnT +rqdUKDT74eA7YH2gvnmJhsifLfkKS8RQouf9eRbHegsYz85M733WB2+Y8a+xwXrXgTW4qhe04MsC +AwEAAaNCMEAwHQYDVR0OBBYEFCnFkKslrxHkYb+j/4hhkeYO/pyBMA4GA1UdDwEB/wQEAwIBBjAP +BgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQAQDdr4Ouwo0RSVgrESLFF6QSU2TJ/s +Px+EnWVUXKgWAkD6bho3hO9ynYYKVZ1WKKxmLNA6VpM0ByWtCLCPyA8JWcqdmBzlVPi5RX9ql2+I +aE1KBiY3iAIOtsbWcpnOa3faYjGkVh+uX4132l32iPwa2Z61gfAyuOOI0JzzaqC5mxRZNTZPz/OO +Xl0XrRWV2N2y1RVuAE6zS89mlOTgzbUF2mNXi+WzqtvALhyQRNsaXRik7r4EW5nVcV9VZWRi1aKb +BFmGyGJ353yCRWo9F7/snXUMrqNvWtMvmDb08PUZqxFdyKbjKlhqQgnDvZImZjINXQhVdP+MmNAK +poRq0Tl9 +-----END CERTIFICATE----- + +D-TRUST Root Class 3 CA 2 2009 +============================== +-----BEGIN CERTIFICATE----- +MIIEMzCCAxugAwIBAgIDCYPzMA0GCSqGSIb3DQEBCwUAME0xCzAJBgNVBAYTAkRFMRUwEwYDVQQK +DAxELVRydXN0IEdtYkgxJzAlBgNVBAMMHkQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgMjAwOTAe +Fw0wOTExMDUwODM1NThaFw0yOTExMDUwODM1NThaME0xCzAJBgNVBAYTAkRFMRUwEwYDVQQKDAxE +LVRydXN0IEdtYkgxJzAlBgNVBAMMHkQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgMjAwOTCCASIw +DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANOySs96R+91myP6Oi/WUEWJNTrGa9v+2wBoqOAD +ER03UAifTUpolDWzU9GUY6cgVq/eUXjsKj3zSEhQPgrfRlWLJ23DEE0NkVJD2IfgXU42tSHKXzlA +BF9bfsyjxiupQB7ZNoTWSPOSHjRGICTBpFGOShrvUD9pXRl/RcPHAY9RySPocq60vFYJfxLLHLGv +KZAKyVXMD9O0Gu1HNVpK7ZxzBCHQqr0ME7UAyiZsxGsMlFqVlNpQmvH/pStmMaTJOKDfHR+4CS7z +p+hnUquVH+BGPtikw8paxTGA6Eian5Rp/hnd2HN8gcqW3o7tszIFZYQ05ub9VxC1X3a/L7AQDcUC +AwEAAaOCARowggEWMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFP3aFMSfMN4hvR5COfyrYyNJ +4PGEMA4GA1UdDwEB/wQEAwIBBjCB0wYDVR0fBIHLMIHIMIGAoH6gfIZ6bGRhcDovL2RpcmVjdG9y +eS5kLXRydXN0Lm5ldC9DTj1ELVRSVVNUJTIwUm9vdCUyMENsYXNzJTIwMyUyMENBJTIwMiUyMDIw +MDksTz1ELVRydXN0JTIwR21iSCxDPURFP2NlcnRpZmljYXRlcmV2b2NhdGlvbmxpc3QwQ6BBoD+G +PWh0dHA6Ly93d3cuZC10cnVzdC5uZXQvY3JsL2QtdHJ1c3Rfcm9vdF9jbGFzc18zX2NhXzJfMjAw +OS5jcmwwDQYJKoZIhvcNAQELBQADggEBAH+X2zDI36ScfSF6gHDOFBJpiBSVYEQBrLLpME+bUMJm +2H6NMLVwMeniacfzcNsgFYbQDfC+rAF1hM5+n02/t2A7nPPKHeJeaNijnZflQGDSNiH+0LS4F9p0 +o3/U37CYAqxva2ssJSRyoWXuJVrl5jLn8t+rSfrzkGkj2wTZ51xY/GXUl77M/C4KzCUqNQT4YJEV +dT1B/yMfGchs64JTBKbkTCJNjYy6zltz7GRUUG3RnFX7acM2w4y8PIWmawomDeCTmGCufsYkl4ph +X5GOZpIJhzbNi5stPvZR1FDUWSi9g/LMKHtThm3YJohw1+qRzT65ysCQblrGXnRl11z+o+I= +-----END CERTIFICATE----- + +D-TRUST Root Class 3 CA 2 EV 2009 +================================= +-----BEGIN CERTIFICATE----- +MIIEQzCCAyugAwIBAgIDCYP0MA0GCSqGSIb3DQEBCwUAMFAxCzAJBgNVBAYTAkRFMRUwEwYDVQQK +DAxELVRydXN0IEdtYkgxKjAoBgNVBAMMIUQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgRVYgMjAw +OTAeFw0wOTExMDUwODUwNDZaFw0yOTExMDUwODUwNDZaMFAxCzAJBgNVBAYTAkRFMRUwEwYDVQQK +DAxELVRydXN0IEdtYkgxKjAoBgNVBAMMIUQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgRVYgMjAw +OTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJnxhDRwui+3MKCOvXwEz75ivJn9gpfS +egpnljgJ9hBOlSJzmY3aFS3nBfwZcyK3jpgAvDw9rKFs+9Z5JUut8Mxk2og+KbgPCdM03TP1YtHh +zRnp7hhPTFiu4h7WDFsVWtg6uMQYZB7jM7K1iXdODL/ZlGsTl28So/6ZqQTMFexgaDbtCHu39b+T +7WYxg4zGcTSHThfqr4uRjRxWQa4iN1438h3Z0S0NL2lRp75mpoo6Kr3HGrHhFPC+Oh25z1uxav60 +sUYgovseO3Dvk5h9jHOW8sXvhXCtKSb8HgQ+HKDYD8tSg2J87otTlZCpV6LqYQXY+U3EJ/pure35 +11H3a6UCAwEAAaOCASQwggEgMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFNOUikxiEyoZLsyv +cop9NteaHNxnMA4GA1UdDwEB/wQEAwIBBjCB3QYDVR0fBIHVMIHSMIGHoIGEoIGBhn9sZGFwOi8v +ZGlyZWN0b3J5LmQtdHJ1c3QubmV0L0NOPUQtVFJVU1QlMjBSb290JTIwQ2xhc3MlMjAzJTIwQ0El +MjAyJTIwRVYlMjAyMDA5LE89RC1UcnVzdCUyMEdtYkgsQz1ERT9jZXJ0aWZpY2F0ZXJldm9jYXRp +b25saXN0MEagRKBChkBodHRwOi8vd3d3LmQtdHJ1c3QubmV0L2NybC9kLXRydXN0X3Jvb3RfY2xh +c3NfM19jYV8yX2V2XzIwMDkuY3JsMA0GCSqGSIb3DQEBCwUAA4IBAQA07XtaPKSUiO8aEXUHL7P+ +PPoeUSbrh/Yp3uDx1MYkCenBz1UbtDDZzhr+BlGmFaQt77JLvyAoJUnRpjZ3NOhk31KxEcdzes05 +nsKtjHEh8lprr988TlWvsoRlFIm5d8sqMb7Po23Pb0iUMkZv53GMoKaEGTcH8gNFCSuGdXzfX2lX +ANtu2KZyIktQ1HWYVt+3GP9DQ1CuekR78HlR10M9p9OB0/DJT7naxpeG0ILD5EJt/rDiZE4OJudA +NCa1CInXCGNjOCd1HjPqbqjdn5lPdE2BiYBL3ZqXKVwvvoFBuYz/6n1gBp7N1z3TLqMVvKjmJuVv +w9y4AyHqnxbxLFS1 +-----END CERTIFICATE----- + +PSCProcert +========== +-----BEGIN CERTIFICATE----- +MIIJhjCCB26gAwIBAgIBCzANBgkqhkiG9w0BAQsFADCCAR4xPjA8BgNVBAMTNUF1dG9yaWRhZCBk +ZSBDZXJ0aWZpY2FjaW9uIFJhaXogZGVsIEVzdGFkbyBWZW5lem9sYW5vMQswCQYDVQQGEwJWRTEQ +MA4GA1UEBxMHQ2FyYWNhczEZMBcGA1UECBMQRGlzdHJpdG8gQ2FwaXRhbDE2MDQGA1UEChMtU2lz +dGVtYSBOYWNpb25hbCBkZSBDZXJ0aWZpY2FjaW9uIEVsZWN0cm9uaWNhMUMwQQYDVQQLEzpTdXBl +cmludGVuZGVuY2lhIGRlIFNlcnZpY2lvcyBkZSBDZXJ0aWZpY2FjaW9uIEVsZWN0cm9uaWNhMSUw +IwYJKoZIhvcNAQkBFhZhY3JhaXpAc3VzY2VydGUuZ29iLnZlMB4XDTEwMTIyODE2NTEwMFoXDTIw +MTIyNTIzNTk1OVowgdExJjAkBgkqhkiG9w0BCQEWF2NvbnRhY3RvQHByb2NlcnQubmV0LnZlMQ8w +DQYDVQQHEwZDaGFjYW8xEDAOBgNVBAgTB01pcmFuZGExKjAoBgNVBAsTIVByb3ZlZWRvciBkZSBD +ZXJ0aWZpY2Fkb3MgUFJPQ0VSVDE2MDQGA1UEChMtU2lzdGVtYSBOYWNpb25hbCBkZSBDZXJ0aWZp +Y2FjaW9uIEVsZWN0cm9uaWNhMQswCQYDVQQGEwJWRTETMBEGA1UEAxMKUFNDUHJvY2VydDCCAiIw +DQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANW39KOUM6FGqVVhSQ2oh3NekS1wwQYalNo97BVC +wfWMrmoX8Yqt/ICV6oNEolt6Vc5Pp6XVurgfoCfAUFM+jbnADrgV3NZs+J74BCXfgI8Qhd19L3uA +3VcAZCP4bsm+lU/hdezgfl6VzbHvvnpC2Mks0+saGiKLt38GieU89RLAu9MLmV+QfI4tL3czkkoh +RqipCKzx9hEC2ZUWno0vluYC3XXCFCpa1sl9JcLB/KpnheLsvtF8PPqv1W7/U0HU9TI4seJfxPmO +EO8GqQKJ/+MMbpfg353bIdD0PghpbNjU5Db4g7ayNo+c7zo3Fn2/omnXO1ty0K+qP1xmk6wKImG2 +0qCZyFSTXai20b1dCl53lKItwIKOvMoDKjSuc/HUtQy9vmebVOvh+qBa7Dh+PsHMosdEMXXqP+UH +0quhJZb25uSgXTcYOWEAM11G1ADEtMo88aKjPvM6/2kwLkDd9p+cJsmWN63nOaK/6mnbVSKVUyqU +td+tFjiBdWbjxywbk5yqjKPK2Ww8F22c3HxT4CAnQzb5EuE8XL1mv6JpIzi4mWCZDlZTOpx+FIyw +Bm/xhnaQr/2v/pDGj59/i5IjnOcVdo/Vi5QTcmn7K2FjiO/mpF7moxdqWEfLcU8UC17IAggmosvp +r2uKGcfLFFb14dq12fy/czja+eevbqQ34gcnAgMBAAGjggMXMIIDEzASBgNVHRMBAf8ECDAGAQH/ +AgEBMDcGA1UdEgQwMC6CD3N1c2NlcnRlLmdvYi52ZaAbBgVghl4CAqASDBBSSUYtRy0yMDAwNDAz +Ni0wMB0GA1UdDgQWBBRBDxk4qpl/Qguk1yeYVKIXTC1RVDCCAVAGA1UdIwSCAUcwggFDgBStuyId +xuDSAaj9dlBSk+2YwU2u06GCASakggEiMIIBHjE+MDwGA1UEAxM1QXV0b3JpZGFkIGRlIENlcnRp +ZmljYWNpb24gUmFpeiBkZWwgRXN0YWRvIFZlbmV6b2xhbm8xCzAJBgNVBAYTAlZFMRAwDgYDVQQH +EwdDYXJhY2FzMRkwFwYDVQQIExBEaXN0cml0byBDYXBpdGFsMTYwNAYDVQQKEy1TaXN0ZW1hIE5h +Y2lvbmFsIGRlIENlcnRpZmljYWNpb24gRWxlY3Ryb25pY2ExQzBBBgNVBAsTOlN1cGVyaW50ZW5k +ZW5jaWEgZGUgU2VydmljaW9zIGRlIENlcnRpZmljYWNpb24gRWxlY3Ryb25pY2ExJTAjBgkqhkiG +9w0BCQEWFmFjcmFpekBzdXNjZXJ0ZS5nb2IudmWCAQowDgYDVR0PAQH/BAQDAgEGME0GA1UdEQRG +MESCDnByb2NlcnQubmV0LnZloBUGBWCGXgIBoAwMClBTQy0wMDAwMDKgGwYFYIZeAgKgEgwQUklG +LUotMzE2MzUzNzMtNzB2BgNVHR8EbzBtMEagRKBChkBodHRwOi8vd3d3LnN1c2NlcnRlLmdvYi52 +ZS9sY3IvQ0VSVElGSUNBRE8tUkFJWi1TSEEzODRDUkxERVIuY3JsMCOgIaAfhh1sZGFwOi8vYWNy +YWl6LnN1c2NlcnRlLmdvYi52ZTA3BggrBgEFBQcBAQQrMCkwJwYIKwYBBQUHMAGGG2h0dHA6Ly9v +Y3NwLnN1c2NlcnRlLmdvYi52ZTBBBgNVHSAEOjA4MDYGBmCGXgMBAjAsMCoGCCsGAQUFBwIBFh5o +dHRwOi8vd3d3LnN1c2NlcnRlLmdvYi52ZS9kcGMwDQYJKoZIhvcNAQELBQADggIBACtZ6yKZu4Sq +T96QxtGGcSOeSwORR3C7wJJg7ODU523G0+1ng3dS1fLld6c2suNUvtm7CpsR72H0xpkzmfWvADmN +g7+mvTV+LFwxNG9s2/NkAZiqlCxB3RWGymspThbASfzXg0gTB1GEMVKIu4YXx2sviiCtxQuPcD4q +uxtxj7mkoP3YldmvWb8lK5jpY5MvYB7Eqvh39YtsL+1+LrVPQA3uvFd359m21D+VJzog1eWuq2w1 +n8GhHVnchIHuTQfiSLaeS5UtQbHh6N5+LwUeaO6/u5BlOsju6rEYNxxik6SgMexxbJHmpHmJWhSn +FFAFTKQAVzAswbVhltw+HoSvOULP5dAssSS830DD7X9jSr3hTxJkhpXzsOfIt+FTvZLm8wyWuevo +5pLtp4EJFAv8lXrPj9Y0TzYS3F7RNHXGRoAvlQSMx4bEqCaJqD8Zm4G7UaRKhqsLEQ+xrmNTbSjq +3TNWOByyrYDT13K9mmyZY+gAu0F2BbdbmRiKw7gSXFbPVgx96OLP7bx0R/vu0xdOIk9W/1DzLuY5 +poLWccret9W6aAjtmcz9opLLabid+Qqkpj5PkygqYWwHJgD/ll9ohri4zspV4KuxPX+Y1zMOWj3Y +eMLEYC/HYvBhkdI4sPaeVdtAgAUSM84dkpvRabP/v/GSCmE1P93+hvS84Bpxs2Km +-----END CERTIFICATE----- + +China Internet Network Information Center EV Certificates Root +============================================================== +-----BEGIN CERTIFICATE----- +MIID9zCCAt+gAwIBAgIESJ8AATANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCQ04xMjAwBgNV +BAoMKUNoaW5hIEludGVybmV0IE5ldHdvcmsgSW5mb3JtYXRpb24gQ2VudGVyMUcwRQYDVQQDDD5D +aGluYSBJbnRlcm5ldCBOZXR3b3JrIEluZm9ybWF0aW9uIENlbnRlciBFViBDZXJ0aWZpY2F0ZXMg +Um9vdDAeFw0xMDA4MzEwNzExMjVaFw0zMDA4MzEwNzExMjVaMIGKMQswCQYDVQQGEwJDTjEyMDAG +A1UECgwpQ2hpbmEgSW50ZXJuZXQgTmV0d29yayBJbmZvcm1hdGlvbiBDZW50ZXIxRzBFBgNVBAMM +PkNoaW5hIEludGVybmV0IE5ldHdvcmsgSW5mb3JtYXRpb24gQ2VudGVyIEVWIENlcnRpZmljYXRl +cyBSb290MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAm35z7r07eKpkQ0H1UN+U8i6y +jUqORlTSIRLIOTJCBumD1Z9S7eVnAztUwYyZmczpwA//DdmEEbK40ctb3B75aDFk4Zv6dOtouSCV +98YPjUesWgbdYavi7NifFy2cyjw1l1VxzUOFsUcW9SxTgHbP0wBkvUCZ3czY28Sf1hNfQYOL+Q2H +klY0bBoQCxfVWhyXWIQ8hBouXJE0bhlffxdpxWXvayHG1VA6v2G5BY3vbzQ6sm8UY78WO5upKv23 +KzhmBsUs4qpnHkWnjQRmQvaPK++IIGmPMowUc9orhpFjIpryp9vOiYurXccUwVswah+xt54ugQEC +7c+WXmPbqOY4twIDAQABo2MwYTAfBgNVHSMEGDAWgBR8cks5x8DbYqVPm6oYNJKiyoOCWTAPBgNV +HRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUfHJLOcfA22KlT5uqGDSSosqD +glkwDQYJKoZIhvcNAQEFBQADggEBACrDx0M3j92tpLIM7twUbY8opJhJywyA6vPtI2Z1fcXTIWd5 +0XPFtQO3WKwMVC/GVhMPMdoG52U7HW8228gd+f2ABsqjPWYWqJ1MFn3AlUa1UeTiH9fqBk1jjZaM +7+czV0I664zBechNdn3e9rG3geCg+aF4RhcaVpjwTj2rHO3sOdwHSPdj/gauwqRcalsyiMXHM4Ws +ZkJHwlgkmeHlPuV1LI5D1l08eB6olYIpUNHRFrrvwb562bTYzB5MRuF3sTGrvSrIzo9uoV1/A3U0 +5K2JRVRevq4opbs/eHnrc7MKDf2+yfdWrPa37S+bISnHOLaVxATywy39FCqQmbkHzJ8= +-----END CERTIFICATE----- + +Swisscom Root CA 2 +================== +-----BEGIN CERTIFICATE----- +MIIF2TCCA8GgAwIBAgIQHp4o6Ejy5e/DfEoeWhhntjANBgkqhkiG9w0BAQsFADBkMQswCQYDVQQG +EwJjaDERMA8GA1UEChMIU3dpc3Njb20xJTAjBgNVBAsTHERpZ2l0YWwgQ2VydGlmaWNhdGUgU2Vy +dmljZXMxGzAZBgNVBAMTElN3aXNzY29tIFJvb3QgQ0EgMjAeFw0xMTA2MjQwODM4MTRaFw0zMTA2 +MjUwNzM4MTRaMGQxCzAJBgNVBAYTAmNoMREwDwYDVQQKEwhTd2lzc2NvbTElMCMGA1UECxMcRGln +aXRhbCBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczEbMBkGA1UEAxMSU3dpc3Njb20gUm9vdCBDQSAyMIIC +IjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAlUJOhJ1R5tMJ6HJaI2nbeHCOFvErjw0DzpPM +LgAIe6szjPTpQOYXTKueuEcUMncy3SgM3hhLX3af+Dk7/E6J2HzFZ++r0rk0X2s682Q2zsKwzxNo +ysjL67XiPS4h3+os1OD5cJZM/2pYmLcX5BtS5X4HAB1f2uY+lQS3aYg5oUFgJWFLlTloYhyxCwWJ +wDaCFCE/rtuh/bxvHGCGtlOUSbkrRsVPACu/obvLP+DHVxxX6NZp+MEkUp2IVd3Chy50I9AU/SpH +Wrumnf2U5NGKpV+GY3aFy6//SSj8gO1MedK75MDvAe5QQQg1I3ArqRa0jG6F6bYRzzHdUyYb3y1a +SgJA/MTAtukxGggo5WDDH8SQjhBiYEQN7Aq+VRhxLKX0srwVYv8c474d2h5Xszx+zYIdkeNL6yxS +NLCK/RJOlrDrcH+eOfdmQrGrrFLadkBXeyq96G4DsguAhYidDMfCd7Camlf0uPoTXGiTOmekl9Ab +mbeGMktg2M7v0Ax/lZ9vh0+Hio5fCHyqW/xavqGRn1V9TrALacywlKinh/LTSlDcX3KwFnUey7QY +Ypqwpzmqm59m2I2mbJYV4+by+PGDYmy7Velhk6M99bFXi08jsJvllGov34zflVEpYKELKeRcVVi3 +qPyZ7iVNTA6z00yPhOgpD/0QVAKFyPnlw4vP5w8CAwEAAaOBhjCBgzAOBgNVHQ8BAf8EBAMCAYYw +HQYDVR0hBBYwFDASBgdghXQBUwIBBgdghXQBUwIBMBIGA1UdEwEB/wQIMAYBAf8CAQcwHQYDVR0O +BBYEFE0mICKJS9PVpAqhb97iEoHF8TwuMB8GA1UdIwQYMBaAFE0mICKJS9PVpAqhb97iEoHF8Twu +MA0GCSqGSIb3DQEBCwUAA4ICAQAyCrKkG8t9voJXiblqf/P0wS4RfbgZPnm3qKhyN2abGu2sEzsO +v2LwnN+ee6FTSA5BesogpxcbtnjsQJHzQq0Qw1zv/2BZf82Fo4s9SBwlAjxnffUy6S8w5X2lejjQ +82YqZh6NM4OKb3xuqFp1mrjX2lhIREeoTPpMSQpKwhI3qEAMw8jh0FcNlzKVxzqfl9NX+Ave5XLz +o9v/tdhZsnPdTSpxsrpJ9csc1fV5yJmz/MFMdOO0vSk3FQQoHt5FRnDsr7p4DooqzgB53MBfGWcs +a0vvaGgLQ+OswWIJ76bdZWGgr4RVSJFSHMYlkSrQwSIjYVmvRRGFHQEkNI/Ps/8XciATwoCqISxx +OQ7Qj1zB09GOInJGTB2Wrk9xseEFKZZZ9LuedT3PDTcNYtsmjGOpI99nBjx8Oto0QuFmtEYE3saW +mA9LSHokMnWRn6z3aOkquVVlzl1h0ydw2Df+n7mvoC5Wt6NlUe07qxS/TFED6F+KBZvuim6c779o ++sjaC+NCydAXFJy3SuCvkychVSa1ZC+N8f+mQAWFBVzKBxlcCxMoTFh/wqXvRdpg065lYZ1Tg3TC +rvJcwhbtkj6EPnNgiLx29CzP0H1907he0ZESEOnN3col49XtmS++dYFLJPlFRpTJKSFTnCZFqhMX +5OfNeOI5wSsSnqaeG8XmDtkx2Q== +-----END CERTIFICATE----- + +Swisscom Root EV CA 2 +===================== +-----BEGIN CERTIFICATE----- +MIIF4DCCA8igAwIBAgIRAPL6ZOJ0Y9ON/RAdBB92ylgwDQYJKoZIhvcNAQELBQAwZzELMAkGA1UE +BhMCY2gxETAPBgNVBAoTCFN3aXNzY29tMSUwIwYDVQQLExxEaWdpdGFsIENlcnRpZmljYXRlIFNl +cnZpY2VzMR4wHAYDVQQDExVTd2lzc2NvbSBSb290IEVWIENBIDIwHhcNMTEwNjI0MDk0NTA4WhcN +MzEwNjI1MDg0NTA4WjBnMQswCQYDVQQGEwJjaDERMA8GA1UEChMIU3dpc3Njb20xJTAjBgNVBAsT +HERpZ2l0YWwgQ2VydGlmaWNhdGUgU2VydmljZXMxHjAcBgNVBAMTFVN3aXNzY29tIFJvb3QgRVYg +Q0EgMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMT3HS9X6lds93BdY7BxUglgRCgz +o3pOCvrY6myLURYaVa5UJsTMRQdBTxB5f3HSek4/OE6zAMaVylvNwSqD1ycfMQ4jFrclyxy0uYAy +Xhqdk/HoPGAsp15XGVhRXrwsVgu42O+LgrQ8uMIkqBPHoCE2G3pXKSinLr9xJZDzRINpUKTk4Rti +GZQJo/PDvO/0vezbE53PnUgJUmfANykRHvvSEaeFGHR55E+FFOtSN+KxRdjMDUN/rhPSays/p8Li +qG12W0OfvrSdsyaGOx9/5fLoZigWJdBLlzin5M8J0TbDC77aO0RYjb7xnglrPvMyxyuHxuxenPaH +Za0zKcQvidm5y8kDnftslFGXEBuGCxobP/YCfnvUxVFkKJ3106yDgYjTdLRZncHrYTNaRdHLOdAG +alNgHa/2+2m8atwBz735j9m9W8E6X47aD0upm50qKGsaCnw8qyIL5XctcfaCNYGu+HuB5ur+rPQa +m3Rc6I8k9l2dRsQs0h4rIWqDJ2dVSqTjyDKXZpBy2uPUZC5f46Fq9mDU5zXNysRojddxyNMkM3Ox +bPlq4SjbX8Y96L5V5jcb7STZDxmPX2MYWFCBUWVv8p9+agTnNCRxunZLWB4ZvRVgRaoMEkABnRDi +xzgHcgplwLa7JSnaFp6LNYth7eVxV4O1PHGf40+/fh6Bn0GXAgMBAAGjgYYwgYMwDgYDVR0PAQH/ +BAQDAgGGMB0GA1UdIQQWMBQwEgYHYIV0AVMCAgYHYIV0AVMCAjASBgNVHRMBAf8ECDAGAQH/AgED +MB0GA1UdDgQWBBRF2aWBbj2ITY1x0kbBbkUe88SAnTAfBgNVHSMEGDAWgBRF2aWBbj2ITY1x0kbB +bkUe88SAnTANBgkqhkiG9w0BAQsFAAOCAgEAlDpzBp9SSzBc1P6xXCX5145v9Ydkn+0UjrgEjihL +j6p7jjm02Vj2e6E1CqGdivdj5eu9OYLU43otb98TPLr+flaYC/NUn81ETm484T4VvwYmneTwkLbU +wp4wLh/vx3rEUMfqe9pQy3omywC0Wqu1kx+AiYQElY2NfwmTv9SoqORjbdlk5LgpWgi/UOGED1V7 +XwgiG/W9mR4U9s70WBCCswo9GcG/W6uqmdjyMb3lOGbcWAXH7WMaLgqXfIeTK7KK4/HsGOV1timH +59yLGn602MnTihdsfSlEvoqq9X46Lmgxk7lq2prg2+kupYTNHAq4Sgj5nPFhJpiTt3tm7JFe3VE/ +23MPrQRYCd0EApUKPtN236YQHoA96M2kZNEzx5LH4k5E4wnJTsJdhw4Snr8PyQUQ3nqjsTzyP6Wq +J3mtMX0f/fwZacXduT98zca0wjAefm6S139hdlqP65VNvBFuIXxZN5nQBrz5Bm0yFqXZaajh3DyA +HmBR3NdUIR7KYndP+tiPsys6DXhyyWhBWkdKwqPrGtcKqzwyVcgKEZzfdNbwQBUdyLmPtTbFr/gi +uMod89a2GQ+fYWVq6nTIfI/DT11lgh/ZDYnadXL77/FHZxOzyNEZiCcmmpl5fx7kLD977vHeTYuW +l8PVP3wbI+2ksx0WckNLIOFZfsLorSa/ovc= +-----END CERTIFICATE----- + +CA Disig Root R1 +================ +-----BEGIN CERTIFICATE----- +MIIFaTCCA1GgAwIBAgIJAMMDmu5QkG4oMA0GCSqGSIb3DQEBBQUAMFIxCzAJBgNVBAYTAlNLMRMw +EQYDVQQHEwpCcmF0aXNsYXZhMRMwEQYDVQQKEwpEaXNpZyBhLnMuMRkwFwYDVQQDExBDQSBEaXNp +ZyBSb290IFIxMB4XDTEyMDcxOTA5MDY1NloXDTQyMDcxOTA5MDY1NlowUjELMAkGA1UEBhMCU0sx +EzARBgNVBAcTCkJyYXRpc2xhdmExEzARBgNVBAoTCkRpc2lnIGEucy4xGTAXBgNVBAMTEENBIERp +c2lnIFJvb3QgUjEwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCqw3j33Jijp1pedxiy +3QRkD2P9m5YJgNXoqqXinCaUOuiZc4yd39ffg/N4T0Dhf9Kn0uXKE5Pn7cZ3Xza1lK/oOI7bm+V8 +u8yN63Vz4STN5qctGS7Y1oprFOsIYgrY3LMATcMjfF9DCCMyEtztDK3AfQ+lekLZWnDZv6fXARz2 +m6uOt0qGeKAeVjGu74IKgEH3G8muqzIm1Cxr7X1r5OJeIgpFy4QxTaz+29FHuvlglzmxZcfe+5nk +CiKxLU3lSCZpq+Kq8/v8kiky6bM+TR8noc2OuRf7JT7JbvN32g0S9l3HuzYQ1VTW8+DiR0jm3hTa +YVKvJrT1cU/J19IG32PK/yHoWQbgCNWEFVP3Q+V8xaCJmGtzxmjOZd69fwX3se72V6FglcXM6pM6 +vpmumwKjrckWtc7dXpl4fho5frLABaTAgqWjR56M6ly2vGfb5ipN0gTco65F97yLnByn1tUD3AjL +LhbKXEAz6GfDLuemROoRRRw1ZS0eRWEkG4IupZ0zXWX4Qfkuy5Q/H6MMMSRE7cderVC6xkGbrPAX +ZcD4XW9boAo0PO7X6oifmPmvTiT6l7Jkdtqr9O3jw2Dv1fkCyC2fg69naQanMVXVz0tv/wQFx1is +XxYb5dKj6zHbHzMVTdDypVP1y+E9Tmgt2BLdqvLmTZtJ5cUoobqwWsagtQIDAQABo0IwQDAPBgNV +HRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUiQq0OJMa5qvum5EY+fU8PjXQ +04IwDQYJKoZIhvcNAQEFBQADggIBADKL9p1Kyb4U5YysOMo6CdQbzoaz3evUuii+Eq5FLAR0rBNR +xVgYZk2C2tXck8An4b58n1KeElb21Zyp9HWc+jcSjxyT7Ff+Bw+r1RL3D65hXlaASfX8MPWbTx9B +LxyE04nH4toCdu0Jz2zBuByDHBb6lM19oMgY0sidbvW9adRtPTXoHqJPYNcHKfyyo6SdbhWSVhlM +CrDpfNIZTUJG7L399ldb3Zh+pE3McgODWF3vkzpBemOqfDqo9ayk0d2iLbYq/J8BjuIQscTK5Gfb +VSUZP/3oNn6z4eGBrxEWi1CXYBmCAMBrTXO40RMHPuq2MU/wQppt4hF05ZSsjYSVPCGvxdpHyN85 +YmLLW1AL14FABZyb7bq2ix4Eb5YgOe2kfSnbSM6C3NQCjR0EMVrHS/BsYVLXtFHCgWzN4funodKS +ds+xDzdYpPJScWc/DIh4gInByLUfkmO+p3qKViwaqKactV2zY9ATIKHrkWzQjX2v3wvkF7mGnjix +lAxYjOBVqjtjbZqJYLhkKpLGN/R+Q0O3c+gB53+XD9fyexn9GtePyfqFa3qdnom2piiZk4hA9z7N +UaPK6u95RyG1/jLix8NRb76AdPCkwzryT+lf3xkK8jsTQ6wxpLPn6/wY1gGp8yqPNg7rtLG8t0zJ +a7+h89n07eLw4+1knj0vllJPgFOL +-----END CERTIFICATE----- + +CA Disig Root R2 +================ +-----BEGIN CERTIFICATE----- +MIIFaTCCA1GgAwIBAgIJAJK4iNuwisFjMA0GCSqGSIb3DQEBCwUAMFIxCzAJBgNVBAYTAlNLMRMw +EQYDVQQHEwpCcmF0aXNsYXZhMRMwEQYDVQQKEwpEaXNpZyBhLnMuMRkwFwYDVQQDExBDQSBEaXNp +ZyBSb290IFIyMB4XDTEyMDcxOTA5MTUzMFoXDTQyMDcxOTA5MTUzMFowUjELMAkGA1UEBhMCU0sx +EzARBgNVBAcTCkJyYXRpc2xhdmExEzARBgNVBAoTCkRpc2lnIGEucy4xGTAXBgNVBAMTEENBIERp +c2lnIFJvb3QgUjIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCio8QACdaFXS1tFPbC +w3OeNcJxVX6B+6tGUODBfEl45qt5WDza/3wcn9iXAng+a0EE6UG9vgMsRfYvZNSrXaNHPWSb6Wia +xswbP7q+sos0Ai6YVRn8jG+qX9pMzk0DIaPY0jSTVpbLTAwAFjxfGs3Ix2ymrdMxp7zo5eFm1tL7 +A7RBZckQrg4FY8aAamkw/dLukO8NJ9+flXP04SXabBbeQTg06ov80egEFGEtQX6sx3dOy1FU+16S +GBsEWmjGycT6txOgmLcRK7fWV8x8nhfRyyX+hk4kLlYMeE2eARKmK6cBZW58Yh2EhN/qwGu1pSqV +g8NTEQxzHQuyRpDRQjrOQG6Vrf/GlK1ul4SOfW+eioANSW1z4nuSHsPzwfPrLgVv2RvPN3YEyLRa +5Beny912H9AZdugsBbPWnDTYltxhh5EF5EQIM8HauQhl1K6yNg3ruji6DOWbnuuNZt2Zz9aJQfYE +koopKW1rOhzndX0CcQ7zwOe9yxndnWCywmZgtrEE7snmhrmaZkCo5xHtgUUDi/ZnWejBBhG93c+A +Ak9lQHhcR1DIm+YfgXvkRKhbhZri3lrVx/k6RGZL5DJUfORsnLMOPReisjQS1n6yqEm70XooQL6i +Fh/f5DcfEXP7kAplQ6INfPgGAVUzfbANuPT1rqVCV3w2EYx7XsQDnYx5nQIDAQABo0IwQDAPBgNV +HRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUtZn4r7CU9eMg1gqtzk5WpC5u +Qu0wDQYJKoZIhvcNAQELBQADggIBACYGXnDnZTPIgm7ZnBc6G3pmsgH2eDtpXi/q/075KMOYKmFM +tCQSin1tERT3nLXK5ryeJ45MGcipvXrA1zYObYVybqjGom32+nNjf7xueQgcnYqfGopTpti72TVV +sRHFqQOzVju5hJMiXn7B9hJSi+osZ7z+Nkz1uM/Rs0mSO9MpDpkblvdhuDvEK7Z4bLQjb/D907Je +dR+Zlais9trhxTF7+9FGs9K8Z7RiVLoJ92Owk6Ka+elSLotgEqv89WBW7xBci8QaQtyDW2QOy7W8 +1k/BfDxujRNt+3vrMNDcTa/F1balTFtxyegxvug4BkihGuLq0t4SOVga/4AOgnXmt8kHbA7v/zjx +mHHEt38OFdAlab0inSvtBfZGR6ztwPDUO+Ls7pZbkBNOHlY667DvlruWIxG68kOGdGSVyCh13x01 +utI3gzhTODY7z2zp+WsO0PsE6E9312UBeIYMej4hYvF/Y3EMyZ9E26gnonW+boE+18DrG5gPcFw0 +sorMwIUY6256s/daoQe/qUKS82Ail+QUoQebTnbAjn39pCXHR+3/H3OszMOl6W8KjptlwlCFtaOg +UxLMVYdh84GuEEZhvUQhuMI9dM9+JDX6HAcOmz0iyu8xL4ysEr3vQCj8KWefshNPZiTEUxnpHikV +7+ZtsH8tZ/3zbBt1RqPlShfppNcL +-----END CERTIFICATE----- + +ACCVRAIZ1 +========= +-----BEGIN CERTIFICATE----- +MIIH0zCCBbugAwIBAgIIXsO3pkN/pOAwDQYJKoZIhvcNAQEFBQAwQjESMBAGA1UEAwwJQUNDVlJB +SVoxMRAwDgYDVQQLDAdQS0lBQ0NWMQ0wCwYDVQQKDARBQ0NWMQswCQYDVQQGEwJFUzAeFw0xMTA1 +MDUwOTM3MzdaFw0zMDEyMzEwOTM3MzdaMEIxEjAQBgNVBAMMCUFDQ1ZSQUlaMTEQMA4GA1UECwwH +UEtJQUNDVjENMAsGA1UECgwEQUNDVjELMAkGA1UEBhMCRVMwggIiMA0GCSqGSIb3DQEBAQUAA4IC +DwAwggIKAoICAQCbqau/YUqXry+XZpp0X9DZlv3P4uRm7x8fRzPCRKPfmt4ftVTdFXxpNRFvu8gM +jmoYHtiP2Ra8EEg2XPBjs5BaXCQ316PWywlxufEBcoSwfdtNgM3802/J+Nq2DoLSRYWoG2ioPej0 +RGy9ocLLA76MPhMAhN9KSMDjIgro6TenGEyxCQ0jVn8ETdkXhBilyNpAlHPrzg5XPAOBOp0KoVdD +aaxXbXmQeOW1tDvYvEyNKKGno6e6Ak4l0Squ7a4DIrhrIA8wKFSVf+DuzgpmndFALW4ir50awQUZ +0m/A8p/4e7MCQvtQqR0tkw8jq8bBD5L/0KIV9VMJcRz/RROE5iZe+OCIHAr8Fraocwa48GOEAqDG +WuzndN9wrqODJerWx5eHk6fGioozl2A3ED6XPm4pFdahD9GILBKfb6qkxkLrQaLjlUPTAYVtjrs7 +8yM2x/474KElB0iryYl0/wiPgL/AlmXz7uxLaL2diMMxs0Dx6M/2OLuc5NF/1OVYm3z61PMOm3WR +5LpSLhl+0fXNWhn8ugb2+1KoS5kE3fj5tItQo05iifCHJPqDQsGH+tUtKSpacXpkatcnYGMN285J +9Y0fkIkyF/hzQ7jSWpOGYdbhdQrqeWZ2iE9x6wQl1gpaepPluUsXQA+xtrn13k/c4LOsOxFwYIRK +Q26ZIMApcQrAZQIDAQABo4ICyzCCAscwfQYIKwYBBQUHAQEEcTBvMEwGCCsGAQUFBzAChkBodHRw +Oi8vd3d3LmFjY3YuZXMvZmlsZWFkbWluL0FyY2hpdm9zL2NlcnRpZmljYWRvcy9yYWl6YWNjdjEu +Y3J0MB8GCCsGAQUFBzABhhNodHRwOi8vb2NzcC5hY2N2LmVzMB0GA1UdDgQWBBTSh7Tj3zcnk1X2 +VuqB5TbMjB4/vTAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFNKHtOPfNyeTVfZW6oHlNsyM +Hj+9MIIBcwYDVR0gBIIBajCCAWYwggFiBgRVHSAAMIIBWDCCASIGCCsGAQUFBwICMIIBFB6CARAA +QQB1AHQAbwByAGkAZABhAGQAIABkAGUAIABDAGUAcgB0AGkAZgBpAGMAYQBjAGkA8wBuACAAUgBh +AO0AegAgAGQAZQAgAGwAYQAgAEEAQwBDAFYAIAAoAEEAZwBlAG4AYwBpAGEAIABkAGUAIABUAGUA +YwBuAG8AbABvAGcA7QBhACAAeQAgAEMAZQByAHQAaQBmAGkAYwBhAGMAaQDzAG4AIABFAGwAZQBj +AHQAcgDzAG4AaQBjAGEALAAgAEMASQBGACAAUQA0ADYAMAAxADEANQA2AEUAKQAuACAAQwBQAFMA +IABlAG4AIABoAHQAdABwADoALwAvAHcAdwB3AC4AYQBjAGMAdgAuAGUAczAwBggrBgEFBQcCARYk +aHR0cDovL3d3dy5hY2N2LmVzL2xlZ2lzbGFjaW9uX2MuaHRtMFUGA1UdHwROMEwwSqBIoEaGRGh0 +dHA6Ly93d3cuYWNjdi5lcy9maWxlYWRtaW4vQXJjaGl2b3MvY2VydGlmaWNhZG9zL3JhaXphY2N2 +MV9kZXIuY3JsMA4GA1UdDwEB/wQEAwIBBjAXBgNVHREEEDAOgQxhY2N2QGFjY3YuZXMwDQYJKoZI +hvcNAQEFBQADggIBAJcxAp/n/UNnSEQU5CmH7UwoZtCPNdpNYbdKl02125DgBS4OxnnQ8pdpD70E +R9m+27Up2pvZrqmZ1dM8MJP1jaGo/AaNRPTKFpV8M9xii6g3+CfYCS0b78gUJyCpZET/LtZ1qmxN +YEAZSUNUY9rizLpm5U9EelvZaoErQNV/+QEnWCzI7UiRfD+mAM/EKXMRNt6GGT6d7hmKG9Ww7Y49 +nCrADdg9ZuM8Db3VlFzi4qc1GwQA9j9ajepDvV+JHanBsMyZ4k0ACtrJJ1vnE5Bc5PUzolVt3OAJ +TS+xJlsndQAJxGJ3KQhfnlmstn6tn1QwIgPBHnFk/vk4CpYY3QIUrCPLBhwepH2NDd4nQeit2hW3 +sCPdK6jT2iWH7ehVRE2I9DZ+hJp4rPcOVkkO1jMl1oRQQmwgEh0q1b688nCBpHBgvgW1m54ERL5h +I6zppSSMEYCUWqKiuUnSwdzRp+0xESyeGabu4VXhwOrPDYTkF7eifKXeVSUG7szAh1xA2syVP1Xg +Nce4hL60Xc16gwFy7ofmXx2utYXGJt/mwZrpHgJHnyqobalbz+xFd3+YJ5oyXSrjhO7FmGYvliAd +3djDJ9ew+f7Zfc3Qn48LFFhRny+Lwzgt3uiP1o2HpPVWQxaZLPSkVrQ0uGE3ycJYgBugl6H8WY3p +EfbRD0tVNEYqi4Y7 +-----END CERTIFICATE----- + +TWCA Global Root CA +=================== +-----BEGIN CERTIFICATE----- +MIIFQTCCAymgAwIBAgICDL4wDQYJKoZIhvcNAQELBQAwUTELMAkGA1UEBhMCVFcxEjAQBgNVBAoT +CVRBSVdBTi1DQTEQMA4GA1UECxMHUm9vdCBDQTEcMBoGA1UEAxMTVFdDQSBHbG9iYWwgUm9vdCBD +QTAeFw0xMjA2MjcwNjI4MzNaFw0zMDEyMzExNTU5NTlaMFExCzAJBgNVBAYTAlRXMRIwEAYDVQQK +EwlUQUlXQU4tQ0ExEDAOBgNVBAsTB1Jvb3QgQ0ExHDAaBgNVBAMTE1RXQ0EgR2xvYmFsIFJvb3Qg +Q0EwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCwBdvI64zEbooh745NnHEKH1Jw7W2C +nJfF10xORUnLQEK1EjRsGcJ0pDFfhQKX7EMzClPSnIyOt7h52yvVavKOZsTuKwEHktSz0ALfUPZV +r2YOy+BHYC8rMjk1Ujoog/h7FsYYuGLWRyWRzvAZEk2tY/XTP3VfKfChMBwqoJimFb3u/Rk28OKR +Q4/6ytYQJ0lM793B8YVwm8rqqFpD/G2Gb3PpN0Wp8DbHzIh1HrtsBv+baz4X7GGqcXzGHaL3SekV +tTzWoWH1EfcFbx39Eb7QMAfCKbAJTibc46KokWofwpFFiFzlmLhxpRUZyXx1EcxwdE8tmx2RRP1W +KKD+u4ZqyPpcC1jcxkt2yKsi2XMPpfRaAok/T54igu6idFMqPVMnaR1sjjIsZAAmY2E2TqNGtz99 +sy2sbZCilaLOz9qC5wc0GZbpuCGqKX6mOL6OKUohZnkfs8O1CWfe1tQHRvMq2uYiN2DLgbYPoA/p +yJV/v1WRBXrPPRXAb94JlAGD1zQbzECl8LibZ9WYkTunhHiVJqRaCPgrdLQABDzfuBSO6N+pjWxn +kjMdwLfS7JLIvgm/LCkFbwJrnu+8vyq8W8BQj0FwcYeyTbcEqYSjMq+u7msXi7Kx/mzhkIyIqJdI +zshNy/MGz19qCkKxHh53L46g5pIOBvwFItIm4TFRfTLcDwIDAQABoyMwITAOBgNVHQ8BAf8EBAMC +AQYwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAgEAXzSBdu+WHdXltdkCY4QWwa6g +cFGn90xHNcgL1yg9iXHZqjNB6hQbbCEAwGxCGX6faVsgQt+i0trEfJdLjbDorMjupWkEmQqSpqsn +LhpNgb+E1HAerUf+/UqdM+DyucRFCCEK2mlpc3INvjT+lIutwx4116KD7+U4x6WFH6vPNOw/KP4M +8VeGTslV9xzU2KV9Bnpv1d8Q34FOIWWxtuEXeZVFBs5fzNxGiWNoRI2T9GRwoD2dKAXDOXC4Ynsg +/eTb6QihuJ49CcdP+yz4k3ZB3lLg4VfSnQO8d57+nile98FRYB/e2guyLXW3Q0iT5/Z5xoRdgFlg +lPx4mI88k1HtQJAH32RjJMtOcQWh15QaiDLxInQirqWm2BJpTGCjAu4r7NRjkgtevi92a6O2JryP +A9gK8kxkRr05YuWW6zRjESjMlfGt7+/cgFhI6Uu46mWs6fyAtbXIRfmswZ/ZuepiiI7E8UuDEq3m +i4TWnsLrgxifarsbJGAzcMzs9zLzXNl5fe+epP7JI8Mk7hWSsT2RTyaGvWZzJBPqpK5jwa19hAM8 +EHiGG3njxPPyBJUgriOCxLM6AGK/5jYk4Ve6xx6QddVfP5VhK8E7zeWzaGHQRiapIVJpLesux+t3 +zqY6tQMzT3bR51xUAV3LePTJDL/PEo4XLSNolOer/qmyKwbQBM0= +-----END CERTIFICATE----- + +TeliaSonera Root CA v1 +====================== +-----BEGIN CERTIFICATE----- +MIIFODCCAyCgAwIBAgIRAJW+FqD3LkbxezmCcvqLzZYwDQYJKoZIhvcNAQEFBQAwNzEUMBIGA1UE +CgwLVGVsaWFTb25lcmExHzAdBgNVBAMMFlRlbGlhU29uZXJhIFJvb3QgQ0EgdjEwHhcNMDcxMDE4 +MTIwMDUwWhcNMzIxMDE4MTIwMDUwWjA3MRQwEgYDVQQKDAtUZWxpYVNvbmVyYTEfMB0GA1UEAwwW +VGVsaWFTb25lcmEgUm9vdCBDQSB2MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMK+ +6yfwIaPzaSZVfp3FVRaRXP3vIb9TgHot0pGMYzHw7CTww6XScnwQbfQ3t+XmfHnqjLWCi65ItqwA +3GV17CpNX8GH9SBlK4GoRz6JI5UwFpB/6FcHSOcZrr9FZ7E3GwYq/t75rH2D+1665I+XZ75Ljo1k +B1c4VWk0Nj0TSO9P4tNmHqTPGrdeNjPUtAa9GAH9d4RQAEX1jF3oI7x+/jXh7VB7qTCNGdMJjmhn +Xb88lxhTuylixcpecsHHltTbLaC0H2kD7OriUPEMPPCs81Mt8Bz17Ww5OXOAFshSsCPN4D7c3TxH +oLs1iuKYaIu+5b9y7tL6pe0S7fyYGKkmdtwoSxAgHNN/Fnct7W+A90m7UwW7XWjH1Mh1Fj+JWov3 +F0fUTPHSiXk+TT2YqGHeOh7S+F4D4MHJHIzTjU3TlTazN19jY5szFPAtJmtTfImMMsJu7D0hADnJ +oWjiUIMusDor8zagrC/kb2HCUQk5PotTubtn2txTuXZZNp1D5SDgPTJghSJRt8czu90VL6R4pgd7 +gUY2BIbdeTXHlSw7sKMXNeVzH7RcWe/a6hBle3rQf5+ztCo3O3CLm1u5K7fsslESl1MpWtTwEhDc +TwK7EpIvYtQ/aUN8Ddb8WHUBiJ1YFkveupD/RwGJBmr2X7KQarMCpgKIv7NHfirZ1fpoeDVNAgMB +AAGjPzA9MA8GA1UdEwEB/wQFMAMBAf8wCwYDVR0PBAQDAgEGMB0GA1UdDgQWBBTwj1k4ALP1j5qW +DNXr+nuqF+gTEjANBgkqhkiG9w0BAQUFAAOCAgEAvuRcYk4k9AwI//DTDGjkk0kiP0Qnb7tt3oNm +zqjMDfz1mgbldxSR651Be5kqhOX//CHBXfDkH1e3damhXwIm/9fH907eT/j3HEbAek9ALCI18Bmx +0GtnLLCo4MBANzX2hFxc469CeP6nyQ1Q6g2EdvZR74NTxnr/DlZJLo961gzmJ1TjTQpgcmLNkQfW +pb/ImWvtxBnmq0wROMVvMeJuScg/doAmAyYp4Db29iBT4xdwNBedY2gea+zDTYa4EzAvXUYNR0PV +G6pZDrlcjQZIrXSHX8f8MVRBE+LHIQ6e4B4N4cB7Q4WQxYpYxmUKeFfyxiMPAdkgS94P+5KFdSpc +c41teyWRyu5FrgZLAMzTsVlQ2jqIOylDRl6XK1TOU2+NSueW+r9xDkKLfP0ooNBIytrEgUy7onOT +JsjrDNYmiLbAJM+7vVvrdX3pCI6GMyx5dwlppYn8s3CQh3aP0yK7Qs69cwsgJirQmz1wHiRszYd2 +qReWt88NkvuOGKmYSdGe/mBEciG5Ge3C9THxOUiIkCR1VBatzvT4aRRkOfujuLpwQMcnHL/EVlP6 +Y2XQ8xwOFvVrhlhNGNTkDY6lnVuR3HYkUD/GKvvZt5y11ubQ2egZixVxSK236thZiNSQvxaz2ems +WWFUyBy6ysHK4bkgTI86k4mloMy/0/Z1pHWWbVY= +-----END CERTIFICATE----- + +E-Tugra Certification Authority +=============================== +-----BEGIN CERTIFICATE----- +MIIGSzCCBDOgAwIBAgIIamg+nFGby1MwDQYJKoZIhvcNAQELBQAwgbIxCzAJBgNVBAYTAlRSMQ8w +DQYDVQQHDAZBbmthcmExQDA+BgNVBAoMN0UtVHXEn3JhIEVCRyBCaWxpxZ9pbSBUZWtub2xvamls +ZXJpIHZlIEhpem1ldGxlcmkgQS7Fni4xJjAkBgNVBAsMHUUtVHVncmEgU2VydGlmaWthc3lvbiBN +ZXJrZXppMSgwJgYDVQQDDB9FLVR1Z3JhIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTEzMDMw +NTEyMDk0OFoXDTIzMDMwMzEyMDk0OFowgbIxCzAJBgNVBAYTAlRSMQ8wDQYDVQQHDAZBbmthcmEx +QDA+BgNVBAoMN0UtVHXEn3JhIEVCRyBCaWxpxZ9pbSBUZWtub2xvamlsZXJpIHZlIEhpem1ldGxl +cmkgQS7Fni4xJjAkBgNVBAsMHUUtVHVncmEgU2VydGlmaWthc3lvbiBNZXJrZXppMSgwJgYDVQQD +DB9FLVR1Z3JhIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIICIjANBgkqhkiG9w0BAQEFAAOCAg8A +MIICCgKCAgEA4vU/kwVRHoViVF56C/UYB4Oufq9899SKa6VjQzm5S/fDxmSJPZQuVIBSOTkHS0vd +hQd2h8y/L5VMzH2nPbxHD5hw+IyFHnSOkm0bQNGZDbt1bsipa5rAhDGvykPL6ys06I+XawGb1Q5K +CKpbknSFQ9OArqGIW66z6l7LFpp3RMih9lRozt6Plyu6W0ACDGQXwLWTzeHxE2bODHnv0ZEoq1+g +ElIwcxmOj+GMB6LDu0rw6h8VqO4lzKRG+Bsi77MOQ7osJLjFLFzUHPhdZL3Dk14opz8n8Y4e0ypQ +BaNV2cvnOVPAmJ6MVGKLJrD3fY185MaeZkJVgkfnsliNZvcHfC425lAcP9tDJMW/hkd5s3kc91r0 +E+xs+D/iWR+V7kI+ua2oMoVJl0b+SzGPWsutdEcf6ZG33ygEIqDUD13ieU/qbIWGvaimzuT6w+Gz +rt48Ue7LE3wBf4QOXVGUnhMMti6lTPk5cDZvlsouDERVxcr6XQKj39ZkjFqzAQqptQpHF//vkUAq +jqFGOjGY5RH8zLtJVor8udBhmm9lbObDyz51Sf6Pp+KJxWfXnUYTTjF2OySznhFlhqt/7x3U+Lzn +rFpct1pHXFXOVbQicVtbC/DP3KBhZOqp12gKY6fgDT+gr9Oq0n7vUaDmUStVkhUXU8u3Zg5mTPj5 +dUyQ5xJwx0UCAwEAAaNjMGEwHQYDVR0OBBYEFC7j27JJ0JxUeVz6Jyr+zE7S6E5UMA8GA1UdEwEB +/wQFMAMBAf8wHwYDVR0jBBgwFoAULuPbsknQnFR5XPonKv7MTtLoTlQwDgYDVR0PAQH/BAQDAgEG +MA0GCSqGSIb3DQEBCwUAA4ICAQAFNzr0TbdF4kV1JI+2d1LoHNgQk2Xz8lkGpD4eKexd0dCrfOAK +kEh47U6YA5n+KGCRHTAduGN8qOY1tfrTYXbm1gdLymmasoR6d5NFFxWfJNCYExL/u6Au/U5Mh/jO +XKqYGwXgAEZKgoClM4so3O0409/lPun++1ndYYRP0lSWE2ETPo+Aab6TR7U1Q9Jauz1c77NCR807 +VRMGsAnb/WP2OogKmW9+4c4bU2pEZiNRCHu8W1Ki/QY3OEBhj0qWuJA3+GbHeJAAFS6LrVE1Uweo +a2iu+U48BybNCAVwzDk/dr2l02cmAYamU9JgO3xDf1WKvJUawSg5TB9D0pH0clmKuVb8P7Sd2nCc +dlqMQ1DujjByTd//SffGqWfZbawCEeI6FiWnWAjLb1NBnEg4R2gz0dfHj9R0IdTDBZB6/86WiLEV +KV0jq9BgoRJP3vQXzTLlyb/IQ639Lo7xr+L0mPoSHyDYwKcMhcWQ9DstliaxLL5Mq+ux0orJ23gT +Dx4JnW2PAJ8C2sH6H3p6CcRK5ogql5+Ji/03X186zjhZhkuvcQu02PJwT58yE+Owp1fl2tpDy4Q0 +8ijE6m30Ku/Ba3ba+367hTzSU8JNvnHhRdH9I2cNE3X7z2VnIp2usAnRCf8dNL/+I5c30jn6PQ0G +C7TbO6Orb1wdtn7os4I07QZcJA== +-----END CERTIFICATE----- + +T-TeleSec GlobalRoot Class 2 +============================ +-----BEGIN CERTIFICATE----- +MIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoM +IlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBU +cnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDIwHhcNMDgx +MDAxMTA0MDE0WhcNMzMxMDAxMjM1OTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lz +dGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBD +ZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDIwggEiMA0GCSqGSIb3 +DQEBAQUAA4IBDwAwggEKAoIBAQCqX9obX+hzkeXaXPSi5kfl82hVYAUdAqSzm1nzHoqvNK38DcLZ +SBnuaY/JIPwhqgcZ7bBcrGXHX+0CfHt8LRvWurmAwhiCFoT6ZrAIxlQjgeTNuUk/9k9uN0goOA/F +vudocP05l03Sx5iRUKrERLMjfTlH6VJi1hKTXrcxlkIF+3anHqP1wvzpesVsqXFP6st4vGCvx970 +2cu+fjOlbpSD8DT6IavqjnKgP6TeMFvvhk1qlVtDRKgQFRzlAVfFmPHmBiiRqiDFt1MmUUOyCxGV +WOHAD3bZwI18gfNycJ5v/hqO2V81xrJvNHy+SE/iWjnX2J14np+GPgNeGYtEotXHAgMBAAGjQjBA +MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS/WSA2AHmgoCJrjNXy +YdK4LMuCSjANBgkqhkiG9w0BAQsFAAOCAQEAMQOiYQsfdOhyNsZt+U2e+iKo4YFWz827n+qrkRk4 +r6p8FU3ztqONpfSO9kSpp+ghla0+AGIWiPACuvxhI+YzmzB6azZie60EI4RYZeLbK4rnJVM3YlNf +vNoBYimipidx5joifsFvHZVwIEoHNN/q/xWA5brXethbdXwFeilHfkCoMRN3zUA7tFFHei4R40cR +3p1m0IvVVGb6g1XqfMIpiRvpb7PO4gWEyS8+eIVibslfwXhjdFjASBgMmTnrpMwatXlajRWc2BQN +9noHV8cigwUtPJslJj0Ys6lDfMjIq2SPDqO/nBudMNva0Bkuqjzx+zOAduTNrRlPBSeOE6Fuwg== +-----END CERTIFICATE----- + +Atos TrustedRoot 2011 +===================== +-----BEGIN CERTIFICATE----- +MIIDdzCCAl+gAwIBAgIIXDPLYixfszIwDQYJKoZIhvcNAQELBQAwPDEeMBwGA1UEAwwVQXRvcyBU +cnVzdGVkUm9vdCAyMDExMQ0wCwYDVQQKDARBdG9zMQswCQYDVQQGEwJERTAeFw0xMTA3MDcxNDU4 +MzBaFw0zMDEyMzEyMzU5NTlaMDwxHjAcBgNVBAMMFUF0b3MgVHJ1c3RlZFJvb3QgMjAxMTENMAsG +A1UECgwEQXRvczELMAkGA1UEBhMCREUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCV +hTuXbyo7LjvPpvMpNb7PGKw+qtn4TaA+Gke5vJrf8v7MPkfoepbCJI419KkM/IL9bcFyYie96mvr +54rMVD6QUM+A1JX76LWC1BTFtqlVJVfbsVD2sGBkWXppzwO3bw2+yj5vdHLqqjAqc2K+SZFhyBH+ +DgMq92og3AIVDV4VavzjgsG1xZ1kCWyjWZgHJ8cblithdHFsQ/H3NYkQ4J7sVaE3IqKHBAUsR320 +HLliKWYoyrfhk/WklAOZuXCFteZI6o1Q/NnezG8HDt0Lcp2AMBYHlT8oDv3FdU9T1nSatCQujgKR +z3bFmx5VdJx4IbHwLfELn8LVlhgf8FQieowHAgMBAAGjfTB7MB0GA1UdDgQWBBSnpQaxLKYJYO7R +l+lwrrw7GWzbITAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFKelBrEspglg7tGX6XCuvDsZ +bNshMBgGA1UdIAQRMA8wDQYLKwYBBAGwLQMEAQEwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEB +CwUAA4IBAQAmdzTblEiGKkGdLD4GkGDEjKwLVLgfuXvTBznk+j57sj1O7Z8jvZfza1zv7v1Apt+h +k6EKhqzvINB5Ab149xnYJDE0BAGmuhWawyfc2E8PzBhj/5kPDpFrdRbhIfzYJsdHt6bPWHJxfrrh +TZVHO8mvbaG0weyJ9rQPOLXiZNwlz6bb65pcmaHFCN795trV1lpFDMS3wrUU77QR/w4VtfX128a9 +61qn8FYiqTxlVMYVqL2Gns2Dlmh6cYGJ4Qvh6hEbaAjMaZ7snkGeRDImeuKHCnE96+RapNLbxc3G +3mB/ufNPRJLvKrcYPqcZ2Qt9sTdBQrC6YB3y/gkRsPCHe6ed +-----END CERTIFICATE----- + diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/StaticClient.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/StaticClient.php new file mode 100644 index 000000000..dbd4c1841 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/StaticClient.php @@ -0,0 +1,157 @@ +createRequest($method, $url, null, null, $options); + + if (isset($options['stream'])) { + if ($options['stream'] instanceof StreamRequestFactoryInterface) { + return $options['stream']->fromRequest($request); + } elseif ($options['stream'] == true) { + $streamFactory = new PhpStreamRequestFactory(); + return $streamFactory->fromRequest($request); + } + } + + return $request->send(); + } + + /** + * Send a GET request + * + * @param string $url URL of the request + * @param array $options Array of request options + * + * @return \Guzzle\Http\Message\Response + * @see Guzzle::request for a list of available options + */ + public static function get($url, $options = array()) + { + return self::request('GET', $url, $options); + } + + /** + * Send a HEAD request + * + * @param string $url URL of the request + * @param array $options Array of request options + * + * @return \Guzzle\Http\Message\Response + * @see Guzzle::request for a list of available options + */ + public static function head($url, $options = array()) + { + return self::request('HEAD', $url, $options); + } + + /** + * Send a DELETE request + * + * @param string $url URL of the request + * @param array $options Array of request options + * + * @return \Guzzle\Http\Message\Response + * @see Guzzle::request for a list of available options + */ + public static function delete($url, $options = array()) + { + return self::request('DELETE', $url, $options); + } + + /** + * Send a POST request + * + * @param string $url URL of the request + * @param array $options Array of request options + * + * @return \Guzzle\Http\Message\Response + * @see Guzzle::request for a list of available options + */ + public static function post($url, $options = array()) + { + return self::request('POST', $url, $options); + } + + /** + * Send a PUT request + * + * @param string $url URL of the request + * @param array $options Array of request options + * + * @return \Guzzle\Http\Message\Response + * @see Guzzle::request for a list of available options + */ + public static function put($url, $options = array()) + { + return self::request('PUT', $url, $options); + } + + /** + * Send a PATCH request + * + * @param string $url URL of the request + * @param array $options Array of request options + * + * @return \Guzzle\Http\Message\Response + * @see Guzzle::request for a list of available options + */ + public static function patch($url, $options = array()) + { + return self::request('PATCH', $url, $options); + } + + /** + * Send an OPTIONS request + * + * @param string $url URL of the request + * @param array $options Array of request options + * + * @return \Guzzle\Http\Message\Response + * @see Guzzle::request for a list of available options + */ + public static function options($url, $options = array()) + { + return self::request('OPTIONS', $url, $options); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Url.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Url.php new file mode 100644 index 000000000..6a4e77245 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/Url.php @@ -0,0 +1,554 @@ + null, 'host' => null, 'path' => null, 'port' => null, 'query' => null, + 'user' => null, 'pass' => null, 'fragment' => null); + + if (false === ($parts = parse_url($url))) { + throw new InvalidArgumentException('Was unable to parse malformed url: ' . $url); + } + + $parts += $defaults; + + // Convert the query string into a QueryString object + if ($parts['query'] || 0 !== strlen($parts['query'])) { + $parts['query'] = QueryString::fromString($parts['query']); + } + + return new static($parts['scheme'], $parts['host'], $parts['user'], + $parts['pass'], $parts['port'], $parts['path'], $parts['query'], + $parts['fragment']); + } + + /** + * Build a URL from parse_url parts. The generated URL will be a relative URL if a scheme or host are not provided. + * + * @param array $parts Array of parse_url parts + * + * @return string + */ + public static function buildUrl(array $parts) + { + $url = $scheme = ''; + + if (isset($parts['scheme'])) { + $scheme = $parts['scheme']; + $url .= $scheme . ':'; + } + + if (isset($parts['host'])) { + $url .= '//'; + if (isset($parts['user'])) { + $url .= $parts['user']; + if (isset($parts['pass'])) { + $url .= ':' . $parts['pass']; + } + $url .= '@'; + } + + $url .= $parts['host']; + + // Only include the port if it is not the default port of the scheme + if (isset($parts['port']) + && !(($scheme == 'http' && $parts['port'] == 80) || ($scheme == 'https' && $parts['port'] == 443)) + ) { + $url .= ':' . $parts['port']; + } + } + + // Add the path component if present + if (isset($parts['path']) && 0 !== strlen($parts['path'])) { + // Always ensure that the path begins with '/' if set and something is before the path + if ($url && $parts['path'][0] != '/' && substr($url, -1) != '/') { + $url .= '/'; + } + $url .= $parts['path']; + } + + // Add the query string if present + if (isset($parts['query'])) { + $url .= '?' . $parts['query']; + } + + // Ensure that # is only added to the url if fragment contains anything. + if (isset($parts['fragment'])) { + $url .= '#' . $parts['fragment']; + } + + return $url; + } + + /** + * Create a new URL from URL parts + * + * @param string $scheme Scheme of the URL + * @param string $host Host of the URL + * @param string $username Username of the URL + * @param string $password Password of the URL + * @param int $port Port of the URL + * @param string $path Path of the URL + * @param QueryString|array|string $query Query string of the URL + * @param string $fragment Fragment of the URL + */ + public function __construct($scheme, $host, $username = null, $password = null, $port = null, $path = null, QueryString $query = null, $fragment = null) + { + $this->scheme = $scheme; + $this->host = $host; + $this->port = $port; + $this->username = $username; + $this->password = $password; + $this->fragment = $fragment; + if (!$query) { + $this->query = new QueryString(); + } else { + $this->setQuery($query); + } + $this->setPath($path); + } + + /** + * Clone the URL + */ + public function __clone() + { + $this->query = clone $this->query; + } + + /** + * Returns the URL as a URL string + * + * @return string + */ + public function __toString() + { + return self::buildUrl($this->getParts()); + } + + /** + * Get the parts of the URL as an array + * + * @return array + */ + public function getParts() + { + $query = (string) $this->query; + + return array( + 'scheme' => $this->scheme, + 'user' => $this->username, + 'pass' => $this->password, + 'host' => $this->host, + 'port' => $this->port, + 'path' => $this->getPath(), + 'query' => $query !== '' ? $query : null, + 'fragment' => $this->fragment, + ); + } + + /** + * Set the host of the request. + * + * @param string $host Host to set (e.g. www.yahoo.com, yahoo.com) + * + * @return Url + */ + public function setHost($host) + { + if (strpos($host, ':') === false) { + $this->host = $host; + } else { + list($host, $port) = explode(':', $host); + $this->host = $host; + $this->setPort($port); + } + + return $this; + } + + /** + * Get the host part of the URL + * + * @return string + */ + public function getHost() + { + return $this->host; + } + + /** + * Set the scheme part of the URL (http, https, ftp, etc) + * + * @param string $scheme Scheme to set + * + * @return Url + */ + public function setScheme($scheme) + { + if ($this->scheme == 'http' && $this->port == 80) { + $this->port = null; + } elseif ($this->scheme == 'https' && $this->port == 443) { + $this->port = null; + } + + $this->scheme = $scheme; + + return $this; + } + + /** + * Get the scheme part of the URL + * + * @return string + */ + public function getScheme() + { + return $this->scheme; + } + + /** + * Set the port part of the URL + * + * @param int $port Port to set + * + * @return Url + */ + public function setPort($port) + { + $this->port = $port; + + return $this; + } + + /** + * Get the port part of the URl. Will return the default port for a given scheme if no port has been set. + * + * @return int|null + */ + public function getPort() + { + if ($this->port) { + return $this->port; + } elseif ($this->scheme == 'http') { + return 80; + } elseif ($this->scheme == 'https') { + return 443; + } + + return null; + } + + /** + * Set the path part of the URL + * + * @param array|string $path Path string or array of path segments + * + * @return Url + */ + public function setPath($path) + { + static $pathReplace = array(' ' => '%20', '?' => '%3F'); + if (is_array($path)) { + $path = '/' . implode('/', $path); + } + + $this->path = strtr($path, $pathReplace); + + return $this; + } + + /** + * Normalize the URL so that double slashes and relative paths are removed + * + * @return Url + */ + public function normalizePath() + { + if (!$this->path || $this->path == '/' || $this->path == '*') { + return $this; + } + + $results = array(); + $segments = $this->getPathSegments(); + foreach ($segments as $segment) { + if ($segment == '..') { + array_pop($results); + } elseif ($segment != '.' && $segment != '') { + $results[] = $segment; + } + } + + // Combine the normalized parts and add the leading slash if needed + $this->path = ($this->path[0] == '/' ? '/' : '') . implode('/', $results); + + // Add the trailing slash if necessary + if ($this->path != '/' && end($segments) == '') { + $this->path .= '/'; + } + + return $this; + } + + /** + * Add a relative path to the currently set path. + * + * @param string $relativePath Relative path to add + * + * @return Url + */ + public function addPath($relativePath) + { + if ($relativePath != '/' && is_string($relativePath) && strlen($relativePath) > 0) { + // Add a leading slash if needed + if ($relativePath[0] != '/') { + $relativePath = '/' . $relativePath; + } + $this->setPath(str_replace('//', '/', $this->path . $relativePath)); + } + + return $this; + } + + /** + * Get the path part of the URL + * + * @return string + */ + public function getPath() + { + return $this->path; + } + + /** + * Get the path segments of the URL as an array + * + * @return array + */ + public function getPathSegments() + { + return array_slice(explode('/', $this->getPath()), 1); + } + + /** + * Set the password part of the URL + * + * @param string $password Password to set + * + * @return Url + */ + public function setPassword($password) + { + $this->password = $password; + + return $this; + } + + /** + * Get the password part of the URL + * + * @return null|string + */ + public function getPassword() + { + return $this->password; + } + + /** + * Set the username part of the URL + * + * @param string $username Username to set + * + * @return Url + */ + public function setUsername($username) + { + $this->username = $username; + + return $this; + } + + /** + * Get the username part of the URl + * + * @return null|string + */ + public function getUsername() + { + return $this->username; + } + + /** + * Get the query part of the URL as a QueryString object + * + * @return QueryString + */ + public function getQuery() + { + return $this->query; + } + + /** + * Set the query part of the URL + * + * @param QueryString|string|array $query Query to set + * + * @return Url + */ + public function setQuery($query) + { + if (is_string($query)) { + $output = null; + parse_str($query, $output); + $this->query = new QueryString($output); + } elseif (is_array($query)) { + $this->query = new QueryString($query); + } elseif ($query instanceof QueryString) { + $this->query = $query; + } + + return $this; + } + + /** + * Get the fragment part of the URL + * + * @return null|string + */ + public function getFragment() + { + return $this->fragment; + } + + /** + * Set the fragment part of the URL + * + * @param string $fragment Fragment to set + * + * @return Url + */ + public function setFragment($fragment) + { + $this->fragment = $fragment; + + return $this; + } + + /** + * Check if this is an absolute URL + * + * @return bool + */ + public function isAbsolute() + { + return $this->scheme && $this->host; + } + + /** + * Combine the URL with another URL. Follows the rules specific in RFC 3986 section 5.4. + * + * @param string $url Relative URL to combine with + * @param bool $strictRfc3986 Set to true to use strict RFC 3986 compliance when merging paths. When first + * released, Guzzle used an incorrect algorithm for combining relative URL paths. In + * order to not break users, we introduced this flag to allow the merging of URLs based + * on strict RFC 3986 section 5.4.1. This means that "http://a.com/foo/baz" merged with + * "bar" would become "http://a.com/foo/bar". When this value is set to false, it would + * become "http://a.com/foo/baz/bar". + * @return Url + * @throws InvalidArgumentException + * @link http://tools.ietf.org/html/rfc3986#section-5.4 + */ + public function combine($url, $strictRfc3986 = false) + { + $url = self::factory($url); + + // Use the more absolute URL as the base URL + if (!$this->isAbsolute() && $url->isAbsolute()) { + $url = $url->combine($this); + } + + // Passing a URL with a scheme overrides everything + if ($buffer = $url->getScheme()) { + $this->scheme = $buffer; + $this->host = $url->getHost(); + $this->port = $url->getPort(); + $this->username = $url->getUsername(); + $this->password = $url->getPassword(); + $this->path = $url->getPath(); + $this->query = $url->getQuery(); + $this->fragment = $url->getFragment(); + return $this; + } + + // Setting a host overrides the entire rest of the URL + if ($buffer = $url->getHost()) { + $this->host = $buffer; + $this->port = $url->getPort(); + $this->username = $url->getUsername(); + $this->password = $url->getPassword(); + $this->path = $url->getPath(); + $this->query = $url->getQuery(); + $this->fragment = $url->getFragment(); + return $this; + } + + $path = $url->getPath(); + $query = $url->getQuery(); + + if (!$path) { + if (count($query)) { + $this->addQuery($query, $strictRfc3986); + } + } else { + if ($path[0] == '/') { + $this->path = $path; + } elseif ($strictRfc3986) { + $this->path .= '/../' . $path; + } else { + $this->path .= '/' . $path; + } + $this->normalizePath(); + $this->addQuery($query, $strictRfc3986); + } + + $this->fragment = $url->getFragment(); + + return $this; + } + + private function addQuery(QueryString $new, $strictRfc386) + { + if (!$strictRfc386) { + $new->merge($this->query); + } + + $this->query = $new; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/composer.json b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/composer.json new file mode 100644 index 000000000..9384a5bf9 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Http/composer.json @@ -0,0 +1,32 @@ +{ + "name": "guzzle/http", + "description": "HTTP libraries used by Guzzle", + "homepage": "http://guzzlephp.org/", + "keywords": ["http client", "http", "client", "Guzzle", "curl"], + "license": "MIT", + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "require": { + "php": ">=5.3.2", + "guzzle/common": "self.version", + "guzzle/parser": "self.version", + "guzzle/stream": "self.version" + }, + "suggest": { + "ext-curl": "*" + }, + "autoload": { + "psr-0": { "Guzzle\\Http": "" } + }, + "target-dir": "Guzzle/Http", + "extra": { + "branch-alias": { + "dev-master": "3.7-dev" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Inflection/Inflector.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Inflection/Inflector.php new file mode 100644 index 000000000..c6997734c --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Inflection/Inflector.php @@ -0,0 +1,38 @@ + array(), + 'camel' => array() + ); + + /** @var int Max entries per cache */ + protected $maxCacheSize; + + /** @var InflectorInterface Decorated inflector */ + protected $decoratedInflector; + + /** + * @param InflectorInterface $inflector Inflector being decorated + * @param int $maxCacheSize Maximum number of cached items to hold per cache + */ + public function __construct(InflectorInterface $inflector, $maxCacheSize = 500) + { + $this->decoratedInflector = $inflector; + $this->maxCacheSize = $maxCacheSize; + } + + public function snake($word) + { + if (!isset($this->cache['snake'][$word])) { + $this->pruneCache('snake'); + $this->cache['snake'][$word] = $this->decoratedInflector->snake($word); + } + + return $this->cache['snake'][$word]; + } + + /** + * Converts strings from snake_case to upper CamelCase + * + * @param string $word Value to convert into upper CamelCase + * + * @return string + */ + public function camel($word) + { + if (!isset($this->cache['camel'][$word])) { + $this->pruneCache('camel'); + $this->cache['camel'][$word] = $this->decoratedInflector->camel($word); + } + + return $this->cache['camel'][$word]; + } + + /** + * Prune one of the named caches by removing 20% of the cache if it is full + * + * @param string $cache Type of cache to prune + */ + protected function pruneCache($cache) + { + if (count($this->cache[$cache]) == $this->maxCacheSize) { + $this->cache[$cache] = array_slice($this->cache[$cache], $this->maxCacheSize * 0.2); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Inflection/PreComputedInflector.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Inflection/PreComputedInflector.php new file mode 100644 index 000000000..db37e4fe4 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Inflection/PreComputedInflector.php @@ -0,0 +1,59 @@ + array(), + 'camel' => array() + ); + + /** @var InflectorInterface Decorated inflector */ + protected $decoratedInflector; + + /** + * @param InflectorInterface $inflector Inflector being decorated + * @param array $snake Hash of pre-computed camel to snake + * @param array $camel Hash of pre-computed snake to camel + * @param bool $mirror Mirror snake and camel reflections + */ + public function __construct(InflectorInterface $inflector, array $snake = array(), array $camel = array(), $mirror = false) + { + if ($mirror) { + $camel = array_merge(array_flip($snake), $camel); + $snake = array_merge(array_flip($camel), $snake); + } + + $this->decoratedInflector = $inflector; + $this->mapping = array( + 'snake' => $snake, + 'camel' => $camel + ); + } + + public function snake($word) + { + return isset($this->mapping['snake'][$word]) + ? $this->mapping['snake'][$word] + : $this->decoratedInflector->snake($word); + } + + /** + * Converts strings from snake_case to upper CamelCase + * + * @param string $word Value to convert into upper CamelCase + * + * @return string + */ + public function camel($word) + { + return isset($this->mapping['camel'][$word]) + ? $this->mapping['camel'][$word] + : $this->decoratedInflector->camel($word); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Inflection/composer.json b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Inflection/composer.json new file mode 100644 index 000000000..93f9e7b72 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Inflection/composer.json @@ -0,0 +1,26 @@ +{ + "name": "guzzle/inflection", + "description": "Guzzle inflection component", + "homepage": "http://guzzlephp.org/", + "keywords": ["inflection", "guzzle"], + "license": "MIT", + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "require": { + "php": ">=5.3.2" + }, + "autoload": { + "psr-0": { "Guzzle\\Inflection": "" } + }, + "target-dir": "Guzzle/Inflection", + "extra": { + "branch-alias": { + "dev-master": "3.7-dev" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Iterator/AppendIterator.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Iterator/AppendIterator.php new file mode 100644 index 000000000..1b6bd7e53 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Iterator/AppendIterator.php @@ -0,0 +1,19 @@ +getArrayIterator()->append($iterator); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Iterator/ChunkedIterator.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Iterator/ChunkedIterator.php new file mode 100644 index 000000000..d76cdd439 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Iterator/ChunkedIterator.php @@ -0,0 +1,56 @@ +chunkSize = $chunkSize; + } + + public function rewind() + { + parent::rewind(); + $this->next(); + } + + public function next() + { + $this->chunk = array(); + for ($i = 0; $i < $this->chunkSize && parent::valid(); $i++) { + $this->chunk[] = parent::current(); + parent::next(); + } + } + + public function current() + { + return $this->chunk; + } + + public function valid() + { + return (bool) $this->chunk; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Iterator/FilterIterator.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Iterator/FilterIterator.php new file mode 100644 index 000000000..b103367b6 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Iterator/FilterIterator.php @@ -0,0 +1,36 @@ +callback = $callback; + } + + public function accept() + { + return call_user_func($this->callback, $this->current()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Iterator/MapIterator.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Iterator/MapIterator.php new file mode 100644 index 000000000..7e586bda6 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Iterator/MapIterator.php @@ -0,0 +1,34 @@ +callback = $callback; + } + + public function current() + { + return call_user_func($this->callback, parent::current()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Iterator/MethodProxyIterator.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Iterator/MethodProxyIterator.php new file mode 100644 index 000000000..de4ab0360 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Iterator/MethodProxyIterator.php @@ -0,0 +1,27 @@ +getInnerIterator(); + while ($i instanceof \OuterIterator) { + $i = $i->getInnerIterator(); + } + + return call_user_func_array(array($i, $name), $args); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Iterator/README.md b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Iterator/README.md new file mode 100644 index 000000000..8bb7e08e2 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Iterator/README.md @@ -0,0 +1,25 @@ +Guzzle Iterator +=============== + +Provides useful Iterators and Iterator decorators + +- ChunkedIterator: Pulls out chunks from an inner iterator and yields the chunks as arrays +- FilterIterator: Used when PHP 5.4's CallbackFilterIterator is not available +- MapIterator: Maps values before yielding +- MethodProxyIterator: Proxies missing method calls to the innermost iterator + +### Installing via Composer + +```bash +# Install Composer +curl -sS https://getcomposer.org/installer | php + +# Add Guzzle as a dependency +php composer.phar require guzzle/iterator:~3.0 +``` + +After installing, you need to require Composer's autoloader: + +```php +require 'vendor/autoload.php'; +``` diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Iterator/composer.json b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Iterator/composer.json new file mode 100644 index 000000000..ee1737987 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Iterator/composer.json @@ -0,0 +1,27 @@ +{ + "name": "guzzle/iterator", + "description": "Provides helpful iterators and iterator decorators", + "keywords": ["iterator", "guzzle"], + "homepage": "http://guzzlephp.org/", + "license": "MIT", + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "require": { + "php": ">=5.3.2", + "guzzle/common": ">=2.8.0" + }, + "autoload": { + "psr-0": { "Guzzle\\Iterator": "/" } + }, + "target-dir": "Guzzle/Iterator", + "extra": { + "branch-alias": { + "dev-master": "3.7-dev" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/AbstractLogAdapter.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/AbstractLogAdapter.php new file mode 100644 index 000000000..7f6271bcb --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/AbstractLogAdapter.php @@ -0,0 +1,16 @@ +log; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/ArrayLogAdapter.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/ArrayLogAdapter.php new file mode 100644 index 000000000..a70fc8d42 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/ArrayLogAdapter.php @@ -0,0 +1,34 @@ +logs[] = array('message' => $message, 'priority' => $priority, 'extras' => $extras); + } + + /** + * Get logged entries + * + * @return array + */ + public function getLogs() + { + return $this->logs; + } + + /** + * Clears logged entries + */ + public function clearLogs() + { + $this->logs = array(); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/ClosureLogAdapter.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/ClosureLogAdapter.php new file mode 100644 index 000000000..d4bb73f21 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/ClosureLogAdapter.php @@ -0,0 +1,23 @@ +log = $logObject; + } + + public function log($message, $priority = LOG_INFO, $extras = array()) + { + call_user_func($this->log, $message, $priority, $extras); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/LogAdapterInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/LogAdapterInterface.php new file mode 100644 index 000000000..d7ac4ea7c --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/LogAdapterInterface.php @@ -0,0 +1,18 @@ +>>>>>>>\n{request}\n<<<<<<<<\n{response}\n--------\n{curl_stderr}"; + const SHORT_FORMAT = '[{ts}] "{method} {resource} {protocol}/{version}" {code}'; + + /** + * @var string Template used to format log messages + */ + protected $template; + + /** + * @param string $template Log message template + */ + public function __construct($template = self::DEFAULT_FORMAT) + { + $this->template = $template ?: self::DEFAULT_FORMAT; + } + + /** + * Set the template to use for logging + * + * @param string $template Log message template + * + * @return self + */ + public function setTemplate($template) + { + $this->template = $template; + + return $this; + } + + /** + * Returns a formatted message + * + * @param RequestInterface $request Request that was sent + * @param Response $response Response that was received + * @param CurlHandle $handle Curl handle associated with the message + * @param array $customData Associative array of custom template data + * + * @return string + */ + public function format( + RequestInterface $request, + Response $response = null, + CurlHandle $handle = null, + array $customData = array() + ) { + $cache = $customData; + + return preg_replace_callback( + '/{\s*([A-Za-z_\-\.0-9]+)\s*}/', + function (array $matches) use ($request, $response, $handle, &$cache) { + + if (array_key_exists($matches[1], $cache)) { + return $cache[$matches[1]]; + } + + $result = ''; + switch ($matches[1]) { + case 'request': + $result = (string) $request; + break; + case 'response': + $result = (string) $response; + break; + case 'req_body': + $result = $request instanceof EntityEnclosingRequestInterface + ? (string) $request->getBody() : ''; + break; + case 'res_body': + $result = $response ? $response->getBody(true) : ''; + break; + case 'ts': + $result = gmdate('c'); + break; + case 'method': + $result = $request->getMethod(); + break; + case 'url': + $result = (string) $request->getUrl(); + break; + case 'resource': + $result = $request->getResource(); + break; + case 'protocol': + $result = 'HTTP'; + break; + case 'version': + $result = $request->getProtocolVersion(); + break; + case 'host': + $result = $request->getHost(); + break; + case 'hostname': + $result = gethostname(); + break; + case 'port': + $result = $request->getPort(); + break; + case 'code': + $result = $response ? $response->getStatusCode() : ''; + break; + case 'phrase': + $result = $response ? $response->getReasonPhrase() : ''; + break; + case 'connect_time': + $result = $handle && $handle->getInfo(CURLINFO_CONNECT_TIME) + ? $handle->getInfo(CURLINFO_CONNECT_TIME) + : ($response ? $response->getInfo('connect_time') : ''); + break; + case 'total_time': + $result = $handle && $handle->getInfo(CURLINFO_TOTAL_TIME) + ? $handle->getInfo(CURLINFO_TOTAL_TIME) + : ($response ? $response->getInfo('total_time') : ''); + break; + case 'curl_error': + $result = $handle ? $handle->getError() : ''; + break; + case 'curl_code': + $result = $handle ? $handle->getErrorNo() : ''; + break; + case 'curl_stderr': + $result = $handle ? $handle->getStderr() : ''; + break; + default: + if (strpos($matches[1], 'req_header_') === 0) { + $result = $request->getHeader(substr($matches[1], 11)); + } elseif ($response && strpos($matches[1], 'res_header_') === 0) { + $result = $response->getHeader(substr($matches[1], 11)); + } + } + + $cache[$matches[1]] = $result; + return $result; + }, + $this->template + ); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/MonologLogAdapter.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/MonologLogAdapter.php new file mode 100644 index 000000000..6afe7b62a --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/MonologLogAdapter.php @@ -0,0 +1,34 @@ + Logger::DEBUG, + LOG_INFO => Logger::INFO, + LOG_WARNING => Logger::WARNING, + LOG_ERR => Logger::ERROR, + LOG_CRIT => Logger::CRITICAL, + LOG_ALERT => Logger::ALERT + ); + + public function __construct(Logger $logObject) + { + $this->log = $logObject; + } + + public function log($message, $priority = LOG_INFO, $extras = array()) + { + $this->log->addRecord(self::$mapping[$priority], $message, $extras); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/PsrLogAdapter.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/PsrLogAdapter.php new file mode 100644 index 000000000..38a2b600d --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/PsrLogAdapter.php @@ -0,0 +1,36 @@ + LogLevel::DEBUG, + LOG_INFO => LogLevel::INFO, + LOG_WARNING => LogLevel::WARNING, + LOG_ERR => LogLevel::ERROR, + LOG_CRIT => LogLevel::CRITICAL, + LOG_ALERT => LogLevel::ALERT + ); + + public function __construct(LoggerInterface $logObject) + { + $this->log = $logObject; + } + + public function log($message, $priority = LOG_INFO, $extras = array()) + { + $this->log->log(self::$mapping[$priority], $message, $extras); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/Zf1LogAdapter.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/Zf1LogAdapter.php new file mode 100644 index 000000000..0ea8e3b1d --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/Zf1LogAdapter.php @@ -0,0 +1,24 @@ +log = $logObject; + Version::warn(__CLASS__ . ' is deprecated'); + } + + public function log($message, $priority = LOG_INFO, $extras = array()) + { + $this->log->log($message, $priority, $extras); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/Zf2LogAdapter.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/Zf2LogAdapter.php new file mode 100644 index 000000000..863f6a1c4 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/Zf2LogAdapter.php @@ -0,0 +1,21 @@ +log = $logObject; + } + + public function log($message, $priority = LOG_INFO, $extras = array()) + { + $this->log->log($priority, $message, $extras); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/composer.json b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/composer.json new file mode 100644 index 000000000..a8213e8b4 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Log/composer.json @@ -0,0 +1,29 @@ +{ + "name": "guzzle/log", + "description": "Guzzle log adapter component", + "homepage": "http://guzzlephp.org/", + "keywords": ["log", "adapter", "guzzle"], + "license": "MIT", + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "require": { + "php": ">=5.3.2" + }, + "autoload": { + "psr-0": { "Guzzle\\Log": "" } + }, + "suggest": { + "guzzle/http": "self.version" + }, + "target-dir": "Guzzle/Log", + "extra": { + "branch-alias": { + "dev-master": "3.7-dev" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Parser/Cookie/CookieParser.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Parser/Cookie/CookieParser.php new file mode 100644 index 000000000..4349eeb38 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Parser/Cookie/CookieParser.php @@ -0,0 +1,131 @@ + 'Domain', + 'path' => 'Path', + 'max_age' => 'Max-Age', + 'expires' => 'Expires', + 'version' => 'Version', + 'secure' => 'Secure', + 'port' => 'Port', + 'discard' => 'Discard', + 'comment' => 'Comment', + 'comment_url' => 'Comment-Url', + 'http_only' => 'HttpOnly' + ); + + public function parseCookie($cookie, $host = null, $path = null, $decode = false) + { + // Explode the cookie string using a series of semicolons + $pieces = array_filter(array_map('trim', explode(';', $cookie))); + + // The name of the cookie (first kvp) must include an equal sign. + if (empty($pieces) || !strpos($pieces[0], '=')) { + return false; + } + + // Create the default return array + $data = array_merge(array_fill_keys(array_keys(self::$cookieParts), null), array( + 'cookies' => array(), + 'data' => array(), + 'path' => null, + 'http_only' => false, + 'discard' => false, + 'domain' => $host + )); + $foundNonCookies = 0; + + // Add the cookie pieces into the parsed data array + foreach ($pieces as $part) { + + $cookieParts = explode('=', $part, 2); + $key = trim($cookieParts[0]); + + if (count($cookieParts) == 1) { + // Can be a single value (e.g. secure, httpOnly) + $value = true; + } else { + // Be sure to strip wrapping quotes + $value = trim($cookieParts[1], " \n\r\t\0\x0B\""); + if ($decode) { + $value = urldecode($value); + } + } + + // Only check for non-cookies when cookies have been found + if (!empty($data['cookies'])) { + foreach (self::$cookieParts as $mapValue => $search) { + if (!strcasecmp($search, $key)) { + $data[$mapValue] = $mapValue == 'port' ? array_map('trim', explode(',', $value)) : $value; + $foundNonCookies++; + continue 2; + } + } + } + + // If cookies have not yet been retrieved, or this value was not found in the pieces array, treat it as a + // cookie. IF non-cookies have been parsed, then this isn't a cookie, it's cookie data. Cookies then data. + $data[$foundNonCookies ? 'data' : 'cookies'][$key] = $value; + } + + // Calculate the expires date + if (!$data['expires'] && $data['max_age']) { + $data['expires'] = time() + (int) $data['max_age']; + } + + // Check path attribute according RFC6265 http://tools.ietf.org/search/rfc6265#section-5.2.4 + // "If the attribute-value is empty or if the first character of the + // attribute-value is not %x2F ("/"): + // Let cookie-path be the default-path. + // Otherwise: + // Let cookie-path be the attribute-value." + if (!$data['path'] || substr($data['path'], 0, 1) !== '/') { + $data['path'] = $this->getDefaultPath($path); + } + + return $data; + } + + /** + * Get default cookie path according to RFC 6265 + * http://tools.ietf.org/search/rfc6265#section-5.1.4 Paths and Path-Match + * + * @param string $path Request uri-path + * + * @return string + */ + protected function getDefaultPath($path) { + // "The user agent MUST use an algorithm equivalent to the following algorithm + // to compute the default-path of a cookie:" + + // "2. If the uri-path is empty or if the first character of the uri-path is not + // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps. + if (empty($path) || substr($path, 0, 1) !== '/') { + return '/'; + } + + // "3. If the uri-path contains no more than one %x2F ("/") character, output + // %x2F ("/") and skip the remaining step." + if ($path === "/") { + return $path; + } + + $rightSlashPos = strrpos($path, '/'); + if ($rightSlashPos === 0) { + return "/"; + } + + // "4. Output the characters of the uri-path from the first character up to, + // but not including, the right-most %x2F ("/")." + return substr($path, 0, $rightSlashPos); + + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Parser/Cookie/CookieParserInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Parser/Cookie/CookieParserInterface.php new file mode 100644 index 000000000..d21ffe21c --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Parser/Cookie/CookieParserInterface.php @@ -0,0 +1,33 @@ + $requestUrl, + 'scheme' => 'http' + ); + + // Check for the Host header + if (isset($parts['headers']['Host'])) { + $urlParts['host'] = $parts['headers']['Host']; + } elseif (isset($parts['headers']['host'])) { + $urlParts['host'] = $parts['headers']['host']; + } else { + $urlParts['host'] = null; + } + + if (false === strpos($urlParts['host'], ':')) { + $urlParts['port'] = ''; + } else { + $hostParts = explode(':', $urlParts['host']); + $urlParts['host'] = trim($hostParts[0]); + $urlParts['port'] = (int) trim($hostParts[1]); + if ($urlParts['port'] == 443) { + $urlParts['scheme'] = 'https'; + } + } + + // Check if a query is present + $path = $urlParts['path']; + $qpos = strpos($path, '?'); + if ($qpos) { + $urlParts['query'] = substr($path, $qpos + 1); + $urlParts['path'] = substr($path, 0, $qpos); + } else { + $urlParts['query'] = ''; + } + + return $urlParts; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Parser/Message/MessageParser.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Parser/Message/MessageParser.php new file mode 100644 index 000000000..efc1aa322 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Parser/Message/MessageParser.php @@ -0,0 +1,110 @@ +parseMessage($message); + + // Parse the protocol and protocol version + if (isset($parts['start_line'][2])) { + $startParts = explode('/', $parts['start_line'][2]); + $protocol = strtoupper($startParts[0]); + $version = isset($startParts[1]) ? $startParts[1] : '1.1'; + } else { + $protocol = 'HTTP'; + $version = '1.1'; + } + + $parsed = array( + 'method' => strtoupper($parts['start_line'][0]), + 'protocol' => $protocol, + 'version' => $version, + 'headers' => $parts['headers'], + 'body' => $parts['body'] + ); + + $parsed['request_url'] = $this->getUrlPartsFromMessage(isset($parts['start_line'][1]) ? $parts['start_line'][1] : '' , $parsed); + + return $parsed; + } + + public function parseResponse($message) + { + if (!$message) { + return false; + } + + $parts = $this->parseMessage($message); + list($protocol, $version) = explode('/', trim($parts['start_line'][0])); + + return array( + 'protocol' => $protocol, + 'version' => $version, + 'code' => $parts['start_line'][1], + 'reason_phrase' => isset($parts['start_line'][2]) ? $parts['start_line'][2] : '', + 'headers' => $parts['headers'], + 'body' => $parts['body'] + ); + } + + /** + * Parse a message into parts + * + * @param string $message Message to parse + * + * @return array + */ + protected function parseMessage($message) + { + $startLine = null; + $headers = array(); + $body = ''; + + // Iterate over each line in the message, accounting for line endings + $lines = preg_split('/(\\r?\\n)/', $message, -1, PREG_SPLIT_DELIM_CAPTURE); + for ($i = 0, $totalLines = count($lines); $i < $totalLines; $i += 2) { + + $line = $lines[$i]; + + // If two line breaks were encountered, then this is the end of body + if (empty($line)) { + if ($i < $totalLines - 1) { + $body = implode('', array_slice($lines, $i + 2)); + } + break; + } + + // Parse message headers + if (!$startLine) { + $startLine = explode(' ', $line, 3); + } elseif (strpos($line, ':')) { + $parts = explode(':', $line, 2); + $key = trim($parts[0]); + $value = isset($parts[1]) ? trim($parts[1]) : ''; + if (!isset($headers[$key])) { + $headers[$key] = $value; + } elseif (!is_array($headers[$key])) { + $headers[$key] = array($headers[$key], $value); + } else { + $headers[$key][] = $value; + } + } + } + + return array( + 'start_line' => $startLine, + 'headers' => $headers, + 'body' => $body + ); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Parser/Message/MessageParserInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Parser/Message/MessageParserInterface.php new file mode 100644 index 000000000..cc448088d --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Parser/Message/MessageParserInterface.php @@ -0,0 +1,27 @@ + $parts->requestMethod, + 'protocol' => 'HTTP', + 'version' => number_format($parts->httpVersion, 1), + 'headers' => $parts->headers, + 'body' => $parts->body + ); + + $parsed['request_url'] = $this->getUrlPartsFromMessage($parts->requestUrl, $parsed); + + return $parsed; + } + + public function parseResponse($message) + { + if (!$message) { + return false; + } + + $parts = http_parse_message($message); + + return array( + 'protocol' => 'HTTP', + 'version' => number_format($parts->httpVersion, 1), + 'code' => $parts->responseCode, + 'reason_phrase' => $parts->responseStatus, + 'headers' => $parts->headers, + 'body' => $parts->body + ); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Parser/ParserRegistry.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Parser/ParserRegistry.php new file mode 100644 index 000000000..f8386831c --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Parser/ParserRegistry.php @@ -0,0 +1,75 @@ + 'Guzzle\\Parser\\Message\\MessageParser', + 'cookie' => 'Guzzle\\Parser\\Cookie\\CookieParser', + 'url' => 'Guzzle\\Parser\\Url\\UrlParser', + 'uri_template' => 'Guzzle\\Parser\\UriTemplate\\UriTemplate', + ); + + /** + * @return self + * @codeCoverageIgnore + */ + public static function getInstance() + { + if (!self::$instance) { + self::$instance = new static; + } + + return self::$instance; + } + + public function __construct() + { + // Use the PECL URI template parser if available + if (extension_loaded('uri_template')) { + $this->mapping['uri_template'] = 'Guzzle\\Parser\\UriTemplate\\PeclUriTemplate'; + } + } + + /** + * Get a parser by name from an instance + * + * @param string $name Name of the parser to retrieve + * + * @return mixed|null + */ + public function getParser($name) + { + if (!isset($this->instances[$name])) { + if (!isset($this->mapping[$name])) { + return null; + } + $class = $this->mapping[$name]; + $this->instances[$name] = new $class(); + } + + return $this->instances[$name]; + } + + /** + * Register a custom parser by name with the register + * + * @param string $name Name or handle of the parser to register + * @param mixed $parser Instantiated parser to register + */ + public function registerParser($name, $parser) + { + $this->instances[$name] = $parser; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Parser/UriTemplate/PeclUriTemplate.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Parser/UriTemplate/PeclUriTemplate.php new file mode 100644 index 000000000..b0764e837 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Parser/UriTemplate/PeclUriTemplate.php @@ -0,0 +1,26 @@ + true, '#' => true, '.' => true, '/' => true, ';' => true, '?' => true, '&' => true + ); + + /** @var array Delimiters */ + private static $delims = array( + ':', '/', '?', '#', '[', ']', '@', '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=' + ); + + /** @var array Percent encoded delimiters */ + private static $delimsPct = array( + '%3A', '%2F', '%3F', '%23', '%5B', '%5D', '%40', '%21', '%24', '%26', '%27', '%28', '%29', '%2A', '%2B', '%2C', + '%3B', '%3D' + ); + + public function expand($template, array $variables) + { + if ($this->regex == self::DEFAULT_PATTERN && false === strpos($template, '{')) { + return $template; + } + + $this->template = $template; + $this->variables = $variables; + + return preg_replace_callback($this->regex, array($this, 'expandMatch'), $this->template); + } + + /** + * Set the regex patten used to expand URI templates + * + * @param string $regexPattern + */ + public function setRegex($regexPattern) + { + $this->regex = $regexPattern; + } + + /** + * Parse an expression into parts + * + * @param string $expression Expression to parse + * + * @return array Returns an associative array of parts + */ + private function parseExpression($expression) + { + // Check for URI operators + $operator = ''; + + if (isset(self::$operatorHash[$expression[0]])) { + $operator = $expression[0]; + $expression = substr($expression, 1); + } + + $values = explode(',', $expression); + foreach ($values as &$value) { + $value = trim($value); + $varspec = array(); + $substrPos = strpos($value, ':'); + if ($substrPos) { + $varspec['value'] = substr($value, 0, $substrPos); + $varspec['modifier'] = ':'; + $varspec['position'] = (int) substr($value, $substrPos + 1); + } elseif (substr($value, -1) == '*') { + $varspec['modifier'] = '*'; + $varspec['value'] = substr($value, 0, -1); + } else { + $varspec['value'] = (string) $value; + $varspec['modifier'] = ''; + } + $value = $varspec; + } + + return array( + 'operator' => $operator, + 'values' => $values + ); + } + + /** + * Process an expansion + * + * @param array $matches Matches met in the preg_replace_callback + * + * @return string Returns the replacement string + */ + private function expandMatch(array $matches) + { + static $rfc1738to3986 = array( + '+' => '%20', + '%7e' => '~' + ); + + $parsed = self::parseExpression($matches[1]); + $replacements = array(); + + $prefix = $parsed['operator']; + $joiner = $parsed['operator']; + $useQueryString = false; + if ($parsed['operator'] == '?') { + $joiner = '&'; + $useQueryString = true; + } elseif ($parsed['operator'] == '&') { + $useQueryString = true; + } elseif ($parsed['operator'] == '#') { + $joiner = ','; + } elseif ($parsed['operator'] == ';') { + $useQueryString = true; + } elseif ($parsed['operator'] == '' || $parsed['operator'] == '+') { + $joiner = ','; + $prefix = ''; + } + + foreach ($parsed['values'] as $value) { + + if (!array_key_exists($value['value'], $this->variables) || $this->variables[$value['value']] === null) { + continue; + } + + $variable = $this->variables[$value['value']]; + $actuallyUseQueryString = $useQueryString; + $expanded = ''; + + if (is_array($variable)) { + + $isAssoc = $this->isAssoc($variable); + $kvp = array(); + foreach ($variable as $key => $var) { + + if ($isAssoc) { + $key = rawurlencode($key); + $isNestedArray = is_array($var); + } else { + $isNestedArray = false; + } + + if (!$isNestedArray) { + $var = rawurlencode($var); + if ($parsed['operator'] == '+' || $parsed['operator'] == '#') { + $var = $this->decodeReserved($var); + } + } + + if ($value['modifier'] == '*') { + if ($isAssoc) { + if ($isNestedArray) { + // Nested arrays must allow for deeply nested structures + $var = strtr(http_build_query(array($key => $var)), $rfc1738to3986); + } else { + $var = $key . '=' . $var; + } + } elseif ($key > 0 && $actuallyUseQueryString) { + $var = $value['value'] . '=' . $var; + } + } + + $kvp[$key] = $var; + } + + if (empty($variable)) { + $actuallyUseQueryString = false; + } elseif ($value['modifier'] == '*') { + $expanded = implode($joiner, $kvp); + if ($isAssoc) { + // Don't prepend the value name when using the explode modifier with an associative array + $actuallyUseQueryString = false; + } + } else { + if ($isAssoc) { + // When an associative array is encountered and the explode modifier is not set, then the + // result must be a comma separated list of keys followed by their respective values. + foreach ($kvp as $k => &$v) { + $v = $k . ',' . $v; + } + } + $expanded = implode(',', $kvp); + } + + } else { + if ($value['modifier'] == ':') { + $variable = substr($variable, 0, $value['position']); + } + $expanded = rawurlencode($variable); + if ($parsed['operator'] == '+' || $parsed['operator'] == '#') { + $expanded = $this->decodeReserved($expanded); + } + } + + if ($actuallyUseQueryString) { + if (!$expanded && $joiner != '&') { + $expanded = $value['value']; + } else { + $expanded = $value['value'] . '=' . $expanded; + } + } + + $replacements[] = $expanded; + } + + $ret = implode($joiner, $replacements); + if ($ret && $prefix) { + return $prefix . $ret; + } + + return $ret; + } + + /** + * Determines if an array is associative + * + * @param array $array Array to check + * + * @return bool + */ + private function isAssoc(array $array) + { + return (bool) count(array_filter(array_keys($array), 'is_string')); + } + + /** + * Removes percent encoding on reserved characters (used with + and # modifiers) + * + * @param string $string String to fix + * + * @return string + */ + private function decodeReserved($string) + { + return str_replace(self::$delimsPct, self::$delims, $string); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Parser/UriTemplate/UriTemplateInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Parser/UriTemplate/UriTemplateInterface.php new file mode 100644 index 000000000..c81d51548 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Parser/UriTemplate/UriTemplateInterface.php @@ -0,0 +1,21 @@ +utf8 = $utf8; + } + + public function parseUrl($url) + { + Version::warn(__CLASS__ . ' is deprecated. Just use parse_url()'); + + static $defaults = array('scheme' => null, 'host' => null, 'path' => null, 'port' => null, 'query' => null, + 'user' => null, 'pass' => null, 'fragment' => null); + + $parts = parse_url($url); + + // Need to handle query parsing specially for UTF-8 requirements + if ($this->utf8 && isset($parts['query'])) { + $queryPos = strpos($url, '?'); + if (isset($parts['fragment'])) { + $parts['query'] = substr($url, $queryPos + 1, strpos($url, '#') - $queryPos - 1); + } else { + $parts['query'] = substr($url, $queryPos + 1); + } + } + + return $parts + $defaults; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Parser/Url/UrlParserInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Parser/Url/UrlParserInterface.php new file mode 100644 index 000000000..89ac4b307 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Parser/Url/UrlParserInterface.php @@ -0,0 +1,19 @@ +=5.3.2" + }, + "autoload": { + "psr-0": { "Guzzle\\Parser": "" } + }, + "target-dir": "Guzzle/Parser", + "extra": { + "branch-alias": { + "dev-master": "3.7-dev" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Async/AsyncPlugin.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Async/AsyncPlugin.php new file mode 100644 index 000000000..ae5941873 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Async/AsyncPlugin.php @@ -0,0 +1,84 @@ + 'onBeforeSend', + 'request.exception' => 'onRequestTimeout', + 'request.sent' => 'onRequestSent', + 'curl.callback.progress' => 'onCurlProgress' + ); + } + + /** + * Event used to ensure that progress callback are emitted from the curl handle's request mediator. + * + * @param Event $event + */ + public function onBeforeSend(Event $event) + { + // Ensure that progress callbacks are dispatched + $event['request']->getCurlOptions()->set('progress', true); + } + + /** + * Event emitted when a curl progress function is called. When the amount of data uploaded == the amount of data to + * upload OR any bytes have been downloaded, then time the request out after 1ms because we're done with + * transmitting the request, and tell curl not download a body. + * + * @param Event $event + */ + public function onCurlProgress(Event $event) + { + if ($event['handle'] && + ($event['downloaded'] || (isset($event['uploaded']) && $event['upload_size'] === $event['uploaded'])) + ) { + // Timeout after 1ms + curl_setopt($event['handle'], CURLOPT_TIMEOUT_MS, 1); + // Even if the response is quick, tell curl not to download the body. + // - Note that we can only perform this shortcut if the request transmitted a body so as to ensure that the + // request method is not converted to a HEAD request before the request was sent via curl. + if ($event['uploaded']) { + curl_setopt($event['handle'], CURLOPT_NOBODY, true); + } + } + } + + /** + * Event emitted when a curl exception occurs. Ignore the exception and set a mock response. + * + * @param Event $event + */ + public function onRequestTimeout(Event $event) + { + if ($event['exception'] instanceof CurlException) { + $event['request']->setResponse(new Response(200, array( + 'X-Guzzle-Async' => 'Did not wait for the response' + ))); + } + } + + /** + * Event emitted when a request completes because it took less than 1ms. Add an X-Guzzle-Async header to notify the + * caller that there is no body in the message. + * + * @param Event $event + */ + public function onRequestSent(Event $event) + { + // Let the caller know this was meant to be async + $event['request']->getResponse()->setHeader('X-Guzzle-Async', 'Did not wait for the response'); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Async/composer.json b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Async/composer.json new file mode 100644 index 000000000..dc3fc5bf8 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Async/composer.json @@ -0,0 +1,27 @@ +{ + "name": "guzzle/plugin-async", + "description": "Guzzle async request plugin", + "homepage": "http://guzzlephp.org/", + "keywords": ["plugin", "guzzle"], + "license": "MIT", + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "require": { + "php": ">=5.3.2", + "guzzle/http": "self.version" + }, + "autoload": { + "psr-0": { "Guzzle\\Plugin\\Async": "" } + }, + "target-dir": "Guzzle/Plugin/Async", + "extra": { + "branch-alias": { + "dev-master": "3.7-dev" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/AbstractBackoffStrategy.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/AbstractBackoffStrategy.php new file mode 100644 index 000000000..0a8598345 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/AbstractBackoffStrategy.php @@ -0,0 +1,91 @@ +next = $next; + } + + /** + * Get the next backoff strategy in the chain + * + * @return AbstractBackoffStrategy|null + */ + public function getNext() + { + return $this->next; + } + + public function getBackoffPeriod( + $retries, + RequestInterface $request, + Response $response = null, + HttpException $e = null + ) { + $delay = $this->getDelay($retries, $request, $response, $e); + if ($delay === false) { + // The strategy knows that this must not be retried + return false; + } elseif ($delay === null) { + // If the strategy is deferring a decision and the next strategy will not make a decision then return false + return !$this->next || !$this->next->makesDecision() + ? false + : $this->next->getBackoffPeriod($retries, $request, $response, $e); + } elseif ($delay === true) { + // if the strategy knows that it must retry but is deferring to the next to determine the delay + if (!$this->next) { + return 0; + } else { + $next = $this->next; + while ($next->makesDecision() && $next->getNext()) { + $next = $next->getNext(); + } + return !$next->makesDecision() ? $next->getBackoffPeriod($retries, $request, $response, $e) : 0; + } + } else { + return $delay; + } + } + + /** + * Check if the strategy does filtering and makes decisions on whether or not to retry. + * + * Strategies that return false will never retry if all of the previous strategies in a chain defer on a backoff + * decision. + * + * @return bool + */ + abstract public function makesDecision(); + + /** + * Implement the concrete strategy + * + * @param int $retries Number of retries of the request + * @param RequestInterface $request Request that was sent + * @param Response $response Response that was received. Note that there may not be a response + * @param HttpException $e Exception that was encountered if any + * + * @return bool|int|null Returns false to not retry or the number of seconds to delay between retries. Return true + * or null to defer to the next strategy if available, and if not, return 0. + */ + abstract protected function getDelay( + $retries, + RequestInterface $request, + Response $response = null, + HttpException $e = null + ); +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/AbstractErrorCodeBackoffStrategy.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/AbstractErrorCodeBackoffStrategy.php new file mode 100644 index 000000000..6ebee6c1a --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/AbstractErrorCodeBackoffStrategy.php @@ -0,0 +1,40 @@ +errorCodes = array_fill_keys($codes ?: static::$defaultErrorCodes, 1); + $this->next = $next; + } + + /** + * Get the default failure codes to retry + * + * @return array + */ + public static function getDefaultFailureCodes() + { + return static::$defaultErrorCodes; + } + + public function makesDecision() + { + return true; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/BackoffLogger.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/BackoffLogger.php new file mode 100644 index 000000000..ec54c289e --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/BackoffLogger.php @@ -0,0 +1,76 @@ +logger = $logger; + $this->formatter = $formatter ?: new MessageFormatter(self::DEFAULT_FORMAT); + } + + public static function getSubscribedEvents() + { + return array(BackoffPlugin::RETRY_EVENT => 'onRequestRetry'); + } + + /** + * Set the template to use for logging + * + * @param string $template Log message template + * + * @return self + */ + public function setTemplate($template) + { + $this->formatter->setTemplate($template); + + return $this; + } + + /** + * Called when a request is being retried + * + * @param Event $event Event emitted + */ + public function onRequestRetry(Event $event) + { + $this->logger->log($this->formatter->format( + $event['request'], + $event['response'], + $event['handle'], + array( + 'retries' => $event['retries'], + 'delay' => $event['delay'] + ) + )); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/BackoffPlugin.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/BackoffPlugin.php new file mode 100644 index 000000000..99ace0538 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/BackoffPlugin.php @@ -0,0 +1,126 @@ +strategy = $strategy; + } + + /** + * Retrieve a basic truncated exponential backoff plugin that will retry HTTP errors and cURL errors + * + * @param int $maxRetries Maximum number of retries + * @param array $httpCodes HTTP response codes to retry + * @param array $curlCodes cURL error codes to retry + * + * @return self + */ + public static function getExponentialBackoff( + $maxRetries = 3, + array $httpCodes = null, + array $curlCodes = null + ) { + return new self(new TruncatedBackoffStrategy($maxRetries, + new HttpBackoffStrategy($httpCodes, + new CurlBackoffStrategy($curlCodes, + new ExponentialBackoffStrategy() + ) + ) + )); + } + + public static function getAllEvents() + { + return array(self::RETRY_EVENT); + } + + public static function getSubscribedEvents() + { + return array( + 'request.sent' => 'onRequestSent', + 'request.exception' => 'onRequestSent', + CurlMultiInterface::POLLING_REQUEST => 'onRequestPoll' + ); + } + + /** + * Called when a request has been sent and isn't finished processing + * + * @param Event $event + */ + public function onRequestSent(Event $event) + { + $request = $event['request']; + $response = $event['response']; + $exception = $event['exception']; + + $params = $request->getParams(); + $retries = (int) $params->get(self::RETRY_PARAM); + $delay = $this->strategy->getBackoffPeriod($retries, $request, $response, $exception); + + if ($delay !== false) { + // Calculate how long to wait until the request should be retried + $params->set(self::RETRY_PARAM, ++$retries) + ->set(self::DELAY_PARAM, microtime(true) + $delay); + // Send the request again + $request->setState(RequestInterface::STATE_TRANSFER); + $this->dispatch(self::RETRY_EVENT, array( + 'request' => $request, + 'response' => $response, + 'handle' => ($exception && $exception instanceof CurlException) ? $exception->getCurlHandle() : null, + 'retries' => $retries, + 'delay' => $delay + )); + } + } + + /** + * Called when a request is polling in the curl multi object + * + * @param Event $event + */ + public function onRequestPoll(Event $event) + { + $request = $event['request']; + $delay = $request->getParams()->get(self::DELAY_PARAM); + + // If the duration of the delay has passed, retry the request using the pool + if (null !== $delay && microtime(true) >= $delay) { + // Remove the request from the pool and then add it back again. This is required for cURL to know that we + // want to retry sending the easy handle. + $request->getParams()->remove(self::DELAY_PARAM); + // Rewind the request body if possible + if ($request instanceof EntityEnclosingRequestInterface && $request->getBody()) { + $request->getBody()->seek(0); + } + $multi = $event['curl_multi']; + $multi->remove($request); + $multi->add($request); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/BackoffStrategyInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/BackoffStrategyInterface.php new file mode 100644 index 000000000..4e590dbe0 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/BackoffStrategyInterface.php @@ -0,0 +1,30 @@ +callback = $callback; + $this->decision = (bool) $decision; + $this->next = $next; + } + + public function makesDecision() + { + return $this->decision; + } + + protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null) + { + return call_user_func($this->callback, $retries, $request, $response, $e); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/ConstantBackoffStrategy.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/ConstantBackoffStrategy.php new file mode 100644 index 000000000..061d2a407 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/ConstantBackoffStrategy.php @@ -0,0 +1,34 @@ +delay = $delay; + } + + public function makesDecision() + { + return false; + } + + protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null) + { + return $this->delay; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/CurlBackoffStrategy.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/CurlBackoffStrategy.php new file mode 100644 index 000000000..a584ed4a2 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/CurlBackoffStrategy.php @@ -0,0 +1,28 @@ +errorCodes[$e->getErrorNo()]) ? true : null; + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/ExponentialBackoffStrategy.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/ExponentialBackoffStrategy.php new file mode 100644 index 000000000..fb2912d50 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/ExponentialBackoffStrategy.php @@ -0,0 +1,25 @@ +isSuccessful()) { + return false; + } else { + return isset($this->errorCodes[$response->getStatusCode()]) ? true : null; + } + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/LinearBackoffStrategy.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/LinearBackoffStrategy.php new file mode 100644 index 000000000..b35e8a490 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/LinearBackoffStrategy.php @@ -0,0 +1,36 @@ +step = $step; + } + + public function makesDecision() + { + return false; + } + + protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null) + { + return $retries * $this->step; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/ReasonPhraseBackoffStrategy.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/ReasonPhraseBackoffStrategy.php new file mode 100644 index 000000000..4fd73fedf --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/ReasonPhraseBackoffStrategy.php @@ -0,0 +1,25 @@ +errorCodes[$response->getReasonPhrase()]) ? true : null; + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/TruncatedBackoffStrategy.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/TruncatedBackoffStrategy.php new file mode 100644 index 000000000..3608f3584 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/TruncatedBackoffStrategy.php @@ -0,0 +1,36 @@ +max = $maxRetries; + $this->next = $next; + } + + public function makesDecision() + { + return true; + } + + protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null) + { + return $retries < $this->max ? null : false; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/composer.json b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/composer.json new file mode 100644 index 000000000..91c122cb4 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Backoff/composer.json @@ -0,0 +1,28 @@ +{ + "name": "guzzle/plugin-backoff", + "description": "Guzzle backoff retry plugins", + "homepage": "http://guzzlephp.org/", + "keywords": ["plugin", "guzzle"], + "license": "MIT", + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "require": { + "php": ">=5.3.2", + "guzzle/http": "self.version", + "guzzle/log": "self.version" + }, + "autoload": { + "psr-0": { "Guzzle\\Plugin\\Backoff": "" } + }, + "target-dir": "Guzzle/Plugin/Backoff", + "extra": { + "branch-alias": { + "dev-master": "3.7-dev" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/CacheKeyProviderInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/CacheKeyProviderInterface.php new file mode 100644 index 000000000..7790f8844 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/CacheKeyProviderInterface.php @@ -0,0 +1,11 @@ + new DefaultCacheStorage($options)); + } elseif ($options instanceof CacheStorageInterface) { + $options = array('storage' => $options); + } elseif ($options) { + $options = array('storage' => new DefaultCacheStorage(CacheAdapterFactory::fromCache($options))); + } elseif (!class_exists('Doctrine\Common\Cache\ArrayCache')) { + // @codeCoverageIgnoreStart + throw new InvalidArgumentException('No cache was provided and Doctrine is not installed'); + // @codeCoverageIgnoreEnd + } + } + + $this->autoPurge = isset($options['auto_purge']) ? $options['auto_purge'] : false; + + // Add a cache storage if a cache adapter was provided + $this->storage = isset($options['storage']) + ? $options['storage'] + : new DefaultCacheStorage(new DoctrineCacheAdapter(new ArrayCache())); + + if (!isset($options['can_cache'])) { + $this->canCache = new DefaultCanCacheStrategy(); + } else { + $this->canCache = is_callable($options['can_cache']) + ? new CallbackCanCacheStrategy($options['can_cache']) + : $options['can_cache']; + } + + // Use the provided revalidation strategy or the default + $this->revalidation = isset($options['revalidation']) + ? $options['revalidation'] + : new DefaultRevalidation($this->storage, $this->canCache); + } + + public static function getSubscribedEvents() + { + return array( + 'request.before_send' => array('onRequestBeforeSend', -255), + 'request.sent' => array('onRequestSent', 255), + 'request.error' => array('onRequestError', 0), + 'request.exception' => array('onRequestException', 0), + ); + } + + /** + * Check if a response in cache will satisfy the request before sending + * + * @param Event $event + */ + public function onRequestBeforeSend(Event $event) + { + $request = $event['request']; + $request->addHeader('Via', sprintf('%s GuzzleCache/%s', $request->getProtocolVersion(), Version::VERSION)); + + if (!$this->canCache->canCacheRequest($request)) { + switch ($request->getMethod()) { + case 'PURGE': + $this->purge($request); + $request->setResponse(new Response(200, array(), 'purged')); + break; + case 'PUT': + case 'POST': + case 'DELETE': + case 'PATCH': + if ($this->autoPurge) { + $this->purge($request); + } + } + return; + } + + if ($response = $this->storage->fetch($request)) { + $params = $request->getParams(); + $params['cache.lookup'] = true; + $response->setHeader( + 'Age', + time() - strtotime($response->getDate() ? : $response->getLastModified() ?: 'now') + ); + // Validate that the response satisfies the request + if ($this->canResponseSatisfyRequest($request, $response)) { + if (!isset($params['cache.hit'])) { + $params['cache.hit'] = true; + } + $request->setResponse($response); + } + } + } + + /** + * If possible, store a response in cache after sending + * + * @param Event $event + */ + public function onRequestSent(Event $event) + { + $request = $event['request']; + $response = $event['response']; + + if ($request->getParams()->get('cache.hit') === null && + $this->canCache->canCacheRequest($request) && + $this->canCache->canCacheResponse($response) + ) { + $this->storage->cache($request, $response); + } + + $this->addResponseHeaders($request, $response); + } + + /** + * If possible, return a cache response on an error + * + * @param Event $event + */ + public function onRequestError(Event $event) + { + $request = $event['request']; + + if (!$this->canCache->canCacheRequest($request)) { + return; + } + + if ($response = $this->storage->fetch($request)) { + $response->setHeader( + 'Age', + time() - strtotime($response->getLastModified() ? : $response->getDate() ?: 'now') + ); + + if ($this->canResponseSatisfyFailedRequest($request, $response)) { + $request->getParams()->set('cache.hit', 'error'); + $this->addResponseHeaders($request, $response); + $event['response'] = $response; + $event->stopPropagation(); + } + } + } + + /** + * If possible, set a cache response on a cURL exception + * + * @param Event $event + * + * @return null + */ + public function onRequestException(Event $event) + { + if (!$event['exception'] instanceof CurlException) { + return; + } + + $request = $event['request']; + if (!$this->canCache->canCacheRequest($request)) { + return; + } + + if ($response = $this->storage->fetch($request)) { + $response->setHeader('Age', time() - strtotime($response->getDate() ? : 'now')); + if (!$this->canResponseSatisfyFailedRequest($request, $response)) { + return; + } + $request->getParams()->set('cache.hit', 'error'); + $request->setResponse($response); + $this->addResponseHeaders($request, $response); + $event->stopPropagation(); + } + } + + /** + * Check if a cache response satisfies a request's caching constraints + * + * @param RequestInterface $request Request to validate + * @param Response $response Response to validate + * + * @return bool + */ + public function canResponseSatisfyRequest(RequestInterface $request, Response $response) + { + $responseAge = $response->calculateAge(); + $reqc = $request->getHeader('Cache-Control'); + $resc = $response->getHeader('Cache-Control'); + + // Check the request's max-age header against the age of the response + if ($reqc && $reqc->hasDirective('max-age') && + $responseAge > $reqc->getDirective('max-age')) { + return false; + } + + // Check the response's max-age header + if ($response->isFresh() === false) { + $maxStale = $reqc ? $reqc->getDirective('max-stale') : null; + if (null !== $maxStale) { + if ($maxStale !== true && $response->getFreshness() < (-1 * $maxStale)) { + return false; + } + } elseif ($resc && $resc->hasDirective('max-age') + && $responseAge > $resc->getDirective('max-age') + ) { + return false; + } + } + + if ($this->revalidation->shouldRevalidate($request, $response)) { + try { + return $this->revalidation->revalidate($request, $response); + } catch (CurlException $e) { + $request->getParams()->set('cache.hit', 'error'); + return $this->canResponseSatisfyFailedRequest($request, $response); + } + } + + return true; + } + + /** + * Check if a cache response satisfies a failed request's caching constraints + * + * @param RequestInterface $request Request to validate + * @param Response $response Response to validate + * + * @return bool + */ + public function canResponseSatisfyFailedRequest(RequestInterface $request, Response $response) + { + $reqc = $request->getHeader('Cache-Control'); + $resc = $response->getHeader('Cache-Control'); + $requestStaleIfError = $reqc ? $reqc->getDirective('stale-if-error') : null; + $responseStaleIfError = $resc ? $resc->getDirective('stale-if-error') : null; + + if (!$requestStaleIfError && !$responseStaleIfError) { + return false; + } + + if (is_numeric($requestStaleIfError) && $response->getAge() - $response->getMaxAge() > $requestStaleIfError) { + return false; + } + + if (is_numeric($responseStaleIfError) && $response->getAge() - $response->getMaxAge() > $responseStaleIfError) { + return false; + } + + return true; + } + + /** + * Purge all cache entries for a given URL + * + * @param string $url URL to purge + */ + public function purge($url) + { + // BC compatibility with previous version that accepted a Request object + $url = $url instanceof RequestInterface ? $url->getUrl() : $url; + $this->storage->purge($url); + } + + /** + * Add the plugin's headers to a response + * + * @param RequestInterface $request Request + * @param Response $response Response to add headers to + */ + protected function addResponseHeaders(RequestInterface $request, Response $response) + { + $params = $request->getParams(); + $response->setHeader('Via', sprintf('%s GuzzleCache/%s', $request->getProtocolVersion(), Version::VERSION)); + + $lookup = ($params['cache.lookup'] === true ? 'HIT' : 'MISS') . ' from GuzzleCache'; + if ($header = $response->getHeader('X-Cache-Lookup')) { + // Don't add duplicates + $values = $header->toArray(); + $values[] = $lookup; + $response->setHeader('X-Cache-Lookup', array_unique($values)); + } else { + $response->setHeader('X-Cache-Lookup', $lookup); + } + + if ($params['cache.hit'] === true) { + $xcache = 'HIT from GuzzleCache'; + } elseif ($params['cache.hit'] == 'error') { + $xcache = 'HIT_ERROR from GuzzleCache'; + } else { + $xcache = 'MISS from GuzzleCache'; + } + + if ($header = $response->getHeader('X-Cache')) { + // Don't add duplicates + $values = $header->toArray(); + $values[] = $xcache; + $response->setHeader('X-Cache', array_unique($values)); + } else { + $response->setHeader('X-Cache', $xcache); + } + + if ($response->isFresh() === false) { + $response->addHeader('Warning', sprintf('110 GuzzleCache/%s "Response is stale"', Version::VERSION)); + if ($params['cache.hit'] === 'error') { + $response->addHeader('Warning', sprintf('111 GuzzleCache/%s "Revalidation failed"', Version::VERSION)); + } + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/CacheStorageInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/CacheStorageInterface.php new file mode 100644 index 000000000..f3d915458 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/CacheStorageInterface.php @@ -0,0 +1,43 @@ +requestCallback = $requestCallback; + $this->responseCallback = $responseCallback; + } + + public function canCacheRequest(RequestInterface $request) + { + return $this->requestCallback + ? call_user_func($this->requestCallback, $request) + : parent::canCacheRequest($request); + } + + public function canCacheResponse(Response $response) + { + return $this->responseCallback + ? call_user_func($this->responseCallback, $response) + : parent::canCacheResponse($response); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/CanCacheStrategyInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/CanCacheStrategyInterface.php new file mode 100644 index 000000000..6e01a8e74 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/CanCacheStrategyInterface.php @@ -0,0 +1,30 @@ +getParams()->get(self::CACHE_KEY); + + if (!$key) { + + $cloned = clone $request; + $cloned->removeHeader('Cache-Control'); + + // Check to see how and if the key should be filtered + foreach (explode(';', $request->getParams()->get(self::CACHE_KEY_FILTER)) as $part) { + $pieces = array_map('trim', explode('=', $part)); + if (isset($pieces[1])) { + foreach (array_map('trim', explode(',', $pieces[1])) as $remove) { + if ($pieces[0] == 'header') { + $cloned->removeHeader($remove); + } elseif ($pieces[0] == 'query') { + $cloned->getQuery()->remove($remove); + } + } + } + } + + $raw = (string) $cloned; + $key = 'GZ' . md5($raw); + $request->getParams()->set(self::CACHE_KEY, $key)->set(self::CACHE_KEY_RAW, $raw); + } + + return $key; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultCacheStorage.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultCacheStorage.php new file mode 100644 index 000000000..26d7a8b27 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultCacheStorage.php @@ -0,0 +1,266 @@ +cache = CacheAdapterFactory::fromCache($cache); + $this->defaultTtl = $defaultTtl; + $this->keyPrefix = $keyPrefix; + } + + public function cache(RequestInterface $request, Response $response) + { + $currentTime = time(); + + $overrideTtl = $request->getParams()->get('cache.override_ttl'); + if ($overrideTtl) { + $ttl = $overrideTtl; + } else { + $maxAge = $response->getMaxAge(); + if ($maxAge !== null) { + $ttl = $maxAge; + } else { + $ttl = $this->defaultTtl; + } + } + + if ($cacheControl = $response->getHeader('Cache-Control')) { + $stale = $cacheControl->getDirective('stale-if-error'); + if ($stale === true) { + $ttl += $ttl; + } else if (is_numeric($stale)) { + $ttl += $stale; + } + } + + // Determine which manifest key should be used + $key = $this->getCacheKey($request); + $persistedRequest = $this->persistHeaders($request); + $entries = array(); + + if ($manifest = $this->cache->fetch($key)) { + // Determine which cache entries should still be in the cache + $vary = $response->getVary(); + foreach (unserialize($manifest) as $entry) { + // Check if the entry is expired + if ($entry[4] < $currentTime) { + continue; + } + $entry[1]['vary'] = isset($entry[1]['vary']) ? $entry[1]['vary'] : ''; + if ($vary != $entry[1]['vary'] || !$this->requestsMatch($vary, $entry[0], $persistedRequest)) { + $entries[] = $entry; + } + } + } + + // Persist the response body if needed + $bodyDigest = null; + if ($response->getBody() && $response->getBody()->getContentLength() > 0) { + $bodyDigest = $this->getBodyKey($request->getUrl(), $response->getBody()); + $this->cache->save($bodyDigest, (string) $response->getBody(), $ttl); + } + + array_unshift($entries, array( + $persistedRequest, + $this->persistHeaders($response), + $response->getStatusCode(), + $bodyDigest, + $currentTime + $ttl + )); + + $this->cache->save($key, serialize($entries)); + } + + public function delete(RequestInterface $request) + { + $key = $this->getCacheKey($request); + if ($entries = $this->cache->fetch($key)) { + // Delete each cached body + foreach (unserialize($entries) as $entry) { + if ($entry[3]) { + $this->cache->delete($entry[3]); + } + } + $this->cache->delete($key); + } + } + + public function purge($url) + { + foreach (array('GET', 'HEAD', 'POST', 'PUT', 'DELETE') as $method) { + $this->delete(new Request($method, $url)); + } + } + + public function fetch(RequestInterface $request) + { + $key = $this->getCacheKey($request); + if (!($entries = $this->cache->fetch($key))) { + return null; + } + + $match = null; + $headers = $this->persistHeaders($request); + $entries = unserialize($entries); + foreach ($entries as $index => $entry) { + if ($this->requestsMatch(isset($entry[1]['vary']) ? $entry[1]['vary'] : '', $headers, $entry[0])) { + $match = $entry; + break; + } + } + + if (!$match) { + return null; + } + + // Ensure that the response is not expired + $response = null; + if ($match[4] < time()) { + $response = -1; + } else { + $response = new Response($match[2], $match[1]); + if ($match[3]) { + if ($body = $this->cache->fetch($match[3])) { + $response->setBody($body); + } else { + // The response is not valid because the body was somehow deleted + $response = -1; + } + } + } + + if ($response === -1) { + // Remove the entry from the metadata and update the cache + unset($entries[$index]); + if ($entries) { + $this->cache->save($key, serialize($entries)); + } else { + $this->cache->delete($key); + } + return null; + } + + return $response; + } + + /** + * Hash a request URL into a string that returns cache metadata + * + * @param RequestInterface $request + * + * @return string + */ + protected function getCacheKey(RequestInterface $request) + { + // Allow cache.key_filter to trim down the URL cache key by removing generate query string values (e.g. auth) + if ($filter = $request->getParams()->get('cache.key_filter')) { + $url = $request->getUrl(true); + foreach (explode(',', $filter) as $remove) { + $url->getQuery()->remove(trim($remove)); + } + } else { + $url = $request->getUrl(); + } + + return $this->keyPrefix . md5($request->getMethod() . ' ' . $url); + } + + /** + * Create a cache key for a response's body + * + * @param string $url URL of the entry + * @param EntityBodyInterface $body Response body + * + * @return string + */ + protected function getBodyKey($url, EntityBodyInterface $body) + { + return $this->keyPrefix . md5($url) . $body->getContentMd5(); + } + + /** + * Determines whether two Request HTTP header sets are non-varying + * + * @param string $vary Response vary header + * @param array $r1 HTTP header array + * @param array $r2 HTTP header array + * + * @return bool + */ + private function requestsMatch($vary, $r1, $r2) + { + if ($vary) { + foreach (explode(',', $vary) as $header) { + $key = trim(strtolower($header)); + $v1 = isset($r1[$key]) ? $r1[$key] : null; + $v2 = isset($r2[$key]) ? $r2[$key] : null; + if ($v1 !== $v2) { + return false; + } + } + } + + return true; + } + + /** + * Creates an array of cacheable and normalized message headers + * + * @param MessageInterface $message + * + * @return array + */ + private function persistHeaders(MessageInterface $message) + { + // Headers are excluded from the caching (see RFC 2616:13.5.1) + static $noCache = array( + 'age' => true, + 'connection' => true, + 'keep-alive' => true, + 'proxy-authenticate' => true, + 'proxy-authorization' => true, + 'te' => true, + 'trailers' => true, + 'transfer-encoding' => true, + 'upgrade' => true, + 'set-cookie' => true, + 'set-cookie2' => true + ); + + // Clone the response to not destroy any necessary headers when caching + $headers = $message->getHeaders()->getAll(); + $headers = array_diff_key($headers, $noCache); + // Cast the headers to a string + $headers = array_map(function ($h) { return (string) $h; }, $headers); + + return $headers; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultCanCacheStrategy.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultCanCacheStrategy.php new file mode 100644 index 000000000..3ca1fbf19 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultCanCacheStrategy.php @@ -0,0 +1,32 @@ +getMethod() != RequestInterface::GET && $request->getMethod() != RequestInterface::HEAD) { + return false; + } + + // Never cache requests when using no-store + if ($request->hasHeader('Cache-Control') && $request->getHeader('Cache-Control')->hasDirective('no-store')) { + return false; + } + + return true; + } + + public function canCacheResponse(Response $response) + { + return $response->isSuccessful() && $response->canCache(); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultRevalidation.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultRevalidation.php new file mode 100644 index 000000000..af33234ee --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DefaultRevalidation.php @@ -0,0 +1,174 @@ +storage = $cache; + $this->canCache = $canCache ?: new DefaultCanCacheStrategy(); + } + + public function revalidate(RequestInterface $request, Response $response) + { + try { + $revalidate = $this->createRevalidationRequest($request, $response); + $validateResponse = $revalidate->send(); + if ($validateResponse->getStatusCode() == 200) { + return $this->handle200Response($request, $validateResponse); + } elseif ($validateResponse->getStatusCode() == 304) { + return $this->handle304Response($request, $validateResponse, $response); + } + } catch (BadResponseException $e) { + $this->handleBadResponse($e); + } + + // Other exceptions encountered in the revalidation request are ignored + // in hopes that sending a request to the origin server will fix it + return false; + } + + public function shouldRevalidate(RequestInterface $request, Response $response) + { + if ($request->getMethod() != RequestInterface::GET) { + return false; + } + + $reqCache = $request->getHeader('Cache-Control'); + $resCache = $response->getHeader('Cache-Control'); + + $revalidate = $request->getHeader('Pragma') == 'no-cache' || + ($reqCache && ($reqCache->hasDirective('no-cache') || $reqCache->hasDirective('must-revalidate'))) || + ($resCache && ($resCache->hasDirective('no-cache') || $resCache->hasDirective('must-revalidate'))); + + // Use the strong ETag validator if available and the response contains no Cache-Control directive + if (!$revalidate && !$resCache && $response->hasHeader('ETag')) { + $revalidate = true; + } + + return $revalidate; + } + + /** + * Handles a bad response when attempting to revalidate + * + * @param BadResponseException $e Exception encountered + * + * @throws BadResponseException + */ + protected function handleBadResponse(BadResponseException $e) + { + // 404 errors mean the resource no longer exists, so remove from + // cache, and prevent an additional request by throwing the exception + if ($e->getResponse()->getStatusCode() == 404) { + $this->storage->delete($e->getRequest()); + throw $e; + } + } + + /** + * Creates a request to use for revalidation + * + * @param RequestInterface $request Request + * @param Response $response Response to revalidate + * + * @return RequestInterface returns a revalidation request + */ + protected function createRevalidationRequest(RequestInterface $request, Response $response) + { + $revalidate = clone $request; + $revalidate->removeHeader('Pragma')->removeHeader('Cache-Control'); + + if ($response->getLastModified()) { + $revalidate->setHeader('If-Modified-Since', $response->getLastModified()); + } + + if ($response->getEtag()) { + $revalidate->setHeader('If-None-Match', $response->getEtag()); + } + + // Remove any cache plugins that might be on the request to prevent infinite recursive revalidations + $dispatcher = $revalidate->getEventDispatcher(); + foreach ($dispatcher->getListeners() as $eventName => $listeners) { + foreach ($listeners as $listener) { + if (is_array($listener) && $listener[0] instanceof CachePlugin) { + $dispatcher->removeListener($eventName, $listener); + } + } + } + + return $revalidate; + } + + /** + * Handles a 200 response response from revalidating. The server does not support validation, so use this response. + * + * @param RequestInterface $request Request that was sent + * @param Response $validateResponse Response received + * + * @return bool Returns true if valid, false if invalid + */ + protected function handle200Response(RequestInterface $request, Response $validateResponse) + { + $request->setResponse($validateResponse); + if ($this->canCache->canCacheResponse($validateResponse)) { + $this->storage->cache($request, $validateResponse); + } + + return false; + } + + /** + * Handle a 304 response and ensure that it is still valid + * + * @param RequestInterface $request Request that was sent + * @param Response $validateResponse Response received + * @param Response $response Original cached response + * + * @return bool Returns true if valid, false if invalid + */ + protected function handle304Response(RequestInterface $request, Response $validateResponse, Response $response) + { + static $replaceHeaders = array('Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified'); + + // Make sure that this response has the same ETag + if ($validateResponse->getEtag() != $response->getEtag()) { + return false; + } + + // Replace cached headers with any of these headers from the + // origin server that might be more up to date + $modified = false; + foreach ($replaceHeaders as $name) { + if ($validateResponse->hasHeader($name)) { + $modified = true; + $response->setHeader($name, $validateResponse->getHeader($name)); + } + } + + // Store the updated response in cache + if ($modified && $this->canCache->canCacheResponse($response)) { + $this->storage->cache($request, $response); + } + + return true; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DenyRevalidation.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DenyRevalidation.php new file mode 100644 index 000000000..88b86f3ca --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cache/DenyRevalidation.php @@ -0,0 +1,19 @@ +=5.3.2", + "guzzle/http": "self.version", + "guzzle/cache": "self.version" + }, + "autoload": { + "psr-0": { "Guzzle\\Plugin\\Cache": "" } + }, + "target-dir": "Guzzle/Plugin/Cache", + "extra": { + "branch-alias": { + "dev-master": "3.7-dev" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/Cookie.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/Cookie.php new file mode 100644 index 000000000..5218e5f0e --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/Cookie.php @@ -0,0 +1,538 @@ + '', + 'value' => '', + 'domain' => '', + 'path' => '/', + 'expires' => null, + 'max_age' => 0, + 'comment' => null, + 'comment_url' => null, + 'port' => array(), + 'version' => null, + 'secure' => false, + 'discard' => false, + 'http_only' => false + ); + + $this->data = array_merge($defaults, $data); + // Extract the expires value and turn it into a UNIX timestamp if needed + if (!$this->getExpires() && $this->getMaxAge()) { + // Calculate the expires date + $this->setExpires(time() + (int) $this->getMaxAge()); + } elseif ($this->getExpires() && !is_numeric($this->getExpires())) { + $this->setExpires(strtotime($this->getExpires())); + } + } + + /** + * Get the cookie as an array + * + * @return array + */ + public function toArray() + { + return $this->data; + } + + /** + * Get the cookie name + * + * @return string + */ + public function getName() + { + return $this->data['name']; + } + + /** + * Set the cookie name + * + * @param string $name Cookie name + * + * @return Cookie + */ + public function setName($name) + { + return $this->setData('name', $name); + } + + /** + * Get the cookie value + * + * @return string + */ + public function getValue() + { + return $this->data['value']; + } + + /** + * Set the cookie value + * + * @param string $value Cookie value + * + * @return Cookie + */ + public function setValue($value) + { + return $this->setData('value', $value); + } + + /** + * Get the domain + * + * @return string|null + */ + public function getDomain() + { + return $this->data['domain']; + } + + /** + * Set the domain of the cookie + * + * @param string $domain + * + * @return Cookie + */ + public function setDomain($domain) + { + return $this->setData('domain', $domain); + } + + /** + * Get the path + * + * @return string + */ + public function getPath() + { + return $this->data['path']; + } + + /** + * Set the path of the cookie + * + * @param string $path Path of the cookie + * + * @return Cookie + */ + public function setPath($path) + { + return $this->setData('path', $path); + } + + /** + * Maximum lifetime of the cookie in seconds + * + * @return int|null + */ + public function getMaxAge() + { + return $this->data['max_age']; + } + + /** + * Set the max-age of the cookie + * + * @param int $maxAge Max age of the cookie in seconds + * + * @return Cookie + */ + public function setMaxAge($maxAge) + { + return $this->setData('max_age', $maxAge); + } + + /** + * The UNIX timestamp when the cookie expires + * + * @return mixed + */ + public function getExpires() + { + return $this->data['expires']; + } + + /** + * Set the unix timestamp for which the cookie will expire + * + * @param int $timestamp Unix timestamp + * + * @return Cookie + */ + public function setExpires($timestamp) + { + return $this->setData('expires', $timestamp); + } + + /** + * Version of the cookie specification. RFC 2965 is 1 + * + * @return mixed + */ + public function getVersion() + { + return $this->data['version']; + } + + /** + * Set the cookie version + * + * @param string|int $version Version to set + * + * @return Cookie + */ + public function setVersion($version) + { + return $this->setData('version', $version); + } + + /** + * Get whether or not this is a secure cookie + * + * @return null|bool + */ + public function getSecure() + { + return $this->data['secure']; + } + + /** + * Set whether or not the cookie is secure + * + * @param bool $secure Set to true or false if secure + * + * @return Cookie + */ + public function setSecure($secure) + { + return $this->setData('secure', (bool) $secure); + } + + /** + * Get whether or not this is a session cookie + * + * @return null|bool + */ + public function getDiscard() + { + return $this->data['discard']; + } + + /** + * Set whether or not this is a session cookie + * + * @param bool $discard Set to true or false if this is a session cookie + * + * @return Cookie + */ + public function setDiscard($discard) + { + return $this->setData('discard', $discard); + } + + /** + * Get the comment + * + * @return string|null + */ + public function getComment() + { + return $this->data['comment']; + } + + /** + * Set the comment of the cookie + * + * @param string $comment Cookie comment + * + * @return Cookie + */ + public function setComment($comment) + { + return $this->setData('comment', $comment); + } + + /** + * Get the comment URL of the cookie + * + * @return string|null + */ + public function getCommentUrl() + { + return $this->data['comment_url']; + } + + /** + * Set the comment URL of the cookie + * + * @param string $commentUrl Cookie comment URL for more information + * + * @return Cookie + */ + public function setCommentUrl($commentUrl) + { + return $this->setData('comment_url', $commentUrl); + } + + /** + * Get an array of acceptable ports this cookie can be used with + * + * @return array + */ + public function getPorts() + { + return $this->data['port']; + } + + /** + * Set a list of acceptable ports this cookie can be used with + * + * @param array $ports Array of acceptable ports + * + * @return Cookie + */ + public function setPorts(array $ports) + { + return $this->setData('port', $ports); + } + + /** + * Get whether or not this is an HTTP only cookie + * + * @return bool + */ + public function getHttpOnly() + { + return $this->data['http_only']; + } + + /** + * Set whether or not this is an HTTP only cookie + * + * @param bool $httpOnly Set to true or false if this is HTTP only + * + * @return Cookie + */ + public function setHttpOnly($httpOnly) + { + return $this->setData('http_only', $httpOnly); + } + + /** + * Get an array of extra cookie data + * + * @return array + */ + public function getAttributes() + { + return $this->data['data']; + } + + /** + * Get a specific data point from the extra cookie data + * + * @param string $name Name of the data point to retrieve + * + * @return null|string + */ + public function getAttribute($name) + { + return array_key_exists($name, $this->data['data']) ? $this->data['data'][$name] : null; + } + + /** + * Set a cookie data attribute + * + * @param string $name Name of the attribute to set + * @param string $value Value to set + * + * @return Cookie + */ + public function setAttribute($name, $value) + { + $this->data['data'][$name] = $value; + + return $this; + } + + /** + * Check if the cookie matches a path value + * + * @param string $path Path to check against + * + * @return bool + */ + public function matchesPath($path) + { + // RFC6265 http://tools.ietf.org/search/rfc6265#section-5.1.4 + // A request-path path-matches a given cookie-path if at least one of + // the following conditions holds: + + // o The cookie-path and the request-path are identical. + if ($path == $this->getPath()) { + return true; + } + + $pos = stripos($path, $this->getPath()); + if ($pos === 0) { + // o The cookie-path is a prefix of the request-path, and the last + // character of the cookie-path is %x2F ("/"). + if (substr($this->getPath(), -1, 1) === "/") { + return true; + } + + // o The cookie-path is a prefix of the request-path, and the first + // character of the request-path that is not included in the cookie- + // path is a %x2F ("/") character. + if (substr($path, strlen($this->getPath()), 1) === "/") { + return true; + } + } + + return false; + } + + /** + * Check if the cookie matches a domain value + * + * @param string $domain Domain to check against + * + * @return bool + */ + public function matchesDomain($domain) + { + // Remove the leading '.' as per spec in RFC 6265: http://tools.ietf.org/html/rfc6265#section-5.2.3 + $cookieDomain = ltrim($this->getDomain(), '.'); + + // Domain not set or exact match. + if (!$cookieDomain || !strcasecmp($domain, $cookieDomain)) { + return true; + } + + // Matching the subdomain according to RFC 6265: http://tools.ietf.org/html/rfc6265#section-5.1.3 + if (filter_var($domain, FILTER_VALIDATE_IP)) { + return false; + } + + return (bool) preg_match('/\.' . preg_quote($cookieDomain, '/') . '$/i', $domain); + } + + /** + * Check if the cookie is compatible with a specific port + * + * @param int $port Port to check + * + * @return bool + */ + public function matchesPort($port) + { + return count($this->getPorts()) == 0 || in_array($port, $this->getPorts()); + } + + /** + * Check if the cookie is expired + * + * @return bool + */ + public function isExpired() + { + return $this->getExpires() && time() > $this->getExpires(); + } + + /** + * Check if the cookie is valid according to RFC 6265 + * + * @return bool|string Returns true if valid or an error message if invalid + */ + public function validate() + { + // Names must not be empty, but can be 0 + $name = $this->getName(); + if (empty($name) && !is_numeric($name)) { + return 'The cookie name must not be empty'; + } + + // Check if any of the invalid characters are present in the cookie name + if (strpbrk($name, self::getInvalidCharacters()) !== false) { + return 'The cookie name must not contain invalid characters: ' . $name; + } + + // Value must not be empty, but can be 0 + $value = $this->getValue(); + if (empty($value) && !is_numeric($value)) { + return 'The cookie value must not be empty'; + } + + // Domains must not be empty, but can be 0 + // A "0" is not a valid internet domain, but may be used as server name in a private network + $domain = $this->getDomain(); + if (empty($domain) && !is_numeric($domain)) { + return 'The cookie domain must not be empty'; + } + + return true; + } + + /** + * Set a value and return the cookie object + * + * @param string $key Key to set + * @param string $value Value to set + * + * @return Cookie + */ + private function setData($key, $value) + { + $this->data[$key] = $value; + + return $this; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookieJar/ArrayCookieJar.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookieJar/ArrayCookieJar.php new file mode 100644 index 000000000..6b675039f --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookieJar/ArrayCookieJar.php @@ -0,0 +1,237 @@ +strictMode = $strictMode; + } + + /** + * Enable or disable strict mode on the cookie jar + * + * @param bool $strictMode Set to true to throw exceptions when invalid cookies are added. False to ignore them. + * + * @return self + */ + public function setStrictMode($strictMode) + { + $this->strictMode = $strictMode; + } + + public function remove($domain = null, $path = null, $name = null) + { + $cookies = $this->all($domain, $path, $name, false, false); + $this->cookies = array_filter($this->cookies, function (Cookie $cookie) use ($cookies) { + return !in_array($cookie, $cookies, true); + }); + + return $this; + } + + public function removeTemporary() + { + $this->cookies = array_filter($this->cookies, function (Cookie $cookie) { + return !$cookie->getDiscard() && $cookie->getExpires(); + }); + + return $this; + } + + public function removeExpired() + { + $currentTime = time(); + $this->cookies = array_filter($this->cookies, function (Cookie $cookie) use ($currentTime) { + return !$cookie->getExpires() || $currentTime < $cookie->getExpires(); + }); + + return $this; + } + + public function all($domain = null, $path = null, $name = null, $skipDiscardable = false, $skipExpired = true) + { + return array_values(array_filter($this->cookies, function (Cookie $cookie) use ( + $domain, + $path, + $name, + $skipDiscardable, + $skipExpired + ) { + return false === (($name && $cookie->getName() != $name) || + ($skipExpired && $cookie->isExpired()) || + ($skipDiscardable && ($cookie->getDiscard() || !$cookie->getExpires())) || + ($path && !$cookie->matchesPath($path)) || + ($domain && !$cookie->matchesDomain($domain))); + })); + } + + public function add(Cookie $cookie) + { + // Only allow cookies with set and valid domain, name, value + $result = $cookie->validate(); + if ($result !== true) { + if ($this->strictMode) { + throw new InvalidCookieException($result); + } else { + $this->removeCookieIfEmpty($cookie); + return false; + } + } + + // Resolve conflicts with previously set cookies + foreach ($this->cookies as $i => $c) { + + // Two cookies are identical, when their path, domain, port and name are identical + if ($c->getPath() != $cookie->getPath() || + $c->getDomain() != $cookie->getDomain() || + $c->getPorts() != $cookie->getPorts() || + $c->getName() != $cookie->getName() + ) { + continue; + } + + // The previously set cookie is a discard cookie and this one is not so allow the new cookie to be set + if (!$cookie->getDiscard() && $c->getDiscard()) { + unset($this->cookies[$i]); + continue; + } + + // If the new cookie's expiration is further into the future, then replace the old cookie + if ($cookie->getExpires() > $c->getExpires()) { + unset($this->cookies[$i]); + continue; + } + + // If the value has changed, we better change it + if ($cookie->getValue() !== $c->getValue()) { + unset($this->cookies[$i]); + continue; + } + + // The cookie exists, so no need to continue + return false; + } + + $this->cookies[] = $cookie; + + return true; + } + + /** + * Serializes the cookie cookieJar + * + * @return string + */ + public function serialize() + { + // Only serialize long term cookies and unexpired cookies + return json_encode(array_map(function (Cookie $cookie) { + return $cookie->toArray(); + }, $this->all(null, null, null, true, true))); + } + + /** + * Unserializes the cookie cookieJar + */ + public function unserialize($data) + { + $data = json_decode($data, true); + if (empty($data)) { + $this->cookies = array(); + } else { + $this->cookies = array_map(function (array $cookie) { + return new Cookie($cookie); + }, $data); + } + } + + /** + * Returns the total number of stored cookies + * + * @return int + */ + public function count() + { + return count($this->cookies); + } + + /** + * Returns an iterator + * + * @return \ArrayIterator + */ + public function getIterator() + { + return new \ArrayIterator($this->cookies); + } + + public function addCookiesFromResponse(Response $response, RequestInterface $request = null) + { + if ($cookieHeader = $response->getHeader('Set-Cookie')) { + $parser = ParserRegistry::getInstance()->getParser('cookie'); + foreach ($cookieHeader as $cookie) { + if ($parsed = $request + ? $parser->parseCookie($cookie, $request->getHost(), $request->getPath()) + : $parser->parseCookie($cookie) + ) { + // Break up cookie v2 into multiple cookies + foreach ($parsed['cookies'] as $key => $value) { + $row = $parsed; + $row['name'] = $key; + $row['value'] = $value; + unset($row['cookies']); + $this->add(new Cookie($row)); + } + } + } + } + } + + public function getMatchingCookies(RequestInterface $request) + { + // Find cookies that match this request + $cookies = $this->all($request->getHost(), $request->getPath()); + // Remove ineligible cookies + foreach ($cookies as $index => $cookie) { + if (!$cookie->matchesPort($request->getPort()) || ($cookie->getSecure() && $request->getScheme() != 'https')) { + unset($cookies[$index]); + } + }; + + return $cookies; + } + + /** + * If a cookie already exists and the server asks to set it again with a null value, the + * cookie must be deleted. + * + * @param \Guzzle\Plugin\Cookie\Cookie $cookie + */ + private function removeCookieIfEmpty(Cookie $cookie) + { + $cookieValue = $cookie->getValue(); + if ($cookieValue === null || $cookieValue === '') { + $this->remove($cookie->getDomain(), $cookie->getPath(), $cookie->getName()); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookieJar/CookieJarInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookieJar/CookieJarInterface.php new file mode 100644 index 000000000..7faa7d21f --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookieJar/CookieJarInterface.php @@ -0,0 +1,85 @@ +filename = $cookieFile; + $this->load(); + } + + /** + * Saves the file when shutting down + */ + public function __destruct() + { + $this->persist(); + } + + /** + * Save the contents of the data array to the file + * + * @throws RuntimeException if the file cannot be found or created + */ + protected function persist() + { + if (false === file_put_contents($this->filename, $this->serialize())) { + // @codeCoverageIgnoreStart + throw new RuntimeException('Unable to open file ' . $this->filename); + // @codeCoverageIgnoreEnd + } + } + + /** + * Load the contents of the json formatted file into the data array and discard any unsaved state + */ + protected function load() + { + $json = file_get_contents($this->filename); + if (false === $json) { + // @codeCoverageIgnoreStart + throw new RuntimeException('Unable to open file ' . $this->filename); + // @codeCoverageIgnoreEnd + } + + $this->unserialize($json); + $this->cookies = $this->cookies ?: array(); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookiePlugin.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookiePlugin.php new file mode 100644 index 000000000..df3210ee1 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/CookiePlugin.php @@ -0,0 +1,70 @@ +cookieJar = $cookieJar ?: new ArrayCookieJar(); + } + + public static function getSubscribedEvents() + { + return array( + 'request.before_send' => array('onRequestBeforeSend', 125), + 'request.sent' => array('onRequestSent', 125) + ); + } + + /** + * Get the cookie cookieJar + * + * @return CookieJarInterface + */ + public function getCookieJar() + { + return $this->cookieJar; + } + + /** + * Add cookies before a request is sent + * + * @param Event $event + */ + public function onRequestBeforeSend(Event $event) + { + $request = $event['request']; + if (!$request->getParams()->get('cookies.disable')) { + $request->removeHeader('Cookie'); + // Find cookies that match this request + foreach ($this->cookieJar->getMatchingCookies($request) as $cookie) { + $request->addCookie($cookie->getName(), $cookie->getValue()); + } + } + } + + /** + * Extract cookies from a sent request + * + * @param Event $event + */ + public function onRequestSent(Event $event) + { + $this->cookieJar->addCookiesFromResponse($event['response'], $event['request']); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/Exception/InvalidCookieException.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/Exception/InvalidCookieException.php new file mode 100644 index 000000000..b1fa6fd89 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Cookie/Exception/InvalidCookieException.php @@ -0,0 +1,7 @@ +=5.3.2", + "guzzle/http": "self.version" + }, + "autoload": { + "psr-0": { "Guzzle\\Plugin\\Cookie": "" } + }, + "target-dir": "Guzzle/Plugin/Cookie", + "extra": { + "branch-alias": { + "dev-master": "3.7-dev" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/CurlAuth/CurlAuthPlugin.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/CurlAuth/CurlAuthPlugin.php new file mode 100644 index 000000000..610e60cad --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/CurlAuth/CurlAuthPlugin.php @@ -0,0 +1,46 @@ +getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest'); + */ +class CurlAuthPlugin implements EventSubscriberInterface +{ + private $username; + private $password; + private $scheme; + + /** + * @param string $username HTTP basic auth username + * @param string $password Password + * @param int $scheme Curl auth scheme + */ + public function __construct($username, $password, $scheme=CURLAUTH_BASIC) + { + Version::warn(__CLASS__ . " is deprecated. Use \$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest');"); + $this->username = $username; + $this->password = $password; + $this->scheme = $scheme; + } + + public static function getSubscribedEvents() + { + return array('client.create_request' => array('onRequestCreate', 255)); + } + + /** + * Add basic auth + * + * @param Event $event + */ + public function onRequestCreate(Event $event) + { + $event['request']->setAuth($this->username, $this->password, $this->scheme); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/CurlAuth/composer.json b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/CurlAuth/composer.json new file mode 100644 index 000000000..edc8b24e5 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/CurlAuth/composer.json @@ -0,0 +1,27 @@ +{ + "name": "guzzle/plugin-curlauth", + "description": "Guzzle cURL authorization plugin", + "homepage": "http://guzzlephp.org/", + "keywords": ["plugin", "curl", "guzzle"], + "license": "MIT", + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "require": { + "php": ">=5.3.2", + "guzzle/http": "self.version" + }, + "autoload": { + "psr-0": { "Guzzle\\Plugin\\CurlAuth": "" } + }, + "target-dir": "Guzzle/Plugin/CurlAuth", + "extra": { + "branch-alias": { + "dev-master": "3.7-dev" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/ErrorResponse/ErrorResponseExceptionInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/ErrorResponse/ErrorResponseExceptionInterface.php new file mode 100644 index 000000000..5dce8bd6c --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/ErrorResponse/ErrorResponseExceptionInterface.php @@ -0,0 +1,22 @@ + array('onCommandBeforeSend', -1)); + } + + /** + * Adds a listener to requests before they sent from a command + * + * @param Event $event Event emitted + */ + public function onCommandBeforeSend(Event $event) + { + $command = $event['command']; + if ($operation = $command->getOperation()) { + if ($operation->getErrorResponses()) { + $request = $command->getRequest(); + $request->getEventDispatcher() + ->addListener('request.complete', $this->getErrorClosure($request, $command, $operation)); + } + } + } + + /** + * @param RequestInterface $request Request that received an error + * @param CommandInterface $command Command that created the request + * @param Operation $operation Operation that defines the request and errors + * + * @return \Closure Returns a closure + * @throws ErrorResponseException + */ + protected function getErrorClosure(RequestInterface $request, CommandInterface $command, Operation $operation) + { + return function (Event $event) use ($request, $command, $operation) { + $response = $event['response']; + foreach ($operation->getErrorResponses() as $error) { + if (!isset($error['class'])) { + continue; + } + if (isset($error['code']) && $response->getStatusCode() != $error['code']) { + continue; + } + if (isset($error['reason']) && $response->getReasonPhrase() != $error['reason']) { + continue; + } + $className = $error['class']; + $errorClassInterface = __NAMESPACE__ . '\\ErrorResponseExceptionInterface'; + if (!class_exists($className)) { + throw new ErrorResponseException("{$className} does not exist"); + } elseif (!(in_array($errorClassInterface, class_implements($className)))) { + throw new ErrorResponseException("{$className} must implement {$errorClassInterface}"); + } + throw $className::fromCommand($command, $response); + } + }; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/ErrorResponse/Exception/ErrorResponseException.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/ErrorResponse/Exception/ErrorResponseException.php new file mode 100644 index 000000000..1d89e40e7 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/ErrorResponse/Exception/ErrorResponseException.php @@ -0,0 +1,7 @@ +=5.3.2", + "guzzle/service": "self.version" + }, + "autoload": { + "psr-0": { "Guzzle\\Plugin\\ErrorResponse": "" } + }, + "target-dir": "Guzzle/Plugin/ErrorResponse", + "extra": { + "branch-alias": { + "dev-master": "3.7-dev" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/History/HistoryPlugin.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/History/HistoryPlugin.php new file mode 100644 index 000000000..7375e892b --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/History/HistoryPlugin.php @@ -0,0 +1,163 @@ + array('onRequestSent', 9999)); + } + + /** + * Convert to a string that contains all request and response headers + * + * @return string + */ + public function __toString() + { + $lines = array(); + foreach ($this->transactions as $entry) { + $response = isset($entry['response']) ? $entry['response'] : ''; + $lines[] = '> ' . trim($entry['request']) . "\n\n< " . trim($response) . "\n"; + } + + return implode("\n", $lines); + } + + /** + * Add a request to the history + * + * @param RequestInterface $request Request to add + * @param Response $response Response of the request + * + * @return HistoryPlugin + */ + public function add(RequestInterface $request, Response $response = null) + { + if (!$response && $request->getResponse()) { + $response = $request->getResponse(); + } + + $this->transactions[] = array('request' => $request, 'response' => $response); + if (count($this->transactions) > $this->getlimit()) { + array_shift($this->transactions); + } + + return $this; + } + + /** + * Set the max number of requests to store + * + * @param int $limit Limit + * + * @return HistoryPlugin + */ + public function setLimit($limit) + { + $this->limit = (int) $limit; + + return $this; + } + + /** + * Get the request limit + * + * @return int + */ + public function getLimit() + { + return $this->limit; + } + + /** + * Get all of the raw transactions in the form of an array of associative arrays containing + * 'request' and 'response' keys. + * + * @return array + */ + public function getAll() + { + return $this->transactions; + } + + /** + * Get the requests in the history + * + * @return \ArrayIterator + */ + public function getIterator() + { + // Return an iterator just like the old iteration of the HistoryPlugin for BC compatibility (use getAll()) + return new \ArrayIterator(array_map(function ($entry) { + $entry['request']->getParams()->set('actual_response', $entry['response']); + return $entry['request']; + }, $this->transactions)); + } + + /** + * Get the number of requests in the history + * + * @return int + */ + public function count() + { + return count($this->transactions); + } + + /** + * Get the last request sent + * + * @return RequestInterface + */ + public function getLastRequest() + { + $last = end($this->transactions); + + return $last['request']; + } + + /** + * Get the last response in the history + * + * @return Response|null + */ + public function getLastResponse() + { + $last = end($this->transactions); + + return isset($last['response']) ? $last['response'] : null; + } + + /** + * Clears the history + * + * @return HistoryPlugin + */ + public function clear() + { + $this->transactions = array(); + + return $this; + } + + public function onRequestSent(Event $event) + { + $this->add($event['request'], $event['response']); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/History/composer.json b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/History/composer.json new file mode 100644 index 000000000..ba0bf2c4d --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/History/composer.json @@ -0,0 +1,27 @@ +{ + "name": "guzzle/plugin-history", + "description": "Guzzle history plugin", + "homepage": "http://guzzlephp.org/", + "keywords": ["plugin", "guzzle"], + "license": "MIT", + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "require": { + "php": ">=5.3.2", + "guzzle/http": "self.version" + }, + "autoload": { + "psr-0": { "Guzzle\\Plugin\\History": "" } + }, + "target-dir": "Guzzle/Plugin/History", + "extra": { + "branch-alias": { + "dev-master": "3.7-dev" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Log/LogPlugin.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Log/LogPlugin.php new file mode 100644 index 000000000..cabdea854 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Log/LogPlugin.php @@ -0,0 +1,161 @@ +logAdapter = $logAdapter; + $this->formatter = $formatter instanceof MessageFormatter ? $formatter : new MessageFormatter($formatter); + $this->wireBodies = $wireBodies; + } + + /** + * Get a log plugin that outputs full request, response, and curl error information to stderr + * + * @param bool $wireBodies Set to false to disable request/response body output when they use are not repeatable + * @param resource $stream Stream to write to when logging. Defaults to STDERR when it is available + * + * @return self + */ + public static function getDebugPlugin($wireBodies = true, $stream = null) + { + if ($stream === null) { + if (defined('STDERR')) { + $stream = STDERR; + } else { + $stream = fopen('php://output', 'w'); + } + } + + return new self(new ClosureLogAdapter(function ($m) use ($stream) { + fwrite($stream, $m . PHP_EOL); + }), "# Request:\n{request}\n\n# Response:\n{response}\n\n# Errors: {curl_code} {curl_error}", $wireBodies); + } + + public static function getSubscribedEvents() + { + return array( + 'curl.callback.write' => array('onCurlWrite', 255), + 'curl.callback.read' => array('onCurlRead', 255), + 'request.before_send' => array('onRequestBeforeSend', 255), + 'request.sent' => array('onRequestSent', 255) + ); + } + + /** + * Event triggered when curl data is read from a request + * + * @param Event $event + */ + public function onCurlRead(Event $event) + { + // Stream the request body to the log if the body is not repeatable + if ($wire = $event['request']->getParams()->get('request_wire')) { + $wire->write($event['read']); + } + } + + /** + * Event triggered when curl data is written to a response + * + * @param Event $event + */ + public function onCurlWrite(Event $event) + { + // Stream the response body to the log if the body is not repeatable + if ($wire = $event['request']->getParams()->get('response_wire')) { + $wire->write($event['write']); + } + } + + /** + * Called before a request is sent + * + * @param Event $event + */ + public function onRequestBeforeSend(Event $event) + { + if ($this->wireBodies) { + $request = $event['request']; + // Ensure that curl IO events are emitted + $request->getCurlOptions()->set('emit_io', true); + // We need to make special handling for content wiring and non-repeatable streams. + if ($request instanceof EntityEnclosingRequestInterface && $request->getBody() + && (!$request->getBody()->isSeekable() || !$request->getBody()->isReadable()) + ) { + // The body of the request cannot be recalled so logging the body will require us to buffer it + $request->getParams()->set('request_wire', EntityBody::factory()); + } + if (!$request->getResponseBody()->isRepeatable()) { + // The body of the response cannot be recalled so logging the body will require us to buffer it + $request->getParams()->set('response_wire', EntityBody::factory()); + } + } + } + + /** + * Triggers the actual log write when a request completes + * + * @param Event $event + */ + public function onRequestSent(Event $event) + { + $request = $event['request']; + $response = $event['response']; + $handle = $event['handle']; + + if ($wire = $request->getParams()->get('request_wire')) { + $request = clone $request; + $request->setBody($wire); + } + + if ($wire = $request->getParams()->get('response_wire')) { + $response = clone $response; + $response->setBody($wire); + } + + // Send the log message to the adapter, adding a category and host + $priority = $response && $response->isError() ? LOG_ERR : LOG_DEBUG; + $message = $this->formatter->format($request, $response, $handle); + $this->logAdapter->log($message, $priority, array( + 'request' => $request, + 'response' => $response, + 'handle' => $handle + )); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Log/composer.json b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Log/composer.json new file mode 100644 index 000000000..130e6da0a --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Log/composer.json @@ -0,0 +1,28 @@ +{ + "name": "guzzle/plugin-log", + "description": "Guzzle log plugin for over the wire logging", + "homepage": "http://guzzlephp.org/", + "keywords": ["plugin", "log", "guzzle"], + "license": "MIT", + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "require": { + "php": ">=5.3.2", + "guzzle/http": "self.version", + "guzzle/log": "self.version" + }, + "autoload": { + "psr-0": { "Guzzle\\Plugin\\Log": "" } + }, + "target-dir": "Guzzle/Plugin/Log", + "extra": { + "branch-alias": { + "dev-master": "3.7-dev" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Md5/CommandContentMd5Plugin.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Md5/CommandContentMd5Plugin.php new file mode 100644 index 000000000..851242433 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Md5/CommandContentMd5Plugin.php @@ -0,0 +1,57 @@ +contentMd5Param = $contentMd5Param; + $this->validateMd5Param = $validateMd5Param; + } + + public static function getSubscribedEvents() + { + return array('command.before_send' => array('onCommandBeforeSend', -255)); + } + + public function onCommandBeforeSend(Event $event) + { + $command = $event['command']; + $request = $command->getRequest(); + + // Only add an MD5 is there is a MD5 option on the operation and it has a payload + if ($request instanceof EntityEnclosingRequestInterface && $request->getBody() + && $command->getOperation()->hasParam($this->contentMd5Param)) { + // Check if an MD5 checksum value should be passed along to the request + if ($command[$this->contentMd5Param] === true) { + if (false !== ($md5 = $request->getBody()->getContentMd5(true, true))) { + $request->setHeader('Content-MD5', $md5); + } + } + } + + // Check if MD5 validation should be used with the response + if ($command[$this->validateMd5Param] === true) { + $request->addSubscriber(new Md5ValidatorPlugin(true, false)); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Md5/Md5ValidatorPlugin.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Md5/Md5ValidatorPlugin.php new file mode 100644 index 000000000..5d7a3785e --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Md5/Md5ValidatorPlugin.php @@ -0,0 +1,88 @@ +contentLengthCutoff = $contentLengthCutoff; + $this->contentEncoded = $contentEncoded; + } + + public static function getSubscribedEvents() + { + return array('request.complete' => array('onRequestComplete', 255)); + } + + /** + * {@inheritdoc} + * @throws UnexpectedValueException + */ + public function onRequestComplete(Event $event) + { + $response = $event['response']; + + if (!$contentMd5 = $response->getContentMd5()) { + return; + } + + $contentEncoding = $response->getContentEncoding(); + if ($contentEncoding && !$this->contentEncoded) { + return false; + } + + // Make sure that the size of the request is under the cutoff size + if ($this->contentLengthCutoff) { + $size = $response->getContentLength() ?: $response->getBody()->getSize(); + if (!$size || $size > $this->contentLengthCutoff) { + return; + } + } + + if (!$contentEncoding) { + $hash = $response->getBody()->getContentMd5(); + } elseif ($contentEncoding == 'gzip') { + $response->getBody()->compress('zlib.deflate'); + $hash = $response->getBody()->getContentMd5(); + $response->getBody()->uncompress(); + } elseif ($contentEncoding == 'compress') { + $response->getBody()->compress('bzip2.compress'); + $hash = $response->getBody()->getContentMd5(); + $response->getBody()->uncompress(); + } else { + return; + } + + if ($contentMd5 !== $hash) { + throw new UnexpectedValueException( + "The response entity body may have been modified over the wire. The Content-MD5 " + . "received ({$contentMd5}) did not match the calculated MD5 hash ({$hash})." + ); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Md5/composer.json b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Md5/composer.json new file mode 100644 index 000000000..0602d0609 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Md5/composer.json @@ -0,0 +1,27 @@ +{ + "name": "guzzle/plugin-md5", + "description": "Guzzle MD5 plugins", + "homepage": "http://guzzlephp.org/", + "keywords": ["plugin", "guzzle"], + "license": "MIT", + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "require": { + "php": ">=5.3.2", + "guzzle/http": "self.version" + }, + "autoload": { + "psr-0": { "Guzzle\\Plugin\\Md5": "" } + }, + "target-dir": "Guzzle/Plugin/Md5", + "extra": { + "branch-alias": { + "dev-master": "3.7-dev" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Mock/MockPlugin.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Mock/MockPlugin.php new file mode 100644 index 000000000..2440578cf --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Mock/MockPlugin.php @@ -0,0 +1,245 @@ +readBodies = $readBodies; + $this->temporary = $temporary; + if ($items) { + foreach ($items as $item) { + if ($item instanceof \Exception) { + $this->addException($item); + } else { + $this->addResponse($item); + } + } + } + } + + public static function getSubscribedEvents() + { + // Use a number lower than the CachePlugin + return array('request.before_send' => array('onRequestBeforeSend', -999)); + } + + public static function getAllEvents() + { + return array('mock.request'); + } + + /** + * Get a mock response from a file + * + * @param string $path File to retrieve a mock response from + * + * @return Response + * @throws InvalidArgumentException if the file is not found + */ + public static function getMockFile($path) + { + if (!file_exists($path)) { + throw new InvalidArgumentException('Unable to open mock file: ' . $path); + } + + return Response::fromMessage(file_get_contents($path)); + } + + /** + * Set whether or not to consume the entity body of a request when a mock + * response is used + * + * @param bool $readBodies Set to true to read and consume entity bodies + * + * @return self + */ + public function readBodies($readBodies) + { + $this->readBodies = $readBodies; + + return $this; + } + + /** + * Returns the number of remaining mock responses + * + * @return int + */ + public function count() + { + return count($this->queue); + } + + /** + * Add a response to the end of the queue + * + * @param string|Response $response Response object or path to response file + * + * @return MockPlugin + * @throws InvalidArgumentException if a string or Response is not passed + */ + public function addResponse($response) + { + if (!($response instanceof Response)) { + if (!is_string($response)) { + throw new InvalidArgumentException('Invalid response'); + } + $response = self::getMockFile($response); + } + + $this->queue[] = $response; + + return $this; + } + + /** + * Add an exception to the end of the queue + * + * @param CurlException $e Exception to throw when the request is executed + * + * @return MockPlugin + */ + public function addException(CurlException $e) + { + $this->queue[] = $e; + + return $this; + } + + /** + * Clear the queue + * + * @return MockPlugin + */ + public function clearQueue() + { + $this->queue = array(); + + return $this; + } + + /** + * Returns an array of mock responses remaining in the queue + * + * @return array + */ + public function getQueue() + { + return $this->queue; + } + + /** + * Check if this is a temporary plugin + * + * @return bool + */ + public function isTemporary() + { + return $this->temporary; + } + + /** + * Get a response from the front of the list and add it to a request + * + * @param RequestInterface $request Request to mock + * + * @return self + * @throws CurlException When request.send is called and an exception is queued + */ + public function dequeue(RequestInterface $request) + { + $this->dispatch('mock.request', array('plugin' => $this, 'request' => $request)); + + $item = array_shift($this->queue); + if ($item instanceof Response) { + if ($this->readBodies && $request instanceof EntityEnclosingRequestInterface) { + $request->getEventDispatcher()->addListener('request.sent', $f = function (Event $event) use (&$f) { + while ($data = $event['request']->getBody()->read(8096)); + // Remove the listener after one-time use + $event['request']->getEventDispatcher()->removeListener('request.sent', $f); + }); + } + $request->setResponse($item); + } elseif ($item instanceof CurlException) { + // Emulates exceptions encountered while transferring requests + $item->setRequest($request); + $state = $request->setState(RequestInterface::STATE_ERROR, array('exception' => $item)); + // Only throw if the exception wasn't handled + if ($state == RequestInterface::STATE_ERROR) { + throw $item; + } + } + + return $this; + } + + /** + * Clear the array of received requests + */ + public function flush() + { + $this->received = array(); + } + + /** + * Get an array of requests that were mocked by this plugin + * + * @return array + */ + public function getReceivedRequests() + { + return $this->received; + } + + /** + * Called when a request is about to be sent + * + * @param Event $event + * @throws \OutOfBoundsException When queue is empty + */ + public function onRequestBeforeSend(Event $event) + { + if (!$this->queue) { + throw new \OutOfBoundsException('Mock queue is empty'); + } + + $request = $event['request']; + $this->received[] = $request; + // Detach the filter from the client so it's a one-time use + if ($this->temporary && count($this->queue) == 1 && $request->getClient()) { + $request->getClient()->getEventDispatcher()->removeSubscriber($this); + } + $this->dequeue($request); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Mock/composer.json b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Mock/composer.json new file mode 100644 index 000000000..f8201e31f --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Mock/composer.json @@ -0,0 +1,27 @@ +{ + "name": "guzzle/plugin-mock", + "description": "Guzzle Mock plugin", + "homepage": "http://guzzlephp.org/", + "keywords": ["mock", "plugin", "guzzle"], + "license": "MIT", + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "require": { + "php": ">=5.3.2", + "guzzle/http": "self.version" + }, + "autoload": { + "psr-0": { "Guzzle\\Plugin\\Mock": "" } + }, + "target-dir": "Guzzle/Plugin/Mock", + "extra": { + "branch-alias": { + "dev-master": "3.7-dev" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Oauth/OauthPlugin.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Oauth/OauthPlugin.php new file mode 100644 index 000000000..95e0c3e4a --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Oauth/OauthPlugin.php @@ -0,0 +1,306 @@ +config = Collection::fromConfig($config, array( + 'version' => '1.0', + 'request_method' => self::REQUEST_METHOD_HEADER, + 'consumer_key' => 'anonymous', + 'consumer_secret' => 'anonymous', + 'signature_method' => 'HMAC-SHA1', + 'signature_callback' => function($stringToSign, $key) { + return hash_hmac('sha1', $stringToSign, $key, true); + } + ), array( + 'signature_method', 'signature_callback', 'version', + 'consumer_key', 'consumer_secret' + )); + } + + public static function getSubscribedEvents() + { + return array( + 'request.before_send' => array('onRequestBeforeSend', -1000) + ); + } + + /** + * Request before-send event handler + * + * @param Event $event Event received + * @return array + * @throws \InvalidArgumentException + */ + public function onRequestBeforeSend(Event $event) + { + $timestamp = $this->getTimestamp($event); + $request = $event['request']; + $nonce = $this->generateNonce($request); + $authorizationParams = $this->getOauthParams($timestamp, $nonce); + $authorizationParams['oauth_signature'] = $this->getSignature($request, $timestamp, $nonce); + + switch ($this->config['request_method']) { + case self::REQUEST_METHOD_HEADER: + $request->setHeader( + 'Authorization', + $this->buildAuthorizationHeader($authorizationParams) + ); + break; + case self::REQUEST_METHOD_QUERY: + foreach ($authorizationParams as $key => $value) { + $request->getQuery()->set($key, $value); + } + break; + default: + throw new \InvalidArgumentException(sprintf( + 'Invalid consumer method "%s"', + $this->config['request_method'] + )); + } + + return $authorizationParams; + } + + /** + * Builds the Authorization header for a request + * + * @param array $authorizationParams Associative array of authorization parameters + * + * @return string + */ + private function buildAuthorizationHeader($authorizationParams) + { + $authorizationString = 'OAuth '; + foreach ($authorizationParams as $key => $val) { + if ($val) { + $authorizationString .= $key . '="' . urlencode($val) . '", '; + } + } + + return substr($authorizationString, 0, -2); + } + + /** + * Calculate signature for request + * + * @param RequestInterface $request Request to generate a signature for + * @param integer $timestamp Timestamp to use for nonce + * @param string $nonce + * + * @return string + */ + public function getSignature(RequestInterface $request, $timestamp, $nonce) + { + $string = $this->getStringToSign($request, $timestamp, $nonce); + $key = urlencode($this->config['consumer_secret']) . '&' . urlencode($this->config['token_secret']); + + return base64_encode(call_user_func($this->config['signature_callback'], $string, $key)); + } + + /** + * Calculate string to sign + * + * @param RequestInterface $request Request to generate a signature for + * @param int $timestamp Timestamp to use for nonce + * @param string $nonce + * + * @return string + */ + public function getStringToSign(RequestInterface $request, $timestamp, $nonce) + { + $params = $this->getParamsToSign($request, $timestamp, $nonce); + + // Convert booleans to strings. + $params = $this->prepareParameters($params); + + // Build signing string from combined params + $parameterString = clone $request->getQuery(); + $parameterString->replace($params); + + $url = Url::factory($request->getUrl())->setQuery('')->setFragment(null); + + return strtoupper($request->getMethod()) . '&' + . rawurlencode($url) . '&' + . rawurlencode((string) $parameterString); + } + + /** + * Get the oauth parameters as named by the oauth spec + * + * @param $timestamp + * @param $nonce + * @return Collection + */ + protected function getOauthParams($timestamp, $nonce) + { + $params = new Collection(array( + 'oauth_consumer_key' => $this->config['consumer_key'], + 'oauth_nonce' => $nonce, + 'oauth_signature_method' => $this->config['signature_method'], + 'oauth_timestamp' => $timestamp, + )); + + // Optional parameters should not be set if they have not been set in the config as + // the parameter may be considered invalid by the Oauth service. + $optionalParams = array( + 'callback' => 'oauth_callback', + 'token' => 'oauth_token', + 'verifier' => 'oauth_verifier', + 'version' => 'oauth_version' + ); + + foreach ($optionalParams as $optionName => $oauthName) { + if (isset($this->config[$optionName]) == true) { + $params[$oauthName] = $this->config[$optionName]; + } + } + + return $params; + } + + /** + * Get all of the parameters required to sign a request including: + * * The oauth params + * * The request GET params + * * The params passed in the POST body (with a content-type of application/x-www-form-urlencoded) + * + * @param RequestInterface $request Request to generate a signature for + * @param integer $timestamp Timestamp to use for nonce + * @param string $nonce + * + * @return array + */ + public function getParamsToSign(RequestInterface $request, $timestamp, $nonce) + { + $params = $this->getOauthParams($timestamp, $nonce); + + // Add query string parameters + $params->merge($request->getQuery()); + + // Add POST fields to signing string if required + if ($this->shouldPostFieldsBeSigned($request)) + { + $params->merge($request->getPostFields()); + } + + // Sort params + $params = $params->toArray(); + uksort($params, 'strcmp'); + + return $params; + } + + /** + * Decide whether the post fields should be added to the base string that Oauth signs. + * This implementation is correct. Non-conformant APIs may require that this method be + * overwritten e.g. the Flickr API incorrectly adds the post fields when the Content-Type + * is 'application/x-www-form-urlencoded' + * + * @param $request + * @return bool Whether the post fields should be signed or not + */ + public function shouldPostFieldsBeSigned($request) + { + if (!$this->config->get('disable_post_params') && + $request instanceof EntityEnclosingRequestInterface && + false !== strpos($request->getHeader('Content-Type'), 'application/x-www-form-urlencoded')) + { + return true; + } + + return false; + } + + /** + * Returns a Nonce Based on the unique id and URL. This will allow for multiple requests in parallel with the same + * exact timestamp to use separate nonce's. + * + * @param RequestInterface $request Request to generate a nonce for + * + * @return string + */ + public function generateNonce(RequestInterface $request) + { + return sha1(uniqid('', true) . $request->getUrl()); + } + + /** + * Gets timestamp from event or create new timestamp + * + * @param Event $event Event containing contextual information + * + * @return int + */ + public function getTimestamp(Event $event) + { + return $event['timestamp'] ?: time(); + } + + /** + * Convert booleans to strings, removed unset parameters, and sorts the array + * + * @param array $data Data array + * + * @return array + */ + protected function prepareParameters($data) + { + ksort($data); + foreach ($data as $key => &$value) { + switch (gettype($value)) { + case 'NULL': + unset($data[$key]); + break; + case 'array': + $data[$key] = self::prepareParameters($value); + break; + case 'boolean': + $data[$key] = $value ? 'true' : 'false'; + break; + } + } + + return $data; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Oauth/composer.json b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Oauth/composer.json new file mode 100644 index 000000000..c9766ba16 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/Oauth/composer.json @@ -0,0 +1,27 @@ +{ + "name": "guzzle/plugin-oauth", + "description": "Guzzle OAuth plugin", + "homepage": "http://guzzlephp.org/", + "keywords": ["oauth", "plugin", "guzzle"], + "license": "MIT", + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "require": { + "php": ">=5.3.2", + "guzzle/http": "self.version" + }, + "autoload": { + "psr-0": { "Guzzle\\Plugin\\Oauth": "" } + }, + "target-dir": "Guzzle/Plugin/Oauth", + "extra": { + "branch-alias": { + "dev-master": "3.7-dev" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/composer.json b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/composer.json new file mode 100644 index 000000000..2bbe64cc5 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Plugin/composer.json @@ -0,0 +1,44 @@ +{ + "name": "guzzle/plugin", + "description": "Guzzle plugin component containing all Guzzle HTTP plugins", + "homepage": "http://guzzlephp.org/", + "keywords": ["http", "client", "plugin", "extension", "guzzle"], + "license": "MIT", + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "require": { + "php": ">=5.3.2", + "guzzle/http": "self.version" + }, + "suggest": { + "guzzle/cache": "self.version", + "guzzle/log": "self.version" + }, + "autoload": { + "psr-0": { "Guzzle\\Plugin": "" } + }, + "target-dir": "Guzzle/Plugin", + "replace": { + "guzzle/plugin-async": "self.version", + "guzzle/plugin-backoff": "self.version", + "guzzle/plugin-cache": "self.version", + "guzzle/plugin-cookie": "self.version", + "guzzle/plugin-curlauth": "self.version", + "guzzle/plugin-error-response": "self.version", + "guzzle/plugin-history": "self.version", + "guzzle/plugin-log": "self.version", + "guzzle/plugin-md5": "self.version", + "guzzle/plugin-mock": "self.version", + "guzzle/plugin-oauth": "self.version" + }, + "extra": { + "branch-alias": { + "dev-master": "3.7-dev" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/AbstractConfigLoader.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/AbstractConfigLoader.php new file mode 100644 index 000000000..cd06f5722 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/AbstractConfigLoader.php @@ -0,0 +1,177 @@ + 'JSON_ERROR_NONE - No errors', + JSON_ERROR_DEPTH => 'JSON_ERROR_DEPTH - Maximum stack depth exceeded', + JSON_ERROR_STATE_MISMATCH => 'JSON_ERROR_STATE_MISMATCH - Underflow or the modes mismatch', + JSON_ERROR_CTRL_CHAR => 'JSON_ERROR_CTRL_CHAR - Unexpected control character found', + JSON_ERROR_SYNTAX => 'JSON_ERROR_SYNTAX - Syntax error, malformed JSON', + JSON_ERROR_UTF8 => 'JSON_ERROR_UTF8 - Malformed UTF-8 characters, possibly incorrectly encoded' + ); + + public function load($config, array $options = array()) + { + // Reset the array of loaded files because this is a new config + $this->loadedFiles = array(); + + if (is_string($config)) { + $config = $this->loadFile($config); + } elseif (!is_array($config)) { + throw new InvalidArgumentException('Unknown type passed to configuration loader: ' . gettype($config)); + } else { + $this->mergeIncludes($config); + } + + return $this->build($config, $options); + } + + /** + * Add an include alias to the loader + * + * @param string $filename Filename to alias (e.g. _foo) + * @param string $alias Actual file to use (e.g. /path/to/foo.json) + * + * @return self + */ + public function addAlias($filename, $alias) + { + $this->aliases[$filename] = $alias; + + return $this; + } + + /** + * Remove an alias from the loader + * + * @param string $alias Alias to remove + * + * @return self + */ + public function removeAlias($alias) + { + unset($this->aliases[$alias]); + + return $this; + } + + /** + * Perform the parsing of a config file and create the end result + * + * @param array $config Configuration data + * @param array $options Options to use when building + * + * @return mixed + */ + protected abstract function build($config, array $options); + + /** + * Load a configuration file (can load JSON or PHP files that return an array when included) + * + * @param string $filename File to load + * + * @return array + * @throws InvalidArgumentException + * @throws RuntimeException when the JSON cannot be parsed + */ + protected function loadFile($filename) + { + if (isset($this->aliases[$filename])) { + $filename = $this->aliases[$filename]; + } + + switch (pathinfo($filename, PATHINFO_EXTENSION)) { + case 'js': + case 'json': + $level = error_reporting(0); + $json = file_get_contents($filename); + error_reporting($level); + + if ($json === false) { + $err = error_get_last(); + throw new InvalidArgumentException("Unable to open {$filename}: " . $err['message']); + } + + $config = json_decode($json, true); + // Throw an exception if there was an error loading the file + if ($error = json_last_error()) { + $message = isset(self::$jsonErrors[$error]) ? self::$jsonErrors[$error] : 'Unknown error'; + throw new RuntimeException("Error loading JSON data from {$filename}: ({$error}) - {$message}"); + } + break; + case 'php': + if (!is_readable($filename)) { + throw new InvalidArgumentException("Unable to open {$filename} for reading"); + } + $config = require $filename; + if (!is_array($config)) { + throw new InvalidArgumentException('PHP files must return an array of configuration data'); + } + break; + default: + throw new InvalidArgumentException('Unknown file extension: ' . $filename); + } + + // Keep track of this file being loaded to prevent infinite recursion + $this->loadedFiles[$filename] = true; + + // Merge include files into the configuration array + $this->mergeIncludes($config, dirname($filename)); + + return $config; + } + + /** + * Merges in all include files + * + * @param array $config Config data that contains includes + * @param string $basePath Base path to use when a relative path is encountered + * + * @return array Returns the merged and included data + */ + protected function mergeIncludes(&$config, $basePath = null) + { + if (!empty($config['includes'])) { + foreach ($config['includes'] as &$path) { + // Account for relative paths + if ($path[0] != DIRECTORY_SEPARATOR && !isset($this->aliases[$path]) && $basePath) { + $path = "{$basePath}/{$path}"; + } + // Don't load the same files more than once + if (!isset($this->loadedFiles[$path])) { + $this->loadedFiles[$path] = true; + $config = $this->mergeData($this->loadFile($path), $config); + } + } + } + } + + /** + * Default implementation for merging two arrays of data (uses array_merge_recursive) + * + * @param array $a Original data + * @param array $b Data to merge into the original and overwrite existing values + * + * @return array + */ + protected function mergeData(array $a, array $b) + { + return array_merge_recursive($a, $b); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Builder/ServiceBuilder.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Builder/ServiceBuilder.php new file mode 100644 index 000000000..38150db4b --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Builder/ServiceBuilder.php @@ -0,0 +1,189 @@ +load($config, $globalParameters); + } + + /** + * @param array $serviceBuilderConfig Service configuration settings: + * - name: Name of the service + * - class: Client class to instantiate using a factory method + * - params: array of key value pair configuration settings for the builder + */ + public function __construct(array $serviceBuilderConfig = array()) + { + $this->builderConfig = $serviceBuilderConfig; + } + + public static function getAllEvents() + { + return array('service_builder.create_client'); + } + + public function unserialize($serialized) + { + $this->builderConfig = json_decode($serialized, true); + } + + public function serialize() + { + return json_encode($this->builderConfig); + } + + /** + * Attach a plugin to every client created by the builder + * + * @param EventSubscriberInterface $plugin Plugin to attach to each client + * + * @return self + */ + public function addGlobalPlugin(EventSubscriberInterface $plugin) + { + $this->plugins[] = $plugin; + + return $this; + } + + /** + * Get data from the service builder without triggering the building of a service + * + * @param string $name Name of the service to retrieve + * + * @return array|null + */ + public function getData($name) + { + return isset($this->builderConfig[$name]) ? $this->builderConfig[$name] : null; + } + + public function get($name, $throwAway = false) + { + if (!isset($this->builderConfig[$name])) { + + // Check to see if arbitrary data is being referenced + if (isset($this->clients[$name])) { + return $this->clients[$name]; + } + + // Check aliases and return a match if found + foreach ($this->builderConfig as $actualName => $config) { + if (isset($config['alias']) && $config['alias'] == $name) { + return $this->get($actualName, $throwAway); + } + } + throw new ServiceNotFoundException('No service is registered as ' . $name); + } + + if (!$throwAway && isset($this->clients[$name])) { + return $this->clients[$name]; + } + + $builder =& $this->builderConfig[$name]; + + // Convert references to the actual client + foreach ($builder['params'] as &$v) { + if (is_string($v) && substr($v, 0, 1) == '{' && substr($v, -1) == '}') { + $v = $this->get(trim($v, '{} ')); + } + } + + // Get the configured parameters and merge in any parameters provided for throw-away clients + $config = $builder['params']; + if (is_array($throwAway)) { + $config = $throwAway + $config; + } + + $client = $builder['class']::factory($config); + + if (!$throwAway) { + $this->clients[$name] = $client; + } + + if ($client instanceof ClientInterface) { + foreach ($this->plugins as $plugin) { + $client->addSubscriber($plugin); + } + // Dispatch an event letting listeners know a client was created + $this->dispatch('service_builder.create_client', array('client' => $client)); + } + + return $client; + } + + public function set($key, $service) + { + if (is_array($service) && isset($service['class']) && isset($service['params'])) { + $this->builderConfig[$key] = $service; + } else { + $this->clients[$key] = $service; + } + + return $this; + } + + public function offsetSet($offset, $value) + { + $this->set($offset, $value); + } + + public function offsetUnset($offset) + { + unset($this->builderConfig[$offset]); + unset($this->clients[$offset]); + } + + public function offsetExists($offset) + { + return isset($this->builderConfig[$offset]) || isset($this->clients[$offset]); + } + + public function offsetGet($offset) + { + return $this->get($offset); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Builder/ServiceBuilderInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Builder/ServiceBuilderInterface.php new file mode 100644 index 000000000..4fc310a47 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Builder/ServiceBuilderInterface.php @@ -0,0 +1,40 @@ + &$service) { + + $service['params'] = isset($service['params']) ? $service['params'] : array(); + + // Check if this client builder extends another client + if (!empty($service['extends'])) { + + // Make sure that the service it's extending has been defined + if (!isset($services[$service['extends']])) { + throw new ServiceNotFoundException( + "{$name} is trying to extend a non-existent service: {$service['extends']}" + ); + } + + $extended = &$services[$service['extends']]; + + // Use the correct class attribute + if (empty($service['class'])) { + $service['class'] = isset($extended['class']) ? $extended['class'] : ''; + } + if ($extendsParams = isset($extended['params']) ? $extended['params'] : false) { + $service['params'] = $service['params'] + $extendsParams; + } + } + + // Overwrite default values with global parameter values + if (!empty($options)) { + $service['params'] = $options + $service['params']; + } + + $service['class'] = isset($service['class']) ? $service['class'] : ''; + } + + return new $class($services); + } + + protected function mergeData(array $a, array $b) + { + $result = $b + $a; + + // Merge services using a recursive union of arrays + if (isset($a['services']) && $b['services']) { + + // Get a union of the services of the two arrays + $result['services'] = $b['services'] + $a['services']; + + // Merge each service in using a union of the two arrays + foreach ($result['services'] as $name => &$service) { + + // By default, services completely override a previously defined service unless it extends itself + if (isset($a['services'][$name]['extends']) + && isset($b['services'][$name]['extends']) + && $b['services'][$name]['extends'] == $name + ) { + $service += $a['services'][$name]; + // Use the `extends` attribute of the parent + $service['extends'] = $a['services'][$name]['extends']; + // Merge parameters using a union if both have parameters + if (isset($a['services'][$name]['params'])) { + $service['params'] += $a['services'][$name]['params']; + } + } + } + } + + return $result; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/CachingConfigLoader.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/CachingConfigLoader.php new file mode 100644 index 000000000..26f8360cc --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/CachingConfigLoader.php @@ -0,0 +1,46 @@ +loader = $loader; + $this->cache = $cache; + } + + public function load($config, array $options = array()) + { + if (!is_string($config)) { + $key = false; + } else { + $key = 'loader_' . crc32($config); + if ($result = $this->cache->fetch($key)) { + return $result; + } + } + + $result = $this->loader->load($config, $options); + if ($key) { + $this->cache->save($key, $result); + } + + return $result; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Client.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Client.php new file mode 100644 index 000000000..3e5f8e53d --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Client.php @@ -0,0 +1,297 @@ +getCommand($method, isset($args[0]) ? $args[0] : array())->getResult(); + } + + public function getCommand($name, array $args = array()) + { + // Add global client options to the command + if ($options = $this->getConfig(self::COMMAND_PARAMS)) { + $args += $options; + } + + if (!($command = $this->getCommandFactory()->factory($name, $args))) { + throw new InvalidArgumentException("Command was not found matching {$name}"); + } + + $command->setClient($this); + $this->dispatch('client.command.create', array('client' => $this, 'command' => $command)); + + return $command; + } + + /** + * Set the command factory used to create commands by name + * + * @param CommandFactoryInterface $factory Command factory + * + * @return self + */ + public function setCommandFactory(CommandFactoryInterface $factory) + { + $this->commandFactory = $factory; + + return $this; + } + + /** + * Set the resource iterator factory associated with the client + * + * @param ResourceIteratorFactoryInterface $factory Resource iterator factory + * + * @return self + */ + public function setResourceIteratorFactory(ResourceIteratorFactoryInterface $factory) + { + $this->resourceIteratorFactory = $factory; + + return $this; + } + + public function getIterator($command, array $commandOptions = null, array $iteratorOptions = array()) + { + if (!($command instanceof CommandInterface)) { + $command = $this->getCommand($command, $commandOptions ?: array()); + } + + return $this->getResourceIteratorFactory()->build($command, $iteratorOptions); + } + + public function execute($command) + { + if ($command instanceof CommandInterface) { + $this->send($this->prepareCommand($command)); + $this->dispatch('command.after_send', array('command' => $command)); + return $command->getResult(); + } elseif (is_array($command) || $command instanceof \Traversable) { + return $this->executeMultiple($command); + } else { + throw new InvalidArgumentException('Command must be a command or array of commands'); + } + } + + public function setDescription(ServiceDescriptionInterface $service) + { + $this->serviceDescription = $service; + + if ($this->getCommandFactory() && $this->getCommandFactory() instanceof CompositeFactory) { + $this->commandFactory->add(new Command\Factory\ServiceDescriptionFactory($service)); + } + + // If a baseUrl was set on the description, then update the client + if ($baseUrl = $service->getBaseUrl()) { + $this->setBaseUrl($baseUrl); + } + + return $this; + } + + public function getDescription() + { + return $this->serviceDescription; + } + + /** + * Set the inflector used with the client + * + * @param InflectorInterface $inflector Inflection object + * + * @return self + */ + public function setInflector(InflectorInterface $inflector) + { + $this->inflector = $inflector; + + return $this; + } + + /** + * Get the inflector used with the client + * + * @return self + */ + public function getInflector() + { + if (!$this->inflector) { + $this->inflector = Inflector::getDefault(); + } + + return $this->inflector; + } + + /** + * Prepare a command for sending and get the RequestInterface object created by the command + * + * @param CommandInterface $command Command to prepare + * + * @return RequestInterface + */ + protected function prepareCommand(CommandInterface $command) + { + // Set the client and prepare the command + $request = $command->setClient($this)->prepare(); + // Set the state to new if the command was previously executed + $request->setState(RequestInterface::STATE_NEW); + $this->dispatch('command.before_send', array('command' => $command)); + + return $request; + } + + /** + * Execute multiple commands in parallel + * + * @param array|Traversable $commands Array of CommandInterface objects to execute + * + * @return array Returns an array of the executed commands + * @throws Exception\CommandTransferException + */ + protected function executeMultiple($commands) + { + $requests = array(); + $commandRequests = new \SplObjectStorage(); + + foreach ($commands as $command) { + $request = $this->prepareCommand($command); + $commandRequests[$request] = $command; + $requests[] = $request; + } + + try { + $this->send($requests); + foreach ($commands as $command) { + $this->dispatch('command.after_send', array('command' => $command)); + } + return $commands; + } catch (MultiTransferException $failureException) { + // Throw a CommandTransferException using the successful and failed commands + $e = CommandTransferException::fromMultiTransferException($failureException); + + // Remove failed requests from the successful requests array and add to the failures array + foreach ($failureException->getFailedRequests() as $request) { + if (isset($commandRequests[$request])) { + $e->addFailedCommand($commandRequests[$request]); + unset($commandRequests[$request]); + } + } + + // Always emit the command after_send events for successful commands + foreach ($commandRequests as $success) { + $e->addSuccessfulCommand($commandRequests[$success]); + $this->dispatch('command.after_send', array('command' => $commandRequests[$success])); + } + + throw $e; + } + } + + protected function getResourceIteratorFactory() + { + if (!$this->resourceIteratorFactory) { + // Build the default resource iterator factory if one is not set + $clientClass = get_class($this); + $prefix = substr($clientClass, 0, strrpos($clientClass, '\\')); + $this->resourceIteratorFactory = new ResourceIteratorClassFactory(array( + "{$prefix}\\Iterator", + "{$prefix}\\Model" + )); + } + + return $this->resourceIteratorFactory; + } + + /** + * Get the command factory associated with the client + * + * @return CommandFactoryInterface + */ + protected function getCommandFactory() + { + if (!$this->commandFactory) { + $this->commandFactory = CompositeFactory::getDefaultChain($this); + } + + return $this->commandFactory; + } + + /** + * @deprecated + * @codeCoverageIgnore + */ + public function enableMagicMethods($isEnabled) + { + Version::warn(__METHOD__ . ' is deprecated'); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/ClientInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/ClientInterface.php new file mode 100644 index 000000000..814154f00 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/ClientInterface.php @@ -0,0 +1,68 @@ +operation = $operation ?: $this->createOperation(); + foreach ($this->operation->getParams() as $name => $arg) { + $currentValue = $this[$name]; + $configValue = $arg->getValue($currentValue); + // If default or static values are set, then this should always be updated on the config object + if ($currentValue !== $configValue) { + $this[$name] = $configValue; + } + } + + $headers = $this[self::HEADERS_OPTION]; + if (!$headers instanceof Collection) { + $this[self::HEADERS_OPTION] = new Collection((array) $headers); + } + + // You can set a command.on_complete option in your parameters to set an onComplete callback + if ($onComplete = $this['command.on_complete']) { + unset($this['command.on_complete']); + $this->setOnComplete($onComplete); + } + + // Set the hidden additional parameters + if (!$this[self::HIDDEN_PARAMS]) { + $this[self::HIDDEN_PARAMS] = array( + self::HEADERS_OPTION, + self::RESPONSE_PROCESSING, + self::HIDDEN_PARAMS, + self::REQUEST_OPTIONS + ); + } + + $this->init(); + } + + /** + * Custom clone behavior + */ + public function __clone() + { + $this->request = null; + $this->result = null; + } + + /** + * Execute the command in the same manner as calling a function + * + * @return mixed Returns the result of {@see AbstractCommand::execute} + */ + public function __invoke() + { + return $this->execute(); + } + + public function getName() + { + return $this->operation->getName(); + } + + /** + * Get the API command information about the command + * + * @return OperationInterface + */ + public function getOperation() + { + return $this->operation; + } + + public function setOnComplete($callable) + { + if (!is_callable($callable)) { + throw new InvalidArgumentException('The onComplete function must be callable'); + } + + $this->onComplete = $callable; + + return $this; + } + + public function execute() + { + if (!$this->client) { + throw new CommandException('A client must be associated with the command before it can be executed.'); + } + + return $this->client->execute($this); + } + + public function getClient() + { + return $this->client; + } + + public function setClient(ClientInterface $client) + { + $this->client = $client; + + return $this; + } + + public function getRequest() + { + if (!$this->request) { + throw new CommandException('The command must be prepared before retrieving the request'); + } + + return $this->request; + } + + public function getResponse() + { + if (!$this->isExecuted()) { + $this->execute(); + } + + return $this->request->getResponse(); + } + + public function getResult() + { + if (!$this->isExecuted()) { + $this->execute(); + } + + if (null === $this->result) { + $this->process(); + // Call the onComplete method if one is set + if ($this->onComplete) { + call_user_func($this->onComplete, $this); + } + } + + return $this->result; + } + + public function setResult($result) + { + $this->result = $result; + + return $this; + } + + public function isPrepared() + { + return $this->request !== null; + } + + public function isExecuted() + { + return $this->request !== null && $this->request->getState() == 'complete'; + } + + public function prepare() + { + if (!$this->isPrepared()) { + if (!$this->client) { + throw new CommandException('A client must be associated with the command before it can be prepared.'); + } + + // If no response processing value was specified, then attempt to use the highest level of processing + if (!isset($this[self::RESPONSE_PROCESSING])) { + $this[self::RESPONSE_PROCESSING] = self::TYPE_MODEL; + } + + // Notify subscribers of the client that the command is being prepared + $this->client->dispatch('command.before_prepare', array('command' => $this)); + + // Fail on missing required arguments, and change parameters via filters + $this->validate(); + // Delegate to the subclass that implements the build method + $this->build(); + + // Add custom request headers set on the command + if ($headers = $this[self::HEADERS_OPTION]) { + foreach ($headers as $key => $value) { + $this->request->setHeader($key, $value); + } + } + + // Add any curl options to the request + if ($options = $this[Client::CURL_OPTIONS]) { + $this->request->getCurlOptions()->overwriteWith(CurlHandle::parseCurlConfig($options)); + } + + // Set a custom response body + if ($responseBody = $this[self::RESPONSE_BODY]) { + $this->request->setResponseBody($responseBody); + } + + $this->client->dispatch('command.after_prepare', array('command' => $this)); + } + + return $this->request; + } + + /** + * Set the validator used to validate and prepare command parameters and nested JSON schemas. If no validator is + * set, then the command will validate using the default {@see SchemaValidator}. + * + * @param ValidatorInterface $validator Validator used to prepare and validate properties against a JSON schema + * + * @return self + */ + public function setValidator(ValidatorInterface $validator) + { + $this->validator = $validator; + + return $this; + } + + public function getRequestHeaders() + { + return $this[self::HEADERS_OPTION]; + } + + /** + * Initialize the command (hook that can be implemented in subclasses) + */ + protected function init() {} + + /** + * Create the request object that will carry out the command + */ + abstract protected function build(); + + /** + * Hook used to create an operation for concrete commands that are not associated with a service description + * + * @return OperationInterface + */ + protected function createOperation() + { + return new Operation(array('name' => get_class($this))); + } + + /** + * Create the result of the command after the request has been completed. + * Override this method in subclasses to customize this behavior + */ + protected function process() + { + $this->result = $this[self::RESPONSE_PROCESSING] != self::TYPE_RAW + ? DefaultResponseParser::getInstance()->parse($this) + : $this->request->getResponse(); + } + + /** + * Validate and prepare the command based on the schema and rules defined by the command's Operation object + * + * @throws ValidationException when validation errors occur + */ + protected function validate() + { + // Do not perform request validation/transformation if it is disable + if ($this[self::DISABLE_VALIDATION]) { + return; + } + + $errors = array(); + $validator = $this->getValidator(); + foreach ($this->operation->getParams() as $name => $schema) { + $value = $this[$name]; + if (!$validator->validate($schema, $value)) { + $errors = array_merge($errors, $validator->getErrors()); + } elseif ($value !== $this[$name]) { + // Update the config value if it changed and no validation errors were encountered + $this->data[$name] = $value; + } + } + + // Validate additional parameters + $hidden = $this[self::HIDDEN_PARAMS]; + + if ($properties = $this->operation->getAdditionalParameters()) { + foreach ($this->toArray() as $name => $value) { + // It's only additional if it isn't defined in the schema + if (!$this->operation->hasParam($name) && !in_array($name, $hidden)) { + // Always set the name so that error messages are useful + $properties->setName($name); + if (!$validator->validate($properties, $value)) { + $errors = array_merge($errors, $validator->getErrors()); + } elseif ($value !== $this[$name]) { + $this->data[$name] = $value; + } + } + } + } + + if (!empty($errors)) { + $e = new ValidationException('Validation errors: ' . implode("\n", $errors)); + $e->setErrors($errors); + throw $e; + } + } + + /** + * Get the validator used to prepare and validate properties. If no validator has been set on the command, then + * the default {@see SchemaValidator} will be used. + * + * @return ValidatorInterface + */ + protected function getValidator() + { + if (!$this->validator) { + $this->validator = SchemaValidator::getInstance(); + } + + return $this->validator; + } + + /** + * Get array of any validation errors + * If no validator has been set then return false + */ + public function getValidationErrors() + { + if (!$this->validator) { + return false; + } + + return $this->validator->getErrors(); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/ClosureCommand.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/ClosureCommand.php new file mode 100644 index 000000000..cb6ac40ce --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/ClosureCommand.php @@ -0,0 +1,41 @@ +request = $closure($this, $this->operation); + + if (!$this->request || !$this->request instanceof RequestInterface) { + throw new UnexpectedValueException('Closure command did not return a RequestInterface object'); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/CommandInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/CommandInterface.php new file mode 100644 index 000000000..fbb61d2ff --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/CommandInterface.php @@ -0,0 +1,128 @@ +stopPropagation(); + } + + /** + * Get the created object + * + * @return mixed + */ + public function getResult() + { + return $this['result']; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/DefaultRequestSerializer.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/DefaultRequestSerializer.php new file mode 100644 index 000000000..2dc4acd37 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/DefaultRequestSerializer.php @@ -0,0 +1,169 @@ +factory = $factory; + } + + /** + * Add a location visitor to the serializer + * + * @param string $location Location to associate with the visitor + * @param RequestVisitorInterface $visitor Visitor to attach + * + * @return self + */ + public function addVisitor($location, RequestVisitorInterface $visitor) + { + $this->factory->addRequestVisitor($location, $visitor); + + return $this; + } + + public function prepare(CommandInterface $command) + { + $request = $this->createRequest($command); + // Keep an array of visitors found in the operation + $foundVisitors = array(); + $operation = $command->getOperation(); + + // Add arguments to the request using the location attribute + foreach ($operation->getParams() as $name => $arg) { + /** @var $arg \Guzzle\Service\Description\Parameter */ + $location = $arg->getLocation(); + // Skip 'uri' locations because they've already been processed + if ($location && $location != 'uri') { + // Instantiate visitors as they are detected in the properties + if (!isset($foundVisitors[$location])) { + $foundVisitors[$location] = $this->factory->getRequestVisitor($location); + } + // Ensure that a value has been set for this parameter + $value = $command[$name]; + if ($value !== null) { + // Apply the parameter value with the location visitor + $foundVisitors[$location]->visit($command, $request, $arg, $value); + } + } + } + + // Serialize additional parameters + if ($additional = $operation->getAdditionalParameters()) { + if ($visitor = $this->prepareAdditionalParameters($operation, $command, $request, $additional)) { + $foundVisitors[$additional->getLocation()] = $visitor; + } + } + + // Call the after method on each visitor found in the operation + foreach ($foundVisitors as $visitor) { + $visitor->after($command, $request); + } + + return $request; + } + + /** + * Serialize additional parameters + * + * @param OperationInterface $operation Operation that owns the command + * @param CommandInterface $command Command to prepare + * @param RequestInterface $request Request to serialize + * @param Parameter $additional Additional parameters + * + * @return null|RequestVisitorInterface + */ + protected function prepareAdditionalParameters( + OperationInterface $operation, + CommandInterface $command, + RequestInterface $request, + Parameter $additional + ) { + if (!($location = $additional->getLocation())) { + return; + } + + $visitor = $this->factory->getRequestVisitor($location); + $hidden = $command[$command::HIDDEN_PARAMS]; + + foreach ($command->toArray() as $key => $value) { + // Ignore values that are null or built-in command options + if ($value !== null + && !in_array($key, $hidden) + && !$operation->hasParam($key) + ) { + $additional->setName($key); + $visitor->visit($command, $request, $additional, $value); + } + } + + return $visitor; + } + + /** + * Create a request for the command and operation + * + * @param CommandInterface $command Command to create a request for + * + * @return RequestInterface + */ + protected function createRequest(CommandInterface $command) + { + $operation = $command->getOperation(); + $client = $command->getClient(); + $options = $command[AbstractCommand::REQUEST_OPTIONS] ?: array(); + + // If the command does not specify a template, then assume the base URL of the client + if (!($uri = $operation->getUri())) { + return $client->createRequest($operation->getHttpMethod(), $client->getBaseUrl(), null, null, $options); + } + + // Get the path values and use the client config settings + $variables = array(); + foreach ($operation->getParams() as $name => $arg) { + if ($arg->getLocation() == 'uri') { + if (isset($command[$name])) { + $variables[$name] = $arg->filter($command[$name]); + if (!is_array($variables[$name])) { + $variables[$name] = (string) $variables[$name]; + } + } + } + } + + return $client->createRequest($operation->getHttpMethod(), array($uri, $variables), null, null, $options); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/DefaultResponseParser.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/DefaultResponseParser.php new file mode 100644 index 000000000..4fe380376 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/DefaultResponseParser.php @@ -0,0 +1,55 @@ +getRequest()->getResponse(); + + // Account for hard coded content-type values specified in service descriptions + if ($contentType = $command['command.expects']) { + $response->setHeader('Content-Type', $contentType); + } else { + $contentType = (string) $response->getHeader('Content-Type'); + } + + return $this->handleParsing($command, $response, $contentType); + } + + protected function handleParsing(CommandInterface $command, Response $response, $contentType) + { + $result = $response; + if ($result->getBody()) { + if (stripos($contentType, 'json') !== false) { + $result = $result->json(); + } elseif (stripos($contentType, 'xml') !== false) { + $result = $result->xml(); + } + } + + return $result; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/AliasFactory.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/AliasFactory.php new file mode 100644 index 000000000..1c5ce0741 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/AliasFactory.php @@ -0,0 +1,39 @@ +client = $client; + $this->aliases = $aliases; + } + + public function factory($name, array $args = array()) + { + if (isset($this->aliases[$name])) { + try { + return $this->client->getCommand($this->aliases[$name], $args); + } catch (InvalidArgumentException $e) { + return null; + } + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/CompositeFactory.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/CompositeFactory.php new file mode 100644 index 000000000..8c46983d6 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/CompositeFactory.php @@ -0,0 +1,154 @@ +getDescription()) { + $factories[] = new ServiceDescriptionFactory($description); + } + $factories[] = new ConcreteClassFactory($client); + + return new self($factories); + } + + /** + * @param array $factories Array of command factories + */ + public function __construct(array $factories = array()) + { + $this->factories = $factories; + } + + /** + * Add a command factory to the chain + * + * @param FactoryInterface $factory Factory to add + * @param string|FactoryInterface $before Insert the new command factory before a command factory class or object + * matching a class name. + * @return CompositeFactory + */ + public function add(FactoryInterface $factory, $before = null) + { + $pos = null; + + if ($before) { + foreach ($this->factories as $i => $f) { + if ($before instanceof FactoryInterface) { + if ($f === $before) { + $pos = $i; + break; + } + } elseif (is_string($before)) { + if ($f instanceof $before) { + $pos = $i; + break; + } + } + } + } + + if ($pos === null) { + $this->factories[] = $factory; + } else { + array_splice($this->factories, $i, 0, array($factory)); + } + + return $this; + } + + /** + * Check if the chain contains a specific command factory + * + * @param FactoryInterface|string $factory Factory to check + * + * @return bool + */ + public function has($factory) + { + return (bool) $this->find($factory); + } + + /** + * Remove a specific command factory from the chain + * + * @param string|FactoryInterface $factory Factory to remove by name or instance + * + * @return CompositeFactory + */ + public function remove($factory = null) + { + if (!($factory instanceof FactoryInterface)) { + $factory = $this->find($factory); + } + + $this->factories = array_values(array_filter($this->factories, function($f) use ($factory) { + return $f !== $factory; + })); + + return $this; + } + + /** + * Get a command factory by class name + * + * @param string|FactoryInterface $factory Command factory class or instance + * + * @return null|FactoryInterface + */ + public function find($factory) + { + foreach ($this->factories as $f) { + if ($factory === $f || (is_string($factory) && $f instanceof $factory)) { + return $f; + } + } + } + + /** + * Create a command using the associated command factories + * + * @param string $name Name of the command + * @param array $args Command arguments + * + * @return CommandInterface + */ + public function factory($name, array $args = array()) + { + foreach ($this->factories as $factory) { + $command = $factory->factory($name, $args); + if ($command) { + return $command; + } + } + } + + public function count() + { + return count($this->factories); + } + + public function getIterator() + { + return new \ArrayIterator($this->factories); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/ConcreteClassFactory.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/ConcreteClassFactory.php new file mode 100644 index 000000000..0e93deaa0 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/ConcreteClassFactory.php @@ -0,0 +1,47 @@ +client = $client; + $this->inflector = $inflector ?: Inflector::getDefault(); + } + + public function factory($name, array $args = array()) + { + // Determine the class to instantiate based on the namespace of the current client and the default directory + $prefix = $this->client->getConfig('command.prefix'); + if (!$prefix) { + // The prefix can be specified in a factory method and is cached + $prefix = implode('\\', array_slice(explode('\\', get_class($this->client)), 0, -1)) . '\\Command\\'; + $this->client->getConfig()->set('command.prefix', $prefix); + } + + $class = $prefix . str_replace(' ', '\\', ucwords(str_replace('.', ' ', $this->inflector->camel($name)))); + + // Create the concrete command if it exists + if (class_exists($class)) { + return new $class($args); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/FactoryInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/FactoryInterface.php new file mode 100644 index 000000000..35c299d9d --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/FactoryInterface.php @@ -0,0 +1,21 @@ +map = $map; + } + + public function factory($name, array $args = array()) + { + if (isset($this->map[$name])) { + $class = $this->map[$name]; + + return new $class($args); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/ServiceDescriptionFactory.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/ServiceDescriptionFactory.php new file mode 100644 index 000000000..b943a5b50 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/Factory/ServiceDescriptionFactory.php @@ -0,0 +1,71 @@ +setServiceDescription($description); + $this->inflector = $inflector; + } + + /** + * Change the service description used with the factory + * + * @param ServiceDescriptionInterface $description Service description to use + * + * @return FactoryInterface + */ + public function setServiceDescription(ServiceDescriptionInterface $description) + { + $this->description = $description; + + return $this; + } + + /** + * Returns the service description + * + * @return ServiceDescriptionInterface + */ + public function getServiceDescription() + { + return $this->description; + } + + public function factory($name, array $args = array()) + { + $command = $this->description->getOperation($name); + + // If a command wasn't found, then try to uppercase the first letter and try again + if (!$command) { + $command = $this->description->getOperation(ucfirst($name)); + // If an inflector was passed, then attempt to get the command using snake_case inflection + if (!$command && $this->inflector) { + $command = $this->description->getOperation($this->inflector->snake($name)); + } + } + + if ($command) { + $class = $command->getClass(); + return new $class($args, $command, $this->description); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/AbstractRequestVisitor.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/AbstractRequestVisitor.php new file mode 100644 index 000000000..adcfca1ba --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/AbstractRequestVisitor.php @@ -0,0 +1,69 @@ +resolveRecursively($value, $param) + : $param->filter($value); + } + + /** + * Map nested parameters into the location_key based parameters + * + * @param array $value Value to map + * @param Parameter $param Parameter that holds information about the current key + * + * @return array Returns the mapped array + */ + protected function resolveRecursively(array $value, Parameter $param) + { + foreach ($value as $name => &$v) { + switch ($param->getType()) { + case 'object': + if ($subParam = $param->getProperty($name)) { + $key = $subParam->getWireName(); + $value[$key] = $this->prepareValue($v, $subParam); + if ($name != $key) { + unset($value[$name]); + } + } elseif ($param->getAdditionalProperties() instanceof Parameter) { + $v = $this->prepareValue($v, $param->getAdditionalProperties()); + } + break; + case 'array': + if ($items = $param->getItems()) { + $v = $this->prepareValue($v, $items); + } + break; + } + } + + return $param->filter($value); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/BodyVisitor.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/BodyVisitor.php new file mode 100644 index 000000000..168d7806f --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/BodyVisitor.php @@ -0,0 +1,58 @@ +filter($value); + $entityBody = EntityBody::factory($value); + $request->setBody($entityBody); + $this->addExpectHeader($request, $entityBody, $param->getData('expect_header')); + // Add the Content-Encoding header if one is set on the EntityBody + if ($encoding = $entityBody->getContentEncoding()) { + $request->setHeader('Content-Encoding', $encoding); + } + } + + /** + * Add the appropriate expect header to a request + * + * @param EntityEnclosingRequestInterface $request Request to update + * @param EntityBodyInterface $body Entity body of the request + * @param string|int $expect Expect header setting + */ + protected function addExpectHeader(EntityEnclosingRequestInterface $request, EntityBodyInterface $body, $expect) + { + // Allow the `expect` data parameter to be set to remove the Expect header from the request + if ($expect === false) { + $request->removeHeader('Expect'); + } elseif ($expect !== true) { + // Default to using a MB as the point in which to start using the expect header + $expect = $expect ?: 1048576; + // If the expect_header value is numeric then only add if the size is greater than the cutoff + if (is_numeric($expect) && $body->getSize()) { + if ($body->getSize() < $expect) { + $request->removeHeader('Expect'); + } else { + $request->setHeader('Expect', '100-Continue'); + } + } + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/HeaderVisitor.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/HeaderVisitor.php new file mode 100644 index 000000000..2a537542c --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/HeaderVisitor.php @@ -0,0 +1,44 @@ +filter($value); + if ($param->getType() == 'object' && $param->getAdditionalProperties() instanceof Parameter) { + $this->addPrefixedHeaders($request, $param, $value); + } else { + $request->setHeader($param->getWireName(), $value); + } + } + + /** + * Add a prefixed array of headers to the request + * + * @param RequestInterface $request Request to update + * @param Parameter $param Parameter object + * @param array $value Header array to add + * + * @throws InvalidArgumentException + */ + protected function addPrefixedHeaders(RequestInterface $request, Parameter $param, $value) + { + if (!is_array($value)) { + throw new InvalidArgumentException('An array of mapped headers expected, but received a single value'); + } + $prefix = $param->getSentAs(); + foreach ($value as $headerName => $headerValue) { + $request->setHeader($prefix . $headerName, $headerValue); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/JsonVisitor.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/JsonVisitor.php new file mode 100644 index 000000000..757e1c520 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/JsonVisitor.php @@ -0,0 +1,63 @@ +data = new \SplObjectStorage(); + } + + /** + * Set the Content-Type header to add to the request if JSON is added to the body. This visitor does not add a + * Content-Type header unless you specify one here. + * + * @param string $header Header to set when JSON is added (e.g. application/json) + * + * @return self + */ + public function setContentTypeHeader($header = 'application/json') + { + $this->jsonContentType = $header; + + return $this; + } + + public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, $value) + { + if (isset($this->data[$command])) { + $json = $this->data[$command]; + } else { + $json = array(); + } + $json[$param->getWireName()] = $this->prepareValue($value, $param); + $this->data[$command] = $json; + } + + public function after(CommandInterface $command, RequestInterface $request) + { + if (isset($this->data[$command])) { + // Don't overwrite the Content-Type if one is set + if ($this->jsonContentType && !$request->hasHeader('Content-Type')) { + $request->setHeader('Content-Type', $this->jsonContentType); + } + + $request->setBody(json_encode($this->data[$command])); + unset($this->data[$command]); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/PostFieldVisitor.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/PostFieldVisitor.php new file mode 100644 index 000000000..975850b74 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/PostFieldVisitor.php @@ -0,0 +1,18 @@ +setPostField($param->getWireName(), $this->prepareValue($value, $param)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/PostFileVisitor.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/PostFileVisitor.php new file mode 100644 index 000000000..0853ebe62 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/PostFileVisitor.php @@ -0,0 +1,24 @@ +filter($value); + if ($value instanceof PostFileInterface) { + $request->addPostFile($value); + } else { + $request->addPostFile($param->getWireName(), $value); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/QueryVisitor.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/QueryVisitor.php new file mode 100644 index 000000000..315877aa0 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/QueryVisitor.php @@ -0,0 +1,18 @@ +getQuery()->set($param->getWireName(), $this->prepareValue($value, $param)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/RequestVisitorInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/RequestVisitorInterface.php new file mode 100644 index 000000000..14e0b2d2b --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/RequestVisitorInterface.php @@ -0,0 +1,31 @@ +setResponseBody($value); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/XmlVisitor.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/XmlVisitor.php new file mode 100644 index 000000000..5b7148787 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Request/XmlVisitor.php @@ -0,0 +1,252 @@ +data = new \SplObjectStorage(); + } + + /** + * Change the content-type header that is added when XML is found + * + * @param string $header Header to set when XML is found + * + * @return self + */ + public function setContentTypeHeader($header) + { + $this->contentType = $header; + + return $this; + } + + public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, $value) + { + $xml = isset($this->data[$command]) + ? $this->data[$command] + : $this->createRootElement($param->getParent()); + $this->addXml($xml, $param, $value); + + $this->data[$command] = $xml; + } + + public function after(CommandInterface $command, RequestInterface $request) + { + $xml = null; + + // If data was found that needs to be serialized, then do so + if (isset($this->data[$command])) { + $xml = $this->finishDocument($this->data[$command]); + unset($this->data[$command]); + } else { + // Check if XML should always be sent for the command + $operation = $command->getOperation(); + if ($operation->getData('xmlAllowEmpty')) { + $xmlWriter = $this->createRootElement($operation); + $xml = $this->finishDocument($xmlWriter); + } + } + + if ($xml) { + // Don't overwrite the Content-Type if one is set + if ($this->contentType && !$request->hasHeader('Content-Type')) { + $request->setHeader('Content-Type', $this->contentType); + } + $request->setBody($xml); + } + } + + /** + * Create the root XML element to use with a request + * + * @param Operation $operation Operation object + * + * @return \XMLWriter + */ + protected function createRootElement(Operation $operation) + { + static $defaultRoot = array('name' => 'Request'); + // If no root element was specified, then just wrap the XML in 'Request' + $root = $operation->getData('xmlRoot') ?: $defaultRoot; + // Allow the XML declaration to be customized with xmlEncoding + $encoding = $operation->getData('xmlEncoding'); + + $xmlWriter = $this->startDocument($encoding); + + $xmlWriter->startElement($root['name']); + // Create the wrapping element with no namespaces if no namespaces were present + if (!empty($root['namespaces'])) { + // Create the wrapping element with an array of one or more namespaces + foreach ((array) $root['namespaces'] as $prefix => $uri) { + $nsLabel = 'xmlns'; + if (!is_numeric($prefix)) { + $nsLabel .= ':'.$prefix; + } + $xmlWriter->writeAttribute($nsLabel, $uri); + } + } + return $xmlWriter; + } + + /** + * Recursively build the XML body + * + * @param \XMLWriter $xmlWriter XML to modify + * @param Parameter $param API Parameter + * @param mixed $value Value to add + */ + protected function addXml(\XMLWriter $xmlWriter, Parameter $param, $value) + { + if ($value === null) { + return; + } + + $value = $param->filter($value); + $type = $param->getType(); + $name = $param->getWireName(); + $prefix = null; + $namespace = $param->getData('xmlNamespace'); + if (false !== strpos($name, ':')) { + list($prefix, $name) = explode(':', $name, 2); + } + + if ($type == 'object' || $type == 'array') { + if (!$param->getData('xmlFlattened')) { + $xmlWriter->startElementNS(null, $name, $namespace); + } + if ($param->getType() == 'array') { + $this->addXmlArray($xmlWriter, $param, $value); + } elseif ($param->getType() == 'object') { + $this->addXmlObject($xmlWriter, $param, $value); + } + if (!$param->getData('xmlFlattened')) { + $xmlWriter->endElement(); + } + return; + } + if ($param->getData('xmlAttribute')) { + $this->writeAttribute($xmlWriter, $prefix, $name, $namespace, $value); + } else { + $this->writeElement($xmlWriter, $prefix, $name, $namespace, $value); + } + } + + /** + * Write an attribute with namespace if used + * + * @param \XMLWriter $xmlWriter XMLWriter instance + * @param string $prefix Namespace prefix if any + * @param string $name Attribute name + * @param string $namespace The uri of the namespace + * @param string $value The attribute content + */ + protected function writeAttribute($xmlWriter, $prefix, $name, $namespace, $value) + { + if (empty($namespace)) { + $xmlWriter->writeAttribute($name, $value); + } else { + $xmlWriter->writeAttributeNS($prefix, $name, $namespace, $value); + } + } + + /** + * Write an element with namespace if used + * + * @param \XMLWriter $xmlWriter XML writer resource + * @param string $prefix Namespace prefix if any + * @param string $name Element name + * @param string $namespace The uri of the namespace + * @param string $value The element content + */ + protected function writeElement(\XMLWriter $xmlWriter, $prefix, $name, $namespace, $value) + { + $xmlWriter->startElementNS($prefix, $name, $namespace); + if (strpbrk($value, '<>&')) { + $xmlWriter->writeCData($value); + } else { + $xmlWriter->writeRaw($value); + } + $xmlWriter->endElement(); + } + + /** + * Create a new xml writer and start a document + * + * @param string $encoding document encoding + * + * @return \XMLWriter the writer resource + */ + protected function startDocument($encoding) + { + $xmlWriter = new \XMLWriter(); + $xmlWriter->openMemory(); + $xmlWriter->startDocument('1.0', $encoding); + + return $xmlWriter; + } + + /** + * End the document and return the output + * + * @param \XMLWriter $xmlWriter + * + * @return \string the writer resource + */ + protected function finishDocument($xmlWriter) + { + $xmlWriter->endDocument(); + + return $xmlWriter->outputMemory(); + } + + /** + * Add an array to the XML + */ + protected function addXmlArray(\XMLWriter $xmlWriter, Parameter $param, &$value) + { + if ($items = $param->getItems()) { + foreach ($value as $v) { + $this->addXml($xmlWriter, $items, $v); + } + } + } + + /** + * Add an object to the XML + */ + protected function addXmlObject(\XMLWriter $xmlWriter, Parameter $param, &$value) + { + $noAttributes = array(); + // add values which have attributes + foreach ($value as $name => $v) { + if ($property = $param->getProperty($name)) { + if ($property->getData('xmlAttribute')) { + $this->addXml($xmlWriter, $property, $v); + } else { + $noAttributes[] = array('value' => $v, 'property' => $property); + } + } + } + // now add values with no attributes + foreach ($noAttributes as $element) { + $this->addXml($xmlWriter, $element['property'], $element['value']); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/AbstractResponseVisitor.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/AbstractResponseVisitor.php new file mode 100644 index 000000000..d87eeb945 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/AbstractResponseVisitor.php @@ -0,0 +1,26 @@ +getName()] = $param->filter($response->getBody()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/HeaderVisitor.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/HeaderVisitor.php new file mode 100644 index 000000000..0f8737cbd --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/HeaderVisitor.php @@ -0,0 +1,50 @@ +getType() == 'object' && $param->getAdditionalProperties() instanceof Parameter) { + $this->processPrefixedHeaders($response, $param, $value); + } else { + $value[$param->getName()] = $param->filter((string) $response->getHeader($param->getWireName())); + } + } + + /** + * Process a prefixed header array + * + * @param Response $response Response that contains the headers + * @param Parameter $param Parameter object + * @param array $value Value response array to modify + */ + protected function processPrefixedHeaders(Response $response, Parameter $param, &$value) + { + // Grab prefixed headers that should be placed into an array with the prefix stripped + if ($prefix = $param->getSentAs()) { + $container = $param->getName(); + $len = strlen($prefix); + // Find all matching headers and place them into the containing element + foreach ($response->getHeaders()->toArray() as $key => $header) { + if (stripos($key, $prefix) === 0) { + // Account for multi-value headers + $value[$container][substr($key, $len)] = count($header) == 1 ? end($header) : $header; + } + } + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/JsonVisitor.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/JsonVisitor.php new file mode 100644 index 000000000..a609ebd8c --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/JsonVisitor.php @@ -0,0 +1,93 @@ +getResponse()->json(); + } + + public function visit( + CommandInterface $command, + Response $response, + Parameter $param, + &$value, + $context = null + ) { + $name = $param->getName(); + $key = $param->getWireName(); + if (isset($value[$key])) { + $this->recursiveProcess($param, $value[$key]); + if ($key != $name) { + $value[$name] = $value[$key]; + unset($value[$key]); + } + } + } + + /** + * Recursively process a parameter while applying filters + * + * @param Parameter $param API parameter being validated + * @param mixed $value Value to validate and process. The value may change during this process. + */ + protected function recursiveProcess(Parameter $param, &$value) + { + if ($value === null) { + return; + } + + if (is_array($value)) { + $type = $param->getType(); + if ($type == 'array') { + foreach ($value as &$item) { + $this->recursiveProcess($param->getItems(), $item); + } + } elseif ($type == 'object' && !isset($value[0])) { + // On the above line, we ensure that the array is associative and not numerically indexed + $knownProperties = array(); + if ($properties = $param->getProperties()) { + foreach ($properties as $property) { + $name = $property->getName(); + $key = $property->getWireName(); + $knownProperties[$name] = 1; + if (isset($value[$key])) { + $this->recursiveProcess($property, $value[$key]); + if ($key != $name) { + $value[$name] = $value[$key]; + unset($value[$key]); + } + } + } + } + + // Remove any unknown and potentially unsafe properties + if ($param->getAdditionalProperties() === false) { + $value = array_intersect_key($value, $knownProperties); + } elseif (($additional = $param->getAdditionalProperties()) !== true) { + // Validate and filter additional properties + foreach ($value as &$v) { + $this->recursiveProcess($additional, $v); + } + } + } + } + + $value = $param->filter($value); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/ReasonPhraseVisitor.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/ReasonPhraseVisitor.php new file mode 100644 index 000000000..1b10ebce7 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/ReasonPhraseVisitor.php @@ -0,0 +1,23 @@ +getName()] = $response->getReasonPhrase(); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/ResponseVisitorInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/ResponseVisitorInterface.php new file mode 100644 index 000000000..033f40c3f --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/ResponseVisitorInterface.php @@ -0,0 +1,46 @@ +getName()] = $response->getStatusCode(); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/XmlVisitor.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/XmlVisitor.php new file mode 100644 index 000000000..bb7124be7 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/Response/XmlVisitor.php @@ -0,0 +1,151 @@ +getResponse()->xml()), true); + } + + public function visit( + CommandInterface $command, + Response $response, + Parameter $param, + &$value, + $context = null + ) { + $sentAs = $param->getWireName(); + $name = $param->getName(); + if (isset($value[$sentAs])) { + $this->recursiveProcess($param, $value[$sentAs]); + if ($name != $sentAs) { + $value[$name] = $value[$sentAs]; + unset($value[$sentAs]); + } + } + } + + /** + * Recursively process a parameter while applying filters + * + * @param Parameter $param API parameter being processed + * @param mixed $value Value to validate and process. The value may change during this process. + */ + protected function recursiveProcess(Parameter $param, &$value) + { + $type = $param->getType(); + + if (!is_array($value)) { + if ($type == 'array') { + // Cast to an array if the value was a string, but should be an array + $this->recursiveProcess($param->getItems(), $value); + $value = array($value); + } + } elseif ($type == 'object') { + $this->processObject($param, $value); + } elseif ($type == 'array') { + $this->processArray($param, $value); + } elseif ($type == 'string' && gettype($value) == 'array') { + $value = ''; + } + + if ($value !== null) { + $value = $param->filter($value); + } + } + + /** + * Process an array + * + * @param Parameter $param API parameter being parsed + * @param mixed $value Value to process + */ + protected function processArray(Parameter $param, &$value) + { + // Convert the node if it was meant to be an array + if (!isset($value[0])) { + // Collections fo nodes are sometimes wrapped in an additional array. For example: + // 12 should become: + // array('Items' => array(array('a' => 1), array('a' => 2)) + // Some nodes are not wrapped. For example: 12 + // should become array('Foo' => array(array('a' => 1), array('a' => 2)) + if ($param->getItems() && isset($value[$param->getItems()->getWireName()])) { + // Account for the case of a collection wrapping wrapped nodes: Items => Item[] + $value = $value[$param->getItems()->getWireName()]; + // If the wrapped node only had one value, then make it an array of nodes + if (!isset($value[0]) || !is_array($value)) { + $value = array($value); + } + } elseif (!empty($value)) { + // Account for repeated nodes that must be an array: Foo => Baz, Foo => Baz, but only if the + // value is set and not empty + $value = array($value); + } + } + + foreach ($value as &$item) { + $this->recursiveProcess($param->getItems(), $item); + } + } + + /** + * Process an object + * + * @param Parameter $param API parameter being parsed + * @param mixed $value Value to process + */ + protected function processObject(Parameter $param, &$value) + { + // Ensure that the array is associative and not numerically indexed + if (!isset($value[0]) && ($properties = $param->getProperties())) { + $knownProperties = array(); + foreach ($properties as $property) { + $name = $property->getName(); + $sentAs = $property->getWireName(); + $knownProperties[$name] = 1; + if ($property->getData('xmlAttribute')) { + $this->processXmlAttribute($property, $value); + } elseif (isset($value[$sentAs])) { + $this->recursiveProcess($property, $value[$sentAs]); + if ($name != $sentAs) { + $value[$name] = $value[$sentAs]; + unset($value[$sentAs]); + } + } + } + + // Remove any unknown and potentially unsafe properties + if ($param->getAdditionalProperties() === false) { + $value = array_intersect_key($value, $knownProperties); + } + } + } + + /** + * Process an XML attribute property + * + * @param Parameter $property Property to process + * @param array $value Value to process and update + */ + protected function processXmlAttribute(Parameter $property, array &$value) + { + $sentAs = $property->getWireName(); + if (isset($value['@attributes'][$sentAs])) { + $value[$property->getName()] = $value['@attributes'][$sentAs]; + unset($value['@attributes'][$sentAs]); + if (empty($value['@attributes'])) { + unset($value['@attributes']); + } + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/VisitorFlyweight.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/VisitorFlyweight.php new file mode 100644 index 000000000..74cb62813 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/LocationVisitor/VisitorFlyweight.php @@ -0,0 +1,138 @@ + 'Guzzle\Service\Command\LocationVisitor\Request\BodyVisitor', + 'request.header' => 'Guzzle\Service\Command\LocationVisitor\Request\HeaderVisitor', + 'request.json' => 'Guzzle\Service\Command\LocationVisitor\Request\JsonVisitor', + 'request.postField' => 'Guzzle\Service\Command\LocationVisitor\Request\PostFieldVisitor', + 'request.postFile' => 'Guzzle\Service\Command\LocationVisitor\Request\PostFileVisitor', + 'request.query' => 'Guzzle\Service\Command\LocationVisitor\Request\QueryVisitor', + 'request.response_body' => 'Guzzle\Service\Command\LocationVisitor\Request\ResponseBodyVisitor', + 'request.responseBody' => 'Guzzle\Service\Command\LocationVisitor\Request\ResponseBodyVisitor', + 'request.xml' => 'Guzzle\Service\Command\LocationVisitor\Request\XmlVisitor', + 'response.body' => 'Guzzle\Service\Command\LocationVisitor\Response\BodyVisitor', + 'response.header' => 'Guzzle\Service\Command\LocationVisitor\Response\HeaderVisitor', + 'response.json' => 'Guzzle\Service\Command\LocationVisitor\Response\JsonVisitor', + 'response.reasonPhrase' => 'Guzzle\Service\Command\LocationVisitor\Response\ReasonPhraseVisitor', + 'response.statusCode' => 'Guzzle\Service\Command\LocationVisitor\Response\StatusCodeVisitor', + 'response.xml' => 'Guzzle\Service\Command\LocationVisitor\Response\XmlVisitor' + ); + + /** @var array Array of mappings of location names to classes */ + protected $mappings; + + /** @var array Cache of instantiated visitors */ + protected $cache = array(); + + /** + * @return self + * @codeCoverageIgnore + */ + public static function getInstance() + { + if (!self::$instance) { + self::$instance = new self(); + } + + return self::$instance; + } + + /** + * @param array $mappings Array mapping request.name and response.name to location visitor classes. Leave null to + * use the default values. + */ + public function __construct(array $mappings = null) + { + $this->mappings = $mappings === null ? self::$defaultMappings : $mappings; + } + + /** + * Get an instance of a request visitor by location name + * + * @param string $visitor Visitor name + * + * @return RequestVisitorInterface + */ + public function getRequestVisitor($visitor) + { + return $this->getKey('request.' . $visitor); + } + + /** + * Get an instance of a response visitor by location name + * + * @param string $visitor Visitor name + * + * @return ResponseVisitorInterface + */ + public function getResponseVisitor($visitor) + { + return $this->getKey('response.' . $visitor); + } + + /** + * Add a response visitor to the factory by name + * + * @param string $name Name of the visitor + * @param RequestVisitorInterface $visitor Visitor to add + * + * @return self + */ + public function addRequestVisitor($name, RequestVisitorInterface $visitor) + { + $this->cache['request.' . $name] = $visitor; + + return $this; + } + + /** + * Add a response visitor to the factory by name + * + * @param string $name Name of the visitor + * @param ResponseVisitorInterface $visitor Visitor to add + * + * @return self + */ + public function addResponseVisitor($name, ResponseVisitorInterface $visitor) + { + $this->cache['response.' . $name] = $visitor; + + return $this; + } + + /** + * Get a visitor by key value name + * + * @param string $key Key name to retrieve + * + * @return mixed + * @throws InvalidArgumentException + */ + private function getKey($key) + { + if (!isset($this->cache[$key])) { + if (!isset($this->mappings[$key])) { + list($type, $name) = explode('.', $key); + throw new InvalidArgumentException("No {$type} visitor has been mapped for {$name}"); + } + $this->cache[$key] = new $this->mappings[$key]; + } + + return $this->cache[$key]; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/OperationCommand.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/OperationCommand.php new file mode 100644 index 000000000..0748b5af0 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/OperationCommand.php @@ -0,0 +1,89 @@ +responseParser = $parser; + + return $this; + } + + /** + * Set the request serializer used with the command + * + * @param RequestSerializerInterface $serializer Request serializer + * + * @return self + */ + public function setRequestSerializer(RequestSerializerInterface $serializer) + { + $this->requestSerializer = $serializer; + + return $this; + } + + /** + * Get the request serializer used with the command + * + * @return RequestSerializerInterface + */ + public function getRequestSerializer() + { + if (!$this->requestSerializer) { + // Use the default request serializer if none was found + $this->requestSerializer = DefaultRequestSerializer::getInstance(); + } + + return $this->requestSerializer; + } + + /** + * Get the response parser used for the operation + * + * @return ResponseParserInterface + */ + public function getResponseParser() + { + if (!$this->responseParser) { + // Use the default response parser if none was found + $this->responseParser = OperationResponseParser::getInstance(); + } + + return $this->responseParser; + } + + protected function build() + { + // Prepare and serialize the request + $this->request = $this->getRequestSerializer()->prepare($this); + } + + protected function process() + { + // Do not process the response if 'command.response_processing' is set to 'raw' + $this->result = $this[self::RESPONSE_PROCESSING] == self::TYPE_RAW + ? $this->request->getResponse() + : $this->getResponseParser()->parse($this); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/OperationResponseParser.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/OperationResponseParser.php new file mode 100644 index 000000000..ca00bc062 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/OperationResponseParser.php @@ -0,0 +1,195 @@ +factory = $factory; + $this->schemaInModels = $schemaInModels; + } + + /** + * Add a location visitor to the command + * + * @param string $location Location to associate with the visitor + * @param ResponseVisitorInterface $visitor Visitor to attach + * + * @return self + */ + public function addVisitor($location, ResponseVisitorInterface $visitor) + { + $this->factory->addResponseVisitor($location, $visitor); + + return $this; + } + + protected function handleParsing(CommandInterface $command, Response $response, $contentType) + { + $operation = $command->getOperation(); + $type = $operation->getResponseType(); + $model = null; + + if ($type == OperationInterface::TYPE_MODEL) { + $model = $operation->getServiceDescription()->getModel($operation->getResponseClass()); + } elseif ($type == OperationInterface::TYPE_CLASS) { + return $this->parseClass($command); + } + + if (!$model) { + // Return basic processing if the responseType is not model or the model cannot be found + return parent::handleParsing($command, $response, $contentType); + } elseif ($command[AbstractCommand::RESPONSE_PROCESSING] != AbstractCommand::TYPE_MODEL) { + // Returns a model with no visiting if the command response processing is not model + return new Model(parent::handleParsing($command, $response, $contentType)); + } else { + // Only inject the schema into the model if "schemaInModel" is true + return new Model($this->visitResult($model, $command, $response), $this->schemaInModels ? $model : null); + } + } + + /** + * Parse a class object + * + * @param CommandInterface $command Command to parse into an object + * + * @return mixed + * @throws ResponseClassException + */ + protected function parseClass(CommandInterface $command) + { + // Emit the operation.parse_class event. If a listener injects a 'result' property, then that will be the result + $event = new CreateResponseClassEvent(array('command' => $command)); + $command->getClient()->getEventDispatcher()->dispatch('command.parse_response', $event); + if ($result = $event->getResult()) { + return $result; + } + + $className = $command->getOperation()->getResponseClass(); + if (!method_exists($className, 'fromCommand')) { + throw new ResponseClassException("{$className} must exist and implement a static fromCommand() method"); + } + + return $className::fromCommand($command); + } + + /** + * Perform transformations on the result array + * + * @param Parameter $model Model that defines the structure + * @param CommandInterface $command Command that performed the operation + * @param Response $response Response received + * + * @return array Returns the array of result data + */ + protected function visitResult(Parameter $model, CommandInterface $command, Response $response) + { + $foundVisitors = $result = $knownProps = array(); + $props = $model->getProperties(); + + foreach ($props as $schema) { + if ($location = $schema->getLocation()) { + // Trigger the before method on the first found visitor of this type + if (!isset($foundVisitors[$location])) { + $foundVisitors[$location] = $this->factory->getResponseVisitor($location); + $foundVisitors[$location]->before($command, $result); + } + } + } + + // Visit additional properties when it is an actual schema + if (($additional = $model->getAdditionalProperties()) instanceof Parameter) { + $this->visitAdditionalProperties($model, $command, $response, $additional, $result, $foundVisitors); + } + + // Apply the parameter value with the location visitor + foreach ($props as $schema) { + $knownProps[$schema->getName()] = 1; + if ($location = $schema->getLocation()) { + $foundVisitors[$location]->visit($command, $response, $schema, $result); + } + } + + // Remove any unknown and potentially unsafe top-level properties + if ($additional === false) { + $result = array_intersect_key($result, $knownProps); + } + + // Call the after() method of each found visitor + foreach ($foundVisitors as $visitor) { + $visitor->after($command); + } + + return $result; + } + + protected function visitAdditionalProperties( + Parameter $model, + CommandInterface $command, + Response $response, + Parameter $additional, + &$result, + array &$foundVisitors + ) { + // Only visit when a location is specified + if ($location = $additional->getLocation()) { + if (!isset($foundVisitors[$location])) { + $foundVisitors[$location] = $this->factory->getResponseVisitor($location); + $foundVisitors[$location]->before($command, $result); + } + // Only traverse if an array was parsed from the before() visitors + if (is_array($result)) { + // Find each additional property + foreach (array_keys($result) as $key) { + // Check if the model actually knows this property. If so, then it is not additional + if (!$model->getProperty($key)) { + // Set the name to the key so that we can parse it with each visitor + $additional->setName($key); + $foundVisitors[$location]->visit($command, $response, $additional, $result); + } + } + // Reset the additionalProperties name to null + $additional->setName(null); + } + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/RequestSerializerInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/RequestSerializerInterface.php new file mode 100644 index 000000000..60b9334d4 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Command/RequestSerializerInterface.php @@ -0,0 +1,21 @@ + true, 'httpMethod' => true, 'uri' => true, 'class' => true, 'responseClass' => true, + 'responseType' => true, 'responseNotes' => true, 'notes' => true, 'summary' => true, 'documentationUrl' => true, + 'deprecated' => true, 'data' => true, 'parameters' => true, 'additionalParameters' => true, + 'errorResponses' => true + ); + + /** @var array Parameters */ + protected $parameters = array(); + + /** @var Parameter Additional parameters schema */ + protected $additionalParameters; + + /** @var string Name of the command */ + protected $name; + + /** @var string HTTP method */ + protected $httpMethod; + + /** @var string This is a short summary of what the operation does */ + protected $summary; + + /** @var string A longer text field to explain the behavior of the operation. */ + protected $notes; + + /** @var string Reference URL providing more information about the operation */ + protected $documentationUrl; + + /** @var string HTTP URI of the command */ + protected $uri; + + /** @var string Class of the command object */ + protected $class; + + /** @var string This is what is returned from the method */ + protected $responseClass; + + /** @var string Type information about the response */ + protected $responseType; + + /** @var string Information about the response returned by the operation */ + protected $responseNotes; + + /** @var bool Whether or not the command is deprecated */ + protected $deprecated; + + /** @var array Array of errors that could occur when running the command */ + protected $errorResponses; + + /** @var ServiceDescriptionInterface */ + protected $description; + + /** @var array Extra operation information */ + protected $data; + + /** + * Builds an Operation object using an array of configuration data: + * - name: (string) Name of the command + * - httpMethod: (string) HTTP method of the operation + * - uri: (string) URI template that can create a relative or absolute URL + * - class: (string) Concrete class that implements this command + * - parameters: (array) Associative array of parameters for the command. {@see Parameter} for information. + * - summary: (string) This is a short summary of what the operation does + * - notes: (string) A longer text field to explain the behavior of the operation. + * - documentationUrl: (string) Reference URL providing more information about the operation + * - responseClass: (string) This is what is returned from the method. Can be a primitive, PSR-0 compliant + * class name, or model. + * - responseNotes: (string) Information about the response returned by the operation + * - responseType: (string) One of 'primitive', 'class', 'model', or 'documentation'. If not specified, this + * value will be automatically inferred based on whether or not there is a model matching the + * name, if a matching PSR-0 compliant class name is found, or set to 'primitive' by default. + * - deprecated: (bool) Set to true if this is a deprecated command + * - errorResponses: (array) Errors that could occur when executing the command. Array of hashes, each with a + * 'code' (the HTTP response code), 'reason' (response reason phrase or description of the + * error), and 'class' (a custom exception class that would be thrown if the error is + * encountered). + * - data: (array) Any extra data that might be used to help build or serialize the operation + * - additionalParameters: (null|array) Parameter schema to use when an option is passed to the operation that is + * not in the schema + * + * @param array $config Array of configuration data + * @param ServiceDescriptionInterface $description Service description used to resolve models if $ref tags are found + */ + public function __construct(array $config = array(), ServiceDescriptionInterface $description = null) + { + $this->description = $description; + + // Get the intersection of the available properties and properties set on the operation + foreach (array_intersect_key($config, self::$properties) as $key => $value) { + $this->{$key} = $value; + } + + $this->class = $this->class ?: self::DEFAULT_COMMAND_CLASS; + $this->deprecated = (bool) $this->deprecated; + $this->errorResponses = $this->errorResponses ?: array(); + $this->data = $this->data ?: array(); + + if (!$this->responseClass) { + $this->responseClass = 'array'; + $this->responseType = 'primitive'; + } elseif ($this->responseType) { + // Set the response type to perform validation + $this->setResponseType($this->responseType); + } else { + // A response class was set and no response type was set, so guess what the type is + $this->inferResponseType(); + } + + // Parameters need special handling when adding + if ($this->parameters) { + foreach ($this->parameters as $name => $param) { + if ($param instanceof Parameter) { + $param->setName($name)->setParent($this); + } elseif (is_array($param)) { + $param['name'] = $name; + $this->addParam(new Parameter($param, $this->description)); + } + } + } + + if ($this->additionalParameters) { + if ($this->additionalParameters instanceof Parameter) { + $this->additionalParameters->setParent($this); + } elseif (is_array($this->additionalParameters)) { + $this->setadditionalParameters(new Parameter($this->additionalParameters, $this->description)); + } + } + } + + public function toArray() + { + $result = array(); + // Grab valid properties and filter out values that weren't set + foreach (array_keys(self::$properties) as $check) { + if ($value = $this->{$check}) { + $result[$check] = $value; + } + } + // Remove the name property + unset($result['name']); + // Parameters need to be converted to arrays + $result['parameters'] = array(); + foreach ($this->parameters as $key => $param) { + $result['parameters'][$key] = $param->toArray(); + } + // Additional parameters need to be cast to an array + if ($this->additionalParameters instanceof Parameter) { + $result['additionalParameters'] = $this->additionalParameters->toArray(); + } + + return $result; + } + + public function getServiceDescription() + { + return $this->description; + } + + public function setServiceDescription(ServiceDescriptionInterface $description) + { + $this->description = $description; + + return $this; + } + + public function getParams() + { + return $this->parameters; + } + + public function getParamNames() + { + return array_keys($this->parameters); + } + + public function hasParam($name) + { + return isset($this->parameters[$name]); + } + + public function getParam($param) + { + return isset($this->parameters[$param]) ? $this->parameters[$param] : null; + } + + /** + * Add a parameter to the command + * + * @param Parameter $param Parameter to add + * + * @return self + */ + public function addParam(Parameter $param) + { + $this->parameters[$param->getName()] = $param; + $param->setParent($this); + + return $this; + } + + /** + * Remove a parameter from the command + * + * @param string $name Name of the parameter to remove + * + * @return self + */ + public function removeParam($name) + { + unset($this->parameters[$name]); + + return $this; + } + + public function getHttpMethod() + { + return $this->httpMethod; + } + + /** + * Set the HTTP method of the command + * + * @param string $httpMethod Method to set + * + * @return self + */ + public function setHttpMethod($httpMethod) + { + $this->httpMethod = $httpMethod; + + return $this; + } + + public function getClass() + { + return $this->class; + } + + /** + * Set the concrete class of the command + * + * @param string $className Concrete class name + * + * @return self + */ + public function setClass($className) + { + $this->class = $className; + + return $this; + } + + public function getName() + { + return $this->name; + } + + /** + * Set the name of the command + * + * @param string $name Name of the command + * + * @return self + */ + public function setName($name) + { + $this->name = $name; + + return $this; + } + + public function getSummary() + { + return $this->summary; + } + + /** + * Set a short summary of what the operation does + * + * @param string $summary Short summary of the operation + * + * @return self + */ + public function setSummary($summary) + { + $this->summary = $summary; + + return $this; + } + + public function getNotes() + { + return $this->notes; + } + + /** + * Set a longer text field to explain the behavior of the operation. + * + * @param string $notes Notes on the operation + * + * @return self + */ + public function setNotes($notes) + { + $this->notes = $notes; + + return $this; + } + + public function getDocumentationUrl() + { + return $this->documentationUrl; + } + + /** + * Set the URL pointing to additional documentation on the command + * + * @param string $docUrl Documentation URL + * + * @return self + */ + public function setDocumentationUrl($docUrl) + { + $this->documentationUrl = $docUrl; + + return $this; + } + + public function getResponseClass() + { + return $this->responseClass; + } + + /** + * Set what is returned from the method. Can be a primitive, class name, or model. For example: 'array', + * 'Guzzle\\Foo\\Baz', or 'MyModelName' (to reference a model by ID). + * + * @param string $responseClass Type of response + * + * @return self + */ + public function setResponseClass($responseClass) + { + $this->responseClass = $responseClass; + $this->inferResponseType(); + + return $this; + } + + public function getResponseType() + { + return $this->responseType; + } + + /** + * Set qualifying information about the responseClass. One of 'primitive', 'class', 'model', or 'documentation' + * + * @param string $responseType Response type information + * + * @return self + * @throws InvalidArgumentException + */ + public function setResponseType($responseType) + { + static $types = array( + self::TYPE_PRIMITIVE => true, + self::TYPE_CLASS => true, + self::TYPE_MODEL => true, + self::TYPE_DOCUMENTATION => true + ); + if (!isset($types[$responseType])) { + throw new InvalidArgumentException('responseType must be one of ' . implode(', ', array_keys($types))); + } + + $this->responseType = $responseType; + + return $this; + } + + public function getResponseNotes() + { + return $this->responseNotes; + } + + /** + * Set notes about the response of the operation + * + * @param string $notes Response notes + * + * @return self + */ + public function setResponseNotes($notes) + { + $this->responseNotes = $notes; + + return $this; + } + + public function getDeprecated() + { + return $this->deprecated; + } + + /** + * Set whether or not the command is deprecated + * + * @param bool $isDeprecated Set to true to mark as deprecated + * + * @return self + */ + public function setDeprecated($isDeprecated) + { + $this->deprecated = $isDeprecated; + + return $this; + } + + public function getUri() + { + return $this->uri; + } + + /** + * Set the URI template of the command + * + * @param string $uri URI template to set + * + * @return self + */ + public function setUri($uri) + { + $this->uri = $uri; + + return $this; + } + + public function getErrorResponses() + { + return $this->errorResponses; + } + + /** + * Add an error to the command + * + * @param string $code HTTP response code + * @param string $reason HTTP response reason phrase or information about the error + * @param string $class Exception class associated with the error + * + * @return self + */ + public function addErrorResponse($code, $reason, $class) + { + $this->errorResponses[] = array('code' => $code, 'reason' => $reason, 'class' => $class); + + return $this; + } + + /** + * Set all of the error responses of the operation + * + * @param array $errorResponses Hash of error name to a hash containing a code, reason, class + * + * @return self + */ + public function setErrorResponses(array $errorResponses) + { + $this->errorResponses = $errorResponses; + + return $this; + } + + public function getData($name) + { + return isset($this->data[$name]) ? $this->data[$name] : null; + } + + /** + * Set a particular data point on the operation + * + * @param string $name Name of the data value + * @param mixed $value Value to set + * + * @return self + */ + public function setData($name, $value) + { + $this->data[$name] = $value; + + return $this; + } + + /** + * Get the additionalParameters of the operation + * + * @return Parameter|null + */ + public function getAdditionalParameters() + { + return $this->additionalParameters; + } + + /** + * Set the additionalParameters of the operation + * + * @param Parameter|null $parameter Parameter to set + * + * @return self + */ + public function setAdditionalParameters($parameter) + { + if ($this->additionalParameters = $parameter) { + $this->additionalParameters->setParent($this); + } + + return $this; + } + + /** + * Infer the response type from the responseClass value + */ + protected function inferResponseType() + { + static $primitives = array('array' => 1, 'boolean' => 1, 'string' => 1, 'integer' => 1, '' => 1); + if (isset($primitives[$this->responseClass])) { + $this->responseType = self::TYPE_PRIMITIVE; + } elseif ($this->description && $this->description->hasModel($this->responseClass)) { + $this->responseType = self::TYPE_MODEL; + } else { + $this->responseType = self::TYPE_CLASS; + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Description/OperationInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Description/OperationInterface.php new file mode 100644 index 000000000..4de41bd67 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Description/OperationInterface.php @@ -0,0 +1,159 @@ +getModel($data['$ref'])) { + $data = $model->toArray() + $data; + } + } elseif (isset($data['extends'])) { + // If this parameter extends from another parameter then start with the actual data + // union in the parent's data (e.g. actual supersedes parent) + if ($extends = $description->getModel($data['extends'])) { + $data += $extends->toArray(); + } + } + } + + // Pull configuration data into the parameter + foreach ($data as $key => $value) { + $this->{$key} = $value; + } + + $this->serviceDescription = $description; + $this->required = (bool) $this->required; + $this->data = (array) $this->data; + + if ($this->filters) { + $this->setFilters((array) $this->filters); + } + + if ($this->type == 'object' && $this->additionalProperties === null) { + $this->additionalProperties = true; + } + } + + /** + * Convert the object to an array + * + * @return array + */ + public function toArray() + { + static $checks = array('required', 'description', 'static', 'type', 'format', 'instanceOf', 'location', 'sentAs', + 'pattern', 'minimum', 'maximum', 'minItems', 'maxItems', 'minLength', 'maxLength', 'data', 'enum', + 'filters'); + + $result = array(); + + // Anything that is in the `Items` attribute of an array *must* include it's name if available + if ($this->parent instanceof self && $this->parent->getType() == 'array' && isset($this->name)) { + $result['name'] = $this->name; + } + + foreach ($checks as $c) { + if ($value = $this->{$c}) { + $result[$c] = $value; + } + } + + if ($this->default !== null) { + $result['default'] = $this->default; + } + + if ($this->items !== null) { + $result['items'] = $this->getItems()->toArray(); + } + + if ($this->additionalProperties !== null) { + $result['additionalProperties'] = $this->getAdditionalProperties(); + if ($result['additionalProperties'] instanceof self) { + $result['additionalProperties'] = $result['additionalProperties']->toArray(); + } + } + + if ($this->type == 'object' && $this->properties) { + $result['properties'] = array(); + foreach ($this->getProperties() as $name => $property) { + $result['properties'][$name] = $property->toArray(); + } + } + + return $result; + } + + /** + * Get the default or static value of the command based on a value + * + * @param string $value Value that is currently set + * + * @return mixed Returns the value, a static value if one is present, or a default value + */ + public function getValue($value) + { + if ($this->static || ($this->default !== null && $value === null)) { + return $this->default; + } + + return $value; + } + + /** + * Run a value through the filters OR format attribute associated with the parameter + * + * @param mixed $value Value to filter + * + * @return mixed Returns the filtered value + */ + public function filter($value) + { + // Formats are applied exclusively and supersed filters + if ($this->format) { + return SchemaFormatter::format($this->format, $value); + } + + // Convert Boolean values + if ($this->type == 'boolean' && !is_bool($value)) { + $value = filter_var($value, FILTER_VALIDATE_BOOLEAN); + } + + // Apply filters to the value + if ($this->filters) { + foreach ($this->filters as $filter) { + if (is_array($filter)) { + // Convert complex filters that hold value place holders + foreach ($filter['args'] as &$data) { + if ($data == '@value') { + $data = $value; + } elseif ($data == '@api') { + $data = $this; + } + } + $value = call_user_func_array($filter['method'], $filter['args']); + } else { + $value = call_user_func($filter, $value); + } + } + } + + return $value; + } + + /** + * Get the name of the parameter + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Get the key of the parameter, where sentAs will supersede name if it is set + * + * @return string + */ + public function getWireName() + { + return $this->sentAs ?: $this->name; + } + + /** + * Set the name of the parameter + * + * @param string $name Name to set + * + * @return self + */ + public function setName($name) + { + $this->name = $name; + + return $this; + } + + /** + * Get the type(s) of the parameter + * + * @return string|array + */ + public function getType() + { + return $this->type; + } + + /** + * Set the type(s) of the parameter + * + * @param string|array $type Type of parameter or array of simple types used in a union + * + * @return self + */ + public function setType($type) + { + $this->type = $type; + + return $this; + } + + /** + * Get if the parameter is required + * + * @return bool + */ + public function getRequired() + { + return $this->required; + } + + /** + * Set if the parameter is required + * + * @param bool $isRequired Whether or not the parameter is required + * + * @return self + */ + public function setRequired($isRequired) + { + $this->required = (bool) $isRequired; + + return $this; + } + + /** + * Get the default value of the parameter + * + * @return string|null + */ + public function getDefault() + { + return $this->default; + } + + /** + * Set the default value of the parameter + * + * @param string|null $default Default value to set + * + * @return self + */ + public function setDefault($default) + { + $this->default = $default; + + return $this; + } + + /** + * Get the description of the parameter + * + * @return string|null + */ + public function getDescription() + { + return $this->description; + } + + /** + * Set the description of the parameter + * + * @param string $description Description + * + * @return self + */ + public function setDescription($description) + { + $this->description = $description; + + return $this; + } + + /** + * Get the minimum acceptable value for an integer + * + * @return int|null + */ + public function getMinimum() + { + return $this->minimum; + } + + /** + * Set the minimum acceptable value for an integer + * + * @param int|null $min Minimum + * + * @return self + */ + public function setMinimum($min) + { + $this->minimum = $min; + + return $this; + } + + /** + * Get the maximum acceptable value for an integer + * + * @return int|null + */ + public function getMaximum() + { + return $this->maximum; + } + + /** + * Set the maximum acceptable value for an integer + * + * @param int $max Maximum + * + * @return self + */ + public function setMaximum($max) + { + $this->maximum = $max; + + return $this; + } + + /** + * Get the minimum allowed length of a string value + * + * @return int + */ + public function getMinLength() + { + return $this->minLength; + } + + /** + * Set the minimum allowed length of a string value + * + * @param int|null $min Minimum + * + * @return self + */ + public function setMinLength($min) + { + $this->minLength = $min; + + return $this; + } + + /** + * Get the maximum allowed length of a string value + * + * @return int|null + */ + public function getMaxLength() + { + return $this->maxLength; + } + + /** + * Set the maximum allowed length of a string value + * + * @param int $max Maximum length + * + * @return self + */ + public function setMaxLength($max) + { + $this->maxLength = $max; + + return $this; + } + + /** + * Get the maximum allowed number of items in an array value + * + * @return int|null + */ + public function getMaxItems() + { + return $this->maxItems; + } + + /** + * Set the maximum allowed number of items in an array value + * + * @param int $max Maximum + * + * @return self + */ + public function setMaxItems($max) + { + $this->maxItems = $max; + + return $this; + } + + /** + * Get the minimum allowed number of items in an array value + * + * @return int + */ + public function getMinItems() + { + return $this->minItems; + } + + /** + * Set the minimum allowed number of items in an array value + * + * @param int|null $min Minimum + * + * @return self + */ + public function setMinItems($min) + { + $this->minItems = $min; + + return $this; + } + + /** + * Get the location of the parameter + * + * @return string|null + */ + public function getLocation() + { + return $this->location; + } + + /** + * Set the location of the parameter + * + * @param string|null $location Location of the parameter + * + * @return self + */ + public function setLocation($location) + { + $this->location = $location; + + return $this; + } + + /** + * Get the sentAs attribute of the parameter that used with locations to sentAs an attribute when it is being + * applied to a location. + * + * @return string|null + */ + public function getSentAs() + { + return $this->sentAs; + } + + /** + * Set the sentAs attribute + * + * @param string|null $name Name of the value as it is sent over the wire + * + * @return self + */ + public function setSentAs($name) + { + $this->sentAs = $name; + + return $this; + } + + /** + * Retrieve a known property from the parameter by name or a data property by name. When not specific name value + * is specified, all data properties will be returned. + * + * @param string|null $name Specify a particular property name to retrieve + * + * @return array|mixed|null + */ + public function getData($name = null) + { + if (!$name) { + return $this->data; + } + + if (isset($this->data[$name])) { + return $this->data[$name]; + } elseif (isset($this->{$name})) { + return $this->{$name}; + } + + return null; + } + + /** + * Set the extra data properties of the parameter or set a specific extra property + * + * @param string|array|null $nameOrData The name of a specific extra to set or an array of extras to set + * @param mixed|null $data When setting a specific extra property, specify the data to set for it + * + * @return self + */ + public function setData($nameOrData, $data = null) + { + if (is_array($nameOrData)) { + $this->data = $nameOrData; + } else { + $this->data[$nameOrData] = $data; + } + + return $this; + } + + /** + * Get whether or not the default value can be changed + * + * @return mixed|null + */ + public function getStatic() + { + return $this->static; + } + + /** + * Set to true if the default value cannot be changed + * + * @param bool $static True or false + * + * @return self + */ + public function setStatic($static) + { + $this->static = (bool) $static; + + return $this; + } + + /** + * Get an array of filters used by the parameter + * + * @return array + */ + public function getFilters() + { + return $this->filters ?: array(); + } + + /** + * Set the array of filters used by the parameter + * + * @param array $filters Array of functions to use as filters + * + * @return self + */ + public function setFilters(array $filters) + { + $this->filters = array(); + foreach ($filters as $filter) { + $this->addFilter($filter); + } + + return $this; + } + + /** + * Add a filter to the parameter + * + * @param string|array $filter Method to filter the value through + * + * @return self + * @throws InvalidArgumentException + */ + public function addFilter($filter) + { + if (is_array($filter)) { + if (!isset($filter['method'])) { + throw new InvalidArgumentException('A [method] value must be specified for each complex filter'); + } + } + + if (!$this->filters) { + $this->filters = array($filter); + } else { + $this->filters[] = $filter; + } + + return $this; + } + + /** + * Get the parent object (an {@see OperationInterface} or {@see Parameter} + * + * @return OperationInterface|Parameter|null + */ + public function getParent() + { + return $this->parent; + } + + /** + * Set the parent object of the parameter + * + * @param OperationInterface|Parameter|null $parent Parent container of the parameter + * + * @return self + */ + public function setParent($parent) + { + $this->parent = $parent; + + return $this; + } + + /** + * Get the properties of the parameter + * + * @return array + */ + public function getProperties() + { + if (!$this->propertiesCache) { + $this->propertiesCache = array(); + foreach (array_keys($this->properties) as $name) { + $this->propertiesCache[$name] = $this->getProperty($name); + } + } + + return $this->propertiesCache; + } + + /** + * Get a specific property from the parameter + * + * @param string $name Name of the property to retrieve + * + * @return null|Parameter + */ + public function getProperty($name) + { + if (!isset($this->properties[$name])) { + return null; + } + + if (!($this->properties[$name] instanceof self)) { + $this->properties[$name]['name'] = $name; + $this->properties[$name] = new static($this->properties[$name], $this->serviceDescription); + $this->properties[$name]->setParent($this); + } + + return $this->properties[$name]; + } + + /** + * Remove a property from the parameter + * + * @param string $name Name of the property to remove + * + * @return self + */ + public function removeProperty($name) + { + unset($this->properties[$name]); + $this->propertiesCache = null; + + return $this; + } + + /** + * Add a property to the parameter + * + * @param Parameter $property Properties to set + * + * @return self + */ + public function addProperty(Parameter $property) + { + $this->properties[$property->getName()] = $property; + $property->setParent($this); + $this->propertiesCache = null; + + return $this; + } + + /** + * Get the additionalProperties value of the parameter + * + * @return bool|Parameter|null + */ + public function getAdditionalProperties() + { + if (is_array($this->additionalProperties)) { + $this->additionalProperties = new static($this->additionalProperties, $this->serviceDescription); + $this->additionalProperties->setParent($this); + } + + return $this->additionalProperties; + } + + /** + * Set the additionalProperties value of the parameter + * + * @param bool|Parameter|null $additional Boolean to allow any, an Parameter to specify a schema, or false to disallow + * + * @return self + */ + public function setAdditionalProperties($additional) + { + $this->additionalProperties = $additional; + + return $this; + } + + /** + * Set the items data of the parameter + * + * @param Parameter|null $items Items to set + * + * @return self + */ + public function setItems(Parameter $items = null) + { + if ($this->items = $items) { + $this->items->setParent($this); + } + + return $this; + } + + /** + * Get the item data of the parameter + * + * @return Parameter|null + */ + public function getItems() + { + if (is_array($this->items)) { + $this->items = new static($this->items, $this->serviceDescription); + $this->items->setParent($this); + } + + return $this->items; + } + + /** + * Get the class that the parameter must implement + * + * @return null|string + */ + public function getInstanceOf() + { + return $this->instanceOf; + } + + /** + * Set the class that the parameter must be an instance of + * + * @param string|null $instanceOf Class or interface name + * + * @return self + */ + public function setInstanceOf($instanceOf) + { + $this->instanceOf = $instanceOf; + + return $this; + } + + /** + * Get the enum of strings that are valid for the parameter + * + * @return array|null + */ + public function getEnum() + { + return $this->enum; + } + + /** + * Set the enum of strings that are valid for the parameter + * + * @param array|null $enum Array of strings or null + * + * @return self + */ + public function setEnum(array $enum = null) + { + $this->enum = $enum; + + return $this; + } + + /** + * Get the regex pattern that must match a value when the value is a string + * + * @return string + */ + public function getPattern() + { + return $this->pattern; + } + + /** + * Set the regex pattern that must match a value when the value is a string + * + * @param string $pattern Regex pattern + * + * @return self + */ + public function setPattern($pattern) + { + $this->pattern = $pattern; + + return $this; + } + + /** + * Get the format attribute of the schema + * + * @return string + */ + public function getFormat() + { + return $this->format; + } + + /** + * Set the format attribute of the schema + * + * @param string $format Format to set (e.g. date, date-time, timestamp, time, date-time-http) + * + * @return self + */ + public function setFormat($format) + { + $this->format = $format; + + return $this; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Description/SchemaFormatter.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Description/SchemaFormatter.php new file mode 100644 index 000000000..7f47fc9d7 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Description/SchemaFormatter.php @@ -0,0 +1,156 @@ +setTimezone(self::getUtcTimeZone())->format($format); + } + + throw new InvalidArgumentException('Date/Time values must be either a string, integer, or DateTime object'); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Description/SchemaValidator.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Description/SchemaValidator.php new file mode 100644 index 000000000..b045422d4 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Description/SchemaValidator.php @@ -0,0 +1,291 @@ +castIntegerToStringType = $castIntegerToStringType; + } + + public function validate(Parameter $param, &$value) + { + $this->errors = array(); + $this->recursiveProcess($param, $value); + + if (empty($this->errors)) { + return true; + } else { + sort($this->errors); + return false; + } + } + + /** + * Get the errors encountered while validating + * + * @return array + */ + public function getErrors() + { + return $this->errors ?: array(); + } + + /** + * Recursively validate a parameter + * + * @param Parameter $param API parameter being validated + * @param mixed $value Value to validate and validate. The value may change during this validate. + * @param string $path Current validation path (used for error reporting) + * @param int $depth Current depth in the validation validate + * + * @return bool Returns true if valid, or false if invalid + */ + protected function recursiveProcess(Parameter $param, &$value, $path = '', $depth = 0) + { + // Update the value by adding default or static values + $value = $param->getValue($value); + + $required = $param->getRequired(); + // if the value is null and the parameter is not required or is static, then skip any further recursion + if ((null === $value && !$required) || $param->getStatic()) { + return true; + } + + $type = $param->getType(); + // Attempt to limit the number of times is_array is called by tracking if the value is an array + $valueIsArray = is_array($value); + // If a name is set then update the path so that validation messages are more helpful + if ($name = $param->getName()) { + $path .= "[{$name}]"; + } + + if ($type == 'object') { + + // Objects are either associative arrays, ToArrayInterface, or some other object + if ($param->getInstanceOf()) { + $instance = $param->getInstanceOf(); + if (!($value instanceof $instance)) { + $this->errors[] = "{$path} must be an instance of {$instance}"; + return false; + } + } + + // Determine whether or not this "value" has properties and should be traversed + $traverse = $temporaryValue = false; + + // Convert the value to an array + if (!$valueIsArray && $value instanceof ToArrayInterface) { + $value = $value->toArray(); + } + + if ($valueIsArray) { + // Ensure that the array is associative and not numerically indexed + if (isset($value[0])) { + $this->errors[] = "{$path} must be an array of properties. Got a numerically indexed array."; + return false; + } + $traverse = true; + } elseif ($value === null) { + // Attempt to let the contents be built up by default values if possible + $value = array(); + $temporaryValue = $valueIsArray = $traverse = true; + } + + if ($traverse) { + + if ($properties = $param->getProperties()) { + // if properties were found, the validate each property of the value + foreach ($properties as $property) { + $name = $property->getName(); + if (isset($value[$name])) { + $this->recursiveProcess($property, $value[$name], $path, $depth + 1); + } else { + $current = null; + $this->recursiveProcess($property, $current, $path, $depth + 1); + // Only set the value if it was populated with something + if (null !== $current) { + $value[$name] = $current; + } + } + } + } + + $additional = $param->getAdditionalProperties(); + if ($additional !== true) { + // If additional properties were found, then validate each against the additionalProperties attr. + $keys = array_keys($value); + // Determine the keys that were specified that were not listed in the properties of the schema + $diff = array_diff($keys, array_keys($properties)); + if (!empty($diff)) { + // Determine which keys are not in the properties + if ($additional instanceOf Parameter) { + foreach ($diff as $key) { + $this->recursiveProcess($additional, $value[$key], "{$path}[{$key}]", $depth); + } + } else { + // if additionalProperties is set to false and there are additionalProperties in the values, then fail + foreach ($diff as $prop) { + $this->errors[] = sprintf('%s[%s] is not an allowed property', $path, $prop); + } + } + } + } + + // A temporary value will be used to traverse elements that have no corresponding input value. + // This allows nested required parameters with default values to bubble up into the input. + // Here we check if we used a temp value and nothing bubbled up, then we need to remote the value. + if ($temporaryValue && empty($value)) { + $value = null; + $valueIsArray = false; + } + } + + } elseif ($type == 'array' && $valueIsArray && $param->getItems()) { + foreach ($value as $i => &$item) { + // Validate each item in an array against the items attribute of the schema + $this->recursiveProcess($param->getItems(), $item, $path . "[{$i}]", $depth + 1); + } + } + + // If the value is required and the type is not null, then there is an error if the value is not set + if ($required && $value === null && $type != 'null') { + $message = "{$path} is " . ($param->getType() ? ('a required ' . implode(' or ', (array) $param->getType())) : 'required'); + if ($param->getDescription()) { + $message .= ': ' . $param->getDescription(); + } + $this->errors[] = $message; + return false; + } + + // Validate that the type is correct. If the type is string but an integer was passed, the class can be + // instructed to cast the integer to a string to pass validation. This is the default behavior. + if ($type && (!$type = $this->determineType($type, $value))) { + if ($this->castIntegerToStringType && $param->getType() == 'string' && is_integer($value)) { + $value = (string) $value; + } else { + $this->errors[] = "{$path} must be of type " . implode(' or ', (array) $param->getType()); + } + } + + // Perform type specific validation for strings, arrays, and integers + if ($type == 'string') { + + // Strings can have enums which are a list of predefined values + if (($enum = $param->getEnum()) && !in_array($value, $enum)) { + $this->errors[] = "{$path} must be one of " . implode(' or ', array_map(function ($s) { + return '"' . addslashes($s) . '"'; + }, $enum)); + } + // Strings can have a regex pattern that the value must match + if (($pattern = $param->getPattern()) && !preg_match($pattern, $value)) { + $this->errors[] = "{$path} must match the following regular expression: {$pattern}"; + } + + $strLen = null; + if ($min = $param->getMinLength()) { + $strLen = strlen($value); + if ($strLen < $min) { + $this->errors[] = "{$path} length must be greater than or equal to {$min}"; + } + } + if ($max = $param->getMaxLength()) { + if (($strLen ?: strlen($value)) > $max) { + $this->errors[] = "{$path} length must be less than or equal to {$max}"; + } + } + + } elseif ($type == 'array') { + + $size = null; + if ($min = $param->getMinItems()) { + $size = count($value); + if ($size < $min) { + $this->errors[] = "{$path} must contain {$min} or more elements"; + } + } + if ($max = $param->getMaxItems()) { + if (($size ?: count($value)) > $max) { + $this->errors[] = "{$path} must contain {$max} or fewer elements"; + } + } + + } elseif ($type == 'integer' || $type == 'number' || $type == 'numeric') { + if (($min = $param->getMinimum()) && $value < $min) { + $this->errors[] = "{$path} must be greater than or equal to {$min}"; + } + if (($max = $param->getMaximum()) && $value > $max) { + $this->errors[] = "{$path} must be less than or equal to {$max}"; + } + } + + return empty($this->errors); + } + + /** + * From the allowable types, determine the type that the variable matches + * + * @param string $type Parameter type + * @param mixed $value Value to determine the type + * + * @return string|bool Returns the matching type on + */ + protected function determineType($type, $value) + { + foreach ((array) $type as $t) { + if ($t == 'string' && (is_string($value) || (is_object($value) && method_exists($value, '__toString')))) { + return 'string'; + } elseif ($t == 'object' && (is_array($value) || is_object($value))) { + return 'object'; + } elseif ($t == 'array' && is_array($value)) { + return 'array'; + } elseif ($t == 'integer' && is_integer($value)) { + return 'integer'; + } elseif ($t == 'boolean' && is_bool($value)) { + return 'boolean'; + } elseif ($t == 'number' && is_numeric($value)) { + return 'number'; + } elseif ($t == 'numeric' && is_numeric($value)) { + return 'numeric'; + } elseif ($t == 'null' && !$value) { + return 'null'; + } elseif ($t == 'any') { + return 'any'; + } + } + + return false; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Description/ServiceDescription.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Description/ServiceDescription.php new file mode 100644 index 000000000..286e65eec --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Description/ServiceDescription.php @@ -0,0 +1,271 @@ +load($config, $options); + } + + /** + * @param array $config Array of configuration data + */ + public function __construct(array $config = array()) + { + $this->fromArray($config); + } + + public function serialize() + { + return json_encode($this->toArray()); + } + + public function unserialize($json) + { + $this->operations = array(); + $this->fromArray(json_decode($json, true)); + } + + public function toArray() + { + $result = array( + 'name' => $this->name, + 'apiVersion' => $this->apiVersion, + 'baseUrl' => $this->baseUrl, + 'description' => $this->description + ) + $this->extraData; + $result['operations'] = array(); + foreach ($this->getOperations() as $name => $operation) { + $result['operations'][$operation->getName() ?: $name] = $operation->toArray(); + } + if (!empty($this->models)) { + $result['models'] = array(); + foreach ($this->models as $id => $model) { + $result['models'][$id] = $model instanceof Parameter ? $model->toArray(): $model; + } + } + + return array_filter($result); + } + + public function getBaseUrl() + { + return $this->baseUrl; + } + + /** + * Set the baseUrl of the description + * + * @param string $baseUrl Base URL of each operation + * + * @return self + */ + public function setBaseUrl($baseUrl) + { + $this->baseUrl = $baseUrl; + + return $this; + } + + public function getOperations() + { + foreach (array_keys($this->operations) as $name) { + $this->getOperation($name); + } + + return $this->operations; + } + + public function hasOperation($name) + { + return isset($this->operations[$name]); + } + + public function getOperation($name) + { + // Lazily retrieve and build operations + if (!isset($this->operations[$name])) { + return null; + } + + if (!($this->operations[$name] instanceof Operation)) { + $this->operations[$name] = new Operation($this->operations[$name], $this); + } + + return $this->operations[$name]; + } + + /** + * Add a operation to the service description + * + * @param OperationInterface $operation Operation to add + * + * @return self + */ + public function addOperation(OperationInterface $operation) + { + $this->operations[$operation->getName()] = $operation->setServiceDescription($this); + + return $this; + } + + public function getModel($id) + { + if (!isset($this->models[$id])) { + return null; + } + + if (!($this->models[$id] instanceof Parameter)) { + $this->models[$id] = new Parameter($this->models[$id] + array('name' => $id), $this); + } + + return $this->models[$id]; + } + + public function getModels() + { + // Ensure all models are converted into parameter objects + foreach (array_keys($this->models) as $id) { + $this->getModel($id); + } + + return $this->models; + } + + public function hasModel($id) + { + return isset($this->models[$id]); + } + + /** + * Add a model to the service description + * + * @param Parameter $model Model to add + * + * @return self + */ + public function addModel(Parameter $model) + { + $this->models[$model->getName()] = $model; + + return $this; + } + + public function getApiVersion() + { + return $this->apiVersion; + } + + public function getName() + { + return $this->name; + } + + public function getDescription() + { + return $this->description; + } + + public function getData($key) + { + return isset($this->extraData[$key]) ? $this->extraData[$key] : null; + } + + public function setData($key, $value) + { + $this->extraData[$key] = $value; + + return $this; + } + + /** + * Initialize the state from an array + * + * @param array $config Configuration data + * @throws InvalidArgumentException + */ + protected function fromArray(array $config) + { + // Keep a list of default keys used in service descriptions that is later used to determine extra data keys + static $defaultKeys = array('name', 'models', 'apiVersion', 'baseUrl', 'description'); + // Pull in the default configuration values + foreach ($defaultKeys as $key) { + if (isset($config[$key])) { + $this->{$key} = $config[$key]; + } + } + + // Account for the Swagger name for Guzzle's baseUrl + if (isset($config['basePath'])) { + $this->baseUrl = $config['basePath']; + } + + // Ensure that the models and operations properties are always arrays + $this->models = (array) $this->models; + $this->operations = (array) $this->operations; + + // We want to add operations differently than adding the other properties + $defaultKeys[] = 'operations'; + + // Create operations for each operation + if (isset($config['operations'])) { + foreach ($config['operations'] as $name => $operation) { + if (!($operation instanceof Operation) && !is_array($operation)) { + throw new InvalidArgumentException('Invalid operation in service description: ' + . gettype($operation)); + } + $this->operations[$name] = $operation; + } + } + + // Get all of the additional properties of the service description and store them in a data array + foreach (array_diff(array_keys($config), $defaultKeys) as $key) { + $this->extraData[$key] = $config[$key]; + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Description/ServiceDescriptionInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Description/ServiceDescriptionInterface.php new file mode 100644 index 000000000..5983e586b --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Description/ServiceDescriptionInterface.php @@ -0,0 +1,106 @@ + $op) { + $name = $op['name'] = isset($op['name']) ? $op['name'] : $name; + // Extend other operations + if (!empty($op['extends'])) { + $this->resolveExtension($name, $op, $operations); + } + $op['parameters'] = isset($op['parameters']) ? $op['parameters'] : array(); + $operations[$name] = $op; + } + } + + return new ServiceDescription(array( + 'apiVersion' => isset($config['apiVersion']) ? $config['apiVersion'] : null, + 'baseUrl' => isset($config['baseUrl']) ? $config['baseUrl'] : null, + 'description' => isset($config['description']) ? $config['description'] : null, + 'operations' => $operations, + 'models' => isset($config['models']) ? $config['models'] : null + ) + $config); + } + + /** + * @param string $name Name of the operation + * @param array $op Operation value array + * @param array $operations Currently loaded operations + * @throws DescriptionBuilderException when extending a non-existent operation + */ + protected function resolveExtension($name, array &$op, array &$operations) + { + $resolved = array(); + $original = empty($op['parameters']) ? false: $op['parameters']; + $hasClass = !empty($op['class']); + foreach ((array) $op['extends'] as $extendedCommand) { + if (empty($operations[$extendedCommand])) { + throw new DescriptionBuilderException("{$name} extends missing operation {$extendedCommand}"); + } + $toArray = $operations[$extendedCommand]; + $resolved = empty($resolved) + ? $toArray['parameters'] + : array_merge($resolved, $toArray['parameters']); + + $op = $op + $toArray; + if (!$hasClass && isset($toArray['class'])) { + $op['class'] = $toArray['class']; + } + } + $op['parameters'] = $original ? array_merge($resolved, $original) : $resolved; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Description/ValidatorInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Description/ValidatorInterface.php new file mode 100644 index 000000000..94ca77da4 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Description/ValidatorInterface.php @@ -0,0 +1,28 @@ +getMessage(), $e->getCode(), $e->getPrevious()); + $ce->setSuccessfulRequests($e->getSuccessfulRequests()); + + $alreadyAddedExceptions = array(); + foreach ($e->getFailedRequests() as $request) { + if ($re = $e->getExceptionForFailedRequest($request)) { + $alreadyAddedExceptions[] = $re; + $ce->addFailedRequestWithException($request, $re); + } else { + $ce->addFailedRequest($request); + } + } + + // Add any exceptions that did not map to a request + if (count($alreadyAddedExceptions) < count($e)) { + foreach ($e as $ex) { + if (!in_array($ex, $alreadyAddedExceptions)) { + $ce->add($ex); + } + } + } + + return $ce; + } + + /** + * Get all of the commands in the transfer + * + * @return array + */ + public function getAllCommands() + { + return array_merge($this->successfulCommands, $this->failedCommands); + } + + /** + * Add to the array of successful commands + * + * @param CommandInterface $command Successful command + * + * @return self + */ + public function addSuccessfulCommand(CommandInterface $command) + { + $this->successfulCommands[] = $command; + + return $this; + } + + /** + * Add to the array of failed commands + * + * @param CommandInterface $command Failed command + * + * @return self + */ + public function addFailedCommand(CommandInterface $command) + { + $this->failedCommands[] = $command; + + return $this; + } + + /** + * Get an array of successful commands + * + * @return array + */ + public function getSuccessfulCommands() + { + return $this->successfulCommands; + } + + /** + * Get an array of failed commands + * + * @return array + */ + public function getFailedCommands() + { + return $this->failedCommands; + } + + /** + * Get the Exception that caused the given $command to fail + * + * @param CommandInterface $command Failed command + * + * @return \Exception|null + */ + public function getExceptionForFailedCommand(CommandInterface $command) + { + return $this->getExceptionForFailedRequest($command->getRequest()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Exception/DescriptionBuilderException.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Exception/DescriptionBuilderException.php new file mode 100644 index 000000000..1407e5687 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Exception/DescriptionBuilderException.php @@ -0,0 +1,7 @@ +invalidCommands = $commands; + parent::__construct( + 'Encountered commands in a batch transfer that use inconsistent clients. The batching ' . + 'strategy you use with a command transfer must divide command batches by client.' + ); + } + + /** + * Get the invalid commands + * + * @return array + */ + public function getCommands() + { + return $this->invalidCommands; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Exception/ResponseClassException.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Exception/ResponseClassException.php new file mode 100644 index 000000000..d59ff2185 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Exception/ResponseClassException.php @@ -0,0 +1,9 @@ +errors = $errors; + } + + /** + * Get any validation errors + * + * @return array + */ + public function getErrors() + { + return $this->errors; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Resource/AbstractResourceIteratorFactory.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Resource/AbstractResourceIteratorFactory.php new file mode 100644 index 000000000..21140e772 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Resource/AbstractResourceIteratorFactory.php @@ -0,0 +1,37 @@ +canBuild($command)) { + throw new InvalidArgumentException('Iterator was not found for ' . $command->getName()); + } + + $className = $this->getClassName($command); + + return new $className($command, $options); + } + + public function canBuild(CommandInterface $command) + { + return (bool) $this->getClassName($command); + } + + /** + * Get the name of the class to instantiate for the command + * + * @param CommandInterface $command Command that is associated with the iterator + * + * @return string + */ + abstract protected function getClassName(CommandInterface $command); +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Resource/CompositeResourceIteratorFactory.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Resource/CompositeResourceIteratorFactory.php new file mode 100644 index 000000000..2efc133c6 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Resource/CompositeResourceIteratorFactory.php @@ -0,0 +1,67 @@ +factories = $factories; + } + + public function build(CommandInterface $command, array $options = array()) + { + if (!($factory = $this->getFactory($command))) { + throw new InvalidArgumentException('Iterator was not found for ' . $command->getName()); + } + + return $factory->build($command, $options); + } + + public function canBuild(CommandInterface $command) + { + return $this->getFactory($command) !== false; + } + + /** + * Add a factory to the composite factory + * + * @param ResourceIteratorFactoryInterface $factory Factory to add + * + * @return self + */ + public function addFactory(ResourceIteratorFactoryInterface $factory) + { + $this->factories[] = $factory; + + return $this; + } + + /** + * Get the factory that matches the command object + * + * @param CommandInterface $command Command retrieving the iterator for + * + * @return ResourceIteratorFactoryInterface|bool + */ + protected function getFactory(CommandInterface $command) + { + foreach ($this->factories as $factory) { + if ($factory->canBuild($command)) { + return $factory; + } + } + + return false; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Resource/MapResourceIteratorFactory.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Resource/MapResourceIteratorFactory.php new file mode 100644 index 000000000..c71ca9d85 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Resource/MapResourceIteratorFactory.php @@ -0,0 +1,34 @@ +map = $map; + } + + public function getClassName(CommandInterface $command) + { + $className = $command->getName(); + + if (isset($this->map[$className])) { + return $this->map[$className]; + } elseif (isset($this->map['*'])) { + // If a wildcard was added, then always use that + return $this->map['*']; + } + + return null; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Resource/Model.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Resource/Model.php new file mode 100644 index 000000000..2322434a5 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Resource/Model.php @@ -0,0 +1,64 @@ +data = $data; + $this->structure = $structure; + } + + /** + * Get the structure of the model + * + * @return Parameter + */ + public function getStructure() + { + return $this->structure ?: new Parameter(); + } + + /** + * Provides debug information about the model object + * + * @return string + */ + public function __toString() + { + $output = 'Debug output of '; + if ($this->structure) { + $output .= $this->structure->getName() . ' '; + } + $output .= 'model'; + $output = str_repeat('=', strlen($output)) . "\n" . $output . "\n" . str_repeat('=', strlen($output)) . "\n\n"; + $output .= "Model data\n-----------\n\n"; + $output .= "This data can be retrieved from the model object using the get() method of the model " + . "(e.g. \$model->get(\$key)) or accessing the model like an associative array (e.g. \$model['key']).\n\n"; + $lines = array_slice(explode("\n", trim(print_r($this->toArray(), true))), 2, -1); + $output .= implode("\n", $lines); + + if ($this->structure) { + $output .= "\n\nModel structure\n---------------\n\n"; + $output .= "The following JSON document defines how the model was parsed from an HTTP response into the " + . "associative array structure you see above.\n\n"; + $output .= ' ' . json_encode($this->structure->toArray()) . "\n\n"; + } + + return $output . "\n"; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIterator.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIterator.php new file mode 100644 index 000000000..e14152432 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIterator.php @@ -0,0 +1,254 @@ +originalCommand = $command; + + // Parse options from the array of options + $this->data = $data; + $this->limit = array_key_exists('limit', $data) ? $data['limit'] : 0; + $this->pageSize = array_key_exists('page_size', $data) ? $data['page_size'] : false; + } + + /** + * Get all of the resources as an array (Warning: this could issue a large number of requests) + * + * @return array + */ + public function toArray() + { + return iterator_to_array($this, false); + } + + public function setLimit($limit) + { + $this->limit = $limit; + $this->resetState(); + + return $this; + } + + public function setPageSize($pageSize) + { + $this->pageSize = $pageSize; + $this->resetState(); + + return $this; + } + + /** + * Get an option from the iterator + * + * @param string $key Key of the option to retrieve + * + * @return mixed|null Returns NULL if not set or the value if set + */ + public function get($key) + { + return array_key_exists($key, $this->data) ? $this->data[$key] : null; + } + + /** + * Set an option on the iterator + * + * @param string $key Key of the option to set + * @param mixed $value Value to set for the option + * + * @return ResourceIterator + */ + public function set($key, $value) + { + $this->data[$key] = $value; + + return $this; + } + + public function current() + { + return $this->resources ? current($this->resources) : false; + } + + public function key() + { + return max(0, $this->iteratedCount - 1); + } + + public function count() + { + return $this->retrievedCount; + } + + /** + * Get the total number of requests sent + * + * @return int + */ + public function getRequestCount() + { + return $this->requestCount; + } + + /** + * Rewind the Iterator to the first element and send the original command + */ + public function rewind() + { + // Use the original command + $this->command = clone $this->originalCommand; + $this->resetState(); + $this->next(); + } + + public function valid() + { + return !$this->invalid && (!$this->resources || $this->current() || $this->nextToken) + && (!$this->limit || $this->iteratedCount < $this->limit + 1); + } + + public function next() + { + $this->iteratedCount++; + + // Check if a new set of resources needs to be retrieved + $sendRequest = false; + if (!$this->resources) { + $sendRequest = true; + } else { + // iterate over the internal array + $current = next($this->resources); + $sendRequest = $current === false && $this->nextToken && (!$this->limit || $this->iteratedCount < $this->limit + 1); + } + + if ($sendRequest) { + + $this->dispatch('resource_iterator.before_send', array( + 'iterator' => $this, + 'resources' => $this->resources + )); + + // Get a new command object from the original command + $this->command = clone $this->originalCommand; + // Send a request and retrieve the newly loaded resources + $this->resources = $this->sendRequest(); + $this->requestCount++; + + // If no resources were found, then the last request was not needed + // and iteration must stop + if (empty($this->resources)) { + $this->invalid = true; + } else { + // Add to the number of retrieved resources + $this->retrievedCount += count($this->resources); + // Ensure that we rewind to the beginning of the array + reset($this->resources); + } + + $this->dispatch('resource_iterator.after_send', array( + 'iterator' => $this, + 'resources' => $this->resources + )); + } + } + + /** + * Retrieve the NextToken that can be used in other iterators. + * + * @return string Returns a NextToken + */ + public function getNextToken() + { + return $this->nextToken; + } + + /** + * Returns the value that should be specified for the page size for a request that will maintain any hard limits, + * but still honor the specified pageSize if the number of items retrieved + pageSize < hard limit + * + * @return int Returns the page size of the next request. + */ + protected function calculatePageSize() + { + if ($this->limit && $this->iteratedCount + $this->pageSize > $this->limit) { + return 1 + ($this->limit - $this->iteratedCount); + } + + return (int) $this->pageSize; + } + + /** + * Reset the internal state of the iterator without triggering a rewind() + */ + protected function resetState() + { + $this->iteratedCount = 0; + $this->retrievedCount = 0; + $this->nextToken = false; + $this->resources = null; + $this->invalid = false; + } + + /** + * Send a request to retrieve the next page of results. Hook for subclasses to implement. + * + * @return array Returns the newly loaded resources + */ + abstract protected function sendRequest(); +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorApplyBatched.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorApplyBatched.php new file mode 100644 index 000000000..6aa36153f --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorApplyBatched.php @@ -0,0 +1,111 @@ +iterator = $iterator; + $this->callback = $callback; + Version::warn(__CLASS__ . ' is deprecated'); + } + + /** + * Apply the callback to the contents of the resource iterator + * + * @param int $perBatch The number of records to group per batch transfer + * + * @return int Returns the number of iterated resources + */ + public function apply($perBatch = 50) + { + $this->iterated = $this->batches = $batches = 0; + $that = $this; + $it = $this->iterator; + $callback = $this->callback; + + $batch = BatchBuilder::factory() + ->createBatchesWith(new BatchSizeDivisor($perBatch)) + ->transferWith(new BatchClosureTransfer(function (array $batch) use ($that, $callback, &$batches, $it) { + $batches++; + $that->dispatch('iterator_batch.before_batch', array('iterator' => $it, 'batch' => $batch)); + call_user_func_array($callback, array($it, $batch)); + $that->dispatch('iterator_batch.after_batch', array('iterator' => $it, 'batch' => $batch)); + })) + ->autoFlushAt($perBatch) + ->build(); + + $this->dispatch('iterator_batch.created_batch', array('batch' => $batch)); + + foreach ($this->iterator as $resource) { + $this->iterated++; + $batch->add($resource); + } + + $batch->flush(); + $this->batches = $batches; + + return $this->iterated; + } + + /** + * Get the total number of batches sent + * + * @return int + */ + public function getBatchCount() + { + return $this->batches; + } + + /** + * Get the total number of iterated resources + * + * @return int + */ + public function getIteratedCount() + { + return $this->iterated; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorClassFactory.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorClassFactory.php new file mode 100644 index 000000000..2fd998071 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorClassFactory.php @@ -0,0 +1,60 @@ + AbcFoo). + */ +class ResourceIteratorClassFactory extends AbstractResourceIteratorFactory +{ + /** @var array List of namespaces used to look for classes */ + protected $namespaces; + + /** @var InflectorInterface Inflector used to determine class names */ + protected $inflector; + + /** + * @param string|array $namespaces List of namespaces for iterator objects + * @param InflectorInterface $inflector Inflector used to resolve class names + */ + public function __construct($namespaces = array(), InflectorInterface $inflector = null) + { + $this->namespaces = (array) $namespaces; + $this->inflector = $inflector ?: Inflector::getDefault(); + } + + /** + * Registers a namespace to check for Iterators + * + * @param string $namespace Namespace which contains Iterator classes + * + * @return self + */ + public function registerNamespace($namespace) + { + array_unshift($this->namespaces, $namespace); + + return $this; + } + + protected function getClassName(CommandInterface $command) + { + $iteratorName = $this->inflector->camel($command->getName()) . 'Iterator'; + + // Determine the name of the class to load + foreach ($this->namespaces as $namespace) { + $potentialClassName = $namespace . '\\' . $iteratorName; + if (class_exists($potentialClassName)) { + return $potentialClassName; + } + } + + return false; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorFactoryInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorFactoryInterface.php new file mode 100644 index 000000000..8b4e8dbe0 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Service/Resource/ResourceIteratorFactoryInterface.php @@ -0,0 +1,30 @@ +=5.3.2", + "guzzle/cache": "self.version", + "guzzle/http": "self.version", + "guzzle/inflection": "self.version" + }, + "autoload": { + "psr-0": { "Guzzle\\Service": "" } + }, + "target-dir": "Guzzle/Service", + "extra": { + "branch-alias": { + "dev-master": "3.7-dev" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Stream/PhpStreamRequestFactory.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Stream/PhpStreamRequestFactory.php new file mode 100644 index 000000000..d115fd890 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Stream/PhpStreamRequestFactory.php @@ -0,0 +1,284 @@ +contextOptions = stream_context_get_options($context); + $this->context = $context; + } elseif (is_array($context) || !$context) { + $this->contextOptions = $context; + $this->createContext($params); + } elseif ($context) { + throw new InvalidArgumentException('$context must be an array or resource'); + } + + // Dispatch the before send event + $request->dispatch('request.before_send', array( + 'request' => $request, + 'context' => $this->context, + 'context_options' => $this->contextOptions + )); + + $this->setUrl($request); + $this->addDefaultContextOptions($request); + $this->addSslOptions($request); + $this->addBodyOptions($request); + $this->addProxyOptions($request); + + // Create the file handle but silence errors + return $this->createStream($params) + ->setCustomData('request', $request) + ->setCustomData('response_headers', $this->getLastResponseHeaders()); + } + + /** + * Set an option on the context and the internal options array + * + * @param string $wrapper Stream wrapper name of http + * @param string $name Context name + * @param mixed $value Context value + * @param bool $overwrite Set to true to overwrite an existing value + */ + protected function setContextValue($wrapper, $name, $value, $overwrite = false) + { + if (!isset($this->contextOptions[$wrapper])) { + $this->contextOptions[$wrapper] = array($name => $value); + } elseif (!$overwrite && isset($this->contextOptions[$wrapper][$name])) { + return; + } + $this->contextOptions[$wrapper][$name] = $value; + stream_context_set_option($this->context, $wrapper, $name, $value); + } + + /** + * Create a stream context + * + * @param array $params Parameter array + */ + protected function createContext(array $params) + { + $options = $this->contextOptions; + $this->context = $this->createResource(function () use ($params, $options) { + return stream_context_create($options, $params); + }); + } + + /** + * Get the last response headers received by the HTTP request + * + * @return array + */ + public function getLastResponseHeaders() + { + return $this->lastResponseHeaders; + } + + /** + * Adds the default context options to the stream context options + * + * @param RequestInterface $request Request + */ + protected function addDefaultContextOptions(RequestInterface $request) + { + $this->setContextValue('http', 'method', $request->getMethod()); + $headers = $request->getHeaderLines(); + + // "Connection: close" is required to get streams to work in HTTP 1.1 + if (!$request->hasHeader('Connection')) { + $headers[] = 'Connection: close'; + } + + $this->setContextValue('http', 'header', $headers); + $this->setContextValue('http', 'protocol_version', $request->getProtocolVersion()); + $this->setContextValue('http', 'ignore_errors', true); + } + + /** + * Set the URL to use with the factory + * + * @param RequestInterface $request Request that owns the URL + */ + protected function setUrl(RequestInterface $request) + { + $this->url = $request->getUrl(true); + + // Check for basic Auth username + if ($request->getUsername()) { + $this->url->setUsername($request->getUsername()); + } + + // Check for basic Auth password + if ($request->getPassword()) { + $this->url->setPassword($request->getPassword()); + } + } + + /** + * Add SSL options to the stream context + * + * @param RequestInterface $request Request + */ + protected function addSslOptions(RequestInterface $request) + { + if ($request->getCurlOptions()->get(CURLOPT_SSL_VERIFYPEER)) { + $this->setContextValue('ssl', 'verify_peer', true, true); + if ($cafile = $request->getCurlOptions()->get(CURLOPT_CAINFO)) { + $this->setContextValue('ssl', 'cafile', $cafile, true); + } + } else { + $this->setContextValue('ssl', 'verify_peer', false, true); + } + } + + /** + * Add body (content) specific options to the context options + * + * @param RequestInterface $request + */ + protected function addBodyOptions(RequestInterface $request) + { + // Add the content for the request if needed + if (!($request instanceof EntityEnclosingRequestInterface)) { + return; + } + + if (count($request->getPostFields())) { + $this->setContextValue('http', 'content', (string) $request->getPostFields(), true); + } elseif ($request->getBody()) { + $this->setContextValue('http', 'content', (string) $request->getBody(), true); + } + + // Always ensure a content-length header is sent + if (isset($this->contextOptions['http']['content'])) { + $headers = isset($this->contextOptions['http']['header']) ? $this->contextOptions['http']['header'] : array(); + $headers[] = 'Content-Length: ' . strlen($this->contextOptions['http']['content']); + $this->setContextValue('http', 'header', $headers, true); + } + } + + /** + * Add proxy parameters to the context if needed + * + * @param RequestInterface $request Request + */ + protected function addProxyOptions(RequestInterface $request) + { + if ($proxy = $request->getCurlOptions()->get(CURLOPT_PROXY)) { + $this->setContextValue('http', 'proxy', $proxy); + } + } + + /** + * Create the stream for the request with the context options + * + * @param array $params Parameters of the stream + * + * @return StreamInterface + */ + protected function createStream(array $params) + { + $http_response_header = null; + $url = $this->url; + $context = $this->context; + $fp = $this->createResource(function () use ($context, $url, &$http_response_header) { + return fopen((string) $url, 'r', false, $context); + }); + + // Determine the class to instantiate + $className = isset($params['stream_class']) ? $params['stream_class'] : __NAMESPACE__ . '\\Stream'; + + /** @var $stream StreamInterface */ + $stream = new $className($fp); + + // Track the response headers of the request + if (isset($http_response_header)) { + $this->lastResponseHeaders = $http_response_header; + $this->processResponseHeaders($stream); + } + + return $stream; + } + + /** + * Process response headers + * + * @param StreamInterface $stream + */ + protected function processResponseHeaders(StreamInterface $stream) + { + // Set the size on the stream if it was returned in the response + foreach ($this->lastResponseHeaders as $header) { + if ((stripos($header, 'Content-Length:')) === 0) { + $stream->setSize(trim(substr($header, 15))); + } + } + } + + /** + * Create a resource and check to ensure it was created successfully + * + * @param callable $callback Closure to invoke that must return a valid resource + * + * @return resource + * @throws RuntimeException on error + */ + protected function createResource($callback) + { + $errors = null; + set_error_handler(function ($_, $msg, $file, $line) use (&$errors) { + $errors[] = array( + 'message' => $msg, + 'file' => $file, + 'line' => $line + ); + return true; + }); + $resource = call_user_func($callback); + restore_error_handler(); + + if (!$resource) { + $message = 'Error creating resource. '; + foreach ($errors as $err) { + foreach ($err as $key => $value) { + $message .= "[$key] $value" . PHP_EOL; + } + } + throw new RuntimeException(trim($message)); + } + + return $resource; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Stream/Stream.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Stream/Stream.php new file mode 100644 index 000000000..12bed268d --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Stream/Stream.php @@ -0,0 +1,289 @@ + array( + 'r' => true, 'w+' => true, 'r+' => true, 'x+' => true, 'c+' => true, + 'rb' => true, 'w+b' => true, 'r+b' => true, 'x+b' => true, 'c+b' => true, + 'rt' => true, 'w+t' => true, 'r+t' => true, 'x+t' => true, 'c+t' => true, 'a+' => true + ), + 'write' => array( + 'w' => true, 'w+' => true, 'rw' => true, 'r+' => true, 'x+' => true, 'c+' => true, + 'wb' => true, 'w+b' => true, 'r+b' => true, 'x+b' => true, 'c+b' => true, + 'w+t' => true, 'r+t' => true, 'x+t' => true, 'c+t' => true, 'a' => true, 'a+' => true + ) + ); + + /** + * @param resource $stream Stream resource to wrap + * @param int $size Size of the stream in bytes. Only pass if the size cannot be obtained from the stream. + * + * @throws InvalidArgumentException if the stream is not a stream resource + */ + public function __construct($stream, $size = null) + { + $this->setStream($stream, $size); + } + + /** + * Closes the stream when the helper is destructed + */ + public function __destruct() + { + $this->close(); + } + + public function __toString() + { + if (!$this->isReadable() || (!$this->isSeekable() && $this->isConsumed())) { + return ''; + } + + $originalPos = $this->ftell(); + $body = stream_get_contents($this->stream, -1, 0); + $this->seek($originalPos); + + return $body; + } + + public function close() + { + if (is_resource($this->stream)) { + fclose($this->stream); + } + $this->cache[self::IS_READABLE] = false; + $this->cache[self::IS_WRITABLE] = false; + } + + /** + * Calculate a hash of a Stream + * + * @param StreamInterface $stream Stream to calculate the hash for + * @param string $algo Hash algorithm (e.g. md5, crc32, etc) + * @param bool $rawOutput Whether or not to use raw output + * + * @return bool|string Returns false on failure or a hash string on success + */ + public static function getHash(StreamInterface $stream, $algo, $rawOutput = false) + { + $pos = $stream->ftell(); + if (!$stream->seek(0)) { + return false; + } + + $ctx = hash_init($algo); + while (!$stream->feof()) { + hash_update($ctx, $stream->read(8192)); + } + + $out = hash_final($ctx, (bool) $rawOutput); + $stream->seek($pos); + + return $out; + } + + public function getMetaData($key = null) + { + $meta = stream_get_meta_data($this->stream); + + return !$key ? $meta : (array_key_exists($key, $meta) ? $meta[$key] : null); + } + + public function getStream() + { + return $this->stream; + } + + public function setStream($stream, $size = null) + { + if (!is_resource($stream)) { + throw new InvalidArgumentException('Stream must be a resource'); + } + + $this->size = $size; + $this->stream = $stream; + $this->rebuildCache(); + + return $this; + } + + public function detachStream() + { + $this->stream = null; + + return $this; + } + + public function getWrapper() + { + return $this->cache[self::WRAPPER_TYPE]; + } + + public function getWrapperData() + { + return $this->getMetaData('wrapper_data') ?: array(); + } + + public function getStreamType() + { + return $this->cache[self::STREAM_TYPE]; + } + + public function getUri() + { + return $this->cache['uri']; + } + + public function getSize() + { + if ($this->size !== null) { + return $this->size; + } + + // If the stream is a file based stream and local, then use fstat + clearstatcache(true, $this->cache['uri']); + $stats = fstat($this->stream); + if (isset($stats['size'])) { + $this->size = $stats['size']; + return $this->size; + } elseif ($this->cache[self::IS_READABLE] && $this->cache[self::SEEKABLE]) { + // Only get the size based on the content if the the stream is readable and seekable + $pos = $this->ftell(); + $this->size = strlen((string) $this); + $this->seek($pos); + return $this->size; + } + + return false; + } + + public function isReadable() + { + return $this->cache[self::IS_READABLE]; + } + + public function isRepeatable() + { + return $this->cache[self::IS_READABLE] && $this->cache[self::SEEKABLE]; + } + + public function isWritable() + { + return $this->cache[self::IS_WRITABLE]; + } + + public function isConsumed() + { + return feof($this->stream); + } + + public function feof() + { + return $this->isConsumed(); + } + + public function isLocal() + { + return $this->cache[self::IS_LOCAL]; + } + + public function isSeekable() + { + return $this->cache[self::SEEKABLE]; + } + + public function setSize($size) + { + $this->size = $size; + + return $this; + } + + public function seek($offset, $whence = SEEK_SET) + { + return $this->cache[self::SEEKABLE] ? fseek($this->stream, $offset, $whence) === 0 : false; + } + + public function read($length) + { + return fread($this->stream, $length); + } + + public function write($string) + { + // We can't know the size after writing anything + $this->size = null; + + return fwrite($this->stream, $string); + } + + public function ftell() + { + return ftell($this->stream); + } + + public function rewind() + { + return $this->seek(0); + } + + public function readLine($maxLength = null) + { + if (!$this->cache[self::IS_READABLE]) { + return false; + } else { + return $maxLength ? fgets($this->getStream(), $maxLength) : fgets($this->getStream()); + } + } + + public function setCustomData($key, $value) + { + $this->customData[$key] = $value; + + return $this; + } + + public function getCustomData($key) + { + return isset($this->customData[$key]) ? $this->customData[$key] : null; + } + + /** + * Reprocess stream metadata + */ + protected function rebuildCache() + { + $this->cache = stream_get_meta_data($this->stream); + $this->cache[self::IS_LOCAL] = stream_is_local($this->stream); + $this->cache[self::IS_READABLE] = isset(self::$readWriteHash['read'][$this->cache['mode']]); + $this->cache[self::IS_WRITABLE] = isset(self::$readWriteHash['write'][$this->cache['mode']]); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/src/Guzzle/Stream/StreamInterface.php b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Stream/StreamInterface.php new file mode 100644 index 000000000..6d7dc3761 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/src/Guzzle/Stream/StreamInterface.php @@ -0,0 +1,218 @@ +=5.3.2", + "guzzle/common": "self.version" + }, + "suggest": { + "guzzle/http": "To convert Guzzle request objects to PHP streams" + }, + "autoload": { + "psr-0": { "Guzzle\\Stream": "" } + }, + "target-dir": "Guzzle/Stream", + "extra": { + "branch-alias": { + "dev-master": "3.7-dev" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/AbstractBatchDecoratorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/AbstractBatchDecoratorTest.php new file mode 100644 index 000000000..951738d2a --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/AbstractBatchDecoratorTest.php @@ -0,0 +1,33 @@ +getMock('Guzzle\Batch\BatchTransferInterface'), + $this->getMock('Guzzle\Batch\BatchDivisorInterface') + ); + + $decoratorA = $this->getMockBuilder('Guzzle\Batch\AbstractBatchDecorator') + ->setConstructorArgs(array($batch)) + ->getMockForAbstractClass(); + + $decoratorB = $this->getMockBuilder('Guzzle\Batch\AbstractBatchDecorator') + ->setConstructorArgs(array($decoratorA)) + ->getMockForAbstractClass(); + + $decoratorA->add('foo'); + $this->assertFalse($decoratorB->isEmpty()); + $this->assertFalse($batch->isEmpty()); + $this->assertEquals(array($decoratorB, $decoratorA), $decoratorB->getDecorators()); + $this->assertEquals(array(), $decoratorB->flush()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchBuilderTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchBuilderTest.php new file mode 100644 index 000000000..4da09d30e --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchBuilderTest.php @@ -0,0 +1,86 @@ +getMock('Guzzle\Batch\BatchTransferInterface'); + } + + private function getMockDivisor() + { + return $this->getMock('Guzzle\Batch\BatchDivisorInterface'); + } + + private function getMockBatchBuilder() + { + return BatchBuilder::factory() + ->transferWith($this->getMockTransfer()) + ->createBatchesWith($this->getMockDivisor()); + } + + public function testFactoryCreatesInstance() + { + $builder = BatchBuilder::factory(); + $this->assertInstanceOf('Guzzle\Batch\BatchBuilder', $builder); + } + + public function testAddsAutoFlush() + { + $batch = $this->getMockBatchBuilder()->autoFlushAt(10)->build(); + $this->assertInstanceOf('Guzzle\Batch\FlushingBatch', $batch); + } + + public function testAddsExceptionBuffering() + { + $batch = $this->getMockBatchBuilder()->bufferExceptions()->build(); + $this->assertInstanceOf('Guzzle\Batch\ExceptionBufferingBatch', $batch); + } + + public function testAddHistory() + { + $batch = $this->getMockBatchBuilder()->keepHistory()->build(); + $this->assertInstanceOf('Guzzle\Batch\HistoryBatch', $batch); + } + + public function testAddsNotify() + { + $batch = $this->getMockBatchBuilder()->notify(function() {})->build(); + $this->assertInstanceOf('Guzzle\Batch\NotifyingBatch', $batch); + } + + /** + * @expectedException Guzzle\Common\Exception\RuntimeException + */ + public function testTransferStrategyMustBeSet() + { + $batch = BatchBuilder::factory()->createBatchesWith($this->getMockDivisor())->build(); + } + + /** + * @expectedException Guzzle\Common\Exception\RuntimeException + */ + public function testDivisorStrategyMustBeSet() + { + $batch = BatchBuilder::factory()->transferWith($this->getMockTransfer())->build(); + } + + public function testTransfersRequests() + { + $batch = BatchBuilder::factory()->transferRequests(10)->build(); + $this->assertInstanceOf('Guzzle\Batch\BatchRequestTransfer', $this->readAttribute($batch, 'transferStrategy')); + } + + public function testTransfersCommands() + { + $batch = BatchBuilder::factory()->transferCommands(10)->build(); + $this->assertInstanceOf('Guzzle\Batch\BatchCommandTransfer', $this->readAttribute($batch, 'transferStrategy')); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchClosureDivisorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchClosureDivisorTest.php new file mode 100644 index 000000000..753db7dab --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchClosureDivisorTest.php @@ -0,0 +1,36 @@ +createBatches($queue); + $this->assertEquals(array(array('foo'), array('baz')), $batches); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchClosureTransferTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchClosureTransferTest.php new file mode 100644 index 000000000..6ba7ae052 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchClosureTransferTest.php @@ -0,0 +1,52 @@ +itemsTransferred = null; + $itemsTransferred =& $this->itemsTransferred; + + $this->transferStrategy = new BatchClosureTransfer(function (array $batch) use (&$itemsTransferred) { + $itemsTransferred = $batch; + return; + }); + } + + public function testTransfersBatch() + { + $batchedItems = array('foo', 'bar', 'baz'); + $this->transferStrategy->transfer($batchedItems); + + $this->assertEquals($batchedItems, $this->itemsTransferred); + } + + public function testTransferBailsOnEmptyBatch() + { + $batchedItems = array(); + $this->transferStrategy->transfer($batchedItems); + + $this->assertNull($this->itemsTransferred); + } + + /** + * @expectedException Guzzle\Common\Exception\InvalidArgumentException + */ + public function testEnsuresCallableIsCallable() + { + $foo = new BatchClosureTransfer('uh oh!'); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchCommandTransferTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchCommandTransferTest.php new file mode 100644 index 000000000..a04efabbb --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchCommandTransferTest.php @@ -0,0 +1,83 @@ + $command) { + if ($i % 2) { + $command->setClient($client1); + } else { + $command->setClient($client2); + } + $queue[] = $command; + } + + $batch = new BatchCommandTransfer(2); + $this->assertEquals(array( + array($commands[0], $commands[2]), + array($commands[4]), + array($commands[1], $commands[3]) + ), $batch->createBatches($queue)); + } + + /** + * @expectedException Guzzle\Common\Exception\InvalidArgumentException + */ + public function testEnsuresAllItemsAreCommands() + { + $queue = new \SplQueue(); + $queue[] = 'foo'; + $batch = new BatchCommandTransfer(2); + $batch->createBatches($queue); + } + + public function testTransfersBatches() + { + $client = $this->getMockBuilder('Guzzle\Service\Client') + ->setMethods(array('send')) + ->getMock(); + $client->expects($this->once()) + ->method('send'); + $command = new Mc(); + $command->setClient($client); + $batch = new BatchCommandTransfer(2); + $batch->transfer(array($command)); + } + + public function testDoesNotTransfersEmptyBatches() + { + $batch = new BatchCommandTransfer(2); + $batch->transfer(array()); + } + + /** + * @expectedException Guzzle\Service\Exception\InconsistentClientTransferException + */ + public function testEnsuresAllCommandsUseTheSameClient() + { + $batch = new BatchCommandTransfer(2); + $client1 = new Client('http://www.example.com'); + $client2 = new Client('http://www.example.com'); + $command1 = new Mc(); + $command1->setClient($client1); + $command2 = new Mc(); + $command2->setClient($client2); + $batch->transfer(array($command1, $command2)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchRequestTransferTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchRequestTransferTest.php new file mode 100644 index 000000000..dec7bd55e --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchRequestTransferTest.php @@ -0,0 +1,80 @@ +setCurlMulti(new CurlMulti()); + + $client2 = new Client('http://www.example.com'); + $client2->setCurlMulti(new CurlMulti()); + + $request1 = $client1->get(); + $request2 = $client2->get(); + $request3 = $client1->get(); + $request4 = $client2->get(); + $request5 = $client1->get(); + + $queue = new \SplQueue(); + $queue[] = $request1; + $queue[] = $request2; + $queue[] = $request3; + $queue[] = $request4; + $queue[] = $request5; + + $batch = new BatchRequestTransfer(2); + $this->assertEquals(array( + array($request1, $request3), + array($request3), + array($request2, $request4) + ), $batch->createBatches($queue)); + } + + /** + * @expectedException \Guzzle\Common\Exception\InvalidArgumentException + */ + public function testEnsuresAllItemsAreRequests() + { + $queue = new \SplQueue(); + $queue[] = 'foo'; + $batch = new BatchRequestTransfer(2); + $batch->createBatches($queue); + } + + public function testTransfersBatches() + { + $client = new Client('http://127.0.0.1:123'); + $request = $client->get(); + // For some reason... PHP unit clones the request, which emits a request.clone event. This causes the + // 'sorted' property of the event dispatcher to contain an array in the cloned request that is not present in + // the original. + $request->dispatch('request.clone'); + + $multi = $this->getMock('Guzzle\Http\Curl\CurlMultiInterface'); + $client->setCurlMulti($multi); + $multi->expects($this->once()) + ->method('add') + ->with($request); + $multi->expects($this->once()) + ->method('send'); + + $batch = new BatchRequestTransfer(2); + $batch->transfer(array($request)); + } + + public function testDoesNotTransfersEmptyBatches() + { + $batch = new BatchRequestTransfer(2); + $batch->transfer(array()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchSizeDivisorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchSizeDivisorTest.php new file mode 100644 index 000000000..5542228fd --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchSizeDivisorTest.php @@ -0,0 +1,24 @@ +assertEquals(3, $d->getSize()); + $d->setSize(2); + $batches = $d->createBatches($queue); + $this->assertEquals(array(array('foo', 'baz'), array('bar')), $batches); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchTest.php new file mode 100644 index 000000000..296f57aef --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/BatchTest.php @@ -0,0 +1,91 @@ +getMock('Guzzle\Batch\BatchTransferInterface'); + } + + private function getMockDivisor() + { + return $this->getMock('Guzzle\Batch\BatchDivisorInterface'); + } + + public function testAddsItemsToQueue() + { + $batch = new Batch($this->getMockTransfer(), $this->getMockDivisor()); + $this->assertSame($batch, $batch->add('foo')); + $this->assertEquals(1, count($batch)); + } + + public function testFlushReturnsItems() + { + $transfer = $this->getMockTransfer(); + $transfer->expects($this->exactly(2)) + ->method('transfer'); + + $divisor = $this->getMockDivisor(); + $divisor->expects($this->once()) + ->method('createBatches') + ->will($this->returnValue(array(array('foo', 'baz'), array('bar')))); + + $batch = new Batch($transfer, $divisor); + + $batch->add('foo')->add('baz')->add('bar'); + $items = $batch->flush(); + + $this->assertEquals(array('foo', 'baz', 'bar'), $items); + } + + public function testThrowsExceptionContainingTheFailedBatch() + { + $called = 0; + $originalException = new \Exception('Foo!'); + + $transfer = $this->getMockTransfer(); + $transfer->expects($this->exactly(2)) + ->method('transfer') + ->will($this->returnCallback(function () use (&$called, $originalException) { + if (++$called == 2) { + throw $originalException; + } + })); + + $divisor = $this->getMockDivisor(); + $batch = new Batch($transfer, $divisor); + + // PHPunit clones objects before passing them to a callback. + // Horrible hack to get around this! + $queue = $this->readAttribute($batch, 'queue'); + + $divisor->expects($this->once()) + ->method('createBatches') + ->will($this->returnCallback(function ($batch) use ($queue) { + foreach ($queue as $item) { + $items[] = $item; + } + return array_chunk($items, 2); + })); + + $batch->add('foo')->add('baz')->add('bar')->add('bee')->add('boo'); + $this->assertFalse($batch->isEmpty()); + + try { + $items = $batch->flush(); + $this->fail('Expected exception'); + } catch (BatchTransferException $e) { + $this->assertEquals($originalException, $e->getPrevious()); + $this->assertEquals(array('bar', 'bee'), array_values($e->getBatch())); + $this->assertEquals(1, count($batch)); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/ExceptionBufferingBatchTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/ExceptionBufferingBatchTest.php new file mode 100644 index 000000000..fd810b11f --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/ExceptionBufferingBatchTest.php @@ -0,0 +1,45 @@ +getMockBuilder('Guzzle\Batch\BatchTransferInterface') + ->setMethods(array('transfer')) + ->getMock(); + + $d = new BatchSizeDivisor(1); + $batch = new Batch($t, $d); + + $called = 0; + $t->expects($this->exactly(3)) + ->method('transfer') + ->will($this->returnCallback(function ($batch) use (&$called) { + if (++$called === 2) { + throw new \Exception('Foo'); + } + })); + + $decorator = new ExceptionBufferingBatch($batch); + $decorator->add('foo')->add('baz')->add('bar'); + $result = $decorator->flush(); + + $e = $decorator->getExceptions(); + $this->assertEquals(1, count($e)); + $this->assertEquals(array('baz'), $e[0]->getBatch()); + + $decorator->clearExceptions(); + $this->assertEquals(0, count($decorator->getExceptions())); + + $this->assertEquals(array('foo', 'bar'), $result); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/FlushingBatchTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/FlushingBatchTest.php new file mode 100644 index 000000000..9b37a485f --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/FlushingBatchTest.php @@ -0,0 +1,40 @@ +getMock('Guzzle\Batch\BatchTransferInterface', array('transfer')); + $d = $this->getMock('Guzzle\Batch\BatchDivisorInterface', array('createBatches')); + + $batch = new Batch($t, $d); + $queue = $this->readAttribute($batch, 'queue'); + + $d->expects($this->exactly(2)) + ->method('createBatches') + ->will($this->returnCallback(function () use ($queue) { + $items = array(); + foreach ($queue as $item) { + $items[] = $item; + } + return array($items); + })); + + $t->expects($this->exactly(2)) + ->method('transfer'); + + $flush = new FlushingBatch($batch, 3); + $this->assertEquals(3, $flush->getThreshold()); + $flush->setThreshold(2); + $flush->add('foo')->add('baz')->add('bar')->add('bee')->add('boo'); + $this->assertEquals(1, count($flush)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/HistoryBatchTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/HistoryBatchTest.php new file mode 100644 index 000000000..60d6f951a --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/HistoryBatchTest.php @@ -0,0 +1,26 @@ +getMock('Guzzle\Batch\BatchTransferInterface'), + $this->getMock('Guzzle\Batch\BatchDivisorInterface') + ); + + $history = new HistoryBatch($batch); + $history->add('foo')->add('baz'); + $this->assertEquals(array('foo', 'baz'), $history->getHistory()); + $history->clearHistory(); + $this->assertEquals(array(), $history->getHistory()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/NotifyingBatchTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/NotifyingBatchTest.php new file mode 100644 index 000000000..69a89007a --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Batch/NotifyingBatchTest.php @@ -0,0 +1,45 @@ +getMock('Guzzle\Batch\Batch', array('flush'), array( + $this->getMock('Guzzle\Batch\BatchTransferInterface'), + $this->getMock('Guzzle\Batch\BatchDivisorInterface') + )); + + $batch->expects($this->once()) + ->method('flush') + ->will($this->returnValue(array('foo', 'baz'))); + + $data = array(); + $decorator = new NotifyingBatch($batch, function ($batch) use (&$data) { + $data[] = $batch; + }); + + $decorator->add('foo')->add('baz'); + $decorator->flush(); + $this->assertEquals(array(array('foo', 'baz')), $data); + } + + /** + * @expectedException Guzzle\Common\Exception\InvalidArgumentException + */ + public function testEnsuresCallableIsValid() + { + $batch = new Batch( + $this->getMock('Guzzle\Batch\BatchTransferInterface'), + $this->getMock('Guzzle\Batch\BatchDivisorInterface') + ); + $decorator = new NotifyingBatch($batch, 'foo'); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Cache/CacheAdapterFactoryTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Cache/CacheAdapterFactoryTest.php new file mode 100644 index 000000000..c4140a91d --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Cache/CacheAdapterFactoryTest.php @@ -0,0 +1,64 @@ +cache = new ArrayCache(); + $this->adapter = new DoctrineCacheAdapter($this->cache); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testEnsuresConfigIsObject() + { + CacheAdapterFactory::fromCache(array()); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testEnsuresKnownType() + { + CacheAdapterFactory::fromCache(new \stdClass()); + } + + public function cacheProvider() + { + return array( + array(new DoctrineCacheAdapter(new ArrayCache()), 'Guzzle\Cache\DoctrineCacheAdapter'), + array(new ArrayCache(), 'Guzzle\Cache\DoctrineCacheAdapter'), + array(StorageFactory::factory(array('adapter' => 'memory')), 'Guzzle\Cache\Zf2CacheAdapter'), + ); + } + + /** + * @dataProvider cacheProvider + */ + public function testCreatesNullCacheAdapterByDefault($cache, $type) + { + $adapter = CacheAdapterFactory::fromCache($cache); + $this->assertInstanceOf($type, $adapter); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Cache/CacheAdapterTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Cache/CacheAdapterTest.php new file mode 100644 index 000000000..3e30dddc5 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Cache/CacheAdapterTest.php @@ -0,0 +1,68 @@ +cache = new ArrayCache(); + $this->adapter = new DoctrineCacheAdapter($this->cache); + } + + /** + * Cleans up the environment after running a test. + */ + protected function tearDown() + { + $this->adapter = null; + $this->cache = null; + parent::tearDown(); + } + + public function testGetCacheObject() + { + $this->assertEquals($this->cache, $this->adapter->getCacheObject()); + } + + public function testSave() + { + $this->assertTrue($this->adapter->save('test', 'data', 1000)); + } + + public function testFetch() + { + $this->assertTrue($this->adapter->save('test', 'data', 1000)); + $this->assertEquals('data', $this->adapter->fetch('test')); + } + + public function testContains() + { + $this->assertTrue($this->adapter->save('test', 'data', 1000)); + $this->assertTrue($this->adapter->contains('test')); + } + + public function testDelete() + { + $this->assertTrue($this->adapter->save('test', 'data', 1000)); + $this->assertTrue($this->adapter->delete('test')); + $this->assertFalse($this->adapter->contains('test')); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Cache/ClosureCacheAdapterTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Cache/ClosureCacheAdapterTest.php new file mode 100644 index 000000000..12de65b5a --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Cache/ClosureCacheAdapterTest.php @@ -0,0 +1,94 @@ +callables = array( + 'contains' => function($id, $options = array()) use ($that) { + return array_key_exists($id, $that->data); + }, + 'delete' => function($id, $options = array()) use ($that) { + unset($that->data[$id]); + return true; + }, + 'fetch' => function($id, $options = array()) use ($that) { + return array_key_exists($id, $that->data) ? $that->data[$id] : null; + }, + 'save' => function($id, $data, $lifeTime, $options = array()) use ($that) { + $that->data[$id] = $data; + return true; + } + ); + + $this->adapter = new ClosureCacheAdapter($this->callables); + } + + /** + * Cleans up the environment after running a test. + */ + protected function tearDown() + { + $this->cache = null; + $this->callables = null; + parent::tearDown(); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testEnsuresCallablesArePresent() + { + $callables = $this->callables; + unset($callables['delete']); + $cache = new ClosureCacheAdapter($callables); + } + + public function testAllCallablesMustBePresent() + { + $cache = new ClosureCacheAdapter($this->callables); + } + + public function testCachesDataUsingCallables() + { + $this->assertTrue($this->adapter->save('test', 'data', 1000)); + $this->assertEquals('data', $this->adapter->fetch('test')); + } + + public function testChecksIfCacheContainsKeys() + { + $this->adapter->save('test', 'data', 1000); + $this->assertTrue($this->adapter->contains('test')); + $this->assertFalse($this->adapter->contains('foo')); + } + + public function testDeletesFromCacheByKey() + { + $this->adapter->save('test', 'data', 1000); + $this->assertTrue($this->adapter->contains('test')); + $this->adapter->delete('test'); + $this->assertFalse($this->adapter->contains('test')); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Cache/NullCacheAdapterTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Cache/NullCacheAdapterTest.php new file mode 100644 index 000000000..e05df3f78 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Cache/NullCacheAdapterTest.php @@ -0,0 +1,20 @@ +assertEquals(false, $c->contains('foo')); + $this->assertEquals(true, $c->delete('foo')); + $this->assertEquals(false, $c->fetch('foo')); + $this->assertEquals(true, $c->save('foo', 'bar')); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Cache/Zf2CacheAdapterTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Cache/Zf2CacheAdapterTest.php new file mode 100644 index 000000000..9077c12d3 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Cache/Zf2CacheAdapterTest.php @@ -0,0 +1,58 @@ +cache = StorageFactory::factory(array( + 'adapter' => 'memory' + )); + $this->adapter = new Zf2CacheAdapter($this->cache); + } + + /** + * Cleans up the environment after running a test. + */ + protected function tearDown() + { + $this->adapter = null; + $this->cache = null; + parent::tearDown(); + } + + public function testCachesDataUsingCallables() + { + $this->assertTrue($this->adapter->save('test', 'data', 1000)); + $this->assertEquals('data', $this->adapter->fetch('test')); + } + + public function testChecksIfCacheContainsKeys() + { + $this->adapter->save('test', 'data', 1000); + $this->assertTrue($this->adapter->contains('test')); + $this->assertFalse($this->adapter->contains('foo')); + } + + public function testDeletesFromCacheByKey() + { + $this->adapter->save('test', 'data', 1000); + $this->assertTrue($this->adapter->contains('test')); + $this->adapter->delete('test'); + $this->assertFalse($this->adapter->contains('test')); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Common/AbstractHasDispatcherTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Common/AbstractHasDispatcherTest.php new file mode 100644 index 000000000..19d12e6f6 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Common/AbstractHasDispatcherTest.php @@ -0,0 +1,63 @@ +assertEquals(array(), AbstractHasDispatcher::getAllEvents()); + } + + public function testAllowsDispatcherToBeInjected() + { + $d = new EventDispatcher(); + $mock = $this->getMockForAbstractClass('Guzzle\Common\AbstractHasDispatcher'); + $this->assertSame($mock, $mock->setEventDispatcher($d)); + $this->assertSame($d, $mock->getEventDispatcher()); + } + + public function testCreatesDefaultEventDispatcherIfNeeded() + { + $mock = $this->getMockForAbstractClass('Guzzle\Common\AbstractHasDispatcher'); + $this->assertInstanceOf('Symfony\Component\EventDispatcher\EventDispatcher', $mock->getEventDispatcher()); + } + + public function testHelperDispatchesEvents() + { + $data = array(); + $mock = $this->getMockForAbstractClass('Guzzle\Common\AbstractHasDispatcher'); + $mock->getEventDispatcher()->addListener('test', function(Event $e) use (&$data) { + $data = $e->getIterator()->getArrayCopy(); + }); + $mock->dispatch('test', array( + 'param' => 'abc' + )); + $this->assertEquals(array( + 'param' => 'abc', + ), $data); + } + + public function testHelperAttachesSubscribers() + { + $mock = $this->getMockForAbstractClass('Guzzle\Common\AbstractHasDispatcher'); + $subscriber = $this->getMockForAbstractClass('Symfony\Component\EventDispatcher\EventSubscriberInterface'); + + $dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcher') + ->setMethods(array('addSubscriber')) + ->getMock(); + + $dispatcher->expects($this->once()) + ->method('addSubscriber'); + + $mock->setEventDispatcher($dispatcher); + $mock->addSubscriber($subscriber); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Common/CollectionTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Common/CollectionTest.php new file mode 100644 index 000000000..0648a02b8 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Common/CollectionTest.php @@ -0,0 +1,529 @@ +coll = new Collection(); + } + + public function testConstructorCanBeCalledWithNoParams() + { + $this->coll = new Collection(); + $p = $this->coll->getAll(); + $this->assertEmpty($p, '-> Collection must be empty when no data is passed'); + } + + public function testConstructorCanBeCalledWithParams() + { + $testData = array( + 'test' => 'value', + 'test_2' => 'value2' + ); + $this->coll = new Collection($testData); + $this->assertEquals($this->coll->getAll(), $testData, '-> getAll() must return the data passed in the constructor'); + $this->assertEquals($this->coll->getAll(), $this->coll->toArray()); + } + + public function testImplementsIteratorAggregate() + { + $this->coll->set('key', 'value'); + $this->assertInstanceOf('ArrayIterator', $this->coll->getIterator()); + $this->assertEquals(1, count($this->coll)); + $total = 0; + foreach ($this->coll as $key => $value) { + $this->assertEquals('key', $key); + $this->assertEquals('value', $value); + $total++; + } + $this->assertEquals(1, $total); + } + + public function testCanAddValuesToExistingKeysByUsingArray() + { + $this->coll->add('test', 'value1'); + $this->assertEquals($this->coll->getAll(), array('test' => 'value1')); + $this->coll->add('test', 'value2'); + $this->assertEquals($this->coll->getAll(), array('test' => array('value1', 'value2'))); + $this->coll->add('test', 'value3'); + $this->assertEquals($this->coll->getAll(), array('test' => array('value1', 'value2', 'value3'))); + } + + public function testHandlesMergingInDisparateDataSources() + { + $params = array( + 'test' => 'value1', + 'test2' => 'value2', + 'test3' => array('value3', 'value4') + ); + $this->coll->merge($params); + $this->assertEquals($this->coll->getAll(), $params); + + // Pass the same object to itself + $this->assertEquals($this->coll->merge($this->coll), $this->coll); + } + + public function testCanClearAllDataOrSpecificKeys() + { + $this->coll->merge(array( + 'test' => 'value1', + 'test2' => 'value2' + )); + + // Clear a specific parameter by name + $this->coll->remove('test'); + + $this->assertEquals($this->coll->getAll(), array( + 'test2' => 'value2' + )); + + // Clear all parameters + $this->coll->clear(); + + $this->assertEquals($this->coll->getAll(), array()); + } + + public function testGetsValuesByKey() + { + $this->assertNull($this->coll->get('test')); + $this->coll->add('test', 'value'); + $this->assertEquals('value', $this->coll->get('test')); + $this->coll->set('test2', 'v2'); + $this->coll->set('test3', 'v3'); + $this->assertEquals(array( + 'test' => 'value', + 'test2' => 'v2' + ), $this->coll->getAll(array('test', 'test2'))); + } + + public function testProvidesKeys() + { + $this->assertEquals(array(), $this->coll->getKeys()); + $this->coll->merge(array( + 'test1' => 'value1', + 'test2' => 'value2' + )); + $this->assertEquals(array('test1', 'test2'), $this->coll->getKeys()); + // Returns the cached array previously returned + $this->assertEquals(array('test1', 'test2'), $this->coll->getKeys()); + $this->coll->remove('test1'); + $this->assertEquals(array('test2'), $this->coll->getKeys()); + $this->coll->add('test3', 'value3'); + $this->assertEquals(array('test2', 'test3'), $this->coll->getKeys()); + } + + public function testChecksIfHasKey() + { + $this->assertFalse($this->coll->hasKey('test')); + $this->coll->add('test', 'value'); + $this->assertEquals(true, $this->coll->hasKey('test')); + $this->coll->add('test2', 'value2'); + $this->assertEquals(true, $this->coll->hasKey('test')); + $this->assertEquals(true, $this->coll->hasKey('test2')); + $this->assertFalse($this->coll->hasKey('testing')); + $this->assertEquals(false, $this->coll->hasKey('AB-C', 'junk')); + } + + public function testChecksIfHasValue() + { + $this->assertFalse($this->coll->hasValue('value')); + $this->coll->add('test', 'value'); + $this->assertEquals('test', $this->coll->hasValue('value')); + $this->coll->add('test2', 'value2'); + $this->assertEquals('test', $this->coll->hasValue('value')); + $this->assertEquals('test2', $this->coll->hasValue('value2')); + $this->assertFalse($this->coll->hasValue('val')); + } + + public function testCanGetAllValuesByArray() + { + $this->coll->add('foo', 'bar'); + $this->coll->add('tEsT', 'value'); + $this->coll->add('tesTing', 'v2'); + $this->coll->add('key', 'v3'); + $this->assertNull($this->coll->get('test')); + $this->assertEquals(array( + 'foo' => 'bar', + 'tEsT' => 'value', + 'tesTing' => 'v2' + ), $this->coll->getAll(array( + 'foo', 'tesTing', 'tEsT' + ))); + } + + public function testImplementsCount() + { + $data = new Collection(); + $this->assertEquals(0, $data->count()); + $data->add('key', 'value'); + $this->assertEquals(1, count($data)); + $data->add('key', 'value2'); + $this->assertEquals(1, count($data)); + $data->add('key_2', 'value3'); + $this->assertEquals(2, count($data)); + } + + public function testAddParamsByMerging() + { + $params = array( + 'test' => 'value1', + 'test2' => 'value2', + 'test3' => array('value3', 'value4') + ); + + // Add some parameters + $this->coll->merge($params); + + // Add more parameters by merging them in + $this->coll->merge(array( + 'test' => 'another', + 'different_key' => 'new value' + )); + + $this->assertEquals(array( + 'test' => array('value1', 'another'), + 'test2' => 'value2', + 'test3' => array('value3', 'value4'), + 'different_key' => 'new value' + ), $this->coll->getAll()); + } + + public function testAllowsFunctionalFilter() + { + $this->coll->merge(array( + 'fruit' => 'apple', + 'number' => 'ten', + 'prepositions' => array('about', 'above', 'across', 'after'), + 'same_number' => 'ten' + )); + + $filtered = $this->coll->filter(function($key, $value) { + return $value == 'ten'; + }); + + $this->assertNotEquals($filtered, $this->coll); + + $this->assertEquals(array( + 'number' => 'ten', + 'same_number' => 'ten' + ), $filtered->getAll()); + } + + public function testAllowsFunctionalMapping() + { + $this->coll->merge(array( + 'number_1' => 1, + 'number_2' => 2, + 'number_3' => 3 + )); + + $mapped = $this->coll->map(function($key, $value) { + return $value * $value; + }); + + $this->assertNotEquals($mapped, $this->coll); + + $this->assertEquals(array( + 'number_1' => 1, + 'number_2' => 4, + 'number_3' => 9 + ), $mapped->getAll()); + } + + public function testImplementsArrayAccess() + { + $this->coll->merge(array( + 'k1' => 'v1', + 'k2' => 'v2' + )); + + $this->assertTrue($this->coll->offsetExists('k1')); + $this->assertFalse($this->coll->offsetExists('Krull')); + + $this->coll->offsetSet('k3', 'v3'); + $this->assertEquals('v3', $this->coll->offsetGet('k3')); + $this->assertEquals('v3', $this->coll->get('k3')); + + $this->coll->offsetUnset('k1'); + $this->assertFalse($this->coll->offsetExists('k1')); + } + + public function testUsesStaticWhenCreatingNew() + { + $qs = new QueryString(array( + 'a' => 'b', + 'c' => 'd' + )); + + $this->assertInstanceOf('Guzzle\\Http\\QueryString', $qs->map(function($a, $b) {})); + $this->assertInstanceOf('Guzzle\\Common\\Collection', $qs->map(function($a, $b) {}, array(), false)); + + $this->assertInstanceOf('Guzzle\\Http\\QueryString', $qs->filter(function($a, $b) {})); + $this->assertInstanceOf('Guzzle\\Common\\Collection', $qs->filter(function($a, $b) {}, false)); + } + + public function testCanReplaceAllData() + { + $this->assertSame($this->coll, $this->coll->replace(array( + 'a' => '123' + ))); + + $this->assertEquals(array( + 'a' => '123' + ), $this->coll->getAll()); + } + + public function dataProvider() + { + return array( + array('this_is_a_test', '{a}_is_a_{b}', array( + 'a' => 'this', + 'b' => 'test' + )), + array('this_is_a_test', '{abc}_is_a_{0}', array( + 'abc' => 'this', + 0 => 'test' + )), + array('this_is_a_test', '{abc}_is_a_{0}', array( + 'abc' => 'this', + 0 => 'test' + )), + array('this_is_a_test', 'this_is_a_test', array( + 'abc' => 'this' + )), + array('{abc}_is_{not_found}a_{0}', '{abc}_is_{not_found}a_{0}', array()) + ); + } + + /** + * @dataProvider dataProvider + */ + public function testInjectsConfigData($output, $input, $config) + { + $collection = new Collection($config); + $this->assertEquals($output, $collection->inject($input)); + } + + public function testCanSearchByKey() + { + $collection = new Collection(array( + 'foo' => 'bar', + 'BaZ' => 'pho' + )); + + $this->assertEquals('foo', $collection->keySearch('FOO')); + $this->assertEquals('BaZ', $collection->keySearch('baz')); + $this->assertEquals(false, $collection->keySearch('Bar')); + } + + public function testPreparesFromConfig() + { + $c = Collection::fromConfig(array( + 'a' => '123', + 'base_url' => 'http://www.test.com/' + ), array( + 'a' => 'xyz', + 'b' => 'lol' + ), array('a')); + + $this->assertInstanceOf('Guzzle\Common\Collection', $c); + $this->assertEquals(array( + 'a' => '123', + 'b' => 'lol', + 'base_url' => 'http://www.test.com/' + ), $c->getAll()); + + try { + $c = Collection::fromConfig(array(), array(), array('a')); + $this->fail('Exception not throw when missing config'); + } catch (InvalidArgumentException $e) { + } + } + + function falseyDataProvider() + { + return array( + array(false, false), + array(null, null), + array('', ''), + array(array(), array()), + array(0, 0), + ); + } + + /** + * @dataProvider falseyDataProvider + */ + public function testReturnsCorrectData($a, $b) + { + $c = new Collection(array('value' => $a)); + $this->assertSame($b, $c->get('value')); + } + + public function testRetrievesNestedKeysUsingPath() + { + $data = array( + 'foo' => 'bar', + 'baz' => array( + 'mesa' => array( + 'jar' => 'jar' + ) + ) + ); + $collection = new Collection($data); + $this->assertEquals('bar', $collection->getPath('foo')); + $this->assertEquals('jar', $collection->getPath('baz/mesa/jar')); + $this->assertNull($collection->getPath('wewewf')); + $this->assertNull($collection->getPath('baz/mesa/jar/jar')); + } + + public function testFalseyKeysStillDescend() + { + $collection = new Collection(array( + '0' => array( + 'a' => 'jar' + ), + 1 => 'other' + )); + $this->assertEquals('jar', $collection->getPath('0/a')); + $this->assertEquals('other', $collection->getPath('1')); + } + + public function getPathProvider() + { + $data = array( + 'foo' => 'bar', + 'baz' => array( + 'mesa' => array( + 'jar' => 'jar', + 'array' => array('a', 'b', 'c') + ), + 'bar' => array( + 'baz' => 'bam', + 'array' => array('d', 'e', 'f') + ) + ), + 'bam' => array( + array('foo' => 1), + array('foo' => 2), + array('array' => array('h', 'i')) + ) + ); + $c = new Collection($data); + + return array( + // Simple path selectors + array($c, 'foo', 'bar'), + array($c, 'baz', $data['baz']), + array($c, 'bam', $data['bam']), + array($c, 'baz/mesa', $data['baz']['mesa']), + array($c, 'baz/mesa/jar', 'jar'), + // Merge everything two levels under baz + array($c, 'baz/*', array( + 'jar' => 'jar', + 'array' => array_merge($data['baz']['mesa']['array'], $data['baz']['bar']['array']), + 'baz' => 'bam' + )), + // Does not barf on missing keys + array($c, 'fefwfw', null), + // Does not barf when a wildcard does not resolve correctly + array($c, '*/*/*/*/*/wefwfe', array()), + // Allows custom separator + array($c, '*|mesa', $data['baz']['mesa'], '|'), + // Merge all 'array' keys two levels under baz (the trailing * does not hurt the results) + array($c, 'baz/*/array/*', array_merge($data['baz']['mesa']['array'], $data['baz']['bar']['array'])), + // Merge all 'array' keys two levels under baz + array($c, 'baz/*/array', array_merge($data['baz']['mesa']['array'], $data['baz']['bar']['array'])), + array($c, 'baz/mesa/array', $data['baz']['mesa']['array']), + // Having a trailing * does not hurt the results + array($c, 'baz/mesa/array/*', $data['baz']['mesa']['array']), + // Merge of anything one level deep + array($c, '*', array_merge(array('bar'), $data['baz'], $data['bam'])), + // Funky merge of anything two levels deep + array($c, '*/*', array( + 'jar' => 'jar', + 'array' => array('a', 'b', 'c', 'd', 'e', 'f', 'h', 'i'), + 'baz' => 'bam', + 'foo' => array(1, 2) + )), + // Funky merge of all 'array' keys that are two levels deep + array($c, '*/*/array', array('a', 'b', 'c', 'd', 'e', 'f', 'h', 'i')) + ); + } + + /** + * @dataProvider getPathProvider + */ + public function testGetPath(Collection $c, $path, $expected, $separator = '/') + { + $this->assertEquals($expected, $c->getPath($path, $separator)); + } + + public function testOverridesSettings() + { + $c = new Collection(array('foo' => 1, 'baz' => 2, 'bar' => 3)); + $c->overwriteWith(array('foo' => 10, 'bar' => 300)); + $this->assertEquals(array('foo' => 10, 'baz' => 2, 'bar' => 300), $c->getAll()); + } + + public function testOverwriteWithCollection() + { + $c = new Collection(array('foo' => 1, 'baz' => 2, 'bar' => 3)); + $b = new Collection(array('foo' => 10, 'bar' => 300)); + $c->overwriteWith($b); + $this->assertEquals(array('foo' => 10, 'baz' => 2, 'bar' => 300), $c->getAll()); + } + + public function testOverwriteWithTraversable() + { + $c = new Collection(array('foo' => 1, 'baz' => 2, 'bar' => 3)); + $b = new Collection(array('foo' => 10, 'bar' => 300)); + $c->overwriteWith($b->getIterator()); + $this->assertEquals(array('foo' => 10, 'baz' => 2, 'bar' => 300), $c->getAll()); + } + + public function testCanSetNestedPathValueThatDoesNotExist() + { + $c = new Collection(array()); + $c->setPath('foo/bar/baz/123', 'hi'); + $this->assertEquals('hi', $c['foo']['bar']['baz']['123']); + } + + public function testCanSetNestedPathValueThatExists() + { + $c = new Collection(array('foo' => array('bar' => 'test'))); + $c->setPath('foo/bar', 'hi'); + $this->assertEquals('hi', $c['foo']['bar']); + } + + /** + * @expectedException \Guzzle\Common\Exception\RuntimeException + */ + public function testVerifiesNestedPathIsValidAtExactLevel() + { + $c = new Collection(array('foo' => 'bar')); + $c->setPath('foo/bar', 'hi'); + $this->assertEquals('hi', $c['foo']['bar']); + } + + /** + * @expectedException \Guzzle\Common\Exception\RuntimeException + */ + public function testVerifiesThatNestedPathIsValidAtAnyLevel() + { + $c = new Collection(array('foo' => 'bar')); + $c->setPath('foo/bar/baz', 'test'); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Common/EventTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Common/EventTest.php new file mode 100644 index 000000000..5484e1446 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Common/EventTest.php @@ -0,0 +1,62 @@ + '123', + 'other' => '456', + 'event' => 'test.notify' + )); + } + + public function testAllowsParameterInjection() + { + $event = new Event(array( + 'test' => '123' + )); + $this->assertEquals('123', $event['test']); + } + + public function testImplementsArrayAccess() + { + $event = $this->getEvent(); + $this->assertEquals('123', $event['test']); + $this->assertNull($event['foobar']); + + $this->assertTrue($event->offsetExists('test')); + $this->assertFalse($event->offsetExists('foobar')); + + unset($event['test']); + $this->assertFalse($event->offsetExists('test')); + + $event['test'] = 'new'; + $this->assertEquals('new', $event['test']); + } + + public function testImplementsIteratorAggregate() + { + $event = $this->getEvent(); + $this->assertInstanceOf('ArrayIterator', $event->getIterator()); + } + + public function testConvertsToArray() + { + $this->assertEquals(array( + 'test' => '123', + 'other' => '456', + 'event' => 'test.notify' + ), $this->getEvent()->toArray()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Common/Exception/BatchTransferExceptionTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Common/Exception/BatchTransferExceptionTest.php new file mode 100644 index 000000000..c72a2a637 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Common/Exception/BatchTransferExceptionTest.php @@ -0,0 +1,21 @@ +getMock('Guzzle\Batch\BatchTransferInterface'); + $d = $this->getMock('Guzzle\Batch\BatchDivisorInterface'); + $transferException = new BatchTransferException(array('foo'), array(1, 2), $e, $t, $d); + $this->assertEquals(array('foo'), $transferException->getBatch()); + $this->assertSame($t, $transferException->getTransferStrategy()); + $this->assertSame($d, $transferException->getDivisorStrategy()); + $this->assertSame($e, $transferException->getPrevious()); + $this->assertEquals(array(1, 2), $transferException->getTransferredItems()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Common/Exception/ExceptionCollectionTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Common/Exception/ExceptionCollectionTest.php new file mode 100644 index 000000000..2aecf2a06 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Common/Exception/ExceptionCollectionTest.php @@ -0,0 +1,66 @@ +getExceptions(); + $e->add($exceptions[0]); + $e->add($exceptions[1]); + $this->assertContains("(Exception) ./tests/Guzzle/Tests/Common/Exception/ExceptionCollectionTest.php line ", $e->getMessage()); + $this->assertContains(" Test\n\n #0 ./", $e->getMessage()); + $this->assertSame($exceptions[0], $e->getFirst()); + } + + public function testCanSetExceptions() + { + $ex = new \Exception('foo'); + $e = new ExceptionCollection(); + $e->setExceptions(array($ex)); + $this->assertSame($ex, $e->getFirst()); + } + + public function testActsAsArray() + { + $e = new ExceptionCollection(); + $exceptions = $this->getExceptions(); + $e->add($exceptions[0]); + $e->add($exceptions[1]); + $this->assertEquals(2, count($e)); + $this->assertEquals($exceptions, $e->getIterator()->getArrayCopy()); + } + + public function testCanAddSelf() + { + $e1 = new ExceptionCollection(); + $e1->add(new \Exception("Test")); + $e2 = new ExceptionCollection('Meta description!'); + $e2->add(new \Exception("Test 2")); + $e3 = new ExceptionCollection(); + $e3->add(new \Exception('Baz')); + $e2->add($e3); + $e1->add($e2); + $message = $e1->getMessage(); + $this->assertContains("(Exception) ./tests/Guzzle/Tests/Common/Exception/ExceptionCollectionTest.php line ", $message); + $this->assertContains("\n Test\n\n #0 ", $message); + $this->assertContains("\n\n(Guzzle\\Common\\Exception\\ExceptionCollection) ./tests/Guzzle/Tests/Common/Exception/ExceptionCollectionTest.php line ", $message); + $this->assertContains("\n\n Meta description!\n\n", $message); + $this->assertContains(" (Exception) ./tests/Guzzle/Tests/Common/Exception/ExceptionCollectionTest.php line ", $message); + $this->assertContains("\n Test 2\n\n #0 ", $message); + $this->assertContains(" (Exception) ./tests/Guzzle/Tests/Common/Exception/ExceptionCollectionTest.php line ", $message); + $this->assertContains(" Baz\n\n #0", $message); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Common/VersionTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Common/VersionTest.php new file mode 100644 index 000000000..c3a81d1e4 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Common/VersionTest.php @@ -0,0 +1,27 @@ +isRunning()) { + self::$server->flush(); + } else { + self::$server->start(); + } + } + + return self::$server; + } + + /** + * Set the service builder to use for tests + * + * @param ServiceBuilderInterface $builder Service builder + */ + public static function setServiceBuilder(ServiceBuilderInterface $builder) + { + self::$serviceBuilder = $builder; + } + + /** + * Get a service builder object that can be used throughout the service tests + * + * @return ServiceBuilder + */ + public static function getServiceBuilder() + { + if (!self::$serviceBuilder) { + throw new RuntimeException('No service builder has been set via setServiceBuilder()'); + } + + return self::$serviceBuilder; + } + + /** + * Check if an event dispatcher has a subscriber + * + * @param HasDispatcherInterface $dispatcher + * @param EventSubscriberInterface $subscriber + * + * @return bool + */ + protected function hasSubscriber(HasDispatcherInterface $dispatcher, EventSubscriberInterface $subscriber) + { + $class = get_class($subscriber); + $all = array_keys(call_user_func(array($class, 'getSubscribedEvents'))); + + foreach ($all as $i => $event) { + foreach ($dispatcher->getEventDispatcher()->getListeners($event) as $e) { + if ($e[0] === $subscriber) { + unset($all[$i]); + break; + } + } + } + + return count($all) == 0; + } + + /** + * Get a wildcard observer for an event dispatcher + * + * @param HasDispatcherInterface $hasDispatcher + * + * @return MockObserver + */ + public function getWildcardObserver(HasDispatcherInterface $hasDispatcher) + { + $class = get_class($hasDispatcher); + $o = new MockObserver(); + $events = call_user_func(array($class, 'getAllEvents')); + foreach ($events as $event) { + $hasDispatcher->getEventDispatcher()->addListener($event, array($o, 'update')); + } + + return $o; + } + + /** + * Set the mock response base path + * + * @param string $path Path to mock response folder + * + * @return GuzzleTestCase + */ + public static function setMockBasePath($path) + { + self::$mockBasePath = $path; + } + + /** + * Mark a request as being mocked + * + * @param RequestInterface $request + * + * @return self + */ + public function addMockedRequest(RequestInterface $request) + { + $this->requests[] = $request; + + return $this; + } + + /** + * Get all of the mocked requests + * + * @return array + */ + public function getMockedRequests() + { + return $this->requests; + } + + /** + * Get a mock response for a client by mock file name + * + * @param string $path Relative path to the mock response file + * + * @return Response + */ + public function getMockResponse($path) + { + return $path instanceof Response + ? $path + : MockPlugin::getMockFile(self::$mockBasePath . DIRECTORY_SEPARATOR . $path); + } + + /** + * Set a mock response from a mock file on the next client request. + * + * This method assumes that mock response files are located under the + * Command/Mock/ directory of the Service being tested + * (e.g. Unfuddle/Command/Mock/). A mock response is added to the next + * request sent by the client. + * + * @param Client $client Client object to modify + * @param string $paths Path to files within the Mock folder of the service + * + * @return MockPlugin returns the created mock plugin + */ + public function setMockResponse(Client $client, $paths) + { + $this->requests = array(); + $that = $this; + $mock = new MockPlugin(null, true); + $client->getEventDispatcher()->removeSubscriber($mock); + $mock->getEventDispatcher()->addListener('mock.request', function(Event $event) use ($that) { + $that->addMockedRequest($event['request']); + }); + + if ($paths instanceof Response) { + // A single response instance has been specified, create an array with that instance + // as the only element for the following loop to work as expected + $paths = array($paths); + } + + foreach ((array) $paths as $path) { + $mock->addResponse($this->getMockResponse($path)); + } + + $client->getEventDispatcher()->addSubscriber($mock); + + return $mock; + } + + /** + * Compare HTTP headers and use special markup to filter values + * A header prefixed with '!' means it must not exist + * A header prefixed with '_' means it must be ignored + * A header value of '*' means anything after the * will be ignored + * + * @param array $filteredHeaders Array of special headers + * @param array $actualHeaders Array of headers to check against + * + * @return array|bool Returns an array of the differences or FALSE if none + */ + public function compareHeaders($filteredHeaders, $actualHeaders) + { + $comparison = new HeaderComparison(); + + return $comparison->compare($filteredHeaders, $actualHeaders); + } + + /** + * Case insensitive assertContains + * + * @param string $needle Search string + * @param string $haystack Search this + * @param string $message Optional failure message + */ + public function assertContainsIns($needle, $haystack, $message = null) + { + $this->assertContains(strtolower($needle), strtolower($haystack), $message); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/AbstractEntityBodyDecoratorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/AbstractEntityBodyDecoratorTest.php new file mode 100644 index 000000000..20feaa875 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/AbstractEntityBodyDecoratorTest.php @@ -0,0 +1,34 @@ +getMockForAbstractClass('Guzzle\Http\AbstractEntityBodyDecorator', array($e)); + + $this->assertSame($e->getStream(), $mock->getStream()); + $this->assertSame($e->getContentLength(), $mock->getContentLength()); + $this->assertSame($e->getSize(), $mock->getSize()); + $this->assertSame($e->getContentMd5(), $mock->getContentMd5()); + $this->assertSame($e->getContentType(), $mock->getContentType()); + $this->assertSame($e->__toString(), $mock->__toString()); + $this->assertSame($e->getUri(), $mock->getUri()); + $this->assertSame($e->getStreamType(), $mock->getStreamType()); + $this->assertSame($e->getWrapper(), $mock->getWrapper()); + $this->assertSame($e->getWrapperData(), $mock->getWrapperData()); + $this->assertSame($e->isReadable(), $mock->isReadable()); + $this->assertSame($e->isWritable(), $mock->isWritable()); + $this->assertSame($e->isConsumed(), $mock->isConsumed()); + $this->assertSame($e->isLocal(), $mock->isLocal()); + $this->assertSame($e->isSeekable(), $mock->isSeekable()); + $this->assertSame($e->getContentEncoding(), $mock->getContentEncoding()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/CachingEntityBodyTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/CachingEntityBodyTest.php new file mode 100644 index 000000000..e6e6cdbf5 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/CachingEntityBodyTest.php @@ -0,0 +1,249 @@ +decorated = EntityBody::factory('testing'); + $this->body = new CachingEntityBody($this->decorated); + } + + public function testUsesRemoteSizeIfPossible() + { + $body = EntityBody::factory('test'); + $caching = new CachingEntityBody($body); + $this->assertEquals(4, $caching->getSize()); + $this->assertEquals(4, $caching->getContentLength()); + } + + /** + * @expectedException \Guzzle\Common\Exception\RuntimeException + * @expectedExceptionMessage does not support custom stream rewind + */ + public function testDoesNotAllowRewindFunction() + { + $this->body->setRewindFunction(true); + } + + /** + * @expectedException \Guzzle\Common\Exception\RuntimeException + * @expectedExceptionMessage Cannot seek to byte 10 + */ + public function testCannotSeekPastWhatHasBeenRead() + { + $this->body->seek(10); + } + + /** + * @expectedException \Guzzle\Common\Exception\RuntimeException + * @expectedExceptionMessage supports only SEEK_SET and SEEK_CUR + */ + public function testCannotUseSeekEnd() + { + $this->body->seek(2, SEEK_END); + } + + public function testChangingUnderlyingStreamUpdatesSizeAndStream() + { + $size = filesize(__FILE__); + $s = fopen(__FILE__, 'r'); + $this->body->setStream($s, $size); + $this->assertEquals($size, $this->body->getSize()); + $this->assertEquals($size, $this->decorated->getSize()); + $this->assertSame($s, $this->body->getStream()); + $this->assertSame($s, $this->decorated->getStream()); + } + + public function testRewindUsesSeek() + { + $a = EntityBody::factory('foo'); + $d = $this->getMockBuilder('Guzzle\Http\CachingEntityBody') + ->setMethods(array('seek')) + ->setConstructorArgs(array($a)) + ->getMock(); + $d->expects($this->once()) + ->method('seek') + ->with(0) + ->will($this->returnValue(true)); + $d->rewind(); + } + + public function testCanSeekToReadBytes() + { + $this->assertEquals('te', $this->body->read(2)); + $this->body->seek(0); + $this->assertEquals('test', $this->body->read(4)); + $this->assertEquals(4, $this->body->ftell()); + $this->body->seek(2); + $this->assertEquals(2, $this->body->ftell()); + $this->body->seek(2, SEEK_CUR); + $this->assertEquals(4, $this->body->ftell()); + $this->assertEquals('ing', $this->body->read(3)); + } + + public function testWritesToBufferStream() + { + $this->body->read(2); + $this->body->write('hi'); + $this->body->rewind(); + $this->assertEquals('tehiing', (string) $this->body); + } + + public function testReadLinesFromBothStreams() + { + $this->body->seek($this->body->ftell()); + $this->body->write("test\n123\nhello\n1234567890\n"); + $this->body->rewind(); + $this->assertEquals("test\n", $this->body->readLine(7)); + $this->assertEquals("123\n", $this->body->readLine(7)); + $this->assertEquals("hello\n", $this->body->readLine(7)); + $this->assertEquals("123456", $this->body->readLine(7)); + $this->assertEquals("7890\n", $this->body->readLine(7)); + // We overwrote the decorated stream, so no more data + $this->assertEquals('', $this->body->readLine(7)); + } + + public function testSkipsOverwrittenBytes() + { + $decorated = EntityBody::factory( + implode("\n", array_map(function ($n) { + return str_pad($n, 4, '0', STR_PAD_LEFT); + }, range(0, 25))) + ); + + $body = new CachingEntityBody($decorated); + + $this->assertEquals("0000\n", $body->readLine()); + $this->assertEquals("0001\n", $body->readLine()); + // Write over part of the body yet to be read, so skip some bytes + $this->assertEquals(5, $body->write("TEST\n")); + $this->assertEquals(5, $this->readAttribute($body, 'skipReadBytes')); + // Read, which skips bytes, then reads + $this->assertEquals("0003\n", $body->readLine()); + $this->assertEquals(0, $this->readAttribute($body, 'skipReadBytes')); + $this->assertEquals("0004\n", $body->readLine()); + $this->assertEquals("0005\n", $body->readLine()); + + // Overwrite part of the cached body (so don't skip any bytes) + $body->seek(5); + $this->assertEquals(5, $body->write("ABCD\n")); + $this->assertEquals(0, $this->readAttribute($body, 'skipReadBytes')); + $this->assertEquals("TEST\n", $body->readLine()); + $this->assertEquals("0003\n", $body->readLine()); + $this->assertEquals("0004\n", $body->readLine()); + $this->assertEquals("0005\n", $body->readLine()); + $this->assertEquals("0006\n", $body->readLine()); + $this->assertEquals(5, $body->write("1234\n")); + $this->assertEquals(5, $this->readAttribute($body, 'skipReadBytes')); + + // Seek to 0 and ensure the overwritten bit is replaced + $body->rewind(); + $this->assertEquals("0000\nABCD\nTEST\n0003\n0004\n0005\n0006\n1234\n0008\n0009\n", $body->read(50)); + + // Ensure that casting it to a string does not include the bit that was overwritten + $this->assertContains("0000\nABCD\nTEST\n0003\n0004\n0005\n0006\n1234\n0008\n0009\n", (string) $body); + } + + public function testWrapsContentType() + { + $a = $this->getMockBuilder('Guzzle\Http\EntityBody') + ->setMethods(array('getContentType')) + ->setConstructorArgs(array(fopen(__FILE__, 'r'))) + ->getMock(); + $a->expects($this->once()) + ->method('getContentType') + ->will($this->returnValue('foo')); + $d = new CachingEntityBody($a); + $this->assertEquals('foo', $d->getContentType()); + } + + public function testWrapsContentEncoding() + { + $a = $this->getMockBuilder('Guzzle\Http\EntityBody') + ->setMethods(array('getContentEncoding')) + ->setConstructorArgs(array(fopen(__FILE__, 'r'))) + ->getMock(); + $a->expects($this->once()) + ->method('getContentEncoding') + ->will($this->returnValue('foo')); + $d = new CachingEntityBody($a); + $this->assertEquals('foo', $d->getContentEncoding()); + } + + public function testWrapsMetadata() + { + $a = $this->getMockBuilder('Guzzle\Http\EntityBody') + ->setMethods(array('getMetadata', 'getWrapper', 'getWrapperData', 'getStreamType', 'getUri')) + ->setConstructorArgs(array(fopen(__FILE__, 'r'))) + ->getMock(); + + $a->expects($this->once()) + ->method('getMetadata') + ->will($this->returnValue(array())); + // Called twice for getWrapper and getWrapperData + $a->expects($this->exactly(1)) + ->method('getWrapper') + ->will($this->returnValue('wrapper')); + $a->expects($this->once()) + ->method('getWrapperData') + ->will($this->returnValue(array())); + $a->expects($this->once()) + ->method('getStreamType') + ->will($this->returnValue('baz')); + $a->expects($this->once()) + ->method('getUri') + ->will($this->returnValue('path/to/foo')); + + $d = new CachingEntityBody($a); + $this->assertEquals(array(), $d->getMetaData()); + $this->assertEquals('wrapper', $d->getWrapper()); + $this->assertEquals(array(), $d->getWrapperData()); + $this->assertEquals('baz', $d->getStreamType()); + $this->assertEquals('path/to/foo', $d->getUri()); + } + + public function testWrapsCustomData() + { + $a = $this->getMockBuilder('Guzzle\Http\EntityBody') + ->setMethods(array('getCustomData', 'setCustomData')) + ->setConstructorArgs(array(fopen(__FILE__, 'r'))) + ->getMock(); + + $a->expects($this->exactly(1)) + ->method('getCustomData') + ->with('foo') + ->will($this->returnValue('bar')); + + $a->expects($this->exactly(1)) + ->method('setCustomData') + ->with('foo', 'bar') + ->will($this->returnSelf()); + + $d = new CachingEntityBody($a); + $this->assertSame($d, $d->setCustomData('foo', 'bar')); + $this->assertEquals('bar', $d->getCustomData('foo')); + } + + public function testClosesBothStreams() + { + $s = fopen('php://temp', 'r'); + $a = EntityBody::factory($s); + $d = new CachingEntityBody($a); + $d->close(); + $this->assertFalse(is_resource($s)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/ClientTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/ClientTest.php new file mode 100644 index 000000000..4a91a18f9 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/ClientTest.php @@ -0,0 +1,601 @@ +assertEquals('http://www.google.com/', $client->getBaseUrl()); + $this->assertSame($client, $client->setConfig(array( + 'test' => '123' + ))); + $this->assertEquals(array('test' => '123'), $client->getConfig()->getAll()); + $this->assertEquals('123', $client->getConfig('test')); + $this->assertSame($client, $client->setBaseUrl('http://www.test.com/{test}')); + $this->assertEquals('http://www.test.com/123', $client->getBaseUrl()); + $this->assertEquals('http://www.test.com/{test}', $client->getBaseUrl(false)); + + try { + $client->setConfig(false); + } catch (\InvalidArgumentException $e) { + } + } + + public function testDescribesEvents() + { + $this->assertEquals(array('client.create_request'), Client::getAllEvents()); + } + + public function testConstructorCanAcceptConfig() + { + $client = new Client('http://www.test.com/', array( + 'data' => '123' + )); + $this->assertEquals('123', $client->getConfig('data')); + } + + public function testCanUseCollectionAsConfig() + { + $client = new Client('http://www.google.com/'); + $client->setConfig(new Collection(array( + 'api' => 'v1', + 'key' => 'value', + 'base_url' => 'http://www.google.com/' + ))); + $this->assertEquals('v1', $client->getConfig('api')); + } + + public function testExpandsUriTemplatesUsingConfig() + { + $client = new Client('http://www.google.com/'); + $client->setConfig(array('api' => 'v1', 'key' => 'value', 'foo' => 'bar')); + $ref = new \ReflectionMethod($client, 'expandTemplate'); + $ref->setAccessible(true); + $this->assertEquals('Testing...api/v1/key/value', $ref->invoke($client, 'Testing...api/{api}/key/{key}')); + } + + public function testClientAttachersObserversToRequests() + { + $this->getServer()->flush(); + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + + $client = new Client($this->getServer()->getUrl()); + $logPlugin = $this->getLogPlugin(); + $client->getEventDispatcher()->addSubscriber($logPlugin); + + // Get a request from the client and ensure the the observer was + // attached to the new request + $request = $client->createRequest(); + $this->assertTrue($this->hasSubscriber($request, $logPlugin)); + } + + public function testClientReturnsValidBaseUrls() + { + $client = new Client('http://www.{foo}.{data}/', array( + 'data' => '123', + 'foo' => 'bar' + )); + $this->assertEquals('http://www.bar.123/', $client->getBaseUrl()); + $client->setBaseUrl('http://www.google.com/'); + $this->assertEquals('http://www.google.com/', $client->getBaseUrl()); + } + + public function testClientAddsCurlOptionsToRequests() + { + $client = new Client('http://www.test.com/', array( + 'api' => 'v1', + // Adds the option using the curl values + 'curl.options' => array( + 'CURLOPT_HTTPAUTH' => 'CURLAUTH_DIGEST', + 'abc' => 'foo', + 'blacklist' => 'abc', + 'debug' => true + ) + )); + + $request = $client->createRequest(); + $options = $request->getCurlOptions(); + $this->assertEquals(CURLAUTH_DIGEST, $options->get(CURLOPT_HTTPAUTH)); + $this->assertEquals('foo', $options->get('abc')); + $this->assertEquals('abc', $options->get('blacklist')); + } + + public function testClientAllowsFineGrainedSslControlButIsSecureByDefault() + { + $client = new Client('https://www.secure.com/'); + + // secure by default + $request = $client->createRequest(); + $options = $request->getCurlOptions(); + $this->assertTrue($options->get(CURLOPT_SSL_VERIFYPEER)); + + // set a capath if you prefer + $client = new Client('https://www.secure.com/'); + $client->setSslVerification(__DIR__); + $request = $client->createRequest(); + $options = $request->getCurlOptions(); + $this->assertSame(__DIR__, $options->get(CURLOPT_CAPATH)); + } + + public function testConfigSettingsControlSslConfiguration() + { + // Use the default ca certs on the system + $client = new Client('https://www.secure.com/', array('ssl.certificate_authority' => 'system')); + $this->assertNull($client->getConfig('curl.options')); + // Can set the cacert value as well + $client = new Client('https://www.secure.com/', array('ssl.certificate_authority' => false)); + $options = $client->getConfig('curl.options'); + $this->assertArrayNotHasKey(CURLOPT_CAINFO, $options); + $this->assertSame(false, $options[CURLOPT_SSL_VERIFYPEER]); + $this->assertSame(0, $options[CURLOPT_SSL_VERIFYHOST]); + } + + public function testClientAllowsUnsafeOperationIfRequested() + { + // be really unsafe if you insist + $client = new Client('https://www.secure.com/', array( + 'api' => 'v1' + )); + + $client->setSslVerification(false); + $request = $client->createRequest(); + $options = $request->getCurlOptions(); + $this->assertFalse($options->get(CURLOPT_SSL_VERIFYPEER)); + $this->assertNull($options->get(CURLOPT_CAINFO)); + } + + /** + * @expectedException \Guzzle\Common\Exception\RuntimeException + */ + public function testThrowsExceptionForInvalidCertificate() + { + $client = new Client('https://www.secure.com/'); + $client->setSslVerification('/path/to/missing/file'); + } + + public function testClientAllowsSettingSpecificSslCaInfo() + { + // set a file other than the provided cacert.pem + $client = new Client('https://www.secure.com/', array( + 'api' => 'v1' + )); + + $client->setSslVerification(__FILE__); + $request = $client->createRequest(); + $options = $request->getCurlOptions(); + $this->assertSame(__FILE__, $options->get(CURLOPT_CAINFO)); + } + + /** + * @expectedException Guzzle\Common\Exception\InvalidArgumentException + */ + public function testClientPreventsInadvertentInsecureVerifyHostSetting() + { + // set a file other than the provided cacert.pem + $client = new Client('https://www.secure.com/', array( + 'api' => 'v1' + )); + $client->setSslVerification(__FILE__, true, true); + } + + /** + * @expectedException Guzzle\Common\Exception\InvalidArgumentException + */ + public function testClientPreventsInvalidVerifyPeerSetting() + { + // set a file other than the provided cacert.pem + $client = new Client('https://www.secure.com/', array( + 'api' => 'v1' + )); + $client->setSslVerification(__FILE__, 'yes'); + } + + public function testClientAddsParamsToRequests() + { + Version::$emitWarnings = false; + $client = new Client('http://www.example.com', array( + 'api' => 'v1', + 'request.params' => array( + 'foo' => 'bar', + 'baz' => 'jar' + ) + )); + $request = $client->createRequest(); + $this->assertEquals('bar', $request->getParams()->get('foo')); + $this->assertEquals('jar', $request->getParams()->get('baz')); + Version::$emitWarnings = true; + } + + public function urlProvider() + { + $u = $this->getServer()->getUrl() . 'base/'; + $u2 = $this->getServer()->getUrl() . 'base?z=1'; + return array( + array($u, '', $u), + array($u, 'relative/path/to/resource', $u . 'relative/path/to/resource'), + array($u, 'relative/path/to/resource?a=b&c=d', $u . 'relative/path/to/resource?a=b&c=d'), + array($u, '/absolute/path/to/resource', $this->getServer()->getUrl() . 'absolute/path/to/resource'), + array($u, '/absolute/path/to/resource?a=b&c=d', $this->getServer()->getUrl() . 'absolute/path/to/resource?a=b&c=d'), + array($u2, '/absolute/path/to/resource?a=b&c=d', $this->getServer()->getUrl() . 'absolute/path/to/resource?a=b&c=d&z=1'), + array($u2, 'relative/path/to/resource', $this->getServer()->getUrl() . 'base/relative/path/to/resource?z=1'), + array($u2, 'relative/path/to/resource?another=query', $this->getServer()->getUrl() . 'base/relative/path/to/resource?another=query&z=1') + ); + } + + /** + * @dataProvider urlProvider + */ + public function testBuildsRelativeUrls($baseUrl, $url, $result) + { + $client = new Client($baseUrl); + $this->assertEquals($result, $client->get($url)->getUrl()); + } + + public function testAllowsConfigsToBeChangedAndInjectedInBaseUrl() + { + $client = new Client('http://{a}/{b}'); + $this->assertEquals('http:///', $client->getBaseUrl()); + $this->assertEquals('http://{a}/{b}', $client->getBaseUrl(false)); + $client->setConfig(array( + 'a' => 'test.com', + 'b' => 'index.html' + )); + $this->assertEquals('http://test.com/index.html', $client->getBaseUrl()); + } + + public function testCreatesRequestsWithDefaultValues() + { + $client = new Client($this->getServer()->getUrl() . 'base'); + + // Create a GET request + $request = $client->createRequest(); + $this->assertEquals('GET', $request->getMethod()); + $this->assertEquals($client->getBaseUrl(), $request->getUrl()); + + // Create a DELETE request + $request = $client->createRequest('DELETE'); + $this->assertEquals('DELETE', $request->getMethod()); + $this->assertEquals($client->getBaseUrl(), $request->getUrl()); + + // Create a HEAD request with custom headers + $request = $client->createRequest('HEAD', 'http://www.test.com/'); + $this->assertEquals('HEAD', $request->getMethod()); + $this->assertEquals('http://www.test.com/', $request->getUrl()); + + // Create a PUT request + $request = $client->createRequest('PUT'); + $this->assertEquals('PUT', $request->getMethod()); + + // Create a PUT request with injected config + $client->getConfig()->set('a', 1)->set('b', 2); + $request = $client->createRequest('PUT', '/path/{a}?q={b}'); + $this->assertEquals($request->getUrl(), $this->getServer()->getUrl() . 'path/1?q=2'); + } + + public function testClientHasHelperMethodsForCreatingRequests() + { + $url = $this->getServer()->getUrl(); + $client = new Client($url . 'base'); + $this->assertEquals('GET', $client->get()->getMethod()); + $this->assertEquals('PUT', $client->put()->getMethod()); + $this->assertEquals('POST', $client->post()->getMethod()); + $this->assertEquals('HEAD', $client->head()->getMethod()); + $this->assertEquals('DELETE', $client->delete()->getMethod()); + $this->assertEquals('OPTIONS', $client->options()->getMethod()); + $this->assertEquals('PATCH', $client->patch()->getMethod()); + $this->assertEquals($url . 'base/abc', $client->get('abc')->getUrl()); + $this->assertEquals($url . 'zxy', $client->put('/zxy')->getUrl()); + $this->assertEquals($url . 'zxy?a=b', $client->post('/zxy?a=b')->getUrl()); + $this->assertEquals($url . 'base?a=b', $client->head('?a=b')->getUrl()); + $this->assertEquals($url . 'base?a=b', $client->delete('/base?a=b')->getUrl()); + } + + public function testClientInjectsConfigsIntoUrls() + { + $client = new Client('http://www.test.com/api/v1', array( + 'test' => '123' + )); + $request = $client->get('relative/{test}'); + $this->assertEquals('http://www.test.com/api/v1/relative/123', $request->getUrl()); + } + + public function testAllowsEmptyBaseUrl() + { + $client = new Client(); + $request = $client->get('http://www.google.com/'); + $this->assertEquals('http://www.google.com/', $request->getUrl()); + $request->setResponse(new Response(200), true); + $request->send(); + } + + public function testAllowsCustomCurlMultiObjects() + { + $mock = $this->getMock('Guzzle\\Http\\Curl\\CurlMulti', array('add', 'send')); + $mock->expects($this->once()) + ->method('add') + ->will($this->returnSelf()); + $mock->expects($this->once()) + ->method('send') + ->will($this->returnSelf()); + + $client = new Client(); + $client->setCurlMulti($mock); + + $request = $client->get(); + $request->setResponse(new Response(200), true); + $client->send($request); + } + + public function testClientSendsMultipleRequests() + { + $client = new Client($this->getServer()->getUrl()); + $mock = new MockPlugin(); + + $responses = array( + new Response(200), + new Response(201), + new Response(202) + ); + + $mock->addResponse($responses[0]); + $mock->addResponse($responses[1]); + $mock->addResponse($responses[2]); + + $client->getEventDispatcher()->addSubscriber($mock); + + $requests = array( + $client->get(), + $client->head(), + $client->put('/', null, 'test') + ); + + $this->assertEquals(array( + $responses[0], + $responses[1], + $responses[2] + ), $client->send($requests)); + } + + public function testClientSendsSingleRequest() + { + $client = new Client($this->getServer()->getUrl()); + $mock = new MockPlugin(); + $response = new Response(200); + $mock->addResponse($response); + $client->getEventDispatcher()->addSubscriber($mock); + $this->assertEquals($response, $client->send($client->get())); + } + + /** + * @expectedException \Guzzle\Http\Exception\BadResponseException + */ + public function testClientThrowsExceptionForSingleRequest() + { + $client = new Client($this->getServer()->getUrl()); + $mock = new MockPlugin(); + $response = new Response(404); + $mock->addResponse($response); + $client->getEventDispatcher()->addSubscriber($mock); + $client->send($client->get()); + } + + /** + * @expectedException \Guzzle\Common\Exception\ExceptionCollection + */ + public function testClientThrowsExceptionForMultipleRequests() + { + $client = new Client($this->getServer()->getUrl()); + $mock = new MockPlugin(); + $mock->addResponse(new Response(200)); + $mock->addResponse(new Response(404)); + $client->getEventDispatcher()->addSubscriber($mock); + $client->send(array($client->get(), $client->head())); + } + + public function testQueryStringsAreNotDoubleEncoded() + { + $client = new Client('http://test.com', array( + 'path' => array('foo', 'bar'), + 'query' => 'hi there', + 'data' => array( + 'test' => 'a&b' + ) + )); + + $request = $client->get('{/path*}{?query,data*}'); + $this->assertEquals('http://test.com/foo/bar?query=hi%20there&test=a%26b', $request->getUrl()); + $this->assertEquals('hi there', $request->getQuery()->get('query')); + $this->assertEquals('a&b', $request->getQuery()->get('test')); + } + + public function testQueryStringsAreNotDoubleEncodedUsingAbsolutePaths() + { + $client = new Client('http://test.com', array( + 'path' => array('foo', 'bar'), + 'query' => 'hi there', + )); + $request = $client->get('http://test.com{?query}'); + $this->assertEquals('http://test.com?query=hi%20there', $request->getUrl()); + $this->assertEquals('hi there', $request->getQuery()->get('query')); + } + + public function testAllowsUriTemplateInjection() + { + $client = new Client('http://test.com'); + $ref = new \ReflectionMethod($client, 'getUriTemplate'); + $ref->setAccessible(true); + $a = $ref->invoke($client); + $this->assertSame($a, $ref->invoke($client)); + $client->setUriTemplate(new UriTemplate()); + $this->assertNotSame($a, $ref->invoke($client)); + } + + public function testAllowsCustomVariablesWhenExpandingTemplates() + { + $client = new Client('http://test.com', array('test' => 'hi')); + $ref = new \ReflectionMethod($client, 'expandTemplate'); + $ref->setAccessible(true); + $uri = $ref->invoke($client, 'http://{test}{?query*}', array('query' => array('han' => 'solo'))); + $this->assertEquals('http://hi?han=solo', $uri); + } + + public function testUriArrayAllowsCustomTemplateVariables() + { + $client = new Client(); + $vars = array( + 'var' => 'hi' + ); + $this->assertEquals('/hi', (string) $client->createRequest('GET', array('/{var}', $vars))->getUrl()); + $this->assertEquals('/hi', (string) $client->get(array('/{var}', $vars))->getUrl()); + $this->assertEquals('/hi', (string) $client->put(array('/{var}', $vars))->getUrl()); + $this->assertEquals('/hi', (string) $client->post(array('/{var}', $vars))->getUrl()); + $this->assertEquals('/hi', (string) $client->head(array('/{var}', $vars))->getUrl()); + $this->assertEquals('/hi', (string) $client->options(array('/{var}', $vars))->getUrl()); + } + + public function testAllowsDefaultHeaders() + { + Version::$emitWarnings = false; + $default = array('X-Test' => 'Hi!'); + $other = array('X-Other' => 'Foo'); + + $client = new Client(); + $client->setDefaultHeaders($default); + $this->assertEquals($default, $client->getDefaultHeaders()->getAll()); + $client->setDefaultHeaders(new Collection($default)); + $this->assertEquals($default, $client->getDefaultHeaders()->getAll()); + + $request = $client->createRequest('GET', null, $other); + $this->assertEquals('Hi!', $request->getHeader('X-Test')); + $this->assertEquals('Foo', $request->getHeader('X-Other')); + + $request = $client->createRequest('GET', null, new Collection($other)); + $this->assertEquals('Hi!', $request->getHeader('X-Test')); + $this->assertEquals('Foo', $request->getHeader('X-Other')); + + $request = $client->createRequest('GET'); + $this->assertEquals('Hi!', $request->getHeader('X-Test')); + Version::$emitWarnings = true; + } + + public function testDontReuseCurlMulti() + { + $client1 = new Client(); + $client2 = new Client(); + $this->assertNotSame($client1->getCurlMulti(), $client2->getCurlMulti()); + } + + public function testGetDefaultUserAgent() + { + $client = new Client(); + $agent = $this->readAttribute($client, 'userAgent'); + $version = curl_version(); + $testAgent = sprintf('Guzzle/%s curl/%s PHP/%s', Version::VERSION, $version['version'], PHP_VERSION); + $this->assertEquals($agent, $testAgent); + + $client->setUserAgent('foo'); + $this->assertEquals('foo', $this->readAttribute($client, 'userAgent')); + } + + public function testOverwritesUserAgent() + { + $client = new Client(); + $request = $client->createRequest('GET', 'http://www.foo.com', array('User-agent' => 'foo')); + $this->assertEquals('foo', (string) $request->getHeader('User-Agent')); + } + + public function testUsesDefaultUserAgent() + { + $client = new Client(); + $request = $client->createRequest('GET', 'http://www.foo.com'); + $this->assertContains('Guzzle/', (string) $request->getHeader('User-Agent')); + } + + public function testCanSetDefaultRequestOptions() + { + $client = new Client(); + $client->getConfig()->set('request.options', array( + 'query' => array('test' => '123', 'other' => 'abc'), + 'headers' => array('Foo' => 'Bar', 'Baz' => 'Bam') + )); + $request = $client->createRequest('GET', 'http://www.foo.com?test=hello', array('Foo' => 'Test')); + // Explicit options on a request should overrule default options + $this->assertEquals('Test', (string) $request->getHeader('Foo')); + $this->assertEquals('hello', $request->getQuery()->get('test')); + // Default options should still be set + $this->assertEquals('abc', $request->getQuery()->get('other')); + $this->assertEquals('Bam', (string) $request->getHeader('Baz')); + } + + public function testCanSetSetOptionsOnRequests() + { + $client = new Client(); + $request = $client->createRequest('GET', 'http://www.foo.com?test=hello', array('Foo' => 'Test'), null, array( + 'cookies' => array('michael' => 'test') + )); + $this->assertEquals('test', $request->getCookie('michael')); + } + + public function testHasDefaultOptionsHelperMethods() + { + $client = new Client(); + // With path + $client->setDefaultOption('headers/foo', 'bar'); + $this->assertEquals('bar', $client->getDefaultOption('headers/foo')); + // With simple key + $client->setDefaultOption('allow_redirects', false); + $this->assertFalse($client->getDefaultOption('allow_redirects')); + + $this->assertEquals(array( + 'headers' => array('foo' => 'bar'), + 'allow_redirects' => false + ), $client->getConfig('request.options')); + + $request = $client->get('/'); + $this->assertEquals('bar', $request->getHeader('foo')); + } + + public function testHeadCanUseOptions() + { + $client = new Client(); + $head = $client->head('http://www.foo.com', array(), array('query' => array('foo' => 'bar'))); + $this->assertEquals('bar', $head->getQuery()->get('foo')); + } + + public function testCanSetRelativeUrlStartingWithHttp() + { + $client = new Client('http://www.foo.com'); + $this->assertEquals( + 'http://www.foo.com/httpfoo', + $client->createRequest('GET', 'httpfoo')->getUrl() + ); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/CurlHandleTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/CurlHandleTest.php new file mode 100644 index 000000000..5bf28de36 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/CurlHandleTest.php @@ -0,0 +1,947 @@ +getEventDispatcher()->addListener('request.sent', function (Event $e) use ($that) { + $that->requestHandle = $e['handle']; + }); + + return $request; + } + + public function setUp() + { + $this->requestHandle = null; + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testConstructorExpectsCurlResource() + { + $h = new CurlHandle(false, array()); + } + + public function testConstructorExpectsProperOptions() + { + $h = curl_init($this->getServer()->getUrl()); + try { + $ha = new CurlHandle($h, false); + $this->fail('Expected InvalidArgumentException'); + } catch (\InvalidArgumentException $e) { + } + + $ha = new CurlHandle($h, array( + CURLOPT_URL => $this->getServer()->getUrl() + )); + $this->assertEquals($this->getServer()->getUrl(), $ha->getOptions()->get(CURLOPT_URL)); + + $ha = new CurlHandle($h, new Collection(array( + CURLOPT_URL => $this->getServer()->getUrl() + ))); + $this->assertEquals($this->getServer()->getUrl(), $ha->getOptions()->get(CURLOPT_URL)); + } + + public function testConstructorInitializesObject() + { + $handle = curl_init($this->getServer()->getUrl()); + $h = new CurlHandle($handle, array( + CURLOPT_URL => $this->getServer()->getUrl() + )); + $this->assertSame($handle, $h->getHandle()); + $this->assertInstanceOf('Guzzle\\Http\\Url', $h->getUrl()); + $this->assertEquals($this->getServer()->getUrl(), (string) $h->getUrl()); + $this->assertEquals($this->getServer()->getUrl(), $h->getOptions()->get(CURLOPT_URL)); + } + + public function testStoresStdErr() + { + $request = RequestFactory::getInstance()->create('GET', 'http://test.com'); + $request->getCurlOptions()->set('debug', true); + $h = CurlHandle::factory($request); + $this->assertEquals($h->getStderr(true), $h->getOptions()->get(CURLOPT_STDERR)); + $this->assertInternalType('resource', $h->getStderr(true)); + $this->assertInternalType('string', $h->getStderr(false)); + $r = $h->getStderr(true); + fwrite($r, 'test'); + $this->assertEquals('test', $h->getStderr(false)); + } + + public function testStoresCurlErrorNumber() + { + $h = new CurlHandle(curl_init('http://test.com'), array(CURLOPT_URL => 'http://test.com')); + $this->assertEquals(CURLE_OK, $h->getErrorNo()); + $h->setErrorNo(CURLE_OPERATION_TIMEOUTED); + $this->assertEquals(CURLE_OPERATION_TIMEOUTED, $h->getErrorNo()); + } + + public function testAccountsForMissingStdErr() + { + $handle = curl_init('http://www.test.com/'); + $h = new CurlHandle($handle, array( + CURLOPT_URL => 'http://www.test.com/' + )); + $this->assertNull($h->getStderr(false)); + } + + public function testDeterminesIfResourceIsAvailable() + { + $handle = curl_init($this->getServer()->getUrl()); + $h = new CurlHandle($handle, array()); + $this->assertTrue($h->isAvailable()); + + // Mess it up by closing the handle + curl_close($handle); + $this->assertFalse($h->isAvailable()); + + // Mess it up by unsetting the handle + $handle = null; + $this->assertFalse($h->isAvailable()); + } + + public function testWrapsErrorsAndInfo() + { + if (!defined('CURLOPT_TIMEOUT_MS')) { + $this->markTestSkipped('Update curl'); + } + + $settings = array( + CURLOPT_PORT => 123, + CURLOPT_CONNECTTIMEOUT_MS => 1, + CURLOPT_TIMEOUT_MS => 1 + ); + + $handle = curl_init($this->getServer()->getUrl()); + curl_setopt_array($handle, $settings); + $h = new CurlHandle($handle, $settings); + @curl_exec($handle); + + $errors = array( + "couldn't connect to host", + 'timeout was reached', + 'connection time-out', + 'connect() timed out!', + 'failed connect to 127.0.0.1:123; connection refused', + 'failed to connect to 127.0.0.1 port 123: connection refused' + ); + $this->assertTrue(in_array(strtolower($h->getError()), $errors), $h->getError() . ' was not the error'); + + $this->assertTrue($h->getErrorNo() > 0); + + $this->assertEquals($this->getServer()->getUrl(), $h->getInfo(CURLINFO_EFFECTIVE_URL)); + $this->assertInternalType('array', $h->getInfo()); + + curl_close($handle); + $this->assertEquals(null, $h->getInfo('url')); + } + + public function testGetInfoWithoutDebugMode() + { + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + $client = new Client($this->getServer()->getUrl()); + $request = $client->get($this->getServer()->getUrl()); + $response = $request->send(); + + $info = $response->getInfo(); + $this->assertFalse(empty($info)); + $this->assertEquals($this->getServer()->getUrl(), $info['url']); + } + + public function testWrapsCurlOptions() + { + $handle = curl_init($this->getServer()->getUrl()); + $h = new CurlHandle($handle, array( + CURLOPT_AUTOREFERER => true, + CURLOPT_BUFFERSIZE => 1024 + )); + + $this->assertEquals(true, $h->getOptions()->get(CURLOPT_AUTOREFERER)); + $this->assertEquals(1024, $h->getOptions()->get(CURLOPT_BUFFERSIZE)); + } + + /** + * Data provider for factory tests + * + * @return array + */ + public function dataProvider() + { + $testFile = __DIR__ . '/../../../../../phpunit.xml.dist'; + + $postBody = new QueryString(array('file' => '@' . $testFile)); + $qs = new QueryString(array( + 'x' => 'y', + 'z' => 'a' + )); + + $client = new Client(); + $userAgent = $client->getDefaultUserAgent(); + $auth = base64_encode('michael:123'); + $testFileSize = filesize($testFile); + + $tests = array( + // Send a regular GET + array('GET', 'http://www.google.com/', null, null, array( + CURLOPT_RETURNTRANSFER => 0, + CURLOPT_HEADER => 0, + CURLOPT_CONNECTTIMEOUT => 150, + CURLOPT_WRITEFUNCTION => 'callback', + CURLOPT_HEADERFUNCTION => 'callback', + CURLOPT_HTTPHEADER => array('Accept:', 'Host: www.google.com', 'User-Agent: ' . $userAgent), + )), + // Test that custom request methods can be used + array('TRACE', 'http://www.google.com/', null, null, array( + CURLOPT_CUSTOMREQUEST => 'TRACE' + )), + // Send a GET using a port + array('GET', 'http://127.0.0.1:8080', null, null, array( + CURLOPT_RETURNTRANSFER => 0, + CURLOPT_HEADER => 0, + CURLOPT_CONNECTTIMEOUT => 150, + CURLOPT_WRITEFUNCTION => 'callback', + CURLOPT_HEADERFUNCTION => 'callback', + CURLOPT_PORT => 8080, + CURLOPT_HTTPHEADER => array('Accept:', 'Host: 127.0.0.1:8080', 'User-Agent: ' . $userAgent), + )), + // Send a HEAD request + array('HEAD', 'http://www.google.com/', null, null, array( + CURLOPT_RETURNTRANSFER => 0, + CURLOPT_HEADER => 0, + CURLOPT_CONNECTTIMEOUT => 150, + CURLOPT_HEADERFUNCTION => 'callback', + CURLOPT_HTTPHEADER => array('Accept:', 'Host: www.google.com', 'User-Agent: ' . $userAgent), + CURLOPT_NOBODY => 1 + )), + // Send a GET using basic auth + array('GET', 'https://michael:123@127.0.0.1/index.html?q=2', null, null, array( + CURLOPT_RETURNTRANSFER => 0, + CURLOPT_HEADER => 0, + CURLOPT_CONNECTTIMEOUT => 150, + CURLOPT_WRITEFUNCTION => 'callback', + CURLOPT_HEADERFUNCTION => 'callback', + CURLOPT_HTTPHEADER => array( + 'Accept:', + 'Host: 127.0.0.1', + 'Authorization: Basic ' . $auth, + 'User-Agent: ' . $userAgent + ), + CURLOPT_PORT => 443 + )), + // Send a GET request with custom headers + array('GET', 'http://127.0.0.1:8124/', array( + 'x-test-data' => 'Guzzle' + ), null, array( + CURLOPT_PORT => 8124, + CURLOPT_HTTPHEADER => array( + 'Accept:', + 'Host: 127.0.0.1:8124', + 'x-test-data: Guzzle', + 'User-Agent: ' . $userAgent + ) + ), array( + 'Host' => '*', + 'User-Agent' => '*', + 'x-test-data' => 'Guzzle' + )), + // Send a POST using a query string + array('POST', 'http://127.0.0.1:8124/post.php', null, $qs, array( + CURLOPT_RETURNTRANSFER => 0, + CURLOPT_HEADER => 0, + CURLOPT_CONNECTTIMEOUT => 150, + CURLOPT_WRITEFUNCTION => 'callback', + CURLOPT_HEADERFUNCTION => 'callback', + CURLOPT_POSTFIELDS => 'x=y&z=a', + CURLOPT_HTTPHEADER => array ( + 'Expect:', + 'Accept:', + 'Host: 127.0.0.1:8124', + 'Content-Type: application/x-www-form-urlencoded; charset=utf-8', + 'User-Agent: ' . $userAgent + ) + ), array( + 'Host' => '*', + 'User-Agent' => '*', + 'Content-Length' => '7', + '!Expect' => null, + 'Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8', + '!Transfer-Encoding' => null + )), + // Send a PUT using raw data + array('PUT', 'http://127.0.0.1:8124/put.php', null, EntityBody::factory(fopen($testFile, 'r+')), array( + CURLOPT_RETURNTRANSFER => 0, + CURLOPT_HEADER => 0, + CURLOPT_CONNECTTIMEOUT => 150, + CURLOPT_WRITEFUNCTION => 'callback', + CURLOPT_HEADERFUNCTION => 'callback', + CURLOPT_READFUNCTION => 'callback', + CURLOPT_INFILESIZE => filesize($testFile), + CURLOPT_HTTPHEADER => array ( + 'Expect:', + 'Accept:', + 'Host: 127.0.0.1:8124', + 'User-Agent: ' . $userAgent + ) + ), array( + 'Host' => '*', + 'User-Agent' => '*', + '!Expect' => null, + 'Content-Length' => $testFileSize, + '!Transfer-Encoding' => null + )), + // Send a POST request using an array of fields + array('POST', 'http://127.0.0.1:8124/post.php', null, array( + 'x' => 'y', + 'a' => 'b' + ), array( + CURLOPT_RETURNTRANSFER => 0, + CURLOPT_HEADER => 0, + CURLOPT_CONNECTTIMEOUT => 150, + CURLOPT_WRITEFUNCTION => 'callback', + CURLOPT_HEADERFUNCTION => 'callback', + CURLOPT_POST => 1, + CURLOPT_POSTFIELDS => 'x=y&a=b', + CURLOPT_HTTPHEADER => array ( + 'Expect:', + 'Accept:', + 'Host: 127.0.0.1:8124', + 'Content-Type: application/x-www-form-urlencoded; charset=utf-8', + 'User-Agent: ' . $userAgent + ) + ), array( + 'Host' => '*', + 'User-Agent' => '*', + 'Content-Length' => '7', + '!Expect' => null, + 'Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8', + '!Transfer-Encoding' => null + )), + // Send a POST request with raw POST data and a custom content-type + array('POST', 'http://127.0.0.1:8124/post.php', array( + 'Content-Type' => 'application/json' + ), '{"hi":"there"}', array( + CURLOPT_RETURNTRANSFER => 0, + CURLOPT_HEADER => 0, + CURLOPT_CONNECTTIMEOUT => 150, + CURLOPT_WRITEFUNCTION => 'callback', + CURLOPT_HEADERFUNCTION => 'callback', + CURLOPT_CUSTOMREQUEST => 'POST', + CURLOPT_UPLOAD => true, + CURLOPT_INFILESIZE => 14, + CURLOPT_HTTPHEADER => array ( + 'Expect:', + 'Accept:', + 'Host: 127.0.0.1:8124', + 'Content-Type: application/json', + 'User-Agent: ' . $userAgent + ), + ), array( + 'Host' => '*', + 'User-Agent' => '*', + 'Content-Type' => 'application/json', + '!Expect' => null, + 'Content-Length' => '14', + '!Transfer-Encoding' => null + )), + // Send a POST request with raw POST data, a custom content-type, and use chunked encoding + array('POST', 'http://127.0.0.1:8124/post.php', array( + 'Content-Type' => 'application/json', + 'Transfer-Encoding' => 'chunked' + ), '{"hi":"there"}', array( + CURLOPT_RETURNTRANSFER => 0, + CURLOPT_HEADER => 0, + CURLOPT_CONNECTTIMEOUT => 150, + CURLOPT_WRITEFUNCTION => 'callback', + CURLOPT_HEADERFUNCTION => 'callback', + CURLOPT_CUSTOMREQUEST => 'POST', + CURLOPT_UPLOAD => true, + CURLOPT_HTTPHEADER => array ( + 'Expect:', + 'Accept:', + 'Host: 127.0.0.1:8124', + 'Transfer-Encoding: chunked', + 'Content-Type: application/json', + 'User-Agent: ' . $userAgent + ), + ), array( + 'Host' => '*', + 'User-Agent' => '*', + 'Content-Type' => 'application/json', + '!Expect' => null, + 'Transfer-Encoding' => 'chunked', + '!Content-Length' => '' + )), + // Send a POST request with no body + array('POST', 'http://127.0.0.1:8124/post.php', null, '', array( + CURLOPT_CUSTOMREQUEST => 'POST', + CURLOPT_HTTPHEADER => array ( + 'Expect:', + 'Accept:', + 'Host: 127.0.0.1:8124', + 'User-Agent: ' . $userAgent + ) + ), array( + 'Host' => '*', + 'User-Agent' => '*', + 'Content-Length' => '0', + '!Transfer-Encoding' => null + )), + // Send a POST request with empty post fields + array('POST', 'http://127.0.0.1:8124/post.php', null, array(), array( + CURLOPT_CUSTOMREQUEST => 'POST', + CURLOPT_HTTPHEADER => array ( + 'Expect:', + 'Accept:', + 'Host: 127.0.0.1:8124', + 'User-Agent: ' . $userAgent + ) + ), array( + 'Host' => '*', + 'User-Agent' => '*', + 'Content-Length' => '0', + '!Transfer-Encoding' => null + )), + // Send a PATCH request + array('PATCH', 'http://127.0.0.1:8124/patch.php', null, 'body', array( + CURLOPT_INFILESIZE => 4, + CURLOPT_HTTPHEADER => array ( + 'Expect:', + 'Accept:', + 'Host: 127.0.0.1:8124', + 'User-Agent: ' . $userAgent + ) + )), + // Send a DELETE request with a body + array('DELETE', 'http://127.0.0.1:8124/delete.php', null, 'body', array( + CURLOPT_CUSTOMREQUEST => 'DELETE', + CURLOPT_INFILESIZE => 4, + CURLOPT_HTTPHEADER => array ( + 'Expect:', + 'Accept:', + 'Host: 127.0.0.1:8124', + 'User-Agent: ' . $userAgent + ) + ), array( + 'Host' => '*', + 'User-Agent' => '*', + 'Content-Length' => '4', + '!Expect' => null, + '!Transfer-Encoding' => null + )), + + /** + * Send a request with empty path and a fragment - the fragment must be + * stripped out before sending it to curl + * + * @issue 453 + * @link https://github.com/guzzle/guzzle/issues/453 + */ + array('GET', 'http://www.google.com#head', null, null, array( + CURLOPT_RETURNTRANSFER => 0, + CURLOPT_HEADER => 0, + CURLOPT_CONNECTTIMEOUT => 150, + CURLOPT_WRITEFUNCTION => 'callback', + CURLOPT_HEADERFUNCTION => 'callback', + CURLOPT_HTTPHEADER => array('Accept:', 'Host: www.google.com', 'User-Agent: ' . $userAgent), + )), + ); + + $postTest = array('POST', 'http://127.0.0.1:8124/post.php', null, $postBody, array( + CURLOPT_RETURNTRANSFER => 0, + CURLOPT_HEADER => 0, + CURLOPT_CONNECTTIMEOUT => 150, + CURLOPT_WRITEFUNCTION => 'callback', + CURLOPT_HEADERFUNCTION => 'callback', + CURLOPT_POST => 1, + CURLOPT_POSTFIELDS => array( + 'file' => '@' . $testFile . ';filename=phpunit.xml.dist;type=application/octet-stream' + ), + CURLOPT_HTTPHEADER => array ( + 'Accept:', + 'Host: 127.0.0.1:8124', + 'Content-Type: multipart/form-data', + 'Expect: 100-Continue', + 'User-Agent: ' . $userAgent + ) + ), array( + 'Host' => '*', + 'User-Agent' => '*', + 'Content-Length' => '*', + 'Expect' => '100-Continue', + 'Content-Type' => 'multipart/form-data; boundary=*', + '!Transfer-Encoding' => null + )); + + if (version_compare(phpversion(), '5.5.0', '>=')) { + $postTest[4][CURLOPT_POSTFIELDS] = array( + 'file' => new \CurlFile($testFile, 'application/octet-stream', 'phpunit.xml.dist') + ); + } + + $tests[] = $postTest; + + return $tests; + } + + /** + * @dataProvider dataProvider + */ + public function testFactoryCreatesCurlBasedOnRequest($method, $url, $headers, $body, $options, $expectedHeaders = null) + { + $client = new Client(); + $request = $client->createRequest($method, $url, $headers, $body); + $request->getCurlOptions()->set('debug', true); + + $originalRequest = clone $request; + $curlTest = clone $request; + $handle = CurlHandle::factory($curlTest); + + $this->assertInstanceOf('Guzzle\\Http\\Curl\\CurlHandle', $handle); + $o = $handle->getOptions()->getAll(); + + // Headers are case-insensitive + if (isset($o[CURLOPT_HTTPHEADER])) { + $o[CURLOPT_HTTPHEADER] = array_map('strtolower', $o[CURLOPT_HTTPHEADER]); + } + if (isset($options[CURLOPT_HTTPHEADER])) { + $options[CURLOPT_HTTPHEADER] = array_map('strtolower', $options[CURLOPT_HTTPHEADER]); + } + + $check = 0; + foreach ($options as $key => $value) { + $check++; + $this->assertArrayHasKey($key, $o, '-> Check number ' . $check); + if ($key != CURLOPT_HTTPHEADER && $key != CURLOPT_POSTFIELDS && (is_array($o[$key])) || $o[$key] instanceof \Closure) { + $this->assertEquals('callback', $value, '-> Check number ' . $check); + } else { + $this->assertTrue($value == $o[$key], '-> Check number ' . $check . ' - ' . var_export($value, true) . ' != ' . var_export($o[$key], true)); + } + } + + // If we are testing the actual sent headers + if ($expectedHeaders) { + + // Send the request to the test server + $client = new Client($this->getServer()->getUrl()); + $request->setClient($client); + $this->getServer()->flush(); + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + $request->send(); + + // Get the request that was sent and create a request that we expected + $requests = $this->getServer()->getReceivedRequests(true); + $this->assertEquals($method, $requests[0]->getMethod()); + + $test = $this->compareHeaders($expectedHeaders, $requests[0]->getHeaders()); + $this->assertFalse($test, $test . "\nSent: \n" . $request . "\n\n" . $requests[0]); + + // Ensure only one Content-Length header is sent + if ($request->getHeader('Content-Length')) { + $this->assertEquals((string) $request->getHeader('Content-Length'), (string) $requests[0]->getHeader('Content-Length')); + } + } + } + + public function testFactoryUsesSpecifiedProtocol() + { + $request = RequestFactory::getInstance()->create('GET', 'http://127.0.0.1:8124/'); + $request->setProtocolVersion('1.1'); + $handle = CurlHandle::factory($request); + $options = $handle->getOptions(); + $this->assertEquals(CURL_HTTP_VERSION_1_1, $options[CURLOPT_HTTP_VERSION]); + } + + public function testUploadsPutData() + { + $this->getServer()->flush(); + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi"); + + $client = new Client($this->getServer()->getUrl()); + $request = $client->put('/'); + $request->getCurlOptions()->set('debug', true); + $request->setBody(EntityBody::factory('test'), 'text/plain', false); + $request->getCurlOptions()->set('progress', true); + + $o = $this->getWildcardObserver($request); + $request->send(); + + // Make sure that the events were dispatched + $this->assertTrue($o->has('curl.callback.progress')); + + // Ensure that the request was received exactly as intended + $r = $this->getServer()->getReceivedRequests(true); + $this->assertFalse($r[0]->hasHeader('Transfer-Encoding')); + $this->assertEquals(4, (string) $r[0]->getHeader('Content-Length')); + $sent = strtolower($r[0]); + $this->assertContains('put / http/1.1', $sent); + $this->assertContains('host: 127.0.0.1', $sent); + $this->assertContains('user-agent:', $sent); + $this->assertContains('content-type: text/plain', $sent); + } + + public function testUploadsPutDataUsingChunkedEncodingWhenLengthCannotBeDetermined() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi" + )); + $client = new Client($this->getServer()->getUrl()); + $request = $client->put('/'); + $request->setBody(EntityBody::factory(fopen($this->getServer()->getUrl(), 'r')), 'text/plain'); + $request->send(); + + $r = $this->getServer()->getReceivedRequests(true); + $this->assertEquals('chunked', $r[1]->getHeader('Transfer-Encoding')); + $this->assertFalse($r[1]->hasHeader('Content-Length')); + } + + public function testUploadsPutDataUsingChunkedEncodingWhenForced() + { + $this->getServer()->flush(); + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi"); + + $client = new Client($this->getServer()->getUrl()); + $request = $client->put('/', array('Transfer-Encoding' => 'chunked'), 'hi!'); + $request->send(); + + $r = $this->getServer()->getReceivedRequests(true); + $this->assertEquals('chunked', $r[0]->getHeader('Transfer-Encoding')); + $this->assertFalse($r[0]->hasHeader('Content-Length')); + $this->assertEquals('hi!', $r[0]->getBody(true)); + } + + public function testSendsPostRequestsWithFields() + { + $this->getServer()->flush(); + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi"); + + $request = RequestFactory::getInstance()->create('POST', $this->getServer()->getUrl()); + $request->getCurlOptions()->set('debug', true); + $request->setClient(new Client()); + $request->addPostFields(array( + 'a' => 'b', + 'c' => 'ay! ~This is a test, isn\'t it?' + )); + $request->send(); + + // Make sure that the request was sent correctly + $r = $this->getServer()->getReceivedRequests(true); + $this->assertEquals('a=b&c=ay%21%20~This%20is%20a%20test%2C%20isn%27t%20it%3F', (string) $r[0]->getBody()); + $this->assertFalse($r[0]->hasHeader('Transfer-Encoding')); + $this->assertEquals(56, (string) $r[0]->getHeader('Content-Length')); + $sent = strtolower($r[0]); + $this->assertContains('post / http/1.1', $sent); + $this->assertContains('content-type: application/x-www-form-urlencoded; charset=utf-8', $sent); + } + + public function testSendsPostRequestsWithFiles() + { + $this->getServer()->flush(); + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi"); + + $request = RequestFactory::getInstance()->create('POST', $this->getServer()->getUrl()); + $request->getCurlOptions()->set('debug', true); + $request->setClient(new Client()); + $request->addPostFiles(array( + 'foo' => __FILE__, + )); + $request->addPostFields(array( + 'bar' => 'baz', + 'arr' => array('a' => 1, 'b' => 2), + )); + $this->updateForHandle($request); + $request->send(); + + // Ensure the CURLOPT_POSTFIELDS option was set properly + $options = $this->requestHandle->getOptions()->getAll(); + if (version_compare(phpversion(), '5.5.0', '<')) { + $this->assertContains('@' . __FILE__ . ';filename=CurlHandleTest.php;type=text/x-', $options[CURLOPT_POSTFIELDS]['foo']); + } else{ + $this->assertInstanceOf('CURLFile', $options[CURLOPT_POSTFIELDS]['foo']); + } + $this->assertEquals('baz', $options[CURLOPT_POSTFIELDS]['bar']); + $this->assertEquals('1', $options[CURLOPT_POSTFIELDS]['arr[a]']); + $this->assertEquals('2', $options[CURLOPT_POSTFIELDS]['arr[b]']); + // Ensure that a Content-Length header was sent by cURL + $this->assertTrue($request->hasHeader('Content-Length')); + } + + public function testCurlConfigurationOptionsAreSet() + { + $request = RequestFactory::getInstance()->create('PUT', $this->getServer()->getUrl()); + $request->setClient(new Client('http://www.example.com')); + $request->getCurlOptions()->set(CURLOPT_CONNECTTIMEOUT, 99); + $request->getCurlOptions()->set('curl.fake_opt', 99); + $request->getCurlOptions()->set(CURLOPT_PORT, 8181); + $handle = CurlHandle::factory($request); + $this->assertEquals(99, $handle->getOptions()->get(CURLOPT_CONNECTTIMEOUT)); + $this->assertEquals(8181, $handle->getOptions()->get(CURLOPT_PORT)); + $this->assertNull($handle->getOptions()->get('curl.fake_opt')); + $this->assertNull($handle->getOptions()->get('fake_opt')); + } + + public function testEnsuresRequestsHaveResponsesWhenUpdatingFromTransfer() + { + $request = RequestFactory::getInstance()->create('PUT', $this->getServer()->getUrl()); + $handle = CurlHandle::factory($request); + $handle->updateRequestFromTransfer($request); + } + + public function testCanSendBodyAsString() + { + $this->getServer()->flush(); + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + $client = new Client($this->getServer()->getUrl()); + $request = $client->put('/', null, 'foo'); + $request->getCurlOptions()->set('body_as_string', true); + $request->send(); + $requests = $this->getServer()->getReceivedRequests(false); + $this->assertContains('PUT /', $requests[0]); + $this->assertContains("\nfoo", $requests[0]); + $this->assertContains('content-length: 3', $requests[0]); + $this->assertNotContains('content-type', $requests[0]); + } + + public function testCanSendPostBodyAsString() + { + $this->getServer()->flush(); + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + $client = new Client($this->getServer()->getUrl()); + $request = $client->post('/', null, 'foo'); + $request->getCurlOptions()->set('body_as_string', true); + $request->send(); + $requests = $this->getServer()->getReceivedRequests(false); + $this->assertContains('POST /', $requests[0]); + $this->assertContains("\nfoo", $requests[0]); + $this->assertContains('content-length: 3', $requests[0]); + $this->assertNotContains('content-type', $requests[0]); + } + + public function testAllowsWireTransferInfoToBeEnabled() + { + $request = RequestFactory::getInstance()->create('PUT', $this->getServer()->getUrl()); + $request->getCurlOptions()->set('debug', true); + $handle = CurlHandle::factory($request); + $this->assertNotNull($handle->getOptions()->get(CURLOPT_STDERR)); + $this->assertNotNull($handle->getOptions()->get(CURLOPT_VERBOSE)); + } + + public function testAddsCustomCurlOptions() + { + $request = RequestFactory::getInstance()->create('PUT', $this->getServer()->getUrl()); + $request->getCurlOptions()->set(CURLOPT_TIMEOUT, 200); + $handle = CurlHandle::factory($request); + $this->assertEquals(200, $handle->getOptions()->get(CURLOPT_TIMEOUT)); + } + + public function testSendsPostUploadsWithContentDispositionHeaders() + { + $this->getServer()->flush(); + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\n\r\nContent-Length: 0\r\n\r\n"); + + $fileToUpload = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'TestData' . DIRECTORY_SEPARATOR . 'test_service.json'; + + $client = new Client($this->getServer()->getUrl()); + $request = $client->post(); + $request->addPostFile('foo', $fileToUpload, 'application/json'); + $request->addPostFile('foo', __FILE__); + + $request->send(); + $requests = $this->getServer()->getReceivedRequests(true); + $body = (string) $requests[0]->getBody(); + + $this->assertContains('Content-Disposition: form-data; name="foo[0]"; filename="', $body); + $this->assertContains('Content-Type: application/json', $body); + $this->assertContains('Content-Type: text/x-', $body); + $this->assertContains('Content-Disposition: form-data; name="foo[1]"; filename="', $body); + } + + public function requestMethodProvider() + { + return array(array('POST'), array('PUT'), array('PATCH')); + } + + /** + * @dataProvider requestMethodProvider + */ + public function testSendsRequestsWithNoBodyUsingContentLengthZero($method) + { + $this->getServer()->flush(); + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + $client = new Client($this->getServer()->getUrl()); + $client->createRequest($method)->send(); + $requests = $this->getServer()->getReceivedRequests(true); + $this->assertFalse($requests[0]->hasHeader('Transfer-Encoding')); + $this->assertTrue($requests[0]->hasHeader('Content-Length')); + $this->assertEquals('0', (string) $requests[0]->getHeader('Content-Length')); + } + + /** + * @dataProvider provideCurlConfig + */ + public function testParseCurlConfigConvertsStringKeysToConstantKeys($options, $expected) + { + $actual = CurlHandle::parseCurlConfig($options); + $this->assertEquals($expected, $actual); + } + + /** + * Data provider for curl configurations + * + * @return array + */ + public function provideCurlConfig() + { + return array( + // Conversion of option name to constant value + array( + array( + 'CURLOPT_PORT' => 10, + 'CURLOPT_TIMEOUT' => 99 + ), + array( + CURLOPT_PORT => 10, + CURLOPT_TIMEOUT => 99 + ) + ), + // Keeps non constant options + array( + array('debug' => true), + array('debug' => true) + ), + // Conversion of constant names to constant values + array( + array('debug' => 'CURLPROXY_HTTP'), + array('debug' => CURLPROXY_HTTP) + ) + ); + } + + public function testSeeksToBeginningOfStreamWhenSending() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n" + )); + + $client = new Client($this->getServer()->getUrl()); + $request = $client->put('/', null, 'test'); + $request->send(); + $request->send(); + + $received = $this->getServer()->getReceivedRequests(true); + $this->assertEquals(2, count($received)); + $this->assertEquals('test', (string) $received[0]->getBody()); + $this->assertEquals('test', (string) $received[1]->getBody()); + } + + public function testAllowsCurloptEncodingToBeSet() + { + $this->getServer()->flush(); + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + + $client = new Client($this->getServer()->getUrl()); + $request = $client->get('/', null); + $request->getCurlOptions()->set(CURLOPT_ENCODING, ''); + $this->updateForHandle($request); + $request->send(); + $options = $this->requestHandle->getOptions()->getAll(); + $this->assertSame('', $options[CURLOPT_ENCODING]); + $received = $this->getServer()->getReceivedRequests(false); + $this->assertContainsIns('accept: */*', $received[0]); + $this->assertContainsIns('accept-encoding: ', $received[0]); + } + + public function testSendsExpectHeaderWhenSizeIsGreaterThanCutoff() + { + $this->getServer()->flush(); + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + $client = new Client($this->getServer()->getUrl()); + $request = $client->put('/', null, 'test'); + // Start sending the expect header to 2 bytes + $this->updateForHandle($request); + $request->setExpectHeaderCutoff(2)->send(); + $options = $this->requestHandle->getOptions()->getAll(); + $this->assertContains('Expect: 100-Continue', $options[CURLOPT_HTTPHEADER]); + $received = $this->getServer()->getReceivedRequests(false); + $this->assertContainsIns('expect: 100-continue', $received[0]); + } + + public function testSetsCurloptEncodingWhenAcceptEncodingHeaderIsSet() + { + $this->getServer()->flush(); + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndata"); + $client = new Client($this->getServer()->getUrl()); + $request = $client->get('/', array( + 'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip, deflate', + )); + $this->updateForHandle($request); + $request->send(); + $options = $this->requestHandle->getOptions()->getAll(); + $this->assertSame('gzip, deflate', $options[CURLOPT_ENCODING]); + $received = $this->getServer()->getReceivedRequests(false); + $this->assertContainsIns('accept: application/json', $received[0]); + $this->assertContainsIns('accept-encoding: gzip, deflate', $received[0]); + } + + public function testSendsPostFieldsForNonPostRequests() + { + $this->getServer()->flush(); + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\n\r\nContent-Length: 0\r\n\r\n"); + + $client = new Client(); + $request = $client->put($this->getServer()->getUrl(), null, array( + 'foo' => 'baz', + 'baz' => 'bar' + )); + + $request->send(); + $requests = $this->getServer()->getReceivedRequests(true); + $this->assertEquals('PUT', $requests[0]->getMethod()); + $this->assertEquals( + 'application/x-www-form-urlencoded; charset=utf-8', + (string) $requests[0]->getHeader('Content-Type') + ); + $this->assertEquals(15, (string) $requests[0]->getHeader('Content-Length')); + $this->assertEquals('foo=baz&baz=bar', (string) $requests[0]->getBody()); + } + + public function testSendsPostFilesForNonPostRequests() + { + $this->getServer()->flush(); + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\n\r\nContent-Length: 0\r\n\r\n"); + + $client = new Client(); + $request = $client->put($this->getServer()->getUrl(), null, array( + 'foo' => '@' . __FILE__ + )); + + $request->send(); + $requests = $this->getServer()->getReceivedRequests(true); + $this->assertEquals('PUT', $requests[0]->getMethod()); + $this->assertContains('multipart/form-data', (string) $requests[0]->getHeader('Content-Type')); + $this->assertContains('testSendsPostFilesForNonPostRequests', (string) $requests[0]->getBody()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/CurlMultiProxyTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/CurlMultiProxyTest.php new file mode 100644 index 000000000..e04141c5f --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/CurlMultiProxyTest.php @@ -0,0 +1,110 @@ +multi = new CurlMultiProxy(self::MAX_HANDLES, self::SELECT_TIMEOUT); + } + + public function tearDown() + { + unset($this->multi); + } + + public function testConstructorSetsMaxHandles() + { + $m = new CurlMultiProxy(self::MAX_HANDLES, self::SELECT_TIMEOUT); + $this->assertEquals(self::MAX_HANDLES, $this->readAttribute($m, 'maxHandles')); + } + + public function testConstructorSetsSelectTimeout() + { + $m = new CurlMultiProxy(self::MAX_HANDLES, self::SELECT_TIMEOUT); + $this->assertEquals(self::SELECT_TIMEOUT, $this->readAttribute($m, 'selectTimeout')); + } + + public function testAddingRequestsAddsToQueue() + { + $r = new Request('GET', 'http://www.foo.com'); + $this->assertSame($this->multi, $this->multi->add($r)); + $this->assertEquals(1, count($this->multi)); + $this->assertEquals(array($r), $this->multi->all()); + + $this->assertTrue($this->multi->remove($r)); + $this->assertFalse($this->multi->remove($r)); + $this->assertEquals(0, count($this->multi)); + } + + public function testResetClearsState() + { + $r = new Request('GET', 'http://www.foo.com'); + $this->multi->add($r); + $this->multi->reset(); + $this->assertEquals(0, count($this->multi)); + } + + public function testSendWillSendQueuedRequestsFirst() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n" + )); + $client = new Client($this->getServer()->getUrl()); + $events = array(); + $client->getCurlMulti()->getEventDispatcher()->addListener( + CurlMultiProxy::ADD_REQUEST, + function ($e) use (&$events) { + $events[] = $e; + } + ); + $request = $client->get(); + $request->getEventDispatcher()->addListener('request.complete', function () use ($client) { + $client->get('/foo')->send(); + }); + $request->send(); + $received = $this->getServer()->getReceivedRequests(true); + $this->assertEquals(2, count($received)); + $this->assertEquals($this->getServer()->getUrl(), $received[0]->getUrl()); + $this->assertEquals($this->getServer()->getUrl() . 'foo', $received[1]->getUrl()); + $this->assertEquals(2, count($events)); + } + + public function testTrimsDownMaxHandleCount() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 307 OK\r\nLocation: /foo\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 307 OK\r\nLocation: /foo\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 307 OK\r\nLocation: /foo\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 307 OK\r\nLocation: /foo\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n" + )); + $client = new Client($this->getServer()->getUrl()); + $client->setCurlMulti(new CurlMultiProxy(self::MAX_HANDLES, self::SELECT_TIMEOUT)); + $request = $client->get(); + $request->send(); + $this->assertEquals(200, $request->getResponse()->getStatusCode()); + $handles = $this->readAttribute($client->getCurlMulti(), 'handles'); + $this->assertEquals(2, count($handles)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/CurlMultiTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/CurlMultiTest.php new file mode 100644 index 000000000..1272281f9 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/CurlMultiTest.php @@ -0,0 +1,455 @@ +multi = new MockMulti(); + } + + public function tearDown() + { + unset($this->multi); + } + + public function testConstructorCreateMultiHandle() + { + $this->assertInternalType('resource', $this->multi->getHandle()); + $this->assertEquals('curl_multi', get_resource_type($this->multi->getHandle())); + } + + public function testDestructorClosesMultiHandle() + { + $handle = $this->multi->getHandle(); + $this->multi->__destruct(); + $this->assertFalse(is_resource($handle)); + } + + public function testRequestsCanBeAddedAndCounted() + { + $multi = new CurlMulti(); + $request1 = new Request('GET', 'http://www.google.com/'); + $multi->add($request1); + $this->assertEquals(array($request1), $multi->all()); + $request2 = new Request('POST', 'http://www.google.com/'); + $multi->add($request2); + $this->assertEquals(array($request1, $request2), $multi->all()); + $this->assertEquals(2, count($multi)); + } + + public function testRequestsCanBeRemoved() + { + $request1 = new Request('GET', 'http://www.google.com/'); + $this->multi->add($request1); + $request2 = new Request('PUT', 'http://www.google.com/'); + $this->multi->add($request2); + $this->assertEquals(array($request1, $request2), $this->multi->all()); + $this->assertTrue($this->multi->remove($request1)); + $this->assertFalse($this->multi->remove($request1)); + $this->assertEquals(array($request2), $this->multi->all()); + } + + public function testsResetRemovesRequestsAndResetsState() + { + $this->multi->add(new Request('GET', 'http://www.google.com/')); + $this->multi->reset(); + $this->assertEquals(array(), $this->multi->all()); + } + + public function testSendsRequestsThroughCurl() + { + $this->getServer()->enqueue(array( + "HTTP/1.1 204 No content\r\n" . + "Content-Length: 0\r\n" . + "Server: Jetty(6.1.3)\r\n\r\n", + "HTTP/1.1 200 OK\r\n" . + "Content-Type: text/html; charset=utf-8\r\n" . + "Content-Length: 4\r\n" . + "Server: Jetty(6.1.3)\r\n\r\n" . + "data" + )); + + $request1 = new Request('GET', $this->getServer()->getUrl()); + $request2 = new Request('GET', $this->getServer()->getUrl()); + $this->multi->add($request1); + $this->multi->add($request2); + $this->multi->send(); + + $response1 = $request1->getResponse(); + $response2 = $request2->getResponse(); + $this->assertInstanceOf('Guzzle\\Http\\Message\\Response', $response1); + $this->assertInstanceOf('Guzzle\\Http\\Message\\Response', $response2); + + $this->assertTrue($response1->getBody(true) == 'data' || $response2->getBody(true) == 'data'); + $this->assertTrue($response1->getBody(true) == '' || $response2->getBody(true) == ''); + $this->assertTrue($response1->getStatusCode() == '204' || $response2->getStatusCode() == '204'); + $this->assertNotEquals((string) $response1, (string) $response2); + } + + public function testSendsThroughCurlAndAggregatesRequestExceptions() + { + $this->getServer()->enqueue(array( + "HTTP/1.1 200 OK\r\n" . + "Content-Type: text/html; charset=utf-8\r\n" . + "Content-Length: 4\r\n" . + "Server: Jetty(6.1.3)\r\n" . + "\r\n" . + "data", + "HTTP/1.1 204 No content\r\n" . + "Content-Length: 0\r\n" . + "Server: Jetty(6.1.3)\r\n" . + "\r\n", + "HTTP/1.1 404 Not Found\r\n" . + "Content-Length: 0\r\n" . + "\r\n" + )); + + $request1 = new Request('GET', $this->getServer()->getUrl()); + $request2 = new Request('HEAD', $this->getServer()->getUrl()); + $request3 = new Request('GET', $this->getServer()->getUrl()); + $this->multi->add($request1); + $this->multi->add($request2); + $this->multi->add($request3); + + try { + $this->multi->send(); + $this->fail('MultiTransferException not thrown when aggregating request exceptions'); + } catch (MultiTransferException $e) { + + $this->assertTrue($e->containsRequest($request1)); + $this->assertTrue($e->containsRequest($request2)); + $this->assertTrue($e->containsRequest($request3)); + $this->assertInstanceOf('ArrayIterator', $e->getIterator()); + $this->assertEquals(1, count($e)); + $exceptions = $e->getIterator(); + + $response1 = $request1->getResponse(); + $response2 = $request2->getResponse(); + $response3 = $request3->getResponse(); + + $this->assertNotEquals((string) $response1, (string) $response2); + $this->assertNotEquals((string) $response3, (string) $response1); + $this->assertInstanceOf('Guzzle\\Http\\Message\\Response', $response1); + $this->assertInstanceOf('Guzzle\\Http\\Message\\Response', $response2); + $this->assertInstanceOf('Guzzle\\Http\\Message\\Response', $response3); + + $failed = $exceptions[0]->getResponse(); + $this->assertEquals(404, $failed->getStatusCode()); + $this->assertEquals(1, count($e)); + + // Test the IteratorAggregate functionality + foreach ($e as $except) { + $this->assertEquals($failed, $except->getResponse()); + } + + $this->assertEquals(1, count($e->getFailedRequests())); + $this->assertEquals(2, count($e->getSuccessfulRequests())); + $this->assertEquals(3, count($e->getAllRequests())); + } + } + + public function testCurlErrorsAreCaught() + { + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + try { + $request = RequestFactory::getInstance()->create('GET', 'http://127.0.0.1:9876/'); + $request->setClient(new Client()); + $request->getCurlOptions()->set(CURLOPT_FRESH_CONNECT, true); + $request->getCurlOptions()->set(CURLOPT_FORBID_REUSE, true); + $request->getCurlOptions()->set(CURLOPT_CONNECTTIMEOUT_MS, 5); + $request->send(); + $this->fail('CurlException not thrown'); + } catch (CurlException $e) { + $m = $e->getMessage(); + $this->assertContains('[curl] ', $m); + $this->assertContains('[url] http://127.0.0.1:9876/', $m); + $this->assertInternalType('array', $e->getCurlInfo()); + } + } + + public function testRemovesQueuedRequests() + { + $request = RequestFactory::getInstance()->create('GET', 'http://127.0.0.1:9876/'); + $r = new Response(200); + $request->setClient(new Client()); + $request->setResponse($r, true); + $this->multi->add($request); + $this->multi->send(); + $this->assertSame($r, $request->getResponse()); + } + + public function testRemovesQueuedRequestsAddedInTransit() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")); + $client = new Client($this->getServer()->getUrl()); + $r = $client->get(); + $r->getEventDispatcher()->addListener('request.receive.status_line', function (Event $event) use ($client) { + // Create a request using a queued response + $request = $client->get()->setResponse(new Response(200), true); + $request->send(); + }); + $r->send(); + $this->assertEquals(1, count($this->getServer()->getReceivedRequests(false))); + } + + public function testCatchesExceptionsBeforeSendingSingleRequest() + { + $client = new Client($this->getServer()->getUrl()); + $multi = new CurlMulti(); + $client->setCurlMulti($multi); + $request = $client->get(); + $request->getEventDispatcher()->addListener('request.before_send', function() { + throw new \RuntimeException('Testing!'); + }); + try { + $request->send(); + $this->fail('Did not throw'); + } catch (\RuntimeException $e) { + // Ensure it was removed + $this->assertEquals(0, count($multi)); + } + } + + /** + * @expectedException \Guzzle\Common\Exception\ExceptionCollection + * @expectedExceptionMessage Thrown before sending! + */ + public function testCatchesExceptionsBeforeSendingMultipleRequests() + { + $client = new Client($this->getServer()->getUrl()); + $request = $client->get(); + $request->getEventDispatcher()->addListener('request.before_send', function() { + throw new \RuntimeException('Thrown before sending!'); + }); + $client->send(array($request)); + } + + public function testCatchesExceptionsWhenRemovingQueuedRequests() + { + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + $client = new Client($this->getServer()->getUrl()); + $r = $client->get(); + $r->getEventDispatcher()->addListener('request.sent', function() use ($client) { + // Create a request using a queued response + $client->get()->setResponse(new Response(404), true)->send(); + }); + try { + $r->send(); + $this->fail('Did not throw'); + } catch (BadResponseException $e) { + $this->assertCount(0, $client->getCurlMulti()); + } + } + + public function testCatchesExceptionsWhenRemovingQueuedRequestsBeforeSending() + { + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + $client = new Client($this->getServer()->getUrl()); + $r = $client->get(); + $r->getEventDispatcher()->addListener('request.before_send', function() use ($client) { + // Create a request using a queued response + $client->get()->setResponse(new Response(404), true)->send(); + }); + try { + $r->send(); + $this->fail('Did not throw'); + } catch (BadResponseException $e) { + $this->assertCount(0, $client->getCurlMulti()); + } + } + + /** + * @expectedException \RuntimeException + * @expectedExceptionMessage test + */ + public function testDoesNotCatchRandomExceptionsThrownDuringPerform() + { + $client = new Client($this->getServer()->getUrl()); + $multi = $this->getMock('Guzzle\\Http\\Curl\\CurlMulti', array('perform')); + $multi->expects($this->once()) + ->method('perform') + ->will($this->throwException(new \RuntimeException('test'))); + $multi->add($client->get()); + $multi->send(); + } + + public function testDoesNotSendRequestsDecliningToBeSent() + { + if (!defined('CURLOPT_TIMEOUT_MS')) { + $this->markTestSkipped('Update curl'); + } + + // Create a client that is bound to fail connecting + $client = new Client('http://127.0.0.1:123', array( + 'curl.CURLOPT_PORT' => 123, + 'curl.CURLOPT_CONNECTTIMEOUT_MS' => 1, + )); + + $request = $client->get(); + $multi = new CurlMulti(); + $multi->add($request); + + // Listen for request exceptions, and when they occur, first change the + // state of the request back to transferring, and then just allow it to + // exception out + $request->getEventDispatcher()->addListener('request.exception', function(Event $event) use ($multi) { + $retries = $event['request']->getParams()->get('retries'); + // Allow the first failure to retry + if ($retries == 0) { + $event['request']->setState('transfer'); + $event['request']->getParams()->set('retries', 1); + // Remove the request to try again + $multi->remove($event['request']); + $multi->add($event['request']); + } + }); + + try { + $multi->send(); + $this->fail('Did not throw an exception at all!?!'); + } catch (\Exception $e) { + $this->assertEquals(1, $request->getParams()->get('retries')); + } + } + + public function testDoesNotThrowExceptionsWhenRequestsRecoverWithRetry() + { + $this->getServer()->flush(); + $client = new Client($this->getServer()->getUrl()); + $request = $client->get(); + $request->getEventDispatcher()->addListener('request.before_send', function(Event $event) { + $event['request']->setResponse(new Response(200)); + }); + + $multi = new CurlMulti(); + $multi->add($request); + $multi->send(); + $this->assertEquals(0, count($this->getServer()->getReceivedRequests(false))); + } + + public function testDoesNotThrowExceptionsWhenRequestsRecoverWithSuccess() + { + // Attempt a port that 99.9% is not listening + $client = new Client('http://127.0.0.1:123'); + $request = $client->get(); + // Ensure it times out quickly if needed + $request->getCurlOptions()->set(CURLOPT_TIMEOUT_MS, 1)->set(CURLOPT_CONNECTTIMEOUT_MS, 1); + + $request->getEventDispatcher()->addListener('request.exception', function(Event $event) use (&$count) { + $event['request']->setResponse(new Response(200)); + }); + + $multi = new CurlMulti(); + $multi->add($request); + $multi->send(); + + // Ensure that the exception was caught, and the response was set manually + $this->assertEquals(200, $request->getResponse()->getStatusCode()); + } + + public function testHardResetReopensMultiHandle() + { + $this->getServer()->enqueue(array( + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n" + )); + + $stream = fopen('php://temp', 'w+'); + $client = new Client($this->getServer()->getUrl()); + $client->getConfig()->set('curl.CURLOPT_VERBOSE', true)->set('curl.CURLOPT_STDERR', $stream); + + $request = $client->get(); + $multi = new CurlMulti(); + $multi->add($request); + $multi->send(); + $multi->reset(true); + $multi->add($request); + $multi->send(); + + rewind($stream); + $this->assertNotContains('Re-using existing connection', stream_get_contents($stream)); + } + + public function testThrowsMeaningfulExceptionsForCurlMultiErrors() + { + $multi = new CurlMulti(); + + // Set the state of the multi object to sending to trigger the exception + $reflector = new \ReflectionMethod('Guzzle\Http\Curl\CurlMulti', 'checkCurlResult'); + $reflector->setAccessible(true); + + // Successful + $reflector->invoke($multi, 0); + + // Known error + try { + $reflector->invoke($multi, CURLM_BAD_HANDLE); + $this->fail('Expected an exception here'); + } catch (CurlException $e) { + $this->assertContains('The passed-in handle is not a valid CURLM handle.', $e->getMessage()); + $this->assertContains('CURLM_BAD_HANDLE', $e->getMessage()); + $this->assertContains(strval(CURLM_BAD_HANDLE), $e->getMessage()); + } + + // Unknown error + try { + $reflector->invoke($multi, 255); + $this->fail('Expected an exception here'); + } catch (CurlException $e) { + $this->assertEquals('Unexpected cURL error: 255', $e->getMessage()); + } + } + + public function testRequestBeforeSendIncludesContentLengthHeaderIfEmptyBody() + { + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + $request = new Request('PUT', $this->getServer()->getUrl()); + $that = $this; + $request->getEventDispatcher()->addListener('request.before_send', function ($event) use ($that) { + $that->assertEquals(0, $event['request']->getHeader('Content-Length')); + }); + $this->multi->add($request); + $this->multi->send(); + } + + public function testRemovesConflictingTransferEncodingHeader() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ntest", + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n" + )); + $client = new Client($this->getServer()->getUrl()); + $request = $client->put('/', null, fopen($this->getServer()->getUrl(), 'r')); + $request->setHeader('Content-Length', 4); + $request->send(); + $received = $this->getServer()->getReceivedRequests(true); + $this->assertFalse($received[1]->hasHeader('Transfer-Encoding')); + $this->assertEquals(4, (string) $received[1]->getHeader('Content-Length')); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/CurlVersionTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/CurlVersionTest.php new file mode 100644 index 000000000..c7b5ee6e9 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/CurlVersionTest.php @@ -0,0 +1,39 @@ +getProperty('version'); + $refProperty->setAccessible(true); + $refProperty->setValue($instance, array()); + + $this->assertEquals($info, $instance->getAll()); + $this->assertEquals($info, $instance->getAll()); + + $this->assertEquals($info['version'], $instance->get('version')); + $this->assertFalse($instance->get('foo')); + } + + public function testIsSingleton() + { + $refObject = new \ReflectionClass('Guzzle\Http\Curl\CurlVersion'); + $refProperty = $refObject->getProperty('instance'); + $refProperty->setAccessible(true); + $refProperty->setValue(null, null); + + $this->assertInstanceOf('Guzzle\Http\Curl\CurlVersion', CurlVersion::getInstance()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/RequestMediatorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/RequestMediatorTest.php new file mode 100644 index 000000000..c69e0c904 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Curl/RequestMediatorTest.php @@ -0,0 +1,67 @@ +events[] = $event; + } + + public function testEmitsEvents() + { + $request = new EntityEnclosingRequest('PUT', 'http://www.example.com'); + $request->setBody('foo'); + $request->setResponse(new Response(200)); + + // Ensure that IO events are emitted + $request->getCurlOptions()->set('emit_io', true); + + // Attach listeners for each event type + $request->getEventDispatcher()->addListener('curl.callback.progress', array($this, 'event')); + $request->getEventDispatcher()->addListener('curl.callback.read', array($this, 'event')); + $request->getEventDispatcher()->addListener('curl.callback.write', array($this, 'event')); + + $mediator = new RequestMediator($request, true); + + $mediator->progress('a', 'b', 'c', 'd'); + $this->assertEquals(1, count($this->events)); + $this->assertEquals('curl.callback.progress', $this->events[0]->getName()); + + $this->assertEquals(3, $mediator->writeResponseBody('foo', 'bar')); + $this->assertEquals(2, count($this->events)); + $this->assertEquals('curl.callback.write', $this->events[1]->getName()); + $this->assertEquals('bar', $this->events[1]['write']); + $this->assertSame($request, $this->events[1]['request']); + + $this->assertEquals('foo', $mediator->readRequestBody('a', 'b', 3)); + $this->assertEquals(3, count($this->events)); + $this->assertEquals('curl.callback.read', $this->events[2]->getName()); + $this->assertEquals('foo', $this->events[2]['read']); + $this->assertSame($request, $this->events[2]['request']); + } + + public function testDoesNotUseRequestResponseBodyWhenNotCustom() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 307 Foo\r\nLocation: /foo\r\nContent-Length: 2\r\n\r\nHI", + "HTTP/1.1 301 Foo\r\nLocation: /foo\r\nContent-Length: 2\r\n\r\nFI", + "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ntest", + )); + $client = new Client($this->getServer()->getUrl()); + $response = $client->get()->send(); + $this->assertEquals('test', $response->getBody(true)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/EntityBodyTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/EntityBodyTest.php new file mode 100644 index 000000000..124a44da6 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/EntityBodyTest.php @@ -0,0 +1,182 @@ +assertEquals('data', (string) $body); + $this->assertEquals(4, $body->getContentLength()); + $this->assertEquals('PHP', $body->getWrapper()); + $this->assertEquals('TEMP', $body->getStreamType()); + + $handle = fopen(__DIR__ . '/../../../../phpunit.xml.dist', 'r'); + if (!$handle) { + $this->fail('Could not open test file'); + } + $body = EntityBody::factory($handle); + $this->assertEquals(__DIR__ . '/../../../../phpunit.xml.dist', $body->getUri()); + $this->assertTrue($body->isLocal()); + $this->assertEquals(__DIR__ . '/../../../../phpunit.xml.dist', $body->getUri()); + $this->assertEquals(filesize(__DIR__ . '/../../../../phpunit.xml.dist'), $body->getContentLength()); + + // make sure that a body will return as the same object + $this->assertTrue($body === EntityBody::factory($body)); + } + + public function testFactoryCreatesTempStreamByDefault() + { + $body = EntityBody::factory(''); + $this->assertEquals('PHP', $body->getWrapper()); + $this->assertEquals('TEMP', $body->getStreamType()); + $body = EntityBody::factory(); + $this->assertEquals('PHP', $body->getWrapper()); + $this->assertEquals('TEMP', $body->getStreamType()); + } + + public function testFactoryCanCreateFromObject() + { + $body = EntityBody::factory(new QueryString(array('foo' => 'bar'))); + $this->assertEquals('foo=bar', (string) $body); + } + + /** + * @expectedException \Guzzle\Common\Exception\InvalidArgumentException + */ + public function testFactoryEnsuresObjectsHaveToStringMethod() + { + EntityBody::factory(new \stdClass('a')); + } + + public function testHandlesCompression() + { + $body = EntityBody::factory('testing 123...testing 123'); + $this->assertFalse($body->getContentEncoding(), '-> getContentEncoding() must initially return FALSE'); + $size = $body->getContentLength(); + $body->compress(); + $this->assertEquals('gzip', $body->getContentEncoding(), '-> getContentEncoding() must return the correct encoding after compressing'); + $this->assertEquals(gzdeflate('testing 123...testing 123'), (string) $body); + $this->assertTrue($body->getContentLength() < $size); + $this->assertTrue($body->uncompress()); + $this->assertEquals('testing 123...testing 123', (string) $body); + $this->assertFalse($body->getContentEncoding(), '-> getContentEncoding() must reset to FALSE'); + + if (in_array('bzip2.*', stream_get_filters())) { + $this->assertTrue($body->compress('bzip2.compress')); + $this->assertEquals('compress', $body->getContentEncoding(), '-> compress() must set \'compress\' as the Content-Encoding'); + } + + $this->assertFalse($body->compress('non-existent'), '-> compress() must return false when a non-existent stream filter is used'); + + // Release the body + unset($body); + + // Use gzip compression on the initial content. This will include a + // gzip header which will need to be stripped when deflating the stream + $body = EntityBody::factory(gzencode('test')); + $this->assertSame($body, $body->setStreamFilterContentEncoding('zlib.deflate')); + $this->assertTrue($body->uncompress('zlib.inflate')); + $this->assertEquals('test', (string) $body); + unset($body); + + // Test using a very long string + $largeString = ''; + for ($i = 0; $i < 25000; $i++) { + $largeString .= chr(rand(33, 126)); + } + $body = EntityBody::factory($largeString); + $this->assertEquals($largeString, (string) $body); + $this->assertTrue($body->compress()); + $this->assertNotEquals($largeString, (string) $body); + $compressed = (string) $body; + $this->assertTrue($body->uncompress()); + $this->assertEquals($largeString, (string) $body); + $this->assertEquals($compressed, gzdeflate($largeString)); + + $body = EntityBody::factory(fopen(__DIR__ . '/../TestData/compress_test', 'w')); + $this->assertFalse($body->compress()); + unset($body); + + unlink(__DIR__ . '/../TestData/compress_test'); + } + + public function testDeterminesContentType() + { + // Test using a string/temp stream + $body = EntityBody::factory('testing 123...testing 123'); + $this->assertNull($body->getContentType()); + + // Use a local file + $body = EntityBody::factory(fopen(__FILE__, 'r')); + $this->assertContains('text/x-', $body->getContentType()); + } + + public function testCreatesMd5Checksum() + { + $body = EntityBody::factory('testing 123...testing 123'); + $this->assertEquals(md5('testing 123...testing 123'), $body->getContentMd5()); + + $server = $this->getServer()->enqueue( + "HTTP/1.1 200 OK" . "\r\n" . + "Content-Length: 3" . "\r\n\r\n" . + "abc" + ); + + $body = EntityBody::factory(fopen($this->getServer()->getUrl(), 'r')); + $this->assertFalse($body->getContentMd5()); + } + + public function testSeeksToOriginalPosAfterMd5() + { + $body = EntityBody::factory('testing 123'); + $body->seek(4); + $this->assertEquals(md5('testing 123'), $body->getContentMd5()); + $this->assertEquals(4, $body->ftell()); + $this->assertEquals('ing 123', $body->read(1000)); + } + + public function testGetTypeFormBodyFactoring() + { + $body = EntityBody::factory(array('key1' => 'val1', 'key2' => 'val2')); + $this->assertEquals('key1=val1&key2=val2', (string) $body); + } + + public function testAllowsCustomRewind() + { + $body = EntityBody::factory('foo'); + $rewound = false; + $body->setRewindFunction(function ($body) use (&$rewound) { + $rewound = true; + return $body->seek(0); + }); + $body->seek(2); + $this->assertTrue($body->rewind()); + $this->assertTrue($rewound); + } + + /** + * @expectedException \Guzzle\Common\Exception\InvalidArgumentException + */ + public function testCustomRewindFunctionMustBeCallable() + { + $body = EntityBody::factory(); + $body->setRewindFunction('foo'); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Exception/CurlExceptionTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Exception/CurlExceptionTest.php new file mode 100644 index 000000000..df3e4b791 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Exception/CurlExceptionTest.php @@ -0,0 +1,27 @@ +assertNull($e->getError()); + $this->assertNull($e->getErrorNo()); + $this->assertSame($e, $e->setError('test', 12)); + $this->assertEquals('test', $e->getError()); + $this->assertEquals(12, $e->getErrorNo()); + + $handle = new CurlHandle(curl_init(), array()); + $e->setCurlHandle($handle); + $this->assertSame($handle, $e->getCurlHandle()); + $handle->close(); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Exception/ExceptionTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Exception/ExceptionTest.php new file mode 100644 index 000000000..12cfd369e --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Exception/ExceptionTest.php @@ -0,0 +1,66 @@ +setRequest($request); + $this->assertEquals($request, $e->getRequest()); + } + + /** + * @covers Guzzle\Http\Exception\BadResponseException + */ + public function testBadResponseException() + { + $e = new BadResponseException('Message'); + $response = new Response(200); + $e->setResponse($response); + $this->assertEquals($response, $e->getResponse()); + } + + /** + * @covers Guzzle\Http\Exception\BadResponseException::factory + */ + public function testCreatesGenericErrorExceptionOnError() + { + $request = new Request('GET', 'http://www.example.com'); + $response = new Response(307); + $e = BadResponseException::factory($request, $response); + $this->assertInstanceOf('Guzzle\Http\Exception\BadResponseException', $e); + } + + /** + * @covers Guzzle\Http\Exception\BadResponseException::factory + */ + public function testCreatesClientErrorExceptionOnClientError() + { + $request = new Request('GET', 'http://www.example.com'); + $response = new Response(404); + $e = BadResponseException::factory($request, $response); + $this->assertInstanceOf('Guzzle\Http\Exception\ClientErrorResponseException', $e); + } + + /** + * @covers Guzzle\Http\Exception\BadResponseException::factory + */ + public function testCreatesServerErrorExceptionOnServerError() + { + $request = new Request('GET', 'http://www.example.com'); + $response = new Response(503); + $e = BadResponseException::factory($request, $response); + $this->assertInstanceOf('Guzzle\Http\Exception\ServerErrorResponseException', $e); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Exception/MultiTransferExceptionTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Exception/MultiTransferExceptionTest.php new file mode 100644 index 000000000..fa4ec2626 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Exception/MultiTransferExceptionTest.php @@ -0,0 +1,51 @@ +addSuccessfulRequest($r1); + $e->addFailedRequest($r2); + $this->assertEquals(array($r1), $e->getSuccessfulRequests()); + $this->assertEquals(array($r2), $e->getSuccessfulRequests()); + $this->assertEquals(array($r1, $r2), $e->getAllRequests()); + $this->assertTrue($e->containsRequest($r1)); + $this->assertTrue($e->containsRequest($r2)); + $this->assertFalse($e->containsRequest(new Request('POST', '/foo'))); + } + + public function testCanSetRequests() + { + $s = array($r1 = new Request('GET', 'http://www.foo.com')); + $f = array($r2 = new Request('GET', 'http://www.foo.com')); + $e = new MultiTransferException(); + $e->setSuccessfulRequests($s); + $e->setFailedRequests($f); + $this->assertEquals(array($r1), $e->getSuccessfulRequests()); + $this->assertEquals(array($r2), $e->getSuccessfulRequests()); + } + + public function testAssociatesExceptionsWithRequests() + { + $r1 = new Request('GET', 'http://www.foo.com'); + $re1 = new \Exception('foo'); + $re2 = new \Exception('bar'); + $e = new MultiTransferException(); + $e->add($re2); + $e->addFailedRequestWithException($r1, $re1); + $this->assertSame($re1, $e->getExceptionForFailedRequest($r1)); + $this->assertNull($e->getExceptionForFailedRequest(new Request('POST', '/foo'))); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/IoEmittingEntityBodyTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/IoEmittingEntityBodyTest.php new file mode 100644 index 000000000..cd6355f3b --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/IoEmittingEntityBodyTest.php @@ -0,0 +1,47 @@ +decorated = EntityBody::factory('hello'); + $this->body = new IoEmittingEntityBody($this->decorated); + } + + public function testEmitsReadEvents() + { + $e = null; + $this->body->getEventDispatcher()->addListener('body.read', function ($event) use (&$e) { + $e = $event; + }); + $this->assertEquals('hel', $this->body->read(3)); + $this->assertEquals('hel', $e['read']); + $this->assertEquals(3, $e['length']); + $this->assertSame($this->body, $e['body']); + } + + public function testEmitsWriteEvents() + { + $e = null; + $this->body->getEventDispatcher()->addListener('body.write', function ($event) use (&$e) { + $e = $event; + }); + $this->body->seek(0, SEEK_END); + $this->assertEquals(5, $this->body->write('there')); + $this->assertEquals('there', $e['write']); + $this->assertEquals(5, $e['result']); + $this->assertSame($this->body, $e['body']); + $this->assertEquals('hellothere', (string) $this->body); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/AbstractMessageTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/AbstractMessageTest.php new file mode 100644 index 000000000..9447d8c5d --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/AbstractMessageTest.php @@ -0,0 +1,136 @@ +mock = $this->getMockForAbstractClass('Guzzle\Http\Message\AbstractMessage'); + } + + public function tearDown() + { + $this->mock = $this->request = null; + } + + public function testGetParams() + { + $request = new Request('GET', 'http://example.com'); + $this->assertInstanceOf('Guzzle\\Common\\Collection', $request->getParams()); + } + + public function testAddHeaders() + { + $this->mock->setHeader('A', 'B'); + + $this->assertEquals($this->mock, $this->mock->addHeaders(array( + 'X-Data' => '123' + ))); + + $this->assertTrue($this->mock->hasHeader('X-Data') !== false); + $this->assertTrue($this->mock->hasHeader('A') !== false); + } + + public function testAllowsHeaderToSetAsHeader() + { + $h = new Header('A', 'B'); + $this->mock->setHeader('A', $h); + $this->assertSame($h, $this->mock->getHeader('A')); + } + + public function testGetHeader() + { + $this->mock->setHeader('Test', '123'); + $this->assertEquals('123', $this->mock->getHeader('Test')); + } + + public function testGetHeaders() + { + $this->assertSame($this->mock, $this->mock->setHeaders(array('a' => 'b', 'c' => 'd'))); + $h = $this->mock->getHeaders(); + $this->assertArrayHasKey('a', $h->toArray()); + $this->assertArrayHasKey('c', $h->toArray()); + $this->assertInstanceOf('Guzzle\Http\Message\Header\HeaderInterface', $h->get('a')); + $this->assertInstanceOf('Guzzle\Http\Message\Header\HeaderInterface', $h->get('c')); + } + + public function testGetHeaderLinesUsesGlue() + { + $this->mock->setHeaders(array('a' => 'b', 'c' => 'd')); + $this->mock->addHeader('a', 'e'); + $this->mock->getHeader('a')->setGlue('!'); + $this->assertEquals(array( + 'a: b! e', + 'c: d' + ), $this->mock->getHeaderLines()); + } + + public function testHasHeader() + { + $this->assertFalse($this->mock->hasHeader('Foo')); + $this->mock->setHeader('Foo', 'Bar'); + $this->assertEquals(true, $this->mock->hasHeader('Foo')); + $this->mock->setHeader('foo', 'yoo'); + $this->assertEquals(true, $this->mock->hasHeader('Foo')); + $this->assertEquals(true, $this->mock->hasHeader('foo')); + $this->assertEquals(false, $this->mock->hasHeader('bar')); + } + + public function testRemoveHeader() + { + $this->mock->setHeader('Foo', 'Bar'); + $this->assertEquals(true, $this->mock->hasHeader('Foo')); + $this->mock->removeHeader('Foo'); + $this->assertFalse($this->mock->hasHeader('Foo')); + } + + public function testReturnsNullWhenHeaderIsNotFound() + { + $this->assertNull($this->mock->getHeader('foo')); + } + + public function testAddingHeadersPreservesOriginalHeaderCase() + { + $this->mock->addHeaders(array( + 'test' => '123', + 'Test' => 'abc' + )); + $this->mock->addHeader('test', '456'); + $this->mock->addHeader('test', '789'); + + $header = $this->mock->getHeader('test'); + $this->assertContains('123', $header->toArray()); + $this->assertContains('456', $header->toArray()); + $this->assertContains('789', $header->toArray()); + $this->assertContains('abc', $header->toArray()); + } + + public function testCanStoreEmptyHeaders() + { + $this->mock->setHeader('Content-Length', 0); + $this->assertTrue($this->mock->hasHeader('Content-Length')); + $this->assertEquals(0, (string) $this->mock->getHeader('Content-Length')); + } + + public function testCanSetCustomHeaderFactory() + { + $f = new Header\HeaderFactory(); + $this->mock->setHeaderFactory($f); + $this->assertSame($f, $this->readAttribute($this->mock, 'headerFactory')); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/EntityEnclosingRequestTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/EntityEnclosingRequestTest.php new file mode 100644 index 000000000..191b02223 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/EntityEnclosingRequestTest.php @@ -0,0 +1,434 @@ +client = new Client(); + } + + public function tearDown() + { + $this->client = null; + } + + public function testConstructorConfiguresRequest() + { + $request = new EntityEnclosingRequest('PUT', 'http://test.com', array( + 'X-Test' => '123' + )); + $request->setBody('Test'); + $this->assertEquals('123', $request->getHeader('X-Test')); + $this->assertNull($request->getHeader('Expect')); + } + + public function testCanSetBodyWithoutOverridingContentType() + { + $request = new EntityEnclosingRequest('PUT', 'http://test.com', array('Content-Type' => 'foooooo')); + $request->setBody('{"a":"b"}'); + $this->assertEquals('foooooo', $request->getHeader('Content-Type')); + } + + public function testRequestIncludesBodyInMessage() + { + + $request = RequestFactory::getInstance()->create('PUT', 'http://www.guzzle-project.com/', null, 'data'); + $this->assertEquals("PUT / HTTP/1.1\r\n" + . "Host: www.guzzle-project.com\r\n" + . "Content-Length: 4\r\n\r\n" + . "data", (string) $request); + } + + public function testRequestIncludesPostBodyInMessageOnlyWhenNoPostFiles() + { + $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/', null, array( + 'foo' => 'bar' + )); + $this->assertEquals("POST / HTTP/1.1\r\n" + . "Host: www.guzzle-project.com\r\n" + . "Content-Type: application/x-www-form-urlencoded; charset=utf-8\r\n\r\n" + . "foo=bar", (string) $request); + + $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/', null, array( + 'foo' => '@' . __FILE__ + )); + $this->assertEquals("POST / HTTP/1.1\r\n" + . "Host: www.guzzle-project.com\r\n" + . "Content-Type: multipart/form-data\r\n" + . "Expect: 100-Continue\r\n\r\n", (string) $request); + } + + public function testAddsPostFieldsAndSetsContentLength() + { + $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/', null, array( + 'data' => '123' + )); + $this->assertEquals("POST / HTTP/1.1\r\n" + . "Host: www.guzzle-project.com\r\n" + . "Content-Type: application/x-www-form-urlencoded; charset=utf-8\r\n\r\n" + . "data=123", (string) $request); + } + + public function testAddsPostFilesAndSetsContentType() + { + $request = RequestFactory::getInstance()->create('POST', 'http://www.test.com/') + ->addPostFiles(array( + 'file' => __FILE__ + ))->addPostFields(array( + 'a' => 'b' + )); + $message = (string) $request; + $this->assertEquals('multipart/form-data', $request->getHeader('Content-Type')); + $this->assertEquals('100-Continue', $request->getHeader('Expect')); + } + + public function testRequestBodyContainsPostFiles() + { + $request = RequestFactory::getInstance()->create('POST', 'http://www.test.com/'); + $request->addPostFields(array( + 'test' => '123' + )); + $this->assertContains("\r\n\r\ntest=123", (string) $request); + } + + public function testRequestBodyAddsContentLength() + { + $request = RequestFactory::getInstance()->create('PUT', 'http://www.test.com/'); + $request->setBody(EntityBody::factory('test')); + $this->assertEquals(4, (string) $request->getHeader('Content-Length')); + $this->assertFalse($request->hasHeader('Transfer-Encoding')); + } + + public function testRequestBodyDoesNotUseContentLengthWhenChunked() + { + $request = RequestFactory::getInstance()->create('PUT', 'http://www.test.com/', array( + 'Transfer-Encoding' => 'chunked' + ), 'test'); + $this->assertNull($request->getHeader('Content-Length')); + $this->assertTrue($request->hasHeader('Transfer-Encoding')); + } + + public function testRequestHasMutableBody() + { + $request = RequestFactory::getInstance()->create('PUT', 'http://www.guzzle-project.com/', null, 'data'); + $body = $request->getBody(); + $this->assertInstanceOf('Guzzle\\Http\\EntityBody', $body); + $this->assertSame($body, $request->getBody()); + + $newBody = EntityBody::factory('foobar'); + $request->setBody($newBody); + $this->assertEquals('foobar', (string) $request->getBody()); + $this->assertSame($newBody, $request->getBody()); + } + + public function testSetPostFields() + { + $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/'); + $this->assertInstanceOf('Guzzle\\Http\\QueryString', $request->getPostFields()); + + $fields = new QueryString(array( + 'a' => 'b' + )); + $request->addPostFields($fields); + $this->assertEquals($fields->getAll(), $request->getPostFields()->getAll()); + $this->assertEquals(array(), $request->getPostFiles()); + } + + public function testSetPostFiles() + { + $request = RequestFactory::getInstance()->create('POST', $this->getServer()->getUrl()) + ->setClient(new Client()) + ->addPostFiles(array(__FILE__)) + ->addPostFields(array( + 'test' => 'abc' + )); + + $request->getCurlOptions()->set('debug', true); + + $this->assertEquals(array( + 'test' => 'abc' + ), $request->getPostFields()->getAll()); + + $files = $request->getPostFiles(); + $post = $files['file'][0]; + $this->assertEquals('file', $post->getFieldName()); + $this->assertContains('text/x-', $post->getContentType()); + $this->assertEquals(__FILE__, $post->getFilename()); + + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + $request->send(); + + $this->assertNotNull($request->getHeader('Content-Length')); + $this->assertContains('multipart/form-data; boundary=', (string) $request->getHeader('Content-Type'), '-> cURL must add the boundary'); + } + + /** + * @expectedException Guzzle\Common\Exception\InvalidArgumentException + */ + public function testSetPostFilesThrowsExceptionWhenFileIsNotFound() + { + $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/') + ->addPostFiles(array( + 'file' => 'filenotfound.ini' + )); + } + + /** + * @expectedException Guzzle\Http\Exception\RequestException + */ + public function testThrowsExceptionWhenNonStringsAreAddedToPost() + { + $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/') + ->addPostFile('foo', new \stdClass()); + } + + public function testAllowsContentTypeInPostUploads() + { + $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/') + ->addPostFile('foo', __FILE__, 'text/plain'); + + $this->assertEquals(array( + new PostFile('foo', __FILE__, 'text/plain') + ), $request->getPostFile('foo')); + } + + public function testGuessesContentTypeOfPostUpload() + { + $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/') + ->addPostFile('foo', __FILE__); + $file = $request->getPostFile('foo'); + $this->assertContains('text/x-', $file[0]->getContentType()); + } + + public function testAllowsContentDispositionFieldsInPostUploadsWhenSettingInBulk() + { + $postFile = new PostFile('foo', __FILE__, 'text/x-php'); + $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/') + ->addPostFiles(array('foo' => $postFile)); + + $this->assertEquals(array($postFile), $request->getPostFile('foo')); + } + + public function testPostRequestsUseApplicationXwwwForUrlEncodedForArrays() + { + $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/'); + $request->setPostField('a', 'b'); + $this->assertContains("\r\n\r\na=b", (string) $request); + $this->assertEquals('application/x-www-form-urlencoded; charset=utf-8', $request->getHeader('Content-Type')); + } + + public function testProcessMethodAddsContentType() + { + $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/'); + $request->setPostField('a', 'b'); + $this->assertEquals('application/x-www-form-urlencoded; charset=utf-8', $request->getHeader('Content-Type')); + } + + public function testPostRequestsUseMultipartFormDataWithFiles() + { + $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/'); + $request->addPostFiles(array('file' => __FILE__)); + $this->assertEquals('multipart/form-data', $request->getHeader('Content-Type')); + } + + public function testCanSendMultipleRequestsUsingASingleRequestObject() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 201 Created\r\nContent-Length: 0\r\n\r\n", + )); + + // Send the first request + $request = RequestFactory::getInstance()->create('PUT', $this->getServer()->getUrl()) + ->setBody('test') + ->setClient(new Client()); + $request->send(); + $this->assertEquals(200, $request->getResponse()->getStatusCode()); + + // Send the second request + $request->setBody('abcdefg', 'application/json', false); + $request->send(); + $this->assertEquals(201, $request->getResponse()->getStatusCode()); + + // Ensure that the same request was sent twice with different bodies + $requests = $this->getServer()->getReceivedRequests(true); + $this->assertEquals(2, count($requests)); + $this->assertEquals(4, (string) $requests[0]->getHeader('Content-Length')); + $this->assertEquals(7, (string) $requests[1]->getHeader('Content-Length')); + } + + public function testRemovingPostFieldRebuildsPostFields() + { + $request = new EntityEnclosingRequest('POST', 'http://test.com'); + $request->setPostField('test', 'value'); + $request->removePostField('test'); + $this->assertNull($request->getPostField('test')); + } + + public function testUsesChunkedTransferWhenBodyLengthCannotBeDetermined() + { + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + $request = new EntityEnclosingRequest('PUT', 'http://test.com/'); + $request->setBody(fopen($this->getServer()->getUrl(), 'r')); + $this->assertEquals('chunked', $request->getHeader('Transfer-Encoding')); + $this->assertFalse($request->hasHeader('Content-Length')); + } + + /** + * @expectedException \Guzzle\Http\Exception\RequestException + */ + public function testThrowsExceptionWhenContentLengthCannotBeDeterminedAndUsingHttp1() + { + $request = new EntityEnclosingRequest('PUT', 'http://test.com/'); + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + $request->setProtocolVersion('1.0'); + $request->setBody(fopen($this->getServer()->getUrl(), 'r')); + } + + public function testAllowsNestedPostData() + { + $request = new EntityEnclosingRequest('POST', 'http://test.com/'); + $request->addPostFields(array( + 'a' => array('b', 'c') + )); + $this->assertEquals(array( + 'a' => array('b', 'c') + ), $request->getPostFields()->getAll()); + } + + public function testAllowsEmptyFields() + { + $request = new EntityEnclosingRequest('POST', 'http://test.com/'); + $request->addPostFields(array( + 'a' => '' + )); + $this->assertEquals(array( + 'a' => '' + ), $request->getPostFields()->getAll()); + } + + /** + * @expectedException \Guzzle\Http\Exception\RequestException + */ + public function testFailsOnInvalidFiles() + { + $request = new EntityEnclosingRequest('POST', 'http://test.com/'); + $request->addPostFiles(array( + 'a' => new \stdClass() + )); + } + + public function testHandlesEmptyStrings() + { + $request = new EntityEnclosingRequest('POST', 'http://test.com/'); + $request->addPostFields(array( + 'a' => '', + 'b' => null, + 'c' => 'Foo' + )); + $this->assertEquals(array( + 'a' => '', + 'b' => null, + 'c' => 'Foo' + ), $request->getPostFields()->getAll()); + } + + public function testHoldsPostFiles() + { + $request = new EntityEnclosingRequest('POST', 'http://test.com/'); + $request->addPostFile('foo', __FILE__); + $request->addPostFile(new PostFile('foo', __FILE__)); + + $this->assertArrayHasKey('foo', $request->getPostFiles()); + $foo = $request->getPostFile('foo'); + $this->assertEquals(2, count($foo)); + $this->assertEquals(__FILE__, $foo[0]->getFilename()); + $this->assertEquals(__FILE__, $foo[1]->getFilename()); + + $request->removePostFile('foo'); + $this->assertEquals(array(), $request->getPostFiles()); + } + + public function testAllowsAtPrefixWhenAddingPostFiles() + { + $request = new EntityEnclosingRequest('POST', 'http://test.com/'); + $request->addPostFiles(array( + 'foo' => '@' . __FILE__ + )); + $foo = $request->getPostFile('foo'); + $this->assertEquals(__FILE__, $foo[0]->getFilename()); + } + + public function testSetStateToTransferWithEmptyBodySetsContentLengthToZero() + { + $request = new EntityEnclosingRequest('POST', 'http://test.com/'); + $request->setState($request::STATE_TRANSFER); + $this->assertEquals('0', (string) $request->getHeader('Content-Length')); + } + + public function testSettingExpectHeaderCutoffChangesRequest() + { + $request = new EntityEnclosingRequest('PUT', 'http://test.com/'); + $request->setHeader('Expect', '100-Continue'); + $request->setExpectHeaderCutoff(false); + $this->assertNull($request->getHeader('Expect')); + // There is not body, so remove the expect header + $request->setHeader('Expect', '100-Continue'); + $request->setExpectHeaderCutoff(10); + $this->assertNull($request->getHeader('Expect')); + // The size is less than the cutoff + $request->setBody('foo'); + $this->assertNull($request->getHeader('Expect')); + // The size is greater than the cutoff + $request->setBody('foobazbarbamboo'); + $this->assertNotNull($request->getHeader('Expect')); + } + + public function testStrictRedirectsCanBeSpecifiedOnEntityEnclosingRequests() + { + $request = new EntityEnclosingRequest('PUT', 'http://test.com/'); + $request->configureRedirects(true); + $this->assertTrue($request->getParams()->get(RedirectPlugin::STRICT_REDIRECTS)); + } + + public function testCanDisableRedirects() + { + $request = new EntityEnclosingRequest('PUT', 'http://test.com/'); + $request->configureRedirects(false, false); + $this->assertTrue($request->getParams()->get(RedirectPlugin::DISABLE)); + } + + public function testSetsContentTypeWhenSettingBodyByGuessingFromEntityBody() + { + $request = new EntityEnclosingRequest('PUT', 'http://test.com/foo'); + $request->setBody(EntityBody::factory(fopen(__FILE__, 'r'))); + $this->assertEquals('text/x-php', (string) $request->getHeader('Content-Type')); + } + + public function testDoesNotCloneBody() + { + $request = new EntityEnclosingRequest('PUT', 'http://test.com/foo'); + $request->setBody('test'); + $newRequest = clone $request; + $newRequest->setBody('foo'); + $this->assertInternalType('string', (string) $request->getBody()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/Header/HeaderFactoryTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/Header/HeaderFactoryTest.php new file mode 100644 index 000000000..62ca5559d --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/Header/HeaderFactoryTest.php @@ -0,0 +1,29 @@ +createHeader('Foo', 'Bar'); + $this->assertInstanceOf('Guzzle\Http\Message\Header', $h); + $this->assertEquals('Foo', $h->getName()); + $this->assertEquals('Bar', (string) $h); + } + + public function testCreatesSpecificHeaders() + { + $f = new HeaderFactory(); + $h = $f->createHeader('Link', '; rel="test"'); + $this->assertInstanceOf('Guzzle\Http\Message\Header\Link', $h); + $this->assertEquals('Link', $h->getName()); + $this->assertEquals('; rel="test"', (string) $h); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/Header/LinkTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/Header/LinkTest.php new file mode 100644 index 000000000..c834d1016 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/Header/LinkTest.php @@ -0,0 +1,63 @@ +; rel=front; type="image/jpeg", ; rel=back; type="image/jpeg", ; rel=side; type="image/jpeg"'); + $links = $link->getLinks(); + $this->assertEquals(array( + array( + 'rel' => 'front', + 'type' => 'image/jpeg', + 'url' => 'http:/.../front.jpeg', + ), + array( + 'rel' => 'back', + 'type' => 'image/jpeg', + 'url' => 'http://.../back.jpeg', + ), + array( + 'rel' => 'side', + 'type' => 'image/jpeg', + 'url' => 'http://.../side.jpeg?test=1' + ) + ), $links); + + $this->assertEquals(array( + 'rel' => 'back', + 'type' => 'image/jpeg', + 'url' => 'http://.../back.jpeg', + ), $link->getLink('back')); + + $this->assertTrue($link->hasLink('front')); + $this->assertFalse($link->hasLink('foo')); + } + + public function testCanAddLink() + { + $link = new Link('Link', '; rel=a; type="image/jpeg"'); + $link->addLink('http://test.com', 'test', array('foo' => 'bar')); + $this->assertEquals( + '; rel=a; type="image/jpeg", ; rel="test"; foo="bar"', + (string) $link + ); + } + + public function testCanParseLinksWithCommas() + { + $link = new Link('Link', '; rel="previous"; title="start, index"'); + $this->assertEquals(array( + array( + 'rel' => 'previous', + 'title' => 'start, index', + 'url' => 'http://example.com/TheBook/chapter1', + ) + ), $link->getLinks()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/HeaderComparison.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/HeaderComparison.php new file mode 100644 index 000000000..a3f511bfc --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/HeaderComparison.php @@ -0,0 +1,135 @@ +toArray(); + } + + foreach ($filteredHeaders as $k => $v) { + if ($k[0] == '_') { + // This header should be ignored + $ignore[] = str_replace('_', '', $k); + } elseif ($k[0] == '!') { + // This header must not be present + $absent[] = str_replace('!', '', $k); + } else { + $expected[$k] = $v; + } + } + + return $this->compareArray($expected, $actualHeaders, $ignore, $absent); + } + + /** + * Check if an array of HTTP headers matches another array of HTTP headers while taking * into account as a wildcard + * + * @param array $expected Expected HTTP headers (allows wildcard values) + * @param array|Collection $actual Actual HTTP header array + * @param array $ignore Headers to ignore from the comparison + * @param array $absent Array of headers that must not be present + * + * @return array|bool Returns an array of the differences or FALSE if none + */ + public function compareArray(array $expected, $actual, array $ignore = array(), array $absent = array()) + { + $differences = array(); + + // Add information about headers that were present but weren't supposed to be + foreach ($absent as $header) { + if ($this->hasKey($header, $actual)) { + $differences["++ {$header}"] = $actual[$header]; + unset($actual[$header]); + } + } + + // Check if expected headers are missing + foreach ($expected as $header => $value) { + if (!$this->hasKey($header, $actual)) { + $differences["- {$header}"] = $value; + } + } + + // Flip the ignore array so it works with the case insensitive helper + $ignore = array_flip($ignore); + // Allow case-insensitive comparisons in wildcards + $expected = array_change_key_case($expected); + + // Compare the expected and actual HTTP headers in no particular order + foreach ($actual as $key => $value) { + + // If this is to be ignored, the skip it + if ($this->hasKey($key, $ignore)) { + continue; + } + + // If the header was not expected + if (!$this->hasKey($key, $expected)) { + $differences["+ {$key}"] = $value; + continue; + } + + // Check values and take wildcards into account + $lkey = strtolower($key); + $pos = is_string($expected[$lkey]) ? strpos($expected[$lkey], '*') : false; + + foreach ((array) $actual[$key] as $v) { + if (($pos === false && $v != $expected[$lkey]) || $pos > 0 && substr($v, 0, $pos) != substr($expected[$lkey], 0, $pos)) { + $differences[$key] = "{$value} != {$expected[$lkey]}"; + } + } + } + + return empty($differences) ? false : $differences; + } + + /** + * Case insensitive check if an array have a key + * + * @param string $key Key to check + * @param array $array Array to check + * + * @return bool + */ + protected function hasKey($key, $array) + { + if ($array instanceof Collection) { + $keys = $array->getKeys(); + } else { + $keys = array_keys($array); + } + + foreach ($keys as $k) { + if (!strcasecmp($k, $key)) { + return true; + } + } + + return false; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/HeaderComparisonTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/HeaderComparisonTest.php new file mode 100644 index 000000000..86c4fe866 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/HeaderComparisonTest.php @@ -0,0 +1,115 @@ + 'Foo' + ), array( + 'Content-Length' => 'Foo' + ), false), + + // Missing header + array(array( + 'X-Foo' => 'Bar' + ), array(), array( + '- X-Foo' => 'Bar' + )), + + // Extra headers is present + array(array( + 'X-Foo' => 'Bar' + ), array( + 'X-Foo' => 'Bar', + 'X-Baz' => 'Jar' + ), array( + '+ X-Baz' => 'Jar' + )), + + // Header is present but must be absent + array(array( + '!X-Foo' => '*' + ), array( + 'X-Foo' => 'Bar' + ), array( + '++ X-Foo' => 'Bar' + )), + + // Different values + array(array( + 'X-Foo' => 'Bar' + ), array( + 'X-Foo' => 'Baz' + ), array( + 'X-Foo' => 'Baz != Bar' + )), + + // Wildcard search passes + array(array( + 'X-Foo' => '*' + ), array( + 'X-Foo' => 'Bar' + ), false), + + // Wildcard search fails + array(array( + 'X-Foo' => '*' + ), array(), array( + '- X-Foo' => '*' + )), + + // Ignore extra header if present + array(array( + 'X-Foo' => '*', + '_X-Bar' => '*', + ), array( + 'X-Foo' => 'Baz', + 'X-Bar' => 'Jar' + ), false), + + // Ignore extra header if present and is not + array(array( + 'X-Foo' => '*', + '_X-Bar' => '*', + ), array( + 'X-Foo' => 'Baz' + ), false), + + // Case insensitive + array(array( + 'X-Foo' => '*', + '_X-Bar' => '*', + ), array( + 'x-foo' => 'Baz', + 'x-BAR' => 'baz' + ), false), + + // Case insensitive with collection + array(array( + 'X-Foo' => '*', + '_X-Bar' => '*', + ), new Collection(array( + 'x-foo' => 'Baz', + 'x-BAR' => 'baz' + )), false), + ); + } + + /** + * @dataProvider filterProvider + */ + public function testComparesHeaders($filters, $headers, $result) + { + $compare = new HeaderComparison(); + $this->assertEquals($result, $compare->compare($filters, $headers)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/HeaderTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/HeaderTest.php new file mode 100644 index 000000000..c7502349f --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/HeaderTest.php @@ -0,0 +1,162 @@ + array('foo', 'Foo'), + 'Zoo' => 'bar', + ); + + public function testStoresHeaderName() + { + $i = new Header('Zoo', $this->test); + $this->assertEquals('Zoo', $i->getName()); + } + + public function testConvertsToString() + { + $i = new Header('Zoo', $this->test); + $this->assertEquals('foo, Foo, bar', (string) $i); + $i->setGlue(';'); + $this->assertEquals('foo; Foo; bar', (string) $i); + } + + public function testNormalizesGluedHeaders() + { + $h = new Header('Zoo', array('foo, Faz', 'bar')); + $result = $h->normalize(true)->toArray(); + natsort($result); + $this->assertEquals(array('bar', 'foo', 'Faz'), $result); + } + + public function testCanSearchForValues() + { + $h = new Header('Zoo', $this->test); + $this->assertTrue($h->hasValue('foo')); + $this->assertTrue($h->hasValue('Foo')); + $this->assertTrue($h->hasValue('bar')); + $this->assertFalse($h->hasValue('moo')); + $this->assertFalse($h->hasValue('FoO')); + } + + public function testIsCountable() + { + $h = new Header('Zoo', $this->test); + $this->assertEquals(3, count($h)); + } + + public function testCanBeIterated() + { + $h = new Header('Zoo', $this->test); + $results = array(); + foreach ($h as $key => $value) { + $results[$key] = $value; + } + $this->assertEquals(array( + 'foo', 'Foo', 'bar' + ), $results); + } + + public function testAllowsFalseyValues() + { + // Allows 0 + $h = new Header('Foo', 0, ';'); + $this->assertEquals('0', (string) $h); + $this->assertEquals(1, count($h)); + $this->assertEquals(';', $h->getGlue()); + + // Does not add a null header by default + $h = new Header('Foo'); + $this->assertEquals('', (string) $h); + $this->assertEquals(0, count($h)); + + // Allows null array for a single null header + $h = new Header('Foo', array(null)); + $this->assertEquals('', (string) $h); + + // Allows empty string + $h = new Header('Foo', ''); + $this->assertEquals('', (string) $h); + $this->assertEquals(1, count($h)); + $this->assertEquals(1, count($h->normalize()->toArray())); + } + + public function testCanRemoveValues() + { + $h = new Header('Foo', array('Foo', 'baz', 'bar')); + $h->removeValue('bar'); + $this->assertTrue($h->hasValue('Foo')); + $this->assertFalse($h->hasValue('bar')); + $this->assertTrue($h->hasValue('baz')); + } + + public function testAllowsArrayInConstructor() + { + $h = new Header('Foo', array('Testing', '123', 'Foo=baz')); + $this->assertEquals(array('Testing', '123', 'Foo=baz'), $h->toArray()); + } + + public function parseParamsProvider() + { + $res1 = array( + array( + '' => '', + 'rel' => 'front', + 'type' => 'image/jpeg', + ), + array( + '' => '', + 'rel' => 'back', + 'type' => 'image/jpeg', + ), + ); + + return array( + array( + '; rel="front"; type="image/jpeg", ; rel=back; type="image/jpeg"', + $res1 + ), + array( + '; rel="front"; type="image/jpeg",; rel=back; type="image/jpeg"', + $res1 + ), + array( + 'foo="baz"; bar=123, boo, test="123", foobar="foo;bar"', + array( + array('foo' => 'baz', 'bar' => '123'), + array('boo' => ''), + array('test' => '123'), + array('foobar' => 'foo;bar') + ) + ), + array( + '; rel="side"; type="image/jpeg",; rel=side; type="image/jpeg"', + array( + array('' => '', 'rel' => 'side', 'type' => 'image/jpeg'), + array('' => '', 'rel' => 'side', 'type' => 'image/jpeg') + ) + ), + array( + '', + array() + ) + ); + } + + /** + * @dataProvider parseParamsProvider + */ + public function testParseParams($header, $result) + { + $response = new Response(200, array('Link' => $header)); + $this->assertEquals($result, $response->getHeader('Link')->parseParams()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/PostFileTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/PostFileTest.php new file mode 100644 index 000000000..be048cb95 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/PostFileTest.php @@ -0,0 +1,88 @@ +assertEquals('foo', $file->getFieldName()); + $this->assertEquals(__FILE__, $file->getFilename()); + $this->assertEquals('boo', $file->getPostName()); + $this->assertEquals('x-foo', $file->getContentType()); + } + + public function testRemovesLeadingAtSymbolFromPath() + { + $file = new PostFile('foo', '@' . __FILE__); + $this->assertEquals(__FILE__, $file->getFilename()); + } + + /** + * @expectedException Guzzle\Common\Exception\InvalidArgumentException + */ + public function testEnsuresFileIsReadable() + { + $file = new PostFile('foo', '/foo/baz/bar'); + } + + public function testCanChangeContentType() + { + $file = new PostFile('foo', '@' . __FILE__); + $file->setContentType('Boo'); + $this->assertEquals('Boo', $file->getContentType()); + } + + public function testCanChangeFieldName() + { + $file = new PostFile('foo', '@' . __FILE__); + $file->setFieldName('Boo'); + $this->assertEquals('Boo', $file->getFieldName()); + } + + public function testReturnsCurlValueString() + { + $file = new PostFile('foo', __FILE__); + if (version_compare(phpversion(), '5.5.0', '<')) { + $this->assertContains('@' . __FILE__ . ';filename=PostFileTest.php;type=text/x-', $file->getCurlValue()); + } else { + $c = $file->getCurlValue(); + $this->assertEquals(__FILE__, $c->getFilename()); + $this->assertEquals('PostFileTest.php', $c->getPostFilename()); + $this->assertContains('text/x-', $c->getMimeType()); + } + } + + public function testReturnsCurlValueStringAndPostname() + { + $file = new PostFile('foo', __FILE__, null, 'NewPostFileTest.php'); + if (version_compare(phpversion(), '5.5.0', '<')) { + $this->assertContains('@' . __FILE__ . ';filename=NewPostFileTest.php;type=text/x-', $file->getCurlValue()); + } else { + $c = $file->getCurlValue(); + $this->assertEquals(__FILE__, $c->getFilename()); + $this->assertEquals('NewPostFileTest.php', $c->getPostFilename()); + $this->assertContains('text/x-', $c->getMimeType()); + } + } + + public function testContentDispositionFilePathIsStripped() + { + $this->getServer()->flush(); + $client = new Client($this->getServer()->getUrl()); + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + $request = $client->post()->addPostFile('file', __FILE__); + $request->send(); + $requests = $this->getServer()->getReceivedRequests(false); + $this->assertContains('POST / HTTP/1.1', $requests[0]); + $this->assertContains('Content-Disposition: form-data; name="file"; filename="PostFileTest.php"', $requests[0]); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/RequestFactoryTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/RequestFactoryTest.php new file mode 100644 index 000000000..80b8d5415 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/RequestFactoryTest.php @@ -0,0 +1,616 @@ +assertSame($factory, RequestFactory::getInstance()); + } + + public function testCreatesNewGetRequests() + { + $request = RequestFactory::getInstance()->create('GET', 'http://www.google.com/'); + $this->assertInstanceOf('Guzzle\\Http\\Message\\MessageInterface', $request); + $this->assertInstanceOf('Guzzle\\Http\\Message\\RequestInterface', $request); + $this->assertInstanceOf('Guzzle\\Http\\Message\\Request', $request); + $this->assertEquals('GET', $request->getMethod()); + $this->assertEquals('http', $request->getScheme()); + $this->assertEquals('http://www.google.com/', $request->getUrl()); + $this->assertEquals('www.google.com', $request->getHost()); + $this->assertEquals('/', $request->getPath()); + $this->assertEquals('/', $request->getResource()); + + // Create a GET request with a custom receiving body + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + $b = EntityBody::factory(); + $request = RequestFactory::getInstance()->create('GET', $this->getServer()->getUrl(), null, $b); + $request->setClient(new Client()); + $response = $request->send(); + $this->assertSame($b, $response->getBody()); + } + + public function testCreatesPutRequests() + { + // Test using a string + $request = RequestFactory::getInstance()->create('PUT', 'http://www.google.com/path?q=1&v=2', null, 'Data'); + $this->assertInstanceOf('Guzzle\\Http\\Message\\EntityEnclosingRequest', $request); + $this->assertEquals('PUT', $request->getMethod()); + $this->assertEquals('http', $request->getScheme()); + $this->assertEquals('http://www.google.com/path?q=1&v=2', $request->getUrl()); + $this->assertEquals('www.google.com', $request->getHost()); + $this->assertEquals('/path', $request->getPath()); + $this->assertEquals('/path?q=1&v=2', $request->getResource()); + $this->assertInstanceOf('Guzzle\\Http\\EntityBody', $request->getBody()); + $this->assertEquals('Data', (string) $request->getBody()); + unset($request); + + // Test using an EntityBody + $request = RequestFactory::getInstance()->create('PUT', 'http://www.google.com/path?q=1&v=2', null, EntityBody::factory('Data')); + $this->assertInstanceOf('Guzzle\\Http\\Message\\EntityEnclosingRequest', $request); + $this->assertEquals('Data', (string) $request->getBody()); + + // Test using a resource + $resource = fopen('php://temp', 'w+'); + fwrite($resource, 'Data'); + $request = RequestFactory::getInstance()->create('PUT', 'http://www.google.com/path?q=1&v=2', null, $resource); + $this->assertInstanceOf('Guzzle\\Http\\Message\\EntityEnclosingRequest', $request); + $this->assertEquals('Data', (string) $request->getBody()); + + // Test using an object that can be cast as a string + $request = RequestFactory::getInstance()->create('PUT', 'http://www.google.com/path?q=1&v=2', null, Url::factory('http://www.example.com/')); + $this->assertInstanceOf('Guzzle\\Http\\Message\\EntityEnclosingRequest', $request); + $this->assertEquals('http://www.example.com/', (string) $request->getBody()); + } + + public function testCreatesHeadAndDeleteRequests() + { + $request = RequestFactory::getInstance()->create('DELETE', 'http://www.test.com/'); + $this->assertEquals('DELETE', $request->getMethod()); + $request = RequestFactory::getInstance()->create('HEAD', 'http://www.test.com/'); + $this->assertEquals('HEAD', $request->getMethod()); + } + + public function testCreatesOptionsRequests() + { + $request = RequestFactory::getInstance()->create('OPTIONS', 'http://www.example.com/'); + $this->assertEquals('OPTIONS', $request->getMethod()); + $this->assertInstanceOf('Guzzle\\Http\\Message\\EntityEnclosingRequest', $request); + } + + public function testCreatesNewPutRequestWithBody() + { + $request = RequestFactory::getInstance()->create('PUT', 'http://www.google.com/path?q=1&v=2', null, 'Data'); + $this->assertEquals('Data', (string) $request->getBody()); + } + + public function testCreatesNewPostRequestWithFields() + { + // Use an array + $request = RequestFactory::getInstance()->create('POST', 'http://www.google.com/path?q=1&v=2', null, array( + 'a' => 'b' + )); + $this->assertEquals(array('a' => 'b'), $request->getPostFields()->getAll()); + unset($request); + + // Use a collection + $request = RequestFactory::getInstance()->create('POST', 'http://www.google.com/path?q=1&v=2', null, new Collection(array( + 'a' => 'b' + ))); + $this->assertEquals(array('a' => 'b'), $request->getPostFields()->getAll()); + + // Use a QueryString + $request = RequestFactory::getInstance()->create('POST', 'http://www.google.com/path?q=1&v=2', null, new QueryString(array( + 'a' => 'b' + ))); + $this->assertEquals(array('a' => 'b'), $request->getPostFields()->getAll()); + + $request = RequestFactory::getInstance()->create('POST', 'http://www.test.com/', null, array( + 'a' => 'b', + 'file' => '@' . __FILE__ + )); + + $this->assertEquals(array( + 'a' => 'b' + ), $request->getPostFields()->getAll()); + + $files = $request->getPostFiles(); + $this->assertInstanceOf('Guzzle\Http\Message\PostFile', $files['file'][0]); + } + + public function testCreatesFromParts() + { + $parts = parse_url('http://michael:123@www.google.com:8080/path?q=1&v=2'); + + $request = RequestFactory::getInstance()->fromParts('PUT', $parts, null, 'Data'); + $this->assertInstanceOf('Guzzle\\Http\\Message\\EntityEnclosingRequest', $request); + $this->assertEquals('PUT', $request->getMethod()); + $this->assertEquals('http', $request->getScheme()); + $this->assertEquals('http://www.google.com:8080/path?q=1&v=2', $request->getUrl()); + $this->assertEquals('www.google.com', $request->getHost()); + $this->assertEquals('www.google.com:8080', $request->getHeader('Host')); + $this->assertEquals('/path', $request->getPath()); + $this->assertEquals('/path?q=1&v=2', $request->getResource()); + $this->assertInstanceOf('Guzzle\\Http\\EntityBody', $request->getBody()); + $this->assertEquals('Data', (string) $request->getBody()); + $this->assertEquals('michael', $request->getUsername()); + $this->assertEquals('123', $request->getPassword()); + $this->assertEquals('8080', $request->getPort()); + $this->assertEquals(array( + 'scheme' => 'http', + 'host' => 'www.google.com', + 'port' => 8080, + 'path' => '/path', + 'query' => 'q=1&v=2', + ), parse_url($request->getUrl())); + } + + public function testCreatesFromMessage() + { + $auth = base64_encode('michael:123'); + $message = "PUT /path?q=1&v=2 HTTP/1.1\r\nHost: www.google.com:8080\r\nContent-Length: 4\r\nAuthorization: Basic {$auth}\r\n\r\nData"; + $request = RequestFactory::getInstance()->fromMessage($message); + $this->assertInstanceOf('Guzzle\\Http\\Message\\EntityEnclosingRequest', $request); + $this->assertEquals('PUT', $request->getMethod()); + $this->assertEquals('http', $request->getScheme()); + $this->assertEquals('http://www.google.com:8080/path?q=1&v=2', $request->getUrl()); + $this->assertEquals('www.google.com', $request->getHost()); + $this->assertEquals('www.google.com:8080', $request->getHeader('Host')); + $this->assertEquals('/path', $request->getPath()); + $this->assertEquals('/path?q=1&v=2', $request->getResource()); + $this->assertInstanceOf('Guzzle\\Http\\EntityBody', $request->getBody()); + $this->assertEquals('Data', (string) $request->getBody()); + $this->assertEquals("Basic {$auth}", (string) $request->getHeader('Authorization')); + $this->assertEquals('8080', $request->getPort()); + + // Test passing a blank message returns false + $this->assertFalse($request = RequestFactory::getInstance()->fromMessage('')); + + // Test passing a url with no port + $message = "PUT /path?q=1&v=2 HTTP/1.1\r\nHost: www.google.com\r\nContent-Length: 4\r\nAuthorization: Basic {$auth}\r\n\r\nData"; + $request = RequestFactory::getInstance()->fromMessage($message); + $this->assertInstanceOf('Guzzle\\Http\\Message\\EntityEnclosingRequest', $request); + $this->assertEquals('PUT', $request->getMethod()); + $this->assertEquals('http', $request->getScheme()); + $this->assertEquals('http://www.google.com/path?q=1&v=2', $request->getUrl()); + $this->assertEquals('www.google.com', $request->getHost()); + $this->assertEquals('/path', $request->getPath()); + $this->assertEquals('/path?q=1&v=2', $request->getResource()); + $this->assertInstanceOf('Guzzle\\Http\\EntityBody', $request->getBody()); + $this->assertEquals('Data', (string) $request->getBody()); + $this->assertEquals("Basic {$auth}", (string) $request->getHeader('Authorization')); + $this->assertEquals(80, $request->getPort()); + } + + public function testCreatesNewTraceRequest() + { + $request = RequestFactory::getInstance()->create('TRACE', 'http://www.google.com/'); + $this->assertFalse($request instanceof \Guzzle\Http\Message\EntityEnclosingRequest); + $this->assertEquals('TRACE', $request->getMethod()); + } + + public function testCreatesProperTransferEncodingRequests() + { + $request = RequestFactory::getInstance()->create('PUT', 'http://www.google.com/', array( + 'Transfer-Encoding' => 'chunked' + ), 'hello'); + $this->assertEquals('chunked', $request->getHeader('Transfer-Encoding')); + $this->assertFalse($request->hasHeader('Content-Length')); + } + + public function testProperlyDealsWithDuplicateHeaders() + { + $parser = new MessageParser(); + + $message = "POST / http/1.1\r\n" + . "DATE:Mon, 09 Sep 2011 23:36:00 GMT\r\n" + . "host:host.foo.com\r\n" + . "ZOO:abc\r\n" + . "ZOO:123\r\n" + . "ZOO:HI\r\n" + . "zoo:456\r\n\r\n"; + + $parts = $parser->parseRequest($message); + $this->assertEquals(array ( + 'DATE' => 'Mon, 09 Sep 2011 23:36:00 GMT', + 'host' => 'host.foo.com', + 'ZOO' => array('abc', '123', 'HI'), + 'zoo' => '456', + ), $parts['headers']); + + $request = RequestFactory::getInstance()->fromMessage($message); + + $this->assertEquals(array( + 'abc', '123', 'HI', '456' + ), $request->getHeader('zoo')->toArray()); + } + + public function testCreatesHttpMessagesWithBodiesAndNormalizesLineEndings() + { + $message = "POST / http/1.1\r\n" + . "Content-Type:application/x-www-form-urlencoded; charset=utf8\r\n" + . "Date:Mon, 09 Sep 2011 23:36:00 GMT\r\n" + . "Host:host.foo.com\r\n\r\n" + . "foo=bar"; + + $request = RequestFactory::getInstance()->fromMessage($message); + $this->assertEquals('application/x-www-form-urlencoded; charset=utf8', (string) $request->getHeader('Content-Type')); + $this->assertEquals('foo=bar', (string) $request->getBody()); + + $message = "POST / http/1.1\n" + . "Content-Type:application/x-www-form-urlencoded; charset=utf8\n" + . "Date:Mon, 09 Sep 2011 23:36:00 GMT\n" + . "Host:host.foo.com\n\n" + . "foo=bar"; + $request = RequestFactory::getInstance()->fromMessage($message); + $this->assertEquals('foo=bar', (string) $request->getBody()); + + $message = "PUT / HTTP/1.1\r\nContent-Length: 0\r\n\r\n"; + $request = RequestFactory::getInstance()->fromMessage($message); + $this->assertTrue($request->hasHeader('Content-Length')); + $this->assertEquals(0, (string) $request->getHeader('Content-Length')); + } + + public function testBugPathIncorrectlyHandled() + { + $message = "POST /foo\r\n\r\nBODY"; + $request = RequestFactory::getInstance()->fromMessage($message); + $this->assertSame('POST', $request->getMethod()); + $this->assertSame('/foo', $request->getPath()); + $this->assertSame('BODY', (string) $request->getBody()); + } + + public function testHandlesChunkedTransferEncoding() + { + $request = RequestFactory::getInstance()->create('PUT', 'http://www.foo.com/', array( + 'Transfer-Encoding' => 'chunked' + ), 'Test'); + $this->assertFalse($request->hasHeader('Content-Length')); + $this->assertEquals('chunked', $request->getHeader('Transfer-Encoding')); + + $request = RequestFactory::getInstance()->create('POST', 'http://www.foo.com/', array( + 'transfer-encoding' => 'chunked' + ), array( + 'foo' => 'bar' + )); + + $this->assertFalse($request->hasHeader('Content-Length')); + $this->assertEquals('chunked', $request->getHeader('Transfer-Encoding')); + } + + public function testClonesRequestsWithMethodWithoutClient() + { + $f = RequestFactory::getInstance(); + $request = $f->create('GET', 'http://www.test.com', array('X-Foo' => 'Bar')); + $request->getParams()->replace(array('test' => '123')); + $request->getCurlOptions()->set('foo', 'bar'); + $cloned = $f->cloneRequestWithMethod($request, 'PUT'); + $this->assertEquals('PUT', $cloned->getMethod()); + $this->assertEquals('Bar', (string) $cloned->getHeader('X-Foo')); + $this->assertEquals('http://www.test.com', $cloned->getUrl()); + // Ensure params are cloned and cleaned up + $this->assertEquals(1, count($cloned->getParams()->getAll())); + $this->assertEquals('123', $cloned->getParams()->get('test')); + // Ensure curl options are cloned + $this->assertEquals('bar', $cloned->getCurlOptions()->get('foo')); + // Ensure event dispatcher is cloned + $this->assertNotSame($request->getEventDispatcher(), $cloned->getEventDispatcher()); + } + + public function testClonesRequestsWithMethodWithClient() + { + $f = RequestFactory::getInstance(); + $client = new Client(); + $request = $client->put('http://www.test.com', array('Content-Length' => 4), 'test'); + $cloned = $f->cloneRequestWithMethod($request, 'GET'); + $this->assertEquals('GET', $cloned->getMethod()); + $this->assertNull($cloned->getHeader('Content-Length')); + $this->assertEquals('http://www.test.com', $cloned->getUrl()); + $this->assertSame($request->getClient(), $cloned->getClient()); + } + + public function testClonesRequestsWithMethodWithClientWithEntityEnclosingChange() + { + $f = RequestFactory::getInstance(); + $client = new Client(); + $request = $client->put('http://www.test.com', array('Content-Length' => 4), 'test'); + $cloned = $f->cloneRequestWithMethod($request, 'POST'); + $this->assertEquals('POST', $cloned->getMethod()); + $this->assertEquals('test', (string) $cloned->getBody()); + } + + public function testCanDisableRedirects() + { + $this->getServer()->enqueue(array( + "HTTP/1.1 307\r\nLocation: " . $this->getServer()->getUrl() . "\r\nContent-Length: 0\r\n\r\n" + )); + $client = new Client($this->getServer()->getUrl()); + $response = $client->get('/', array(), array('allow_redirects' => false))->send(); + $this->assertEquals(307, $response->getStatusCode()); + } + + public function testCanAddCookies() + { + $client = new Client($this->getServer()->getUrl()); + $request = $client->get('/', array(), array('cookies' => array('Foo' => 'Bar'))); + $this->assertEquals('Bar', $request->getCookie('Foo')); + } + + public function testCanAddQueryString() + { + $request = RequestFactory::getInstance()->create('GET', 'http://foo.com', array(), null, array( + 'query' => array('Foo' => 'Bar') + )); + $this->assertEquals('Bar', $request->getQuery()->get('Foo')); + } + + public function testCanSetDefaultQueryString() + { + $request = new Request('GET', 'http://www.foo.com?test=abc'); + RequestFactory::getInstance()->applyOptions($request, array( + 'query' => array('test' => '123', 'other' => 't123') + ), RequestFactory::OPTIONS_AS_DEFAULTS); + $this->assertEquals('abc', $request->getQuery()->get('test')); + $this->assertEquals('t123', $request->getQuery()->get('other')); + } + + public function testCanAddBasicAuth() + { + $request = RequestFactory::getInstance()->create('GET', 'http://foo.com', array(), null, array( + 'auth' => array('michael', 'test') + )); + $this->assertEquals('michael', $request->getUsername()); + $this->assertEquals('test', $request->getPassword()); + } + + public function testCanAddDigestAuth() + { + $request = RequestFactory::getInstance()->create('GET', 'http://foo.com', array(), null, array( + 'auth' => array('michael', 'test', 'digest') + )); + $this->assertEquals(CURLAUTH_DIGEST, $request->getCurlOptions()->get(CURLOPT_HTTPAUTH)); + $this->assertEquals('michael', $request->getUsername()); + $this->assertEquals('test', $request->getPassword()); + } + + public function testCanAddEvents() + { + $foo = null; + $client = new Client(); + $client->addSubscriber(new MockPlugin(array(new Response(200)))); + $request = $client->get($this->getServer()->getUrl(), array(), array( + 'events' => array( + 'request.before_send' => function () use (&$foo) { $foo = true; } + ) + )); + $request->send(); + $this->assertTrue($foo); + } + + public function testCanAddEventsWithPriority() + { + $foo = null; + $client = new Client(); + $client->addSubscriber(new MockPlugin(array(new Response(200)))); + $request = $client->get($this->getServer()->getUrl(), array(), array( + 'events' => array( + 'request.before_send' => array(function () use (&$foo) { $foo = true; }, 100) + ) + )); + $request->send(); + $this->assertTrue($foo); + } + + public function testCanAddPlugins() + { + $mock = new MockPlugin(array( + new Response(200), + new Response(200) + )); + $client = new Client(); + $client->addSubscriber($mock); + $request = $client->get('/', array(), array( + 'plugins' => array($mock) + )); + $request->send(); + } + + public function testCanDisableExceptions() + { + $client = new Client(); + $request = $client->get('/', array(), array( + 'plugins' => array(new MockPlugin(array(new Response(500)))), + 'exceptions' => false + )); + $this->assertEquals(500, $request->send()->getStatusCode()); + } + + public function testCanDisableExceptionsWithErrorListener() + { + $client = new Client(); + $client->getEventDispatcher()->addListener('request.error', function () {}); + $request = $client->get('/', array(), array( + 'plugins' => array(new MockPlugin(array(new Response(500)))), + 'exceptions' => false + )); + $this->assertEquals(500, $request->send()->getStatusCode()); + } + + public function testCanChangeSaveToLocation() + { + $r = EntityBody::factory(); + $client = new Client(); + $request = $client->get('/', array(), array( + 'plugins' => array(new MockPlugin(array(new Response(200, array(), 'testing')))), + 'save_to' => $r + )); + $request->send(); + $this->assertEquals('testing', (string) $r); + } + + public function testCanSetProxy() + { + $client = new Client(); + $request = $client->get('/', array(), array('proxy' => '192.168.16.121')); + $this->assertEquals('192.168.16.121', $request->getCurlOptions()->get(CURLOPT_PROXY)); + } + + public function testCanSetHeadersOption() + { + $client = new Client(); + $request = $client->get('/', array(), array('headers' => array('Foo' => 'Bar'))); + $this->assertEquals('Bar', (string) $request->getHeader('Foo')); + } + + public function testCanSetDefaultHeadersOptions() + { + $request = new Request('GET', 'http://www.foo.com', array('Foo' => 'Bar')); + RequestFactory::getInstance()->applyOptions($request, array( + 'headers' => array('Foo' => 'Baz', 'Bam' => 't123') + ), RequestFactory::OPTIONS_AS_DEFAULTS); + $this->assertEquals('Bar', (string) $request->getHeader('Foo')); + $this->assertEquals('t123', (string) $request->getHeader('Bam')); + } + + public function testCanSetBodyOption() + { + $client = new Client(); + $request = $client->put('/', array(), null, array('body' => 'test')); + $this->assertEquals('test', (string) $request->getBody()); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testValidatesBodyOption() + { + $client = new Client(); + $client->get('/', array(), array('body' => 'test')); + } + + public function testCanSetTimeoutOption() + { + $client = new Client(); + $request = $client->get('/', array(), array('timeout' => 1.5)); + $this->assertEquals(1500, $request->getCurlOptions()->get(CURLOPT_TIMEOUT_MS)); + } + + public function testCanSetConnectTimeoutOption() + { + $client = new Client(); + $request = $client->get('/', array(), array('connect_timeout' => 1.5)); + $this->assertEquals(1500, $request->getCurlOptions()->get(CURLOPT_CONNECTTIMEOUT_MS)); + } + + public function testCanSetDebug() + { + $client = new Client(); + $request = $client->get('/', array(), array('debug' => true)); + $this->assertTrue($request->getCurlOptions()->get(CURLOPT_VERBOSE)); + } + + public function testCanSetVerifyToOff() + { + $client = new Client(); + $request = $client->get('/', array(), array('verify' => false)); + $this->assertNull($request->getCurlOptions()->get(CURLOPT_CAINFO)); + $this->assertSame(0, $request->getCurlOptions()->get(CURLOPT_SSL_VERIFYHOST)); + $this->assertFalse($request->getCurlOptions()->get(CURLOPT_SSL_VERIFYPEER)); + } + + public function testCanSetVerifyToOn() + { + $client = new Client(); + $request = $client->get('/', array(), array('verify' => true)); + $this->assertNotNull($request->getCurlOptions()->get(CURLOPT_CAINFO)); + $this->assertSame(2, $request->getCurlOptions()->get(CURLOPT_SSL_VERIFYHOST)); + $this->assertTrue($request->getCurlOptions()->get(CURLOPT_SSL_VERIFYPEER)); + } + + public function testCanSetVerifyToPath() + { + $client = new Client(); + $request = $client->get('/', array(), array('verify' => '/foo.pem')); + $this->assertEquals('/foo.pem', $request->getCurlOptions()->get(CURLOPT_CAINFO)); + $this->assertSame(2, $request->getCurlOptions()->get(CURLOPT_SSL_VERIFYHOST)); + $this->assertTrue($request->getCurlOptions()->get(CURLOPT_SSL_VERIFYPEER)); + } + + public function inputValidation() + { + return array_map(function ($option) { return array($option); }, array( + 'headers', 'query', 'cookies', 'auth', 'events', 'plugins', 'params' + )); + } + + /** + * @dataProvider inputValidation + * @expectedException \Guzzle\Common\Exception\InvalidArgumentException + */ + public function testValidatesInput($option) + { + $client = new Client(); + $client->get('/', array(), array($option => 'foo')); + } + + public function testCanAddRequestParams() + { + $client = new Client(); + $request = $client->put('/', array(), null, array('params' => array('foo' => 'test'))); + $this->assertEquals('test', $request->getParams()->get('foo')); + } + + public function testCanAddSslKey() + { + $client = new Client(); + $request = $client->get('/', array(), array('ssl_key' => '/foo.pem')); + $this->assertEquals('/foo.pem', $request->getCurlOptions()->get(CURLOPT_SSLKEY)); + } + + public function testCanAddSslKeyPassword() + { + $client = new Client(); + $request = $client->get('/', array(), array('ssl_key' => array('/foo.pem', 'bar'))); + $this->assertEquals('/foo.pem', $request->getCurlOptions()->get(CURLOPT_SSLKEY)); + $this->assertEquals('bar', $request->getCurlOptions()->get(CURLOPT_SSLKEYPASSWD)); + } + + public function testCanAddSslCert() + { + $client = new Client(); + $request = $client->get('/', array(), array('cert' => '/foo.pem')); + $this->assertEquals('/foo.pem', $request->getCurlOptions()->get(CURLOPT_SSLCERT)); + } + + public function testCanAddSslCertPassword() + { + $client = new Client(); + $request = $client->get('/', array(), array('cert' => array('/foo.pem', 'bar'))); + $this->assertEquals('/foo.pem', $request->getCurlOptions()->get(CURLOPT_SSLCERT)); + $this->assertEquals('bar', $request->getCurlOptions()->get(CURLOPT_SSLCERTPASSWD)); + } + + public function testCreatesBodyWithoutZeroString() + { + $request = RequestFactory::getInstance()->create('PUT', 'http://test.com', array(), '0'); + $this->assertSame('0', (string) $request->getBody()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/RequestTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/RequestTest.php new file mode 100644 index 000000000..5bf624829 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/RequestTest.php @@ -0,0 +1,639 @@ +client = new Client($this->getServer()->getUrl()); + $this->request = $this->client->get(); + } + + public function tearDown() + { + unset($this->request); + unset($this->client); + } + + public function testConstructorBuildsRequestWithArrayHeaders() + { + // Test passing an array of headers + $request = new Request('GET', 'http://www.guzzle-project.com/', array( + 'foo' => 'bar' + )); + + $this->assertEquals('GET', $request->getMethod()); + $this->assertEquals('http://www.guzzle-project.com/', $request->getUrl()); + $this->assertEquals('bar', $request->getHeader('foo')); + } + + public function testDescribesEvents() + { + $this->assertInternalType('array', Request::getAllEvents()); + } + + public function testConstructorBuildsRequestWithCollectionHeaders() + { + $request = new Request('GET', 'http://www.guzzle-project.com/', new Collection(array( + 'foo' => 'bar' + ))); + $this->assertEquals('bar', $request->getHeader('foo')); + } + + public function testConstructorBuildsRequestWithNoHeaders() + { + $request = new Request('GET', 'http://www.guzzle-project.com/', null); + $this->assertFalse($request->hasHeader('foo')); + } + + public function testConstructorHandlesNonBasicAuth() + { + $request = new Request('GET', 'http://www.guzzle-project.com/', array( + 'Authorization' => 'Foo bar' + )); + $this->assertNull($request->getUserName()); + $this->assertNull($request->getPassword()); + $this->assertEquals('Foo bar', (string) $request->getHeader('Authorization')); + } + + public function testRequestsCanBeConvertedToRawMessageStrings() + { + $auth = base64_encode('michael:123'); + $message = "PUT /path?q=1&v=2 HTTP/1.1\r\n" + . "Host: www.google.com\r\n" + . "Authorization: Basic {$auth}\r\n" + . "Content-Length: 4\r\n\r\nData"; + + $request = RequestFactory::getInstance()->create('PUT', 'http://www.google.com/path?q=1&v=2', array( + 'Authorization' => 'Basic ' . $auth + ), 'Data'); + + $this->assertEquals($message, $request->__toString()); + } + + /** + * Add authorization after the fact and see that it was put in the message + */ + public function testRequestStringsIncludeAuth() + { + $auth = base64_encode('michael:123'); + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + $request = RequestFactory::getInstance()->create('PUT', $this->getServer()->getUrl(), null, 'Data') + ->setClient($this->client) + ->setAuth('michael', '123', CURLAUTH_BASIC); + $request->send(); + + $this->assertContains('Authorization: Basic ' . $auth, (string) $request); + } + + public function testGetEventDispatcher() + { + $d = $this->request->getEventDispatcher(); + $this->assertInstanceOf('Symfony\\Component\\EventDispatcher\\EventDispatcherInterface', $d); + $this->assertEquals($d, $this->request->getEventDispatcher()); + } + + public function testRequestsManageClients() + { + $request = new Request('GET', 'http://test.com'); + $this->assertNull($request->getClient()); + $request->setClient($this->client); + $this->assertSame($this->client, $request->getClient()); + } + + /** + * @expectedException \RuntimeException + * @expectedExceptionMessage A client must be set on the request + */ + public function testRequestsRequireClients() + { + $request = new Request('GET', 'http://test.com'); + $request->send(); + } + + public function testSend() + { + $response = new Response(200, array( + 'Content-Length' => 3 + ), 'abc'); + $this->request->setResponse($response, true); + $r = $this->request->send(); + + $this->assertSame($response, $r); + $this->assertInstanceOf('Guzzle\\Http\\Message\\Response', $this->request->getResponse()); + $this->assertSame($r, $this->request->getResponse()); + $this->assertEquals('complete', $this->request->getState()); + } + + public function testGetResponse() + { + $this->assertNull($this->request->getResponse()); + $response = new Response(200, array('Content-Length' => 3), 'abc'); + + $this->request->setResponse($response); + $this->assertEquals($response, $this->request->getResponse()); + + $client = new Client('http://www.google.com'); + $request = $client->get('http://www.google.com/'); + $request->setResponse($response, true); + $request->send(); + $requestResponse = $request->getResponse(); + $this->assertSame($response, $requestResponse); + + // Try again, making sure it's still the same response + $this->assertSame($requestResponse, $request->getResponse()); + + $response = new Response(204); + $request = $client->get(); + $request->setResponse($response, true); + $request->send(); + $requestResponse = $request->getResponse(); + $this->assertSame($response, $requestResponse); + $this->assertInstanceOf('Guzzle\\Http\\EntityBody', $response->getBody()); + } + + public function testRequestThrowsExceptionOnBadResponse() + { + try { + $this->request->setResponse(new Response(404, array('Content-Length' => 3), 'abc'), true); + $this->request->send(); + $this->fail('Expected exception not thrown'); + } catch (BadResponseException $e) { + $this->assertInstanceOf('Guzzle\\Http\\Message\\RequestInterface', $e->getRequest()); + $this->assertInstanceOf('Guzzle\\Http\\Message\\Response', $e->getResponse()); + $this->assertContains('Client error response', $e->getMessage()); + } + } + + public function testManagesQuery() + { + $this->assertInstanceOf('Guzzle\\Http\\QueryString', $this->request->getQuery()); + $this->request->getQuery()->set('test', '123'); + $this->assertEquals('test=123', $this->request->getQuery(true)); + } + + public function testRequestHasMethod() + { + $this->assertEquals('GET', $this->request->getMethod()); + } + + public function testRequestHasScheme() + { + $this->assertEquals('http', $this->request->getScheme()); + $this->assertEquals($this->request, $this->request->setScheme('https')); + $this->assertEquals('https', $this->request->getScheme()); + } + + public function testRequestHasHost() + { + $this->assertEquals('127.0.0.1', $this->request->getHost()); + $this->assertEquals('127.0.0.1:8124', (string) $this->request->getHeader('Host')); + + $this->assertSame($this->request, $this->request->setHost('www2.google.com')); + $this->assertEquals('www2.google.com', $this->request->getHost()); + $this->assertEquals('www2.google.com:8124', (string) $this->request->getHeader('Host')); + + $this->assertSame($this->request, $this->request->setHost('www.test.com:8081')); + $this->assertEquals('www.test.com', $this->request->getHost()); + $this->assertEquals(8081, $this->request->getPort()); + } + + public function testRequestHasProtocol() + { + $this->assertEquals('1.1', $this->request->getProtocolVersion()); + $this->assertEquals($this->request, $this->request->setProtocolVersion('1.1')); + $this->assertEquals('1.1', $this->request->getProtocolVersion()); + $this->assertEquals($this->request, $this->request->setProtocolVersion('1.0')); + $this->assertEquals('1.0', $this->request->getProtocolVersion()); + } + + public function testRequestHasPath() + { + $this->assertEquals('/', $this->request->getPath()); + $this->assertEquals($this->request, $this->request->setPath('/index.html')); + $this->assertEquals('/index.html', $this->request->getPath()); + $this->assertEquals($this->request, $this->request->setPath('index.html')); + $this->assertEquals('/index.html', $this->request->getPath()); + } + + public function testPermitsFalsyComponents() + { + $request = new Request('GET', 'http://0/0?0'); + $this->assertSame('0', $request->getHost()); + $this->assertSame('/0', $request->getPath()); + $this->assertSame('0', $request->getQuery(true)); + + $request = new Request('GET', '0'); + $this->assertEquals('/0', $request->getPath()); + } + + public function testRequestHasPort() + { + $this->assertEquals(8124, $this->request->getPort()); + $this->assertEquals('127.0.0.1:8124', $this->request->getHeader('Host')); + + $this->assertEquals($this->request, $this->request->setPort('8080')); + $this->assertEquals('8080', $this->request->getPort()); + $this->assertEquals('127.0.0.1:8080', $this->request->getHeader('Host')); + + $this->request->setPort(80); + $this->assertEquals('127.0.0.1', $this->request->getHeader('Host')); + } + + public function testRequestHandlesAuthorization() + { + // Uninitialized auth + $this->assertEquals(null, $this->request->getUsername()); + $this->assertEquals(null, $this->request->getPassword()); + + // Set an auth + $this->assertSame($this->request, $this->request->setAuth('michael', '123')); + $this->assertEquals('michael', $this->request->getUsername()); + $this->assertEquals('123', $this->request->getPassword()); + + // Set an auth with blank password + $this->assertSame($this->request, $this->request->setAuth('michael', '')); + $this->assertEquals('michael', $this->request->getUsername()); + $this->assertEquals('', $this->request->getPassword()); + + // Remove the auth + $this->request->setAuth(false); + $this->assertEquals(null, $this->request->getUsername()); + $this->assertEquals(null, $this->request->getPassword()); + + // Make sure that the cURL based auth works too + $request = new Request('GET', $this->getServer()->getUrl()); + $request->setAuth('michael', 'password', CURLAUTH_DIGEST); + $this->assertEquals('michael:password', $request->getCurlOptions()->get(CURLOPT_USERPWD)); + $this->assertEquals(CURLAUTH_DIGEST, $request->getCurlOptions()->get(CURLOPT_HTTPAUTH)); + } + + /** + * @expectedException \Guzzle\Common\Exception\InvalidArgumentException + */ + public function testValidatesAuth() + { + $this->request->setAuth('foo', 'bar', 'bam'); + } + + public function testGetResourceUri() + { + $this->assertEquals('/', $this->request->getResource()); + $this->request->setPath('/index.html'); + $this->assertEquals('/index.html', $this->request->getResource()); + $this->request->getQuery()->add('v', '1'); + $this->assertEquals('/index.html?v=1', $this->request->getResource()); + } + + public function testRequestHasMutableUrl() + { + $url = 'http://www.test.com:8081/path?q=123#fragment'; + $u = Url::factory($url); + $this->assertSame($this->request, $this->request->setUrl($url)); + $this->assertEquals($url, $this->request->getUrl()); + + $this->assertSame($this->request, $this->request->setUrl($u)); + $this->assertEquals($url, $this->request->getUrl()); + } + + public function testRequestHasState() + { + $this->assertEquals(RequestInterface::STATE_NEW, $this->request->getState()); + $this->request->setState(RequestInterface::STATE_TRANSFER); + $this->assertEquals(RequestInterface::STATE_TRANSFER, $this->request->getState()); + } + + public function testSetManualResponse() + { + $response = new Response(200, array( + 'Date' => 'Sat, 16 Oct 2010 17:27:14 GMT', + 'Expires' => '-1', + 'Cache-Control' => 'private, max-age=0', + 'Content-Type' => 'text/html; charset=ISO-8859-1', + ), 'response body'); + + $this->assertSame($this->request, $this->request->setResponse($response), '-> setResponse() must use a fluent interface'); + $this->assertEquals('complete', $this->request->getState(), '-> setResponse() must change the state of the request to complete'); + $this->assertSame($response, $this->request->getResponse(), '-> setResponse() must set the exact same response that was passed in to it'); + } + + public function testRequestCanHaveManuallySetResponseBody() + { + $file = __DIR__ . '/../../TestData/temp.out'; + if (file_exists($file)) { + unlink($file); + } + + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndata"); + $request = RequestFactory::getInstance()->create('GET', $this->getServer()->getUrl()); + $request->setClient($this->client); + $entityBody = EntityBody::factory(fopen($file, 'w+')); + $request->setResponseBody($entityBody); + $response = $request->send(); + $this->assertSame($entityBody, $response->getBody()); + + $this->assertTrue(file_exists($file)); + $this->assertEquals('data', file_get_contents($file)); + unlink($file); + + $this->assertEquals('data', $response->getBody(true)); + } + + public function testHoldsCookies() + { + $this->assertNull($this->request->getCookie('test')); + + // Set a cookie + $this->assertSame($this->request, $this->request->addCookie('test', 'abc')); + $this->assertEquals('abc', $this->request->getCookie('test')); + + // Multiple cookies by setting the Cookie header + $this->request->setHeader('Cookie', '__utma=1.638370270.1344367610.1374365610.1944450276.2; __utmz=1.1346368610.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); hl=de; PHPSESSID=ak93pqashi5uubuoq8fjv60897'); + $this->assertEquals('1.638370270.1344367610.1374365610.1944450276.2', $this->request->getCookie('__utma')); + $this->assertEquals('1.1346368610.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)', $this->request->getCookie('__utmz')); + $this->assertEquals('de', $this->request->getCookie('hl')); + $this->assertEquals('ak93pqashi5uubuoq8fjv60897', $this->request->getCookie('PHPSESSID')); + + // Unset the cookies by setting the Cookie header to null + $this->request->setHeader('Cookie', null); + $this->assertNull($this->request->getCookie('test')); + $this->request->removeHeader('Cookie'); + + // Set and remove a cookie + $this->assertSame($this->request, $this->request->addCookie('test', 'abc')); + $this->assertEquals('abc', $this->request->getCookie('test')); + $this->assertSame($this->request, $this->request->removeCookie('test')); + $this->assertNull($this->request->getCookie('test')); + + // Remove the cookie header + $this->assertSame($this->request, $this->request->addCookie('test', 'abc')); + $this->request->removeHeader('Cookie'); + $this->assertEquals('', (string) $this->request->getHeader('Cookie')); + + // Remove a cookie value + $this->request->addCookie('foo', 'bar')->addCookie('baz', 'boo'); + $this->request->removeCookie('foo'); + $this->assertEquals(array( + 'baz' => 'boo' + ), $this->request->getCookies()); + + $this->request->addCookie('foo', 'bar'); + $this->assertEquals('baz=boo; foo=bar', (string) $this->request->getHeader('Cookie')); + } + + /** + * @expectedException \Guzzle\Http\Exception\RequestException + * @expectedExceptionMessage Error completing request + */ + public function testRequestThrowsExceptionWhenSetToCompleteWithNoResponse() + { + $this->request->setState(RequestInterface::STATE_COMPLETE); + } + + public function testClonedRequestsUseNewInternalState() + { + $p = new AsyncPlugin(); + $this->request->getEventDispatcher()->addSubscriber($p); + $h = $this->request->getHeader('Host'); + + $r = clone $this->request; + $this->assertEquals(RequestInterface::STATE_NEW, $r->getState()); + $this->assertNotSame($r->getQuery(), $this->request->getQuery()); + $this->assertNotSame($r->getCurlOptions(), $this->request->getCurlOptions()); + $this->assertNotSame($r->getEventDispatcher(), $this->request->getEventDispatcher()); + $this->assertEquals($r->getHeaders(), $this->request->getHeaders()); + $this->assertNotSame($h, $r->getHeader('Host')); + $this->assertNotSame($r->getParams(), $this->request->getParams()); + $this->assertTrue($this->request->getEventDispatcher()->hasListeners('request.sent')); + } + + public function testRecognizesBasicAuthCredentialsInUrls() + { + $this->request->setUrl('http://michael:test@test.com/'); + $this->assertEquals('michael', $this->request->getUsername()); + $this->assertEquals('test', $this->request->getPassword()); + } + + public function testRequestCanBeSentUsingCurl() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 200 OK\r\nContent-Length: 4\r\nExpires: Thu, 01 Dec 1994 16:00:00 GMT\r\nConnection: close\r\n\r\ndata", + "HTTP/1.1 200 OK\r\nContent-Length: 4\r\nExpires: Thu, 01 Dec 1994 16:00:00 GMT\r\nConnection: close\r\n\r\ndata", + "HTTP/1.1 404 Not Found\r\nContent-Encoding: application/xml\r\nContent-Length: 48\r\n\r\nFile not found" + )); + + $request = RequestFactory::getInstance()->create('GET', $this->getServer()->getUrl()); + $request->setClient($this->client); + $response = $request->send(); + + $this->assertEquals('data', $response->getBody(true)); + $this->assertEquals(200, (int) $response->getStatusCode()); + $this->assertEquals('OK', $response->getReasonPhrase()); + $this->assertEquals(4, $response->getContentLength()); + $this->assertEquals('Thu, 01 Dec 1994 16:00:00 GMT', $response->getExpires()); + + // Test that the same handle can be sent twice without setting state to new + $response2 = $request->send(); + $this->assertNotSame($response, $response2); + + try { + $request = RequestFactory::getInstance()->create('GET', $this->getServer()->getUrl() . 'index.html'); + $request->setClient($this->client); + $response = $request->send(); + $this->fail('Request did not receive a 404 response'); + } catch (BadResponseException $e) { + } + + $requests = $this->getServer()->getReceivedRequests(true); + $messages = $this->getServer()->getReceivedRequests(false); + $port = $this->getServer()->getPort(); + + $userAgent = $this->client->getDefaultUserAgent(); + + $this->assertEquals('127.0.0.1:' . $port, $requests[0]->getHeader('Host')); + $this->assertEquals('127.0.0.1:' . $port, $requests[1]->getHeader('Host')); + $this->assertEquals('127.0.0.1:' . $port, $requests[2]->getHeader('Host')); + + $this->assertEquals('/', $requests[0]->getPath()); + $this->assertEquals('/', $requests[1]->getPath()); + $this->assertEquals('/index.html', $requests[2]->getPath()); + + $parts = explode("\r\n", $messages[0]); + $this->assertEquals('GET / HTTP/1.1', $parts[0]); + + $parts = explode("\r\n", $messages[1]); + $this->assertEquals('GET / HTTP/1.1', $parts[0]); + + $parts = explode("\r\n", $messages[2]); + $this->assertEquals('GET /index.html HTTP/1.1', $parts[0]); + } + + public function testThrowsExceptionsWhenUnsuccessfulResponseIsReceivedByDefault() + { + $this->getServer()->flush(); + $this->getServer()->enqueue("HTTP/1.1 404 Not found\r\nContent-Length: 0\r\n\r\n"); + + try { + $request = $this->client->get('/index.html'); + $response = $request->send(); + $this->fail('Request did not receive a 404 response'); + } catch (BadResponseException $e) { + $this->assertContains('Client error response', $e->getMessage()); + $this->assertContains('[status code] 404', $e->getMessage()); + $this->assertContains('[reason phrase] Not found', $e->getMessage()); + } + } + + public function testCanShortCircuitErrorHandling() + { + $request = $this->request; + $response = new Response(404); + $request->setResponse($response, true); + $out = ''; + $that = $this; + $request->getEventDispatcher()->addListener('request.error', function($event) use (&$out, $that) { + $out .= $event['request'] . "\n" . $event['response'] . "\n"; + $event->stopPropagation(); + }); + $request->send(); + $this->assertContains((string) $request, $out); + $this->assertContains((string) $request->getResponse(), $out); + $this->assertSame($response, $request->getResponse()); + } + + public function testCanOverrideUnsuccessfulResponses() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 404 NOT FOUND\r\n" . + "Content-Length: 0\r\n" . + "\r\n", + "HTTP/1.1 200 OK\r\n" . + "Content-Length: 0\r\n" . + "\r\n" + )); + + $newResponse = null; + + $request = $this->request; + $request->getEventDispatcher()->addListener('request.error', function($event) use (&$newResponse) { + if ($event['response']->getStatusCode() == 404) { + $newRequest = clone $event['request']; + $newResponse = $newRequest->send(); + // Override the original response and bypass additional response processing + $event['response'] = $newResponse; + // Call $event['request']->setResponse($newResponse); to re-apply events + $event->stopPropagation(); + } + }); + + $request->send(); + + $this->assertEquals(200, $request->getResponse()->getStatusCode()); + $this->assertSame($newResponse, $request->getResponse()); + $this->assertEquals(2, count($this->getServer()->getReceivedRequests())); + } + + public function testCanRetrieveUrlObject() + { + $request = new Request('GET', 'http://www.example.com/foo?abc=d'); + $this->assertInstanceOf('Guzzle\Http\Url', $request->getUrl(true)); + $this->assertEquals('http://www.example.com/foo?abc=d', $request->getUrl()); + $this->assertEquals('http://www.example.com/foo?abc=d', (string) $request->getUrl(true)); + } + + public function testUnresolvedRedirectsReturnResponse() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 303 SEE OTHER\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 301 Foo\r\nLocation: /foo\r\nContent-Length: 0\r\n\r\n" + )); + $request = $this->request; + $this->assertEquals(303, $request->send()->getStatusCode()); + $request->getParams()->set(RedirectPlugin::DISABLE, true); + $this->assertEquals(301, $request->send()->getStatusCode()); + } + + public function testCanSendCustomRequests() + { + $this->getServer()->flush(); + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + $request = $this->client->createRequest('PROPFIND', $this->getServer()->getUrl(), array( + 'Content-Type' => 'text/plain' + ), 'foo'); + $response = $request->send(); + $requests = $this->getServer()->getReceivedRequests(true); + $this->assertEquals('PROPFIND', $requests[0]->getMethod()); + $this->assertEquals(3, (string) $requests[0]->getHeader('Content-Length')); + $this->assertEquals('foo', (string) $requests[0]->getBody()); + } + + /** + * @expectedException \PHPUnit_Framework_Error_Warning + */ + public function testEnsuresFileCanBeCreated() + { + $this->getServer()->flush(); + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ntest"); + $this->client->get('/')->setResponseBody('/wefwefefefefwewefwe/wefwefwefefwe/wefwefewfw.txt')->send(); + } + + public function testAllowsFilenameForDownloadingContent() + { + $this->getServer()->flush(); + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ntest"); + $name = sys_get_temp_dir() . '/foo.txt'; + $this->client->get('/')->setResponseBody($name)->send(); + $this->assertEquals('test', file_get_contents($name)); + unlink($name); + } + + public function testUsesCustomResponseBodyWhenItIsCustom() + { + $en = EntityBody::factory(); + $request = $this->client->get(); + $request->setResponseBody($en); + $request->setResponse(new Response(200, array(), 'foo')); + $this->assertEquals('foo', (string) $en); + } + + public function testCanChangePortThroughScheme() + { + $request = new Request('GET', 'http://foo.com'); + $request->setScheme('https'); + $this->assertEquals('https://foo.com', (string) $request->getUrl()); + $this->assertEquals('foo.com', $request->getHost()); + $request->setScheme('http'); + $this->assertEquals('http://foo.com', (string) $request->getUrl()); + $this->assertEquals('foo.com', $request->getHost()); + $request->setPort(null); + $this->assertEquals('http://foo.com', (string) $request->getUrl()); + $this->assertEquals('foo.com', $request->getHost()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/ResponseTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/ResponseTest.php new file mode 100644 index 000000000..08b4df878 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Message/ResponseTest.php @@ -0,0 +1,677 @@ +response = new Response(200, new Collection(array( + 'Accept-Ranges' => 'bytes', + 'Age' => '12', + 'Allow' => 'GET, HEAD', + 'Cache-Control' => 'no-cache', + 'Content-Encoding' => 'gzip', + 'Content-Language' => 'da', + 'Content-Length' => '348', + 'Content-Location' => '/index.htm', + 'Content-Disposition' => 'attachment; filename=fname.ext', + 'Content-MD5' => 'Q2hlY2sgSW50ZWdyaXR5IQ==', + 'Content-Range' => 'bytes 21010-47021/47022', + 'Content-Type' => 'text/html; charset=utf-8', + 'Date' => 'Tue, 15 Nov 1994 08:12:31 GMT', + 'ETag' => '737060cd8c284d8af7ad3082f209582d', + 'Expires' => 'Thu, 01 Dec 1994 16:00:00 GMT', + 'Last-Modified' => 'Tue, 15 Nov 1994 12:45:26 GMT', + 'Location' => 'http://www.w3.org/pub/WWW/People.html', + 'Pragma' => 'no-cache', + 'Proxy-Authenticate' => 'Basic', + 'Retry-After' => '120', + 'Server' => 'Apache/1.3.27 (Unix) (Red-Hat/Linux)', + 'Set-Cookie' => 'UserID=JohnDoe; Max-Age=3600; Version=1', + 'Trailer' => 'Max-Forwards', + 'Transfer-Encoding' => 'chunked', + 'Vary' => '*', + 'Via' => '1.0 fred, 1.1 nowhere.com (Apache/1.1)', + 'Warning' => '199 Miscellaneous warning', + 'WWW-Authenticate' => 'Basic' + )), 'body'); + } + + public function tearDown() + { + unset($this->response); + } + + public function testConstructor() + { + $params = new Collection(); + $body = EntityBody::factory(''); + $response = new Response(200, $params, $body); + $this->assertEquals(200, $response->getStatusCode()); + $this->assertEquals($body, $response->getBody()); + $this->assertEquals('OK', $response->getReasonPhrase()); + $this->assertEquals("HTTP/1.1 200 OK\r\n\r\n", $response->getRawHeaders()); + + // Make sure Content-Length is set automatically + $response = new Response(200, $params); + $this->assertEquals("HTTP/1.1 200 OK\r\n\r\n", $response->getRawHeaders()); + + // Pass bodies to the response + $response = new Response(200, null, 'data'); + $this->assertInstanceOf('Guzzle\\Http\\EntityBody', $response->getBody()); + $response = new Response(200, null, EntityBody::factory('data')); + $this->assertInstanceOf('Guzzle\\Http\\EntityBody', $response->getBody()); + $this->assertEquals('data', $response->getBody(true)); + $response = new Response(200, null, '0'); + $this->assertSame('0', $response->getBody(true), 'getBody(true) should return "0" if response body is "0".'); + + // Make sure the proper exception is thrown + try { + //$response = new Response(200, null, array('foo' => 'bar')); + //$this->fail('Response did not throw exception when passing invalid body'); + } catch (HttpException $e) { + } + + // Ensure custom codes can be set + $response = new Response(2); + $this->assertEquals(2, $response->getStatusCode()); + $this->assertEquals('', $response->getReasonPhrase()); + + // Make sure the proper exception is thrown when sending invalid headers + try { + $response = new Response(200, 'adidas'); + $this->fail('Response did not throw exception when passing invalid $headers'); + } catch (BadResponseException $e) { + } + } + + public function test__toString() + { + $response = new Response(200); + $this->assertEquals("HTTP/1.1 200 OK\r\n\r\n", (string) $response); + + // Add another header + $response = new Response(200, array( + 'X-Test' => 'Guzzle' + )); + $this->assertEquals("HTTP/1.1 200 OK\r\nX-Test: Guzzle\r\n\r\n", (string) $response); + + $response = new Response(200, array( + 'Content-Length' => 4 + ), 'test'); + $this->assertEquals("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ntest", (string) $response); + } + + public function testFactory() + { + $response = Response::fromMessage("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ntest"); + $this->assertEquals(200, $response->getStatusCode()); + $this->assertEquals('OK', $response->getReasonPhrase()); + $this->assertEquals(4, (string) $response->getContentLength()); + $this->assertEquals('test', $response->getBody(true)); + + // Make sure that automatic Content-Length works + $response = Response::fromMessage("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ntest"); + $this->assertEquals(4, (string) $response->getContentLength()); + $this->assertEquals('test', $response->getBody(true)); + } + + public function testFactoryCanCreateHeadResponses() + { + $response = Response::fromMessage("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\n"); + $this->assertEquals(200, $response->getStatusCode()); + $this->assertEquals('OK', $response->getReasonPhrase()); + $this->assertEquals(4, (string) $response->getContentLength()); + $this->assertEquals('', $response->getBody(true)); + } + + public function testFactoryRequiresMessage() + { + $this->assertFalse(Response::fromMessage('')); + } + + public function testGetBody() + { + $body = EntityBody::factory(''); + $response = new Response(403, new Collection(), $body); + $this->assertEquals($body, $response->getBody()); + $response->setBody('foo'); + $this->assertEquals('foo', $response->getBody(true)); + } + + public function testManagesStatusCode() + { + $response = new Response(403); + $this->assertEquals(403, $response->getStatusCode()); + } + + public function testGetMessage() + { + $response = new Response(200, new Collection(array( + 'Content-Length' => 4 + )), 'body'); + + $this->assertEquals("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\nbody", $response->getMessage()); + } + + public function testGetRawHeaders() + { + $response = new Response(200, new Collection(array( + 'Keep-Alive' => 155, + 'User-Agent' => 'Guzzle', + 'Content-Length' => 4 + )), 'body'); + + $this->assertEquals("HTTP/1.1 200 OK\r\nKeep-Alive: 155\r\nUser-Agent: Guzzle\r\nContent-Length: 4\r\n\r\n", $response->getRawHeaders()); + } + + public function testHandlesStatusAndStatusCodes() + { + $response = new Response(200, new Collection(), 'body'); + $this->assertEquals('OK', $response->getReasonPhrase()); + + $this->assertSame($response, $response->setStatus(204)); + $this->assertEquals('No Content', $response->getReasonPhrase()); + $this->assertEquals(204, $response->getStatusCode()); + + $this->assertSame($response, $response->setStatus(204, 'Testing!')); + $this->assertEquals('Testing!', $response->getReasonPhrase()); + $this->assertEquals(204, $response->getStatusCode()); + + $response->setStatus(2000); + $this->assertEquals(2000, $response->getStatusCode()); + $this->assertEquals('', $response->getReasonPhrase()); + + $response->setStatus(200, 'Foo'); + $this->assertEquals(200, $response->getStatusCode()); + $this->assertEquals('Foo', $response->getReasonPhrase()); + } + + public function testIsClientError() + { + $response = new Response(403); + $this->assertTrue($response->isClientError()); + $response = new Response(200); + $this->assertFalse($response->isClientError()); + } + + public function testIsError() + { + $response = new Response(403); + $this->assertTrue($response->isError()); + $response = new Response(200); + $this->assertFalse($response->isError()); + $response = new Response(500); + $this->assertTrue($response->isError()); + } + + public function testIsInformational() + { + $response = new Response(100); + $this->assertTrue($response->isInformational()); + $response = new Response(200); + $this->assertFalse($response->isInformational()); + } + + public function testIsRedirect() + { + $response = new Response(301); + $this->assertTrue($response->isRedirect()); + $response = new Response(200); + $this->assertFalse($response->isRedirect()); + } + + public function testIsServerError() + { + $response = new Response(500); + $this->assertTrue($response->isServerError()); + $response = new Response(400); + $this->assertFalse($response->isServerError()); + } + + public function testIsSuccessful() + { + $response = new Response(200); + $this->assertTrue($response->isSuccessful()); + $response = new Response(403); + $this->assertFalse($response->isSuccessful()); + } + + public function testGetAcceptRanges() + { + $this->assertEquals('bytes', $this->response->getAcceptRanges()); + } + + public function testCalculatesAge() + { + $this->assertEquals(12, $this->response->calculateAge()); + + $this->response->removeHeader('Age'); + $this->response->removeHeader('Date'); + $this->assertNull($this->response->calculateAge()); + + $this->response->setHeader('Date', gmdate(ClientInterface::HTTP_DATE, strtotime('-1 minute'))); + // If the test runs slowly, still pass with a +5 second allowance + $this->assertTrue($this->response->getAge() - 60 <= 5); + } + + public function testGetAllow() + { + $this->assertEquals('GET, HEAD', $this->response->getAllow()); + } + + public function testGetCacheControl() + { + $this->assertEquals('no-cache', $this->response->getCacheControl()); + } + + public function testGetContentEncoding() + { + $this->assertEquals('gzip', $this->response->getContentEncoding()); + } + + public function testGetContentLanguage() + { + $this->assertEquals('da', $this->response->getContentLanguage()); + } + + public function testGetContentLength() + { + $this->assertEquals('348', $this->response->getContentLength()); + } + + public function testGetContentLocation() + { + $this->assertEquals('/index.htm', $this->response->getContentLocation()); + } + + public function testGetContentDisposition() + { + $this->assertEquals('attachment; filename=fname.ext', $this->response->getContentDisposition()); + } + + public function testGetContentMd5() + { + $this->assertEquals('Q2hlY2sgSW50ZWdyaXR5IQ==', $this->response->getContentMd5()); + } + + public function testGetContentRange() + { + $this->assertEquals('bytes 21010-47021/47022', $this->response->getContentRange()); + } + + public function testGetContentType() + { + $this->assertEquals('text/html; charset=utf-8', $this->response->getContentType()); + } + + public function testGetDate() + { + $this->assertEquals('Tue, 15 Nov 1994 08:12:31 GMT', $this->response->getDate()); + } + + public function testGetEtag() + { + $this->assertEquals('737060cd8c284d8af7ad3082f209582d', $this->response->getEtag()); + } + + public function testGetExpires() + { + $this->assertEquals('Thu, 01 Dec 1994 16:00:00 GMT', $this->response->getExpires()); + } + + public function testGetLastModified() + { + $this->assertEquals('Tue, 15 Nov 1994 12:45:26 GMT', $this->response->getLastModified()); + } + + public function testGetLocation() + { + $this->assertEquals('http://www.w3.org/pub/WWW/People.html', $this->response->getLocation()); + } + + public function testGetPragma() + { + $this->assertEquals('no-cache', $this->response->getPragma()); + } + + public function testGetProxyAuthenticate() + { + $this->assertEquals('Basic', $this->response->getProxyAuthenticate()); + } + + public function testGetServer() + { + $this->assertEquals('Apache/1.3.27 (Unix) (Red-Hat/Linux)', $this->response->getServer()); + } + + public function testGetSetCookie() + { + $this->assertEquals('UserID=JohnDoe; Max-Age=3600; Version=1', $this->response->getSetCookie()); + } + + public function testGetMultipleSetCookie() + { + $this->response->addHeader('Set-Cookie', 'UserID=Mike; Max-Age=200'); + $this->assertEquals(array( + 'UserID=JohnDoe; Max-Age=3600; Version=1', + 'UserID=Mike; Max-Age=200', + ), $this->response->getHeader('Set-Cookie')->toArray()); + } + + public function testGetSetCookieNormalizesHeaders() + { + $this->response->addHeaders(array( + 'Set-Cooke' => 'boo', + 'set-cookie' => 'foo' + )); + + $this->assertEquals(array( + 'UserID=JohnDoe; Max-Age=3600; Version=1', + 'foo' + ), $this->response->getHeader('Set-Cookie')->toArray()); + + $this->response->addHeaders(array( + 'set-cookie' => 'fubu' + )); + $this->assertEquals( + array('UserID=JohnDoe; Max-Age=3600; Version=1', 'foo', 'fubu'), + $this->response->getHeader('Set-Cookie')->toArray() + ); + } + + public function testGetTrailer() + { + $this->assertEquals('Max-Forwards', $this->response->getTrailer()); + } + + public function testGetTransferEncoding() + { + $this->assertEquals('chunked', $this->response->getTransferEncoding()); + } + + public function testGetVary() + { + $this->assertEquals('*', $this->response->getVary()); + } + + public function testReturnsViaHeader() + { + $this->assertEquals('1.0 fred, 1.1 nowhere.com (Apache/1.1)', $this->response->getVia()); + } + public function testGetWarning() + { + $this->assertEquals('199 Miscellaneous warning', $this->response->getWarning()); + } + + public function testReturnsWwwAuthenticateHeader() + { + $this->assertEquals('Basic', $this->response->getWwwAuthenticate()); + } + + public function testReturnsConnectionHeader() + { + $this->assertEquals(null, $this->response->getConnection()); + $this->response->setHeader('Connection', 'close'); + $this->assertEquals('close', $this->response->getConnection()); + } + + public function testReturnsHeaders() + { + $this->assertEquals('Basic', $this->response->getHeader('WWW-Authenticate', null, true)); + $this->assertEquals('chunked', $this->response->getHeader('Transfer-Encoding', null, false)); + } + + public function testHasTransferInfo() + { + $stats = array ( + 'url' => 'http://www.google.com/', + 'content_type' => 'text/html; charset=ISO-8859-1', + 'http_code' => 200, + 'header_size' => 606, + 'request_size' => 53, + 'filetime' => -1, + 'ssl_verify_result' => 0, + 'redirect_count' => 0, + 'total_time' => 0.093284, + 'namelookup_time' => 0.001349, + 'connect_time' => 0.01635, + 'pretransfer_time' => 0.016358, + 'size_upload' => 0, + 'size_download' => 10330, + 'speed_download' => 110737, + 'speed_upload' => 0, + 'download_content_length' => -1, + 'upload_content_length' => 0, + 'starttransfer_time' => 0.07066, + 'redirect_time' => 0, + ); + + // Uninitialized state + $this->assertNull($this->response->getInfo('url')); + $this->assertEquals(array(), $this->response->getInfo()); + + // Set the stats + $this->response->setInfo($stats); + $this->assertEquals($stats, $this->response->getInfo()); + $this->assertEquals(606, $this->response->getInfo('header_size')); + $this->assertNull($this->response->getInfo('does_not_exist')); + } + + /** + * @return Response + */ + private function getResponse($code, array $headers = null, EntityBody $body = null) + { + return new Response($code, $headers, $body); + } + + public function testDeterminesIfItCanBeCached() + { + $this->assertTrue($this->getResponse(200)->canCache()); + $this->assertTrue($this->getResponse(410)->canCache()); + $this->assertFalse($this->getResponse(404)->canCache()); + $this->assertTrue($this->getResponse(200, array( + 'Cache-Control' => 'public' + ))->canCache()); + + // This has the no-store directive + $this->assertFalse($this->getResponse(200, array( + 'Cache-Control' => 'private, no-store' + ))->canCache()); + + // The body cannot be read, so it cannot be cached + $tmp = tempnam('/tmp', 'not-readable'); + $resource = fopen($tmp, 'w'); + $this->assertFalse($this->getResponse(200, array( + 'Transfer-Encoding' => 'chunked' + ), EntityBody::factory($resource, 10))->canCache()); + unlink($tmp); + + // The body is 0 length, cannot be read, so it can be cached + $tmp = tempnam('/tmp', 'not-readable'); + $resource = fopen($tmp, 'w'); + $this->assertTrue($this->getResponse(200, array(array( + 'Content-Length' => 0 + )), EntityBody::factory($resource, 0))->canCache()); + unlink($tmp); + } + + public function testDeterminesResponseMaxAge() + { + $this->assertEquals(null, $this->getResponse(200)->getMaxAge()); + + // Uses the response's s-maxage + $this->assertEquals(140, $this->getResponse(200, array( + 'Cache-Control' => 's-maxage=140' + ))->getMaxAge()); + + // Uses the response's max-age + $this->assertEquals(120, $this->getResponse(200, array( + 'Cache-Control' => 'max-age=120' + ))->getMaxAge()); + + // Uses the response's max-age + $this->assertEquals(120, $this->getResponse(200, array( + 'Cache-Control' => 'max-age=120', + 'Expires' => gmdate(ClientInterface::HTTP_DATE, strtotime('+1 day')) + ))->getMaxAge()); + + // Uses the Expires date + $this->assertGreaterThanOrEqual(82400, $this->getResponse(200, array( + 'Expires' => gmdate(ClientInterface::HTTP_DATE, strtotime('+1 day')) + ))->getMaxAge()); + + // Uses the Expires date + $this->assertGreaterThanOrEqual(82400, $this->getResponse(200, array( + 'Expires' => gmdate(ClientInterface::HTTP_DATE, strtotime('+1 day')) + ))->getMaxAge()); + } + + public function testDeterminesIfItCanValidate() + { + $response = new Response(200); + $this->assertFalse($response->canValidate()); + $response->setHeader('ETag', '123'); + $this->assertTrue($response->canValidate()); + $response->removeHeader('ETag'); + $this->assertFalse($response->canValidate()); + $response->setHeader('Last-Modified', '123'); + $this->assertTrue($response->canValidate()); + } + + public function testCalculatesFreshness() + { + $response = new Response(200); + $this->assertNull($response->isFresh()); + $this->assertNull($response->getFreshness()); + + $response->setHeader('Cache-Control', 'max-age=120'); + $response->setHeader('Age', 100); + $this->assertEquals(20, $response->getFreshness()); + $this->assertTrue($response->isFresh()); + + $response->setHeader('Age', 120); + $this->assertEquals(0, $response->getFreshness()); + $this->assertTrue($response->isFresh()); + + $response->setHeader('Age', 150); + $this->assertEquals(-30, $response->getFreshness()); + $this->assertFalse($response->isFresh()); + } + + public function testHandlesProtocols() + { + $this->assertSame($this->response, $this->response->setProtocol('HTTP', '1.0')); + $this->assertEquals('HTTP', $this->response->getProtocol()); + $this->assertEquals('1.0', $this->response->getProtocolVersion()); + } + + public function testComparesContentType() + { + $response = new Response(200, array( + 'Content-Type' => 'text/html; charset=ISO-8859-4' + )); + + $this->assertTrue($response->isContentType('text/html')); + $this->assertTrue($response->isContentType('TExT/html')); + $this->assertTrue($response->isContentType('charset=ISO-8859-4')); + $this->assertFalse($response->isContentType('application/xml')); + } + + public function testResponseDeterminesIfMethodIsAllowedBaseOnAllowHeader() + { + $response = new Response(200, array( + 'Allow' => 'OPTIONS, POST, deletE,GET' + )); + + $this->assertTrue($response->isMethodAllowed('get')); + $this->assertTrue($response->isMethodAllowed('GET')); + $this->assertTrue($response->isMethodAllowed('options')); + $this->assertTrue($response->isMethodAllowed('post')); + $this->assertTrue($response->isMethodAllowed('Delete')); + $this->assertFalse($response->isMethodAllowed('put')); + $this->assertFalse($response->isMethodAllowed('PUT')); + + $response = new Response(200); + $this->assertFalse($response->isMethodAllowed('get')); + } + + public function testParsesJsonResponses() + { + $response = new Response(200, array(), '{"foo": "bar"}'); + $this->assertEquals(array('foo' => 'bar'), $response->json()); + // Return array when null is a service response + $response = new Response(200); + $this->assertEquals(array(), $response->json()); + } + + /** + * @expectedException \Guzzle\Common\Exception\RuntimeException + * @expectedExceptionMessage Unable to parse response body into JSON: 4 + */ + public function testThrowsExceptionWhenFailsToParseJsonResponse() + { + $response = new Response(200, array(), '{"foo": "'); + $response->json(); + } + + public function testParsesXmlResponses() + { + $response = new Response(200, array(), 'bar'); + $this->assertEquals('bar', (string) $response->xml()->foo); + // Always return a SimpleXMLElement from the xml method + $response = new Response(200); + $this->assertEmpty((string) $response->xml()->foo); + } + + /** + * @expectedException \Guzzle\Common\Exception\RuntimeException + * @expectedExceptionMessage Unable to parse response body into XML: String could not be parsed as XML + */ + public function testThrowsExceptionWhenFailsToParseXmlResponse() + { + $response = new Response(200, array(), 'xml(); + } + + public function testResponseIsSerializable() + { + $response = new Response(200, array('Foo' => 'bar'), 'test'); + $r = unserialize(serialize($response)); + $this->assertEquals(200, $r->getStatusCode()); + $this->assertEquals('bar', (string) $r->getHeader('Foo')); + $this->assertEquals('test', (string) $r->getBody()); + } + + public function testPreventsComplexExternalEntities() + { + $xml = ']>&test;'; + $response = new Response(200, array(), $xml); + + $oldCwd = getcwd(); + chdir(__DIR__); + try { + $xml = $response->xml(); + chdir($oldCwd); + $this->markTestIncomplete('Did not throw the expected exception! XML resolved as: ' . $xml->asXML()); + } catch (\Exception $e) { + chdir($oldCwd); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/MimetypesTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/MimetypesTest.php new file mode 100644 index 000000000..722845340 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/MimetypesTest.php @@ -0,0 +1,31 @@ +assertEquals('text/x-php', Mimetypes::getInstance()->fromExtension('php')); + } + + public function testGetsFromFilename() + { + $this->assertEquals('text/x-php', Mimetypes::getInstance()->fromFilename(__FILE__)); + } + + public function testGetsFromCaseInsensitiveFilename() + { + $this->assertEquals('text/x-php', Mimetypes::getInstance()->fromFilename(strtoupper(__FILE__))); + } + + public function testReturnsNullWhenNoMatchFound() + { + $this->assertNull(Mimetypes::getInstance()->fromExtension('foobar')); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/QueryAggregator/CommaAggregatorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/QueryAggregator/CommaAggregatorTest.php new file mode 100644 index 000000000..549d3edd9 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/QueryAggregator/CommaAggregatorTest.php @@ -0,0 +1,30 @@ +aggregate($key, $value, $query); + $this->assertEquals(array('test%20123' => 'foo%20123,baz,bar'), $result); + } + + public function testEncodes() + { + $query = new QueryString(); + $query->useUrlEncoding(false); + $a = new Ag(); + $key = 'test 123'; + $value = array('foo 123', 'baz', 'bar'); + $result = $a->aggregate($key, $value, $query); + $this->assertEquals(array('test 123' => 'foo 123,baz,bar'), $result); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/QueryAggregator/DuplicateAggregatorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/QueryAggregator/DuplicateAggregatorTest.php new file mode 100644 index 000000000..6a4d9d95b --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/QueryAggregator/DuplicateAggregatorTest.php @@ -0,0 +1,30 @@ +aggregate($key, $value, $query); + $this->assertEquals(array('facet%201' => array('size%20a', 'width%20b')), $result); + } + + public function testEncodes() + { + $query = new QueryString(); + $query->useUrlEncoding(false); + $a = new Ag(); + $key = 'facet 1'; + $value = array('size a', 'width b'); + $result = $a->aggregate($key, $value, $query); + $this->assertEquals(array('facet 1' => array('size a', 'width b')), $result); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/QueryAggregator/PhpAggregatorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/QueryAggregator/PhpAggregatorTest.php new file mode 100644 index 000000000..1e7f0c27a --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/QueryAggregator/PhpAggregatorTest.php @@ -0,0 +1,32 @@ +useUrlEncoding(false); + $a = new Ag(); + $key = 't'; + $value = array( + 'v1' => 'a', + 'v2' => 'b', + 'v3' => array( + 'v4' => 'c', + 'v5' => 'd', + ) + ); + $result = $a->aggregate($key, $value, $query); + $this->assertEquals(array( + 't[v1]' => 'a', + 't[v2]' => 'b', + 't[v3][v4]' => 'c', + 't[v3][v5]' => 'd', + ), $result); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/QueryStringTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/QueryStringTest.php new file mode 100644 index 000000000..948db442d --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/QueryStringTest.php @@ -0,0 +1,233 @@ +q = new QueryString(); + } + + public function testGetFieldSeparator() + { + $this->assertEquals('&', $this->q->getFieldSeparator()); + } + + public function testGetValueSeparator() + { + $this->assertEquals('=', $this->q->getValueSeparator()); + } + + public function testIsUrlEncoding() + { + $this->assertEquals('RFC 3986', $this->q->getUrlEncoding()); + $this->assertTrue($this->q->isUrlEncoding()); + $this->assertEquals('foo%20bar', $this->q->encodeValue('foo bar')); + + $this->q->useUrlEncoding(QueryString::FORM_URLENCODED); + $this->assertTrue($this->q->isUrlEncoding()); + $this->assertEquals(QueryString::FORM_URLENCODED, $this->q->getUrlEncoding()); + $this->assertEquals('foo+bar', $this->q->encodeValue('foo bar')); + + $this->assertSame($this->q, $this->q->useUrlEncoding(false)); + $this->assertFalse($this->q->isUrlEncoding()); + $this->assertFalse($this->q->isUrlEncoding()); + } + + public function testSetFieldSeparator() + { + $this->assertEquals($this->q, $this->q->setFieldSeparator('/')); + $this->assertEquals('/', $this->q->getFieldSeparator()); + } + + public function testSetValueSeparator() + { + $this->assertEquals($this->q, $this->q->setValueSeparator('/')); + $this->assertEquals('/', $this->q->getValueSeparator()); + } + + public function testUrlEncode() + { + $params = array( + 'test' => 'value', + 'test 2' => 'this is a test?', + 'test3' => array('v1', 'v2', 'v3'), + 'ሴ' => 'bar' + ); + $encoded = array( + 'test' => 'value', + 'test%202' => rawurlencode('this is a test?'), + 'test3%5B0%5D' => 'v1', + 'test3%5B1%5D' => 'v2', + 'test3%5B2%5D' => 'v3', + '%E1%88%B4' => 'bar' + ); + $this->q->replace($params); + $this->assertEquals($encoded, $this->q->urlEncode()); + + // Disable encoding + $testData = array('test 2' => 'this is a test'); + $this->q->replace($testData); + $this->q->useUrlEncoding(false); + $this->assertEquals($testData, $this->q->urlEncode()); + } + + public function testToString() + { + // Check with no parameters + $this->assertEquals('', $this->q->__toString()); + + $params = array( + 'test' => 'value', + 'test 2' => 'this is a test?', + 'test3' => array('v1', 'v2', 'v3'), + 'test4' => null, + ); + $this->q->replace($params); + $this->assertEquals('test=value&test%202=this%20is%20a%20test%3F&test3%5B0%5D=v1&test3%5B1%5D=v2&test3%5B2%5D=v3&test4', $this->q->__toString()); + $this->q->useUrlEncoding(false); + $this->assertEquals('test=value&test 2=this is a test?&test3[0]=v1&test3[1]=v2&test3[2]=v3&test4', $this->q->__toString()); + + // Use an alternative aggregator + $this->q->setAggregator(new CommaAggregator()); + $this->assertEquals('test=value&test 2=this is a test?&test3=v1,v2,v3&test4', $this->q->__toString()); + } + + public function testAllowsMultipleValuesPerKey() + { + $q = new QueryString(); + $q->add('facet', 'size'); + $q->add('facet', 'width'); + $q->add('facet.field', 'foo'); + // Use the duplicate aggregator + $q->setAggregator(new DuplicateAggregator()); + $this->assertEquals('facet=size&facet=width&facet.field=foo', $q->__toString()); + } + + public function testAllowsNestedQueryData() + { + $this->q->replace(array( + 'test' => 'value', + 't' => array( + 'v1' => 'a', + 'v2' => 'b', + 'v3' => array( + 'v4' => 'c', + 'v5' => 'd', + ) + ) + )); + + $this->q->useUrlEncoding(false); + $this->assertEquals('test=value&t[v1]=a&t[v2]=b&t[v3][v4]=c&t[v3][v5]=d', $this->q->__toString()); + } + + public function parseQueryProvider() + { + return array( + // Ensure that multiple query string values are allowed per value + array('q=a&q=b', array('q' => array('a', 'b'))), + // Ensure that PHP array style query string values are parsed + array('q[]=a&q[]=b', array('q' => array('a', 'b'))), + // Ensure that a single PHP array style query string value is parsed into an array + array('q[]=a', array('q' => array('a'))), + // Ensure that decimals are allowed in query strings + array('q.a=a&q.b=b', array( + 'q.a' => 'a', + 'q.b' => 'b' + )), + // Ensure that query string values are percent decoded + array('q%20a=a%20b', array('q a' => 'a b')), + // Ensure null values can be added + array('q&a', array('q' => false, 'a' => false)), + ); + } + + /** + * @dataProvider parseQueryProvider + */ + public function testParsesQueryStrings($query, $data) + { + $query = QueryString::fromString($query); + $this->assertEquals($data, $query->getAll()); + } + + public function testProperlyDealsWithDuplicateQueryStringValues() + { + $query = QueryString::fromString('foo=a&foo=b&?µ=c'); + $this->assertEquals(array('a', 'b'), $query->get('foo')); + $this->assertEquals('c', $query->get('?µ')); + } + + public function testAllowsBlankQueryStringValues() + { + $query = QueryString::fromString('foo'); + $this->assertEquals('foo', (string) $query); + $query->set('foo', QueryString::BLANK); + $this->assertEquals('foo', (string) $query); + } + + public function testAllowsFalsyQueryStringValues() + { + $query = QueryString::fromString('0'); + $this->assertEquals('0', (string) $query); + $query->set('0', QueryString::BLANK); + $this->assertSame('0', (string) $query); + } + + public function testFromStringIgnoresQuestionMark() + { + $query = QueryString::fromString('foo=baz&bar=boo'); + $this->assertEquals('foo=baz&bar=boo', (string) $query); + } + + public function testConvertsPlusSymbolsToSpaces() + { + $query = QueryString::fromString('var=foo+bar'); + $this->assertEquals('foo bar', $query->get('var')); + } + + public function testFromStringDoesntMangleZeroes() + { + $query = QueryString::fromString('var=0'); + $this->assertSame('0', $query->get('var')); + } + + public function testAllowsZeroValues() + { + $query = new QueryString(array( + 'foo' => 0, + 'baz' => '0', + 'bar' => null, + 'boo' => false, + 'bam' => '' + )); + $this->assertEquals('foo=0&baz=0&bar&boo&bam=', (string) $query); + } + + public function testFromStringDoesntStripTrailingEquals() + { + $query = QueryString::fromString('data=mF0b3IiLCJUZWFtIERldiJdfX0='); + $this->assertEquals('mF0b3IiLCJUZWFtIERldiJdfX0=', $query->get('data')); + } + + public function testGuessesIfDuplicateAggregatorShouldBeUsed() + { + $query = QueryString::fromString('test=a&test=b'); + $this->assertEquals('test=a&test=b', (string) $query); + } + + public function testGuessesIfDuplicateAggregatorShouldBeUsedAndChecksForPhpStyle() + { + $query = QueryString::fromString('test[]=a&test[]=b'); + $this->assertEquals('test%5B0%5D=a&test%5B1%5D=b', (string) $query); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/ReadLimitEntityBodyTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/ReadLimitEntityBodyTest.php new file mode 100644 index 000000000..6bb3fed18 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/ReadLimitEntityBodyTest.php @@ -0,0 +1,81 @@ +decorated = EntityBody::factory(fopen(__FILE__, 'r')); + $this->body = new ReadLimitEntityBody($this->decorated, 10, 3); + } + + public function testReturnsSubsetWhenCastToString() + { + $body = EntityBody::factory('foo_baz_bar'); + $limited = new ReadLimitEntityBody($body, 3, 4); + $this->assertEquals('baz', (string) $limited); + } + + public function testReturnsSubsetOfEmptyBodyWhenCastToString() + { + $body = EntityBody::factory(''); + $limited = new ReadLimitEntityBody($body, 0, 10); + $this->assertEquals('', (string) $limited); + } + + public function testSeeksWhenConstructed() + { + $this->assertEquals(3, $this->body->ftell()); + } + + public function testAllowsBoundedSeek() + { + $this->body->seek(100); + $this->assertEquals(13, $this->body->ftell()); + $this->body->seek(0); + $this->assertEquals(3, $this->body->ftell()); + $this->assertEquals(false, $this->body->seek(1000, SEEK_END)); + } + + public function testReadsOnlySubsetOfData() + { + $data = $this->body->read(100); + $this->assertEquals(10, strlen($data)); + $this->assertFalse($this->body->read(1000)); + + $this->body->setOffset(10); + $newData = $this->body->read(100); + $this->assertEquals(10, strlen($newData)); + $this->assertNotSame($data, $newData); + } + + public function testClaimsConsumedWhenReadLimitIsReached() + { + $this->assertFalse($this->body->isConsumed()); + $this->body->read(1000); + $this->assertTrue($this->body->isConsumed()); + } + + public function testContentLengthIsBounded() + { + $this->assertEquals(10, $this->body->getContentLength()); + } + + public function testContentMd5IsBasedOnSubsection() + { + $this->assertNotSame($this->body->getContentMd5(), $this->decorated->getContentMd5()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/RedirectPluginTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/RedirectPluginTest.php new file mode 100755 index 000000000..886236ddd --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/RedirectPluginTest.php @@ -0,0 +1,277 @@ +getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect1\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect2\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", + )); + + // Create a client that uses the default redirect behavior + $client = new Client($this->getServer()->getUrl()); + $history = new HistoryPlugin(); + $client->addSubscriber($history); + + $request = $client->get('/foo'); + $response = $request->send(); + $this->assertEquals(200, $response->getStatusCode()); + $this->assertContains('/redirect2', $response->getEffectiveUrl()); + + // Ensure that two requests were sent + $requests = $this->getServer()->getReceivedRequests(true); + $this->assertEquals('/foo', $requests[0]->getResource()); + $this->assertEquals('GET', $requests[0]->getMethod()); + $this->assertEquals('/redirect1', $requests[1]->getResource()); + $this->assertEquals('GET', $requests[1]->getMethod()); + $this->assertEquals('/redirect2', $requests[2]->getResource()); + $this->assertEquals('GET', $requests[2]->getMethod()); + + // Ensure that the redirect count was incremented + $this->assertEquals(2, $request->getParams()->get(RedirectPlugin::REDIRECT_COUNT)); + $this->assertCount(3, $history); + $requestHistory = $history->getAll(); + + $this->assertEquals(301, $requestHistory[0]['response']->getStatusCode()); + $this->assertEquals('/redirect1', (string) $requestHistory[0]['response']->getHeader('Location')); + $this->assertEquals(301, $requestHistory[1]['response']->getStatusCode()); + $this->assertEquals('/redirect2', (string) $requestHistory[1]['response']->getHeader('Location')); + $this->assertEquals(200, $requestHistory[2]['response']->getStatusCode()); + } + + public function testCanLimitNumberOfRedirects() + { + // Flush the server and queue up a redirect followed by a successful response + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect1\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect2\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect3\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect4\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect5\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect6\r\nContent-Length: 0\r\n\r\n" + )); + + try { + $client = new Client($this->getServer()->getUrl()); + $client->get('/foo')->send(); + $this->fail('Did not throw expected exception'); + } catch (TooManyRedirectsException $e) { + $this->assertContains( + "5 redirects were issued for this request:\nGET /foo HTTP/1.1\r\n", + $e->getMessage() + ); + } + } + + public function testDefaultBehaviorIsToRedirectWithGetForEntityEnclosingRequests() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", + )); + + $client = new Client($this->getServer()->getUrl()); + $client->post('/foo', array('X-Baz' => 'bar'), 'testing')->send(); + + $requests = $this->getServer()->getReceivedRequests(true); + $this->assertEquals('POST', $requests[0]->getMethod()); + $this->assertEquals('GET', $requests[1]->getMethod()); + $this->assertEquals('bar', (string) $requests[1]->getHeader('X-Baz')); + $this->assertEquals('GET', $requests[2]->getMethod()); + } + + public function testCanRedirectWithStrictRfcCompliance() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", + )); + + $client = new Client($this->getServer()->getUrl()); + $request = $client->post('/foo', array('X-Baz' => 'bar'), 'testing'); + $request->getParams()->set(RedirectPlugin::STRICT_REDIRECTS, true); + $request->send(); + + $requests = $this->getServer()->getReceivedRequests(true); + $this->assertEquals('POST', $requests[0]->getMethod()); + $this->assertEquals('POST', $requests[1]->getMethod()); + $this->assertEquals('bar', (string) $requests[1]->getHeader('X-Baz')); + $this->assertEquals('POST', $requests[2]->getMethod()); + } + + public function testRedirect303WithGet() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 303 Moved Permanently\r\nLocation: /redirect\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", + )); + + $client = new Client($this->getServer()->getUrl()); + $request = $client->post('/foo'); + $request->send(); + + $requests = $this->getServer()->getReceivedRequests(true); + $this->assertEquals('POST', $requests[0]->getMethod()); + $this->assertEquals('GET', $requests[1]->getMethod()); + } + + public function testRedirect303WithGetWithStrictRfcCompliance() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 303 Moved Permanently\r\nLocation: /redirect\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", + )); + + $client = new Client($this->getServer()->getUrl()); + $request = $client->post('/foo'); + $request->getParams()->set(RedirectPlugin::STRICT_REDIRECTS, true); + $request->send(); + + $requests = $this->getServer()->getReceivedRequests(true); + $this->assertEquals('POST', $requests[0]->getMethod()); + $this->assertEquals('GET', $requests[1]->getMethod()); + } + + public function testRewindsStreamWhenRedirectingIfNeeded() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", + )); + + $client = new Client($this->getServer()->getUrl()); + $request = $client->put(); + $request->configureRedirects(true); + $body = EntityBody::factory('foo'); + $body->read(1); + $request->setBody($body); + $request->send(); + $requests = $this->getServer()->getReceivedRequests(true); + $this->assertEquals('foo', (string) $requests[0]->getBody()); + } + + /** + * @expectedException \Guzzle\Http\Exception\CouldNotRewindStreamException + */ + public function testThrowsExceptionWhenStreamCannotBeRewound() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi", + "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect\r\nContent-Length: 0\r\n\r\n" + )); + + $client = new Client($this->getServer()->getUrl()); + $request = $client->put(); + $request->configureRedirects(true); + $body = EntityBody::factory(fopen($this->getServer()->getUrl(), 'r')); + $body->read(1); + $request->setBody($body)->send(); + } + + public function testRedirectsCanBeDisabledPerRequest() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array("HTTP/1.1 301 Foo\r\nLocation: /foo\r\nContent-Length: 0\r\n\r\n")); + $client = new Client($this->getServer()->getUrl()); + $request = $client->put(); + $request->configureRedirects(false, 0); + $this->assertEquals(301, $request->send()->getStatusCode()); + } + + public function testCanRedirectWithNoLeadingSlashAndQuery() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 301 Moved Permanently\r\nLocation: redirect?foo=bar\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", + )); + $client = new Client($this->getServer()->getUrl()); + $request = $client->get('?foo=bar'); + $request->send(); + $requests = $this->getServer()->getReceivedRequests(true); + $this->assertEquals($this->getServer()->getUrl() . '?foo=bar', $requests[0]->getUrl()); + $this->assertEquals($this->getServer()->getUrl() . 'redirect?foo=bar', $requests[1]->getUrl()); + // Ensure that the history on the actual request is correct + $this->assertEquals($this->getServer()->getUrl() . '?foo=bar', $request->getUrl()); + } + + public function testRedirectWithStrictRfc386Compliance() + { + // Flush the server and queue up a redirect followed by a successful response + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 301 Moved Permanently\r\nLocation: redirect\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n" + )); + $client = new Client($this->getServer()->getUrl()); + $request = $client->get('/foo'); + $request->send(); + $requests = $this->getServer()->getReceivedRequests(true); + $this->assertEquals('/redirect', $requests[1]->getResource()); + } + + public function testResetsHistoryEachSend() + { + // Flush the server and queue up a redirect followed by a successful response + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect1\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect2\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n" + )); + + // Create a client that uses the default redirect behavior + $client = new Client($this->getServer()->getUrl()); + $history = new HistoryPlugin(); + $client->addSubscriber($history); + + $request = $client->get('/foo'); + $response = $request->send(); + $this->assertEquals(3, count($history)); + $this->assertTrue($request->getParams()->hasKey('redirect.count')); + $this->assertContains('/redirect2', $response->getEffectiveUrl()); + + $request->send(); + $this->assertFalse($request->getParams()->hasKey('redirect.count')); + } + + public function testHandlesRedirectsWithSpacesProperly() + { + // Flush the server and queue up a redirect followed by a successful response + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect 1\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n" + )); + $client = new Client($this->getServer()->getUrl()); + $request = $client->get('/foo'); + $request->send(); + $reqs = $this->getServer()->getReceivedRequests(true); + $this->assertEquals('/redirect%201', $reqs[1]->getResource()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Server.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Server.php new file mode 100644 index 000000000..94eb59a4d --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/Server.php @@ -0,0 +1,191 @@ +port = $port ?: self::DEFAULT_PORT; + $this->client = new Client($this->getUrl()); + register_shutdown_function(array($this, 'stop')); + } + + /** + * Flush the received requests from the server + * @throws RuntimeException + */ + public function flush() + { + $this->client->delete('guzzle-server/requests')->send(); + } + + /** + * Queue an array of responses or a single response on the server. + * + * Any currently queued responses will be overwritten. Subsequent requests + * on the server will return queued responses in FIFO order. + * + * @param array|Response $responses A single or array of Responses to queue + * @throws BadResponseException + */ + public function enqueue($responses) + { + $data = array(); + foreach ((array) $responses as $response) { + + // Create the response object from a string + if (is_string($response)) { + $response = Response::fromMessage($response); + } elseif (!($response instanceof Response)) { + throw new BadResponseException('Responses must be strings or implement Response'); + } + + $data[] = array( + 'statusCode' => $response->getStatusCode(), + 'reasonPhrase' => $response->getReasonPhrase(), + 'headers' => $response->getHeaders()->toArray(), + 'body' => $response->getBody(true) + ); + } + + $request = $this->client->put('guzzle-server/responses', null, json_encode($data)); + $request->send(); + } + + /** + * Check if the server is running + * + * @return bool + */ + public function isRunning() + { + if ($this->running) { + return true; + } + + try { + $this->client->get('guzzle-server/perf', array(), array('timeout' => 5))->send(); + $this->running = true; + return true; + } catch (\Exception $e) { + return false; + } + } + + /** + * Get the URL to the server + * + * @return string + */ + public function getUrl() + { + return 'http://127.0.0.1:' . $this->getPort() . '/'; + } + + /** + * Get the port that the server is listening on + * + * @return int + */ + public function getPort() + { + return $this->port; + } + + /** + * Get all of the received requests + * + * @param bool $hydrate Set to TRUE to turn the messages into + * actual {@see RequestInterface} objects. If $hydrate is FALSE, + * requests will be returned as strings. + * + * @return array + * @throws RuntimeException + */ + public function getReceivedRequests($hydrate = false) + { + $response = $this->client->get('guzzle-server/requests')->send(); + $data = array_filter(explode(self::REQUEST_DELIMITER, $response->getBody(true))); + if ($hydrate) { + $data = array_map(function($message) { + return RequestFactory::getInstance()->fromMessage($message); + }, $data); + } + + return $data; + } + + /** + * Start running the node.js server in the background + */ + public function start() + { + if (!$this->isRunning()) { + exec('node ' . __DIR__ . \DIRECTORY_SEPARATOR + . 'server.js ' . $this->port + . ' >> /tmp/server.log 2>&1 &'); + // Wait at most 5 seconds for the server the setup before + // proceeding. + $start = time(); + while (!$this->isRunning() && time() - $start < 5); + if (!$this->running) { + throw new RuntimeException( + 'Unable to contact server.js. Have you installed node.js v0.5.0+? node must be in your path.' + ); + } + } + } + + /** + * Stop running the node.js server + */ + public function stop() + { + if (!$this->isRunning()) { + return false; + } + + $this->running = false; + $this->client->delete('guzzle-server')->send(); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/StaticClientTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/StaticClientTest.php new file mode 100644 index 000000000..091314bb7 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/StaticClientTest.php @@ -0,0 +1,67 @@ +assertTrue(class_exists('FooBazBar')); + $this->assertSame($client, $this->readAttribute('Guzzle\Http\StaticClient', 'client')); + } + + public function requestProvider() + { + return array_map( + function ($m) { return array($m); }, + array('GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS') + ); + } + + /** + * @dataProvider requestProvider + */ + public function testSendsRequests($method) + { + $mock = new MockPlugin(array(new Response(200))); + call_user_func('Guzzle\Http\StaticClient::' . $method, 'http://foo.com', array( + 'plugins' => array($mock) + )); + $requests = $mock->getReceivedRequests(); + $this->assertCount(1, $requests); + $this->assertEquals($method, $requests[0]->getMethod()); + } + + public function testCanCreateStreamsUsingDefaultFactory() + { + $this->getServer()->enqueue(array("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ntest")); + $stream = StaticClient::get($this->getServer()->getUrl(), array('stream' => true)); + $this->assertInstanceOf('Guzzle\Stream\StreamInterface', $stream); + $this->assertEquals('test', (string) $stream); + } + + public function testCanCreateStreamsUsingCustomFactory() + { + $stream = $this->getMockBuilder('Guzzle\Stream\StreamRequestFactoryInterface') + ->setMethods(array('fromRequest')) + ->getMockForAbstractClass(); + $resource = new Stream(fopen('php://temp', 'r+')); + $stream->expects($this->once()) + ->method('fromRequest') + ->will($this->returnValue($resource)); + $this->getServer()->enqueue(array("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ntest")); + $result = StaticClient::get($this->getServer()->getUrl(), array('stream' => $stream)); + $this->assertSame($resource, $result); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/UrlTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/UrlTest.php new file mode 100644 index 000000000..28f26718b --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/UrlTest.php @@ -0,0 +1,303 @@ +assertEquals('', (string) $url); + } + + public function testPortIsDeterminedFromScheme() + { + $this->assertEquals(80, Url::factory('http://www.test.com/')->getPort()); + $this->assertEquals(443, Url::factory('https://www.test.com/')->getPort()); + $this->assertEquals(null, Url::factory('ftp://www.test.com/')->getPort()); + $this->assertEquals(8192, Url::factory('http://www.test.com:8192/')->getPort()); + } + + public function testCloneCreatesNewInternalObjects() + { + $u1 = Url::factory('http://www.test.com/'); + $u2 = clone $u1; + $this->assertNotSame($u1->getQuery(), $u2->getQuery()); + } + + public function testValidatesUrlPartsInFactory() + { + $url = Url::factory('/index.php'); + $this->assertEquals('/index.php', (string) $url); + $this->assertFalse($url->isAbsolute()); + + $url = 'http://michael:test@test.com:80/path/123?q=abc#test'; + $u = Url::factory($url); + $this->assertEquals('http://michael:test@test.com/path/123?q=abc#test', (string) $u); + $this->assertTrue($u->isAbsolute()); + } + + public function testAllowsFalsyUrlParts() + { + $url = Url::factory('http://0:50/0?0#0'); + $this->assertSame('0', $url->getHost()); + $this->assertEquals(50, $url->getPort()); + $this->assertSame('/0', $url->getPath()); + $this->assertEquals('0', (string) $url->getQuery()); + $this->assertSame('0', $url->getFragment()); + $this->assertEquals('http://0:50/0?0#0', (string) $url); + + $url = Url::factory(''); + $this->assertSame('', (string) $url); + + $url = Url::factory('0'); + $this->assertSame('0', (string) $url); + } + + public function testBuildsRelativeUrlsWithFalsyParts() + { + $url = Url::buildUrl(array( + 'host' => '0', + 'path' => '0', + )); + + $this->assertSame('//0/0', $url); + + $url = Url::buildUrl(array( + 'path' => '0', + )); + $this->assertSame('0', $url); + } + + public function testUrlStoresParts() + { + $url = Url::factory('http://test:pass@www.test.com:8081/path/path2/?a=1&b=2#fragment'); + $this->assertEquals('http', $url->getScheme()); + $this->assertEquals('test', $url->getUsername()); + $this->assertEquals('pass', $url->getPassword()); + $this->assertEquals('www.test.com', $url->getHost()); + $this->assertEquals(8081, $url->getPort()); + $this->assertEquals('/path/path2/', $url->getPath()); + $this->assertEquals('fragment', $url->getFragment()); + $this->assertEquals('a=1&b=2', (string) $url->getQuery()); + + $this->assertEquals(array( + 'fragment' => 'fragment', + 'host' => 'www.test.com', + 'pass' => 'pass', + 'path' => '/path/path2/', + 'port' => 8081, + 'query' => 'a=1&b=2', + 'scheme' => 'http', + 'user' => 'test' + ), $url->getParts()); + } + + public function testHandlesPathsCorrectly() + { + $url = Url::factory('http://www.test.com'); + $this->assertEquals('', $url->getPath()); + $url->setPath('test'); + $this->assertEquals('test', $url->getPath()); + + $url->setPath('/test/123/abc'); + $this->assertEquals(array('test', '123', 'abc'), $url->getPathSegments()); + + $parts = parse_url('http://www.test.com/test'); + $parts['path'] = ''; + $this->assertEquals('http://www.test.com', Url::buildUrl($parts)); + $parts['path'] = 'test'; + $this->assertEquals('http://www.test.com/test', Url::buildUrl($parts)); + } + + public function testAddsQueryStringIfPresent() + { + $this->assertEquals('?foo=bar', Url::buildUrl(array( + 'query' => 'foo=bar' + ))); + } + + public function testAddsToPath() + { + // Does nothing here + $this->assertEquals('http://e.com/base?a=1', (string) Url::factory('http://e.com/base?a=1')->addPath(false)); + $this->assertEquals('http://e.com/base?a=1', (string) Url::factory('http://e.com/base?a=1')->addPath(null)); + $this->assertEquals('http://e.com/base?a=1', (string) Url::factory('http://e.com/base?a=1')->addPath(array())); + $this->assertEquals('http://e.com/base?a=1', (string) Url::factory('http://e.com/base?a=1')->addPath(new \stdClass())); + $this->assertEquals('http://e.com/base?a=1', (string) Url::factory('http://e.com/base?a=1')->addPath('')); + $this->assertEquals('http://e.com/base?a=1', (string) Url::factory('http://e.com/base?a=1')->addPath('/')); + $this->assertEquals('http://e.com/baz/foo', (string) Url::factory('http://e.com/baz/')->addPath('foo')); + $this->assertEquals('http://e.com/base/relative?a=1', (string) Url::factory('http://e.com/base?a=1')->addPath('relative')); + $this->assertEquals('http://e.com/base/relative?a=1', (string) Url::factory('http://e.com/base?a=1')->addPath('/relative')); + $this->assertEquals('http://e.com/base/0', (string) Url::factory('http://e.com/base')->addPath('0')); + $this->assertEquals('http://e.com/base/0/1', (string) Url::factory('http://e.com/base')->addPath('0')->addPath('1')); + } + + /** + * URL combination data provider + * + * @return array + */ + public function urlCombineDataProvider() + { + return array( + array('http://www.example.com/', 'http://www.example.com/', 'http://www.example.com/'), + array('http://www.example.com/path', '/absolute', 'http://www.example.com/absolute'), + array('http://www.example.com/path', '/absolute?q=2', 'http://www.example.com/absolute?q=2'), + array('http://www.example.com/path', 'more', 'http://www.example.com/path/more'), + array('http://www.example.com/path', 'more?q=1', 'http://www.example.com/path/more?q=1'), + array('http://www.example.com/', '?q=1', 'http://www.example.com/?q=1'), + array('http://www.example.com/path', 'http://test.com', 'http://test.com'), + array('http://www.example.com:8080/path', 'http://test.com', 'http://test.com'), + array('http://www.example.com:8080/path', '?q=2#abc', 'http://www.example.com:8080/path?q=2#abc'), + array('http://u:a@www.example.com/path', 'test', 'http://u:a@www.example.com/path/test'), + array('http://www.example.com/path', 'http://u:a@www.example.com/', 'http://u:a@www.example.com/'), + array('/path?q=2', 'http://www.test.com/', 'http://www.test.com/path?q=2'), + array('http://api.flickr.com/services/', 'http://www.flickr.com/services/oauth/access_token', 'http://www.flickr.com/services/oauth/access_token'), + array('http://www.example.com/?foo=bar', 'some/path', 'http://www.example.com/some/path?foo=bar'), + array('http://www.example.com/?foo=bar', 'some/path?boo=moo', 'http://www.example.com/some/path?boo=moo&foo=bar'), + array('http://www.example.com/some/', 'path?foo=bar&foo=baz', 'http://www.example.com/some/path?foo=bar&foo=baz'), + ); + } + + /** + * @dataProvider urlCombineDataProvider + */ + public function testCombinesUrls($a, $b, $c) + { + $this->assertEquals($c, (string) Url::factory($a)->combine($b)); + } + + public function testHasGettersAndSetters() + { + $url = Url::factory('http://www.test.com/'); + $this->assertEquals('example.com', $url->setHost('example.com')->getHost()); + $this->assertEquals('8080', $url->setPort(8080)->getPort()); + $this->assertEquals('/foo/bar', $url->setPath(array('foo', 'bar'))->getPath()); + $this->assertEquals('a', $url->setPassword('a')->getPassword()); + $this->assertEquals('b', $url->setUsername('b')->getUsername()); + $this->assertEquals('abc', $url->setFragment('abc')->getFragment()); + $this->assertEquals('https', $url->setScheme('https')->getScheme()); + $this->assertEquals('a=123', (string) $url->setQuery('a=123')->getQuery()); + $this->assertEquals('https://b:a@example.com:8080/foo/bar?a=123#abc', (string) $url); + $this->assertEquals('b=boo', (string) $url->setQuery(new QueryString(array( + 'b' => 'boo' + )))->getQuery()); + $this->assertEquals('https://b:a@example.com:8080/foo/bar?b=boo#abc', (string) $url); + } + + public function testSetQueryAcceptsArray() + { + $url = Url::factory('http://www.test.com'); + $url->setQuery(array('a' => 'b')); + $this->assertEquals('http://www.test.com?a=b', (string) $url); + } + + public function urlProvider() + { + return array( + array('/foo/..', '/'), + array('//foo//..', '/'), + array('/foo/../..', '/'), + array('/foo/../.', '/'), + array('/./foo/..', '/'), + array('/./foo', '/foo'), + array('/./foo/', '/foo/'), + array('/./foo/bar/baz/pho/../..', '/foo/bar'), + array('*', '*'), + array('/foo', '/foo'), + array('/abc/123/../foo/', '/abc/foo/'), + array('/a/b/c/./../../g', '/a/g'), + array('/b/c/./../../g', '/g'), + array('/b/c/./../../g', '/g'), + array('/c/./../../g', '/g'), + array('/./../../g', '/g'), + ); + } + + /** + * @dataProvider urlProvider + */ + public function testNormalizesPaths($path, $result) + { + $url = Url::factory('http://www.example.com/'); + $url->setPath($path)->normalizePath(); + $this->assertEquals($result, $url->getPath()); + } + + public function testSettingHostWithPortModifiesPort() + { + $url = Url::factory('http://www.example.com'); + $url->setHost('foo:8983'); + $this->assertEquals('foo', $url->getHost()); + $this->assertEquals(8983, $url->getPort()); + } + + /** + * @expectedException \Guzzle\Common\Exception\InvalidArgumentException + */ + public function testValidatesUrlCanBeParsed() + { + Url::factory('foo:////'); + } + + public function testConvertsSpecialCharsInPathWhenCastingToString() + { + $url = Url::factory('http://foo.com/baz bar?a=b'); + $url->addPath('?'); + $this->assertEquals('http://foo.com/baz%20bar/%3F?a=b', (string) $url); + } + + /** + * @link http://tools.ietf.org/html/rfc3986#section-5.4.1 + */ + public function rfc3986UrlProvider() + { + $result = array( + array('g', 'http://a/b/c/g'), + array('./g', 'http://a/b/c/g'), + array('g/', 'http://a/b/c/g/'), + array('/g', 'http://a/g'), + array('?y', 'http://a/b/c/d;p?y'), + array('g?y', 'http://a/b/c/g?y'), + array('#s', 'http://a/b/c/d;p?q#s'), + array('g#s', 'http://a/b/c/g#s'), + array('g?y#s', 'http://a/b/c/g?y#s'), + array(';x', 'http://a/b/c/;x'), + array('g;x', 'http://a/b/c/g;x'), + array('g;x?y#s', 'http://a/b/c/g;x?y#s'), + array('', 'http://a/b/c/d;p?q'), + array('.', 'http://a/b/c'), + array('./', 'http://a/b/c/'), + array('..', 'http://a/b'), + array('../', 'http://a/b/'), + array('../g', 'http://a/b/g'), + array('../..', 'http://a/'), + array('../../', 'http://a/'), + array('../../g', 'http://a/g') + ); + + // This support was added in PHP 5.4.7: https://bugs.php.net/bug.php?id=62844 + if (version_compare(PHP_VERSION, '5.4.7', '>=')) { + $result[] = array('//g', 'http://g'); + } + + return $result; + } + + /** + * @dataProvider rfc3986UrlProvider + */ + public function testCombinesUrlsUsingRfc3986($relative, $result) + { + $a = Url::factory('http://a/b/c/d;p?q'); + $b = Url::factory($relative); + $this->assertEquals($result, trim((string) $a->combine($b, true), '=')); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/server.js b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/server.js new file mode 100644 index 000000000..4156f1aad --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Http/server.js @@ -0,0 +1,146 @@ +/** + * Guzzle node.js test server to return queued responses to HTTP requests and + * expose a RESTful API for enqueueing responses and retrieving the requests + * that have been received. + * + * - Delete all requests that have been received: + * DELETE /guzzle-server/requests + * Host: 127.0.0.1:8124 + * + * - Enqueue responses + * PUT /guzzle-server/responses + * Host: 127.0.0.1:8124 + * + * [{ "statusCode": 200, "reasonPhrase": "OK", "headers": {}, "body": "" }] + * + * - Get the received requests + * GET /guzzle-server/requests + * Host: 127.0.0.1:8124 + * + * - Shutdown the server + * DELETE /guzzle-server + * Host: 127.0.0.1:8124 + * + * @package Guzzle PHP + * @license See the LICENSE file that was distributed with this source code. + */ + +var http = require("http"); + +/** + * Guzzle node.js server + * @class + */ +var GuzzleServer = function(port, log) { + + this.port = port; + this.log = log; + this.responses = []; + this.requests = []; + var that = this; + + var controlRequest = function(request, req, res) { + if (req.url == '/guzzle-server/perf') { + res.writeHead(200, "OK", {"Content-Length": 16}); + res.end("Body of response"); + } else if (req.method == "DELETE") { + if (req.url == "/guzzle-server/requests") { + // Clear the received requests + that.requests = []; + res.writeHead(200, "OK", { "Content-Length": 0 }); + res.end(); + if (this.log) { + console.log("Flushing requests"); + } + } else if (req.url == "/guzzle-server") { + // Shutdown the server + res.writeHead(200, "OK", { "Content-Length": 0, "Connection": "close" }); + res.end(); + if (this.log) { + console.log("Shutting down"); + } + that.server.close(); + } + } else if (req.method == "GET") { + if (req.url === "/guzzle-server/requests") { + // Get received requests + var data = that.requests.join("\n----[request]\n"); + res.writeHead(200, "OK", { "Content-Length": data.length }); + res.end(data); + if (that.log) { + console.log("Sending receiving requests"); + } + } + } else if (req.method == "PUT") { + if (req.url == "/guzzle-server/responses") { + if (that.log) { + console.log("Adding responses..."); + } + // Received response to queue + var data = request.split("\r\n\r\n")[1]; + if (!data) { + if (that.log) { + console.log("No response data was provided"); + } + res.writeHead(400, "NO RESPONSES IN REQUEST", { "Content-Length": 0 }); + } else { + that.responses = eval("(" + data + ")"); + if (that.log) { + console.log(that.responses); + } + res.writeHead(200, "OK", { "Content-Length": 0 }); + } + res.end(); + } + } + }; + + var receivedRequest = function(request, req, res) { + if (req.url.indexOf("/guzzle-server") === 0) { + controlRequest(request, req, res); + } else if (req.url.indexOf("/guzzle-server") == -1 && !that.responses.length) { + res.writeHead(500); + res.end("No responses in queue"); + } else { + var response = that.responses.shift(); + res.writeHead(response.statusCode, response.reasonPhrase, response.headers); + res.end(response.body); + that.requests.push(request); + } + }; + + this.start = function() { + + that.server = http.createServer(function(req, res) { + + var request = req.method + " " + req.url + " HTTP/" + req.httpVersion + "\r\n"; + for (var i in req.headers) { + request += i + ": " + req.headers[i] + "\r\n"; + } + request += "\r\n"; + + // Receive each chunk of the request body + req.addListener("data", function(chunk) { + request += chunk; + }); + + // Called when the request completes + req.addListener("end", function() { + receivedRequest(request, req, res); + }); + }); + that.server.listen(port, "127.0.0.1"); + + if (this.log) { + console.log("Server running at http://127.0.0.1:8124/"); + } + }; +}; + +// Get the port from the arguments +port = process.argv.length >= 3 ? process.argv[2] : 8124; +log = process.argv.length >= 4 ? process.argv[3] : false; + +// Start the server +server = new GuzzleServer(port, log); +server.start(); diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Inflection/InflectorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Inflection/InflectorTest.php new file mode 100644 index 000000000..990c0af66 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Inflection/InflectorTest.php @@ -0,0 +1,37 @@ +assertSame(Inflector::getDefault(), Inflector::getDefault()); + } + + public function testSnake() + { + $this->assertEquals('camel_case', Inflector::getDefault()->snake('camelCase')); + $this->assertEquals('camel_case', Inflector::getDefault()->snake('CamelCase')); + $this->assertEquals('camel_case_words', Inflector::getDefault()->snake('CamelCaseWords')); + $this->assertEquals('camel_case_words', Inflector::getDefault()->snake('CamelCase_words')); + $this->assertEquals('test', Inflector::getDefault()->snake('test')); + $this->assertEquals('test', Inflector::getDefault()->snake('test')); + $this->assertEquals('expect100_continue', Inflector::getDefault()->snake('Expect100Continue')); + } + + public function testCamel() + { + $this->assertEquals('CamelCase', Inflector::getDefault()->camel('camel_case')); + $this->assertEquals('CamelCaseWords', Inflector::getDefault()->camel('camel_case_words')); + $this->assertEquals('Test', Inflector::getDefault()->camel('test')); + $this->assertEquals('Expect100Continue', ucfirst(Inflector::getDefault()->camel('expect100_continue'))); + // Get from cache + $this->assertEquals('Test', Inflector::getDefault()->camel('test', false)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Inflection/MemoizingInflectorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Inflection/MemoizingInflectorTest.php new file mode 100644 index 000000000..f00b7fad8 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Inflection/MemoizingInflectorTest.php @@ -0,0 +1,46 @@ +getMock('Guzzle\Inflection\Inflector', array('snake', 'camel')); + $mock->expects($this->once())->method('snake')->will($this->returnValue('foo_bar')); + $mock->expects($this->once())->method('camel')->will($this->returnValue('FooBar')); + + $inflector = new MemoizingInflector($mock); + $this->assertEquals('foo_bar', $inflector->snake('FooBar')); + $this->assertEquals('foo_bar', $inflector->snake('FooBar')); + $this->assertEquals('FooBar', $inflector->camel('foo_bar')); + $this->assertEquals('FooBar', $inflector->camel('foo_bar')); + } + + public function testProtectsAgainstCacheOverflow() + { + $inflector = new MemoizingInflector(new Inflector(), 10); + for ($i = 1; $i < 11; $i++) { + $inflector->camel('foo_' . $i); + $inflector->snake('Foo' . $i); + } + + $cache = $this->readAttribute($inflector, 'cache'); + $this->assertEquals(10, count($cache['snake'])); + $this->assertEquals(10, count($cache['camel'])); + + $inflector->camel('baz!'); + $inflector->snake('baz!'); + + // Now ensure that 20% of the cache was removed (2), then the item was added + $cache = $this->readAttribute($inflector, 'cache'); + $this->assertEquals(9, count($cache['snake'])); + $this->assertEquals(9, count($cache['camel'])); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Inflection/PreComputedInflectorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Inflection/PreComputedInflectorTest.php new file mode 100644 index 000000000..ff2654cf6 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Inflection/PreComputedInflectorTest.php @@ -0,0 +1,45 @@ +getMock('Guzzle\Inflection\Inflector', array('snake', 'camel')); + $mock->expects($this->once())->method('snake')->with('Test')->will($this->returnValue('test')); + $mock->expects($this->once())->method('camel')->with('Test')->will($this->returnValue('Test')); + $inflector = new PreComputedInflector($mock, array('FooBar' => 'foo_bar'), array('foo_bar' => 'FooBar')); + $this->assertEquals('FooBar', $inflector->camel('foo_bar')); + $this->assertEquals('foo_bar', $inflector->snake('FooBar')); + $this->assertEquals('Test', $inflector->camel('Test')); + $this->assertEquals('test', $inflector->snake('Test')); + } + + public function testMirrorsPrecomputedValues() + { + $mock = $this->getMock('Guzzle\Inflection\Inflector', array('snake', 'camel')); + $mock->expects($this->never())->method('snake'); + $mock->expects($this->never())->method('camel'); + $inflector = new PreComputedInflector($mock, array('Zeep' => 'zeep'), array(), true); + $this->assertEquals('Zeep', $inflector->camel('zeep')); + $this->assertEquals('zeep', $inflector->snake('Zeep')); + } + + public function testMirrorsPrecomputedValuesByMerging() + { + $mock = $this->getMock('Guzzle\Inflection\Inflector', array('snake', 'camel')); + $mock->expects($this->never())->method('snake'); + $mock->expects($this->never())->method('camel'); + $inflector = new PreComputedInflector($mock, array('Zeep' => 'zeep'), array('foo' => 'Foo'), true); + $this->assertEquals('Zeep', $inflector->camel('zeep')); + $this->assertEquals('zeep', $inflector->snake('Zeep')); + $this->assertEquals('Foo', $inflector->camel('foo')); + $this->assertEquals('foo', $inflector->snake('Foo')); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Iterator/AppendIteratorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Iterator/AppendIteratorTest.php new file mode 100644 index 000000000..8d6ae845a --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Iterator/AppendIteratorTest.php @@ -0,0 +1,29 @@ + 1, + 'b' => 2 + )); + $b = new \ArrayIterator(array()); + $c = new \ArrayIterator(array( + 'c' => 3, + 'd' => 4 + )); + $i = new AppendIterator(); + $i->append($a); + $i->append($b); + $i->append($c); + $this->assertEquals(array(1, 2, 3, 4), iterator_to_array($i, false)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Iterator/ChunkedIteratorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Iterator/ChunkedIteratorTest.php new file mode 100644 index 000000000..ec4c1294c --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Iterator/ChunkedIteratorTest.php @@ -0,0 +1,52 @@ +assertEquals(11, count($chunks)); + foreach ($chunks as $j => $chunk) { + $this->assertEquals(range($j * 10, min(100, $j * 10 + 9)), $chunk); + } + } + + public function testChunksIteratorWithOddValues() + { + $chunked = new ChunkedIterator(new \ArrayIterator(array(1, 2, 3, 4, 5)), 2); + $chunks = iterator_to_array($chunked, false); + $this->assertEquals(3, count($chunks)); + $this->assertEquals(array(1, 2), $chunks[0]); + $this->assertEquals(array(3, 4), $chunks[1]); + $this->assertEquals(array(5), $chunks[2]); + } + + public function testMustNotTerminateWithTraversable() + { + $traversable = simplexml_load_string('')->foo; + $chunked = new ChunkedIterator($traversable, 2); + $actual = iterator_to_array($chunked, false); + $this->assertCount(2, $actual); + } + + public function testSizeOfZeroMakesIteratorInvalid() { + $chunked = new ChunkedIterator(new \ArrayIterator(range(1, 5)), 0); + $chunked->rewind(); + $this->assertFalse($chunked->valid()); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testSizeLowerZeroThrowsException() { + new ChunkedIterator(new \ArrayIterator(range(1, 5)), -1); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Iterator/FilterIteratorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Iterator/FilterIteratorTest.php new file mode 100644 index 000000000..73b4f6987 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Iterator/FilterIteratorTest.php @@ -0,0 +1,28 @@ +assertEquals(range(1, 99, 2), iterator_to_array($i, false)); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testValidatesCallable() + { + $i = new FilterIterator(new \ArrayIterator(), new \stdClass()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Iterator/MapIteratorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Iterator/MapIteratorTest.php new file mode 100644 index 000000000..4de4a6bc1 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Iterator/MapIteratorTest.php @@ -0,0 +1,28 @@ +assertEquals(range(0, 1000, 10), iterator_to_array($i, false)); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testValidatesCallable() + { + $i = new MapIterator(new \ArrayIterator(), new \stdClass()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Iterator/MethodProxyIteratorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Iterator/MethodProxyIteratorTest.php new file mode 100644 index 000000000..5bcf06fb0 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Iterator/MethodProxyIteratorTest.php @@ -0,0 +1,28 @@ +append('a'); + $proxy->append('b'); + $this->assertEquals(array('a', 'b'), $i->getArrayCopy()); + $this->assertEquals(array('a', 'b'), $proxy->getArrayCopy()); + } + + public function testUsesInnerIterator() + { + $i = new MethodProxyIterator(new ChunkedIterator(new \ArrayIterator(array(1, 2, 3, 4, 5)), 2)); + $this->assertEquals(3, count(iterator_to_array($i, false))); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Log/ArrayLogAdapterTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Log/ArrayLogAdapterTest.php new file mode 100644 index 000000000..a66882f6f --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Log/ArrayLogAdapterTest.php @@ -0,0 +1,23 @@ +log('test', \LOG_NOTICE, '127.0.0.1'); + $this->assertEquals(array(array('message' => 'test', 'priority' => \LOG_NOTICE, 'extras' => '127.0.0.1')), $adapter->getLogs()); + } + + public function testClearLog() + { + $adapter = new ArrayLogAdapter(); + $adapter->log('test', \LOG_NOTICE, '127.0.0.1'); + $adapter->clearLogs(); + $this->assertEquals(array(), $adapter->getLogs()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Log/ClosureLogAdapterTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Log/ClosureLogAdapterTest.php new file mode 100644 index 000000000..0177dc071 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Log/ClosureLogAdapterTest.php @@ -0,0 +1,30 @@ +adapter = new ClosureLogAdapter(function($message, $priority, $extras = null) use ($that, &$modified) { + $modified = array($message, $priority, $extras); + }); + $this->adapter->log('test', LOG_NOTICE, '127.0.0.1'); + $this->assertEquals(array('test', LOG_NOTICE, '127.0.0.1'), $modified); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testThrowsExceptionWhenNotCallable() + { + $this->adapter = new ClosureLogAdapter(123); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Log/MessageFormatterTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Log/MessageFormatterTest.php new file mode 100644 index 000000000..3ff4b0737 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Log/MessageFormatterTest.php @@ -0,0 +1,143 @@ +request = new EntityEnclosingRequest('POST', 'http://foo.com?q=test', array( + 'X-Foo' => 'bar', + 'Authorization' => 'Baz' + )); + $this->request->setBody(EntityBody::factory('Hello')); + + $this->response = new Response(200, array( + 'X-Test' => 'Abc' + ), 'Foo'); + + $this->handle = $this->getMockBuilder('Guzzle\Http\Curl\CurlHandle') + ->disableOriginalConstructor() + ->setMethods(array('getError', 'getErrorNo', 'getStderr', 'getInfo')) + ->getMock(); + + $this->handle->expects($this->any()) + ->method('getError') + ->will($this->returnValue('e')); + + $this->handle->expects($this->any()) + ->method('getErrorNo') + ->will($this->returnValue('123')); + + $this->handle->expects($this->any()) + ->method('getStderr') + ->will($this->returnValue('testing')); + + $this->handle->expects($this->any()) + ->method('getInfo') + ->will($this->returnValueMap(array( + array(CURLINFO_CONNECT_TIME, '123'), + array(CURLINFO_TOTAL_TIME, '456') + ))); + } + + public function logProvider() + { + return array( + // Uses the cache for the second time + array('{method} - {method}', 'POST - POST'), + array('{url}', 'http://foo.com?q=test'), + array('{port}', '80'), + array('{resource}', '/?q=test'), + array('{host}', 'foo.com'), + array('{hostname}', gethostname()), + array('{protocol}/{version}', 'HTTP/1.1'), + array('{code} {phrase}', '200 OK'), + array('{req_header_Foo}', ''), + array('{req_header_X-Foo}', 'bar'), + array('{req_header_Authorization}', 'Baz'), + array('{res_header_foo}', ''), + array('{res_header_X-Test}', 'Abc'), + array('{req_body}', 'Hello'), + array('{res_body}', 'Foo'), + array('{curl_stderr}', 'testing'), + array('{curl_error}', 'e'), + array('{curl_code}', '123'), + array('{connect_time}', '123'), + array('{total_time}', '456') + ); + } + + /** + * @dataProvider logProvider + */ + public function testFormatsMessages($template, $output) + { + $formatter = new MessageFormatter($template); + $this->assertEquals($output, $formatter->format($this->request, $this->response, $this->handle)); + } + + public function testFormatsRequestsAndResponses() + { + $formatter = new MessageFormatter(); + $formatter->setTemplate('{request}{response}'); + $this->assertEquals($this->request . $this->response, $formatter->format($this->request, $this->response)); + } + + public function testAddsTimestamp() + { + $formatter = new MessageFormatter('{ts}'); + $this->assertNotEmpty($formatter->format($this->request, $this->response)); + } + + public function testUsesResponseWhenNoHandleAndGettingCurlInformation() + { + $formatter = new MessageFormatter('{connect_time}/{total_time}'); + $response = $this->getMockBuilder('Guzzle\Http\Message\Response') + ->setConstructorArgs(array(200)) + ->setMethods(array('getInfo')) + ->getMock(); + $response->expects($this->exactly(2)) + ->method('getInfo') + ->will($this->returnValueMap(array( + array('connect_time', '1'), + array('total_time', '2'), + ))); + $this->assertEquals('1/2', $formatter->format($this->request, $response)); + } + + public function testUsesEmptyStringWhenNoHandleAndNoResponse() + { + $formatter = new MessageFormatter('{connect_time}/{total_time}'); + $this->assertEquals('/', $formatter->format($this->request)); + } + + public function testInjectsTotalTime() + { + $out = ''; + $formatter = new MessageFormatter('{connect_time}/{total_time}'); + $adapter = new ClosureLogAdapter(function ($m) use (&$out) { $out .= $m; }); + $log = new LogPlugin($adapter, $formatter); + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nHI"); + $client = new Client($this->getServer()->getUrl()); + $client->addSubscriber($log); + $client->get('/')->send(); + $this->assertNotEquals('/', $out); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Log/PsrLogAdapterTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Log/PsrLogAdapterTest.php new file mode 100644 index 000000000..7b72dd6a0 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Log/PsrLogAdapterTest.php @@ -0,0 +1,25 @@ +pushHandler($handler); + $adapter = new PsrLogAdapter($log); + $adapter->log('test!', LOG_INFO); + $this->assertTrue($handler->hasInfoRecords()); + $this->assertSame($log, $adapter->getLogObject()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Log/Zf2LogAdapterTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Log/Zf2LogAdapterTest.php new file mode 100644 index 000000000..1b6128365 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Log/Zf2LogAdapterTest.php @@ -0,0 +1,51 @@ +stream = fopen('php://temp', 'r+'); + $this->log = new Logger(); + $this->log->addWriter(new Stream($this->stream)); + $this->adapter = new Zf2LogAdapter($this->log); + + } + + public function testLogsMessagesToAdaptedObject() + { + // Test without a priority + $this->adapter->log('Zend_Test!', \LOG_NOTICE); + rewind($this->stream); + $contents = stream_get_contents($this->stream); + $this->assertEquals(1, substr_count($contents, 'Zend_Test!')); + + // Test with a priority + $this->adapter->log('Zend_Test!', \LOG_ALERT); + rewind($this->stream); + $contents = stream_get_contents($this->stream); + $this->assertEquals(2, substr_count($contents, 'Zend_Test!')); + } + + public function testExposesAdaptedLogObject() + { + $this->assertEquals($this->log, $this->adapter->getLogObject()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Mock/CustomResponseModel.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Mock/CustomResponseModel.php new file mode 100644 index 000000000..3fb6527be --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Mock/CustomResponseModel.php @@ -0,0 +1,21 @@ +command = $command; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Mock/ErrorResponseMock.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Mock/ErrorResponseMock.php new file mode 100644 index 000000000..aabb15f9c --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Mock/ErrorResponseMock.php @@ -0,0 +1,25 @@ +command = $command; + $this->response = $response; + $this->message = 'Error from ' . $response; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Mock/ExceptionMock.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Mock/ExceptionMock.php new file mode 100644 index 000000000..97a197487 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Mock/ExceptionMock.php @@ -0,0 +1,11 @@ +multiHandle; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Mock/MockObserver.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Mock/MockObserver.php new file mode 100644 index 000000000..11e22eb46 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Mock/MockObserver.php @@ -0,0 +1,65 @@ +events as $event) { + if ($event->getName() == $eventName) { + return true; + } + } + + return false; + } + + public function getLastEvent() + { + return end($this->events); + } + + public function count() + { + return count($this->events); + } + + public function getGrouped() + { + $events = array(); + foreach ($this->events as $event) { + if (!isset($events[$event->getName()])) { + $events[$event->getName()] = array(); + } + $events[$event->getName()][] = $event; + } + + return $events; + } + + public function getData($event, $key, $occurrence = 0) + { + $grouped = $this->getGrouped(); + if (isset($grouped[$event])) { + return $grouped[$event][$occurrence][$key]; + } + + return null; + } + + public function update(Event $event) + { + $this->events[] = $event; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Mock/MockSubject.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Mock/MockSubject.php new file mode 100644 index 000000000..e011959bb --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Mock/MockSubject.php @@ -0,0 +1,7 @@ + 'allseeing-i.com', + 'path' => '/', + 'data' => array( + 'PHPSESSID' => '6c951590e7a9359bcedde25cda73e43c' + ), + 'max_age' => NULL, + 'expires' => 'Sat, 26-Jul-2008 17:00:42 GMT', + 'version' => NULL, + 'secure' => NULL, + 'discard' => NULL, + 'port' => NULL, + 'cookies' => array( + 'ASIHTTPRequestTestCookie' => 'This+is+the+value' + ), + 'comment' => null, + 'comment_url' => null, + 'http_only' => false + ) + ), + array('', false), + array('foo', false), + // Test setting a blank value for a cookie + array(array( + 'foo=', 'foo =', 'foo =;', 'foo= ;', 'foo =', 'foo= '), + array( + 'cookies' => array( + 'foo' => '' + ), + 'data' => array(), + 'discard' => null, + 'domain' => null, + 'expires' => null, + 'max_age' => null, + 'path' => '/', + 'port' => null, + 'secure' => null, + 'version' => null, + 'comment' => null, + 'comment_url' => null, + 'http_only' => false + ) + ), + // Test setting a value and removing quotes + array(array( + 'foo=1', 'foo =1', 'foo =1;', 'foo=1 ;', 'foo =1', 'foo= 1', 'foo = 1 ;', 'foo="1"', 'foo="1";', 'foo= "1";'), + array( + 'cookies' => array( + 'foo' => '1' + ), + 'data' => array(), + 'discard' => null, + 'domain' => null, + 'expires' => null, + 'max_age' => null, + 'path' => '/', + 'port' => null, + 'secure' => null, + 'version' => null, + 'comment' => null, + 'comment_url' => null, + 'http_only' => false + ) + ), + // Test setting multiple values + array(array( + 'foo=1; bar=2;', 'foo =1; bar = "2"', 'foo=1; bar=2'), + array( + 'cookies' => array( + 'foo' => '1', + 'bar' => '2', + ), + 'data' => array(), + 'discard' => null, + 'domain' => null, + 'expires' => null, + 'max_age' => null, + 'path' => '/', + 'port' => null, + 'secure' => null, + 'version' => null, + 'comment' => null, + 'comment_url' => null, + 'http_only' => false + ) + ), + // Tests getting the domain and path from a reference request + array(array( + 'foo=1; port="80,8081"; httponly', 'foo=1; port="80,8081"; domain=www.test.com; HttpOnly;', 'foo=1; ; domain=www.test.com; path=/path; port="80,8081"; HttpOnly;'), + array( + 'cookies' => array( + 'foo' => 1 + ), + 'data' => array(), + 'discard' => null, + 'domain' => 'www.test.com', + 'expires' => null, + 'max_age' => null, + 'path' => '/path', + 'port' => array('80', '8081'), + 'secure' => null, + 'version' => null, + 'comment' => null, + 'comment_url' => null, + 'http_only' => true + ), + 'http://www.test.com/path/' + ), + // Some of the following tests are based on http://framework.zend.com/svn/framework/standard/trunk/tests/Zend/Http/CookieTest.php + array( + 'justacookie=foo; domain=example.com', + array( + 'cookies' => array( + 'justacookie' => 'foo' + ), + 'domain' => 'example.com', + 'data' => array(), + 'discard' => null, + 'expires' => null, + 'max_age' => null, + 'path' => '/', + 'port' => null, + 'secure' => null, + 'version' => null, + 'comment' => null, + 'comment_url' => null, + 'http_only' => false + ) + ), + array( + 'expires=tomorrow; secure; path=/Space Out/; expires=Tue, 21-Nov-2006 08:33:44 GMT; domain=.example.com', + array( + 'cookies' => array( + 'expires' => 'tomorrow' + ), + 'domain' => '.example.com', + 'path' => '/Space Out/', + 'expires' => 'Tue, 21-Nov-2006 08:33:44 GMT', + 'data' => array(), + 'discard' => null, + 'port' => null, + 'secure' => true, + 'version' => null, + 'max_age' => null, + 'comment' => null, + 'comment_url' => null, + 'http_only' => false + ) + ), + array( + 'domain=unittests; expires=Tue, 21-Nov-2006 08:33:44 GMT; domain=example.com; path=/some value/', + array( + 'cookies' => array( + 'domain' => 'unittests' + ), + 'domain' => 'example.com', + 'path' => '/some value/', + 'expires' => 'Tue, 21-Nov-2006 08:33:44 GMT', + 'secure' => false, + 'data' => array(), + 'discard' => null, + 'max_age' => null, + 'port' => null, + 'version' => null, + 'comment' => null, + 'comment_url' => null, + 'http_only' => false + ) + ), + array( + 'path=indexAction; path=/; domain=.foo.com; expires=Tue, 21-Nov-2006 08:33:44 GMT', + array( + 'cookies' => array( + 'path' => 'indexAction' + ), + 'domain' => '.foo.com', + 'path' => '/', + 'expires' => 'Tue, 21-Nov-2006 08:33:44 GMT', + 'secure' => false, + 'data' => array(), + 'discard' => null, + 'max_age' => null, + 'port' => null, + 'version' => null, + 'comment' => null, + 'comment_url' => null, + 'http_only' => false + ) + ), + array( + 'secure=sha1; secure; SECURE; domain=some.really.deep.domain.com; version=1; Max-Age=86400', + array( + 'cookies' => array( + 'secure' => 'sha1' + ), + 'domain' => 'some.really.deep.domain.com', + 'path' => '/', + 'secure' => true, + 'data' => array(), + 'discard' => null, + 'expires' => time() + 86400, + 'max_age' => 86400, + 'port' => null, + 'version' => 1, + 'comment' => null, + 'comment_url' => null, + 'http_only' => false + ) + ), + array( + 'PHPSESSID=123456789+abcd%2Cef; secure; discard; domain=.localdomain; path=/foo/baz; expires=Tue, 21-Nov-2006 08:33:44 GMT;', + array( + 'cookies' => array( + 'PHPSESSID' => '123456789+abcd%2Cef' + ), + 'domain' => '.localdomain', + 'path' => '/foo/baz', + 'expires' => 'Tue, 21-Nov-2006 08:33:44 GMT', + 'secure' => true, + 'data' => array(), + 'discard' => true, + 'max_age' => null, + 'port' => null, + 'version' => null, + 'comment' => null, + 'comment_url' => null, + 'http_only' => false + ) + ), + // rfc6265#section-5.1.4 + array( + 'cookie=value', + array( + 'cookies' => array( + 'cookie' => 'value' + ), + 'domain' => 'example.com', + 'data' => array(), + 'discard' => null, + 'expires' => null, + 'max_age' => null, + 'path' => '/some/path', + 'port' => null, + 'secure' => null, + 'version' => null, + 'comment' => null, + 'comment_url' => null, + 'http_only' => false + ), + 'http://example.com/some/path/test.html' + ), + array( + 'empty=path', + array( + 'cookies' => array( + 'empty' => 'path' + ), + 'domain' => 'example.com', + 'data' => array(), + 'discard' => null, + 'expires' => null, + 'max_age' => null, + 'path' => '/', + 'port' => null, + 'secure' => null, + 'version' => null, + 'comment' => null, + 'comment_url' => null, + 'http_only' => false + ), + 'http://example.com/test.html' + ), + array( + 'baz=qux', + array( + 'cookies' => array( + 'baz' => 'qux' + ), + 'domain' => 'example.com', + 'data' => array(), + 'discard' => null, + 'expires' => null, + 'max_age' => null, + 'path' => '/', + 'port' => null, + 'secure' => null, + 'version' => null, + 'comment' => null, + 'comment_url' => null, + 'http_only' => false + ), + 'http://example.com?query=here' + ), + array( + 'test=noSlashPath; path=someString', + array( + 'cookies' => array( + 'test' => 'noSlashPath' + ), + 'domain' => 'example.com', + 'data' => array(), + 'discard' => null, + 'expires' => null, + 'max_age' => null, + 'path' => '/real/path', + 'port' => null, + 'secure' => null, + 'version' => null, + 'comment' => null, + 'comment_url' => null, + 'http_only' => false + ), + 'http://example.com/real/path/' + ), + ); + } + + /** + * @dataProvider cookieParserDataProvider + */ + public function testParseCookie($cookie, $parsed, $url = null) + { + $c = $this->cookieParserClass; + $parser = new $c(); + + $request = null; + if ($url) { + $url = Url::factory($url); + $host = $url->getHost(); + $path = $url->getPath(); + } else { + $host = ''; + $path = ''; + } + + foreach ((array) $cookie as $c) { + $p = $parser->parseCookie($c, $host, $path); + + // Remove expires values from the assertion if they are relatively equal by allowing a 5 minute difference + if ($p['expires'] != $parsed['expires']) { + if (abs($p['expires'] - $parsed['expires']) < 300) { + unset($p['expires']); + unset($parsed['expires']); + } + } + + if (is_array($parsed)) { + foreach ($parsed as $key => $value) { + $this->assertEquals($parsed[$key], $p[$key], 'Comparing ' . $key . ' ' . var_export($value, true) . ' : ' . var_export($parsed, true) . ' | ' . var_export($p, true)); + } + + foreach ($p as $key => $value) { + $this->assertEquals($p[$key], $parsed[$key], 'Comparing ' . $key . ' ' . var_export($value, true) . ' : ' . var_export($parsed, true) . ' | ' . var_export($p, true)); + } + } else { + $this->assertEquals($parsed, $p); + } + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/Cookie/CookieParserTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/Cookie/CookieParserTest.php new file mode 100644 index 000000000..75d336fa5 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/Cookie/CookieParserTest.php @@ -0,0 +1,22 @@ +parseCookie('foo=baz+bar', null, null, true); + $this->assertEquals(array( + 'foo' => 'baz bar' + ), $result['cookies']); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/Message/MessageParserProvider.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/Message/MessageParserProvider.php new file mode 100644 index 000000000..da58bb465 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/Message/MessageParserProvider.php @@ -0,0 +1,225 @@ + 'GET', + 'protocol' => 'HTTP', + 'version' => '1.1', + 'request_url' => array( + 'scheme' => 'http', + 'host' => '', + 'port' => '', + 'path' => '/', + 'query' => '' + ), + 'headers' => array(), + 'body' => '' + )), + // Path and query string, multiple header values per header and case sensitive storage + array("HEAD /path?query=foo HTTP/1.0\r\nHost: example.com\r\nX-Foo: foo\r\nx-foo: Bar\r\nX-Foo: foo\r\nX-Foo: Baz\r\n\r\n", array( + 'method' => 'HEAD', + 'protocol' => 'HTTP', + 'version' => '1.0', + 'request_url' => array( + 'scheme' => 'http', + 'host' => 'example.com', + 'port' => '', + 'path' => '/path', + 'query' => 'query=foo' + ), + 'headers' => array( + 'Host' => 'example.com', + 'X-Foo' => array('foo', 'foo', 'Baz'), + 'x-foo' => 'Bar' + ), + 'body' => '' + )), + // Includes a body + array("PUT / HTTP/1.0\r\nhost: example.com:443\r\nContent-Length: 4\r\n\r\ntest", array( + 'method' => 'PUT', + 'protocol' => 'HTTP', + 'version' => '1.0', + 'request_url' => array( + 'scheme' => 'https', + 'host' => 'example.com', + 'port' => '443', + 'path' => '/', + 'query' => '' + ), + 'headers' => array( + 'host' => 'example.com:443', + 'Content-Length' => '4' + ), + 'body' => 'test' + )), + // Includes Authorization headers + array("GET / HTTP/1.1\r\nHost: example.com:8080\r\nAuthorization: Basic {$auth}\r\n\r\n", array( + 'method' => 'GET', + 'protocol' => 'HTTP', + 'version' => '1.1', + 'request_url' => array( + 'scheme' => 'http', + 'host' => 'example.com', + 'port' => '8080', + 'path' => '/', + 'query' => '' + ), + 'headers' => array( + 'Host' => 'example.com:8080', + 'Authorization' => "Basic {$auth}" + ), + 'body' => '' + )), + // Include authorization header + array("GET / HTTP/1.1\r\nHost: example.com:8080\r\nauthorization: Basic {$auth}\r\n\r\n", array( + 'method' => 'GET', + 'protocol' => 'HTTP', + 'version' => '1.1', + 'request_url' => array( + 'scheme' => 'http', + 'host' => 'example.com', + 'port' => '8080', + 'path' => '/', + 'query' => '' + ), + 'headers' => array( + 'Host' => 'example.com:8080', + 'authorization' => "Basic {$auth}" + ), + 'body' => '' + )), + ); + } + + public function responseProvider() + { + return array( + // Empty request + array('', false), + + array("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", array( + 'protocol' => 'HTTP', + 'version' => '1.1', + 'code' => '200', + 'reason_phrase' => 'OK', + 'headers' => array( + 'Content-Length' => 0 + ), + 'body' => '' + )), + array("HTTP/1.0 400 Bad Request\r\nContent-Length: 0\r\n\r\n", array( + 'protocol' => 'HTTP', + 'version' => '1.0', + 'code' => '400', + 'reason_phrase' => 'Bad Request', + 'headers' => array( + 'Content-Length' => 0 + ), + 'body' => '' + )), + array("HTTP/1.0 100 Continue\r\n\r\n", array( + 'protocol' => 'HTTP', + 'version' => '1.0', + 'code' => '100', + 'reason_phrase' => 'Continue', + 'headers' => array(), + 'body' => '' + )), + array("HTTP/1.1 204 No Content\r\nX-Foo: foo\r\nx-foo: Bar\r\nX-Foo: foo\r\n\r\n", array( + 'protocol' => 'HTTP', + 'version' => '1.1', + 'code' => '204', + 'reason_phrase' => 'No Content', + 'headers' => array( + 'X-Foo' => array('foo', 'foo'), + 'x-foo' => 'Bar' + ), + 'body' => '' + )), + array("HTTP/1.1 200 Ok that is great!\r\nContent-Length: 4\r\n\r\nTest", array( + 'protocol' => 'HTTP', + 'version' => '1.1', + 'code' => '200', + 'reason_phrase' => 'Ok that is great!', + 'headers' => array( + 'Content-Length' => 4 + ), + 'body' => 'Test' + )), + ); + } + + public function compareRequestResults($result, $expected) + { + if (!$result) { + $this->assertFalse($expected); + return; + } + + $this->assertEquals($result['method'], $expected['method']); + $this->assertEquals($result['protocol'], $expected['protocol']); + $this->assertEquals($result['version'], $expected['version']); + $this->assertEquals($result['request_url'], $expected['request_url']); + $this->assertEquals($result['body'], $expected['body']); + $this->compareHttpHeaders($result['headers'], $expected['headers']); + } + + public function compareResponseResults($result, $expected) + { + if (!$result) { + $this->assertFalse($expected); + return; + } + + $this->assertEquals($result['protocol'], $expected['protocol']); + $this->assertEquals($result['version'], $expected['version']); + $this->assertEquals($result['code'], $expected['code']); + $this->assertEquals($result['reason_phrase'], $expected['reason_phrase']); + $this->assertEquals($result['body'], $expected['body']); + $this->compareHttpHeaders($result['headers'], $expected['headers']); + } + + protected function normalizeHeaders($headers) + { + $normalized = array(); + foreach ($headers as $key => $value) { + $key = strtolower($key); + if (!isset($normalized[$key])) { + $normalized[$key] = $value; + } elseif (!is_array($normalized[$key])) { + $normalized[$key] = array($value); + } else { + $normalized[$key][] = $value; + } + } + + foreach ($normalized as $key => &$value) { + if (is_array($value)) { + sort($value); + } + } + + return $normalized; + } + + public function compareHttpHeaders($result, $expected) + { + // Aggregate all headers case-insensitively + $result = $this->normalizeHeaders($result); + $expected = $this->normalizeHeaders($expected); + $this->assertEquals($result, $expected); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/Message/MessageParserTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/Message/MessageParserTest.php new file mode 100644 index 000000000..2f5222893 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/Message/MessageParserTest.php @@ -0,0 +1,58 @@ +compareRequestResults($parts, $parser->parseRequest($message)); + } + + /** + * @dataProvider responseProvider + */ + public function testParsesResponses($message, $parts) + { + $parser = new MessageParser(); + $this->compareResponseResults($parts, $parser->parseResponse($message)); + } + + public function testParsesRequestsWithMissingProtocol() + { + $parser = new MessageParser(); + $parts = $parser->parseRequest("GET /\r\nHost: Foo.com\r\n\r\n"); + $this->assertEquals('GET', $parts['method']); + $this->assertEquals('HTTP', $parts['protocol']); + $this->assertEquals('1.1', $parts['version']); + } + + public function testParsesRequestsWithMissingVersion() + { + $parser = new MessageParser(); + $parts = $parser->parseRequest("GET / HTTP\r\nHost: Foo.com\r\n\r\n"); + $this->assertEquals('GET', $parts['method']); + $this->assertEquals('HTTP', $parts['protocol']); + $this->assertEquals('1.1', $parts['version']); + } + + public function testParsesResponsesWithMissingReasonPhrase() + { + $parser = new MessageParser(); + $parts = $parser->parseResponse("HTTP/1.1 200\r\n\r\n"); + $this->assertEquals('200', $parts['code']); + $this->assertEquals('', $parts['reason_phrase']); + $this->assertEquals('HTTP', $parts['protocol']); + $this->assertEquals('1.1', $parts['version']); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/Message/PeclHttpMessageParserTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/Message/PeclHttpMessageParserTest.php new file mode 100644 index 000000000..6706e2063 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/Message/PeclHttpMessageParserTest.php @@ -0,0 +1,36 @@ +markTestSkipped('pecl_http is not available.'); + } + } + + /** + * @dataProvider requestProvider + */ + public function testParsesRequests($message, $parts) + { + $parser = new PeclHttpMessageParser(); + $this->compareRequestResults($parts, $parser->parseRequest($message)); + } + + /** + * @dataProvider responseProvider + */ + public function testParsesResponses($message, $parts) + { + $parser = new PeclHttpMessageParser(); + $this->compareResponseResults($parts, $parser->parseResponse($message)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/ParserRegistryTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/ParserRegistryTest.php new file mode 100644 index 000000000..7675efb96 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/ParserRegistryTest.php @@ -0,0 +1,33 @@ +registerParser('foo', $c); + $this->assertSame($c, $r->getParser('foo')); + } + + public function testReturnsNullWhenNotFound() + { + $r = new ParserRegistry(); + $this->assertNull($r->getParser('FOO')); + } + + public function testReturnsLazyLoadedDefault() + { + $r = new ParserRegistry(); + $c = $r->getParser('cookie'); + $this->assertInstanceOf('Guzzle\Parser\Cookie\CookieParser', $c); + $this->assertSame($c, $r->getParser('cookie')); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/UriTemplate/AbstractUriTemplateTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/UriTemplate/AbstractUriTemplateTest.php new file mode 100644 index 000000000..a05fc2e4d --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/UriTemplate/AbstractUriTemplateTest.php @@ -0,0 +1,113 @@ + 'value', + 'hello' => 'Hello World!', + 'empty' => '', + 'path' => '/foo/bar', + 'x' => '1024', + 'y' => '768', + 'null' => null, + 'list' => array('red', 'green', 'blue'), + 'keys' => array( + "semi" => ';', + "dot" => '.', + "comma" => ',' + ), + 'empty_keys' => array(), + ); + + return array_map(function($t) use ($params) { + $t[] = $params; + return $t; + }, array( + array('foo', 'foo'), + array('{var}', 'value'), + array('{hello}', 'Hello%20World%21'), + array('{+var}', 'value'), + array('{+hello}', 'Hello%20World!'), + array('{+path}/here', '/foo/bar/here'), + array('here?ref={+path}', 'here?ref=/foo/bar'), + array('X{#var}', 'X#value'), + array('X{#hello}', 'X#Hello%20World!'), + array('map?{x,y}', 'map?1024,768'), + array('{x,hello,y}', '1024,Hello%20World%21,768'), + array('{+x,hello,y}', '1024,Hello%20World!,768'), + array('{+path,x}/here', '/foo/bar,1024/here'), + array('{#x,hello,y}', '#1024,Hello%20World!,768'), + array('{#path,x}/here', '#/foo/bar,1024/here'), + array('X{.var}', 'X.value'), + array('X{.x,y}', 'X.1024.768'), + array('{/var}', '/value'), + array('{/var,x}/here', '/value/1024/here'), + array('{;x,y}', ';x=1024;y=768'), + array('{;x,y,empty}', ';x=1024;y=768;empty'), + array('{?x,y}', '?x=1024&y=768'), + array('{?x,y,empty}', '?x=1024&y=768&empty='), + array('?fixed=yes{&x}', '?fixed=yes&x=1024'), + array('{&x,y,empty}', '&x=1024&y=768&empty='), + array('{var:3}', 'val'), + array('{var:30}', 'value'), + array('{list}', 'red,green,blue'), + array('{list*}', 'red,green,blue'), + array('{keys}', 'semi,%3B,dot,.,comma,%2C'), + array('{keys*}', 'semi=%3B,dot=.,comma=%2C'), + array('{+path:6}/here', '/foo/b/here'), + array('{+list}', 'red,green,blue'), + array('{+list*}', 'red,green,blue'), + array('{+keys}', 'semi,;,dot,.,comma,,'), + array('{+keys*}', 'semi=;,dot=.,comma=,'), + array('{#path:6}/here', '#/foo/b/here'), + array('{#list}', '#red,green,blue'), + array('{#list*}', '#red,green,blue'), + array('{#keys}', '#semi,;,dot,.,comma,,'), + array('{#keys*}', '#semi=;,dot=.,comma=,'), + array('X{.var:3}', 'X.val'), + array('X{.list}', 'X.red,green,blue'), + array('X{.list*}', 'X.red.green.blue'), + array('X{.keys}', 'X.semi,%3B,dot,.,comma,%2C'), + array('X{.keys*}', 'X.semi=%3B.dot=..comma=%2C'), + array('{/var:1,var}', '/v/value'), + array('{/list}', '/red,green,blue'), + array('{/list*}', '/red/green/blue'), + array('{/list*,path:4}', '/red/green/blue/%2Ffoo'), + array('{/keys}', '/semi,%3B,dot,.,comma,%2C'), + array('{/keys*}', '/semi=%3B/dot=./comma=%2C'), + array('{;hello:5}', ';hello=Hello'), + array('{;list}', ';list=red,green,blue'), + array('{;list*}', ';list=red;list=green;list=blue'), + array('{;keys}', ';keys=semi,%3B,dot,.,comma,%2C'), + array('{;keys*}', ';semi=%3B;dot=.;comma=%2C'), + array('{?var:3}', '?var=val'), + array('{?list}', '?list=red,green,blue'), + array('{?list*}', '?list=red&list=green&list=blue'), + array('{?keys}', '?keys=semi,%3B,dot,.,comma,%2C'), + array('{?keys*}', '?semi=%3B&dot=.&comma=%2C'), + array('{&var:3}', '&var=val'), + array('{&list}', '&list=red,green,blue'), + array('{&list*}', '&list=red&list=green&list=blue'), + array('{&keys}', '&keys=semi,%3B,dot,.,comma,%2C'), + array('{&keys*}', '&semi=%3B&dot=.&comma=%2C'), + array('{.null}', ''), + array('{.null,var}', '.value'), + array('X{.empty_keys*}', 'X'), + array('X{.empty_keys}', 'X'), + // Test that missing expansions are skipped + array('test{&missing*}', 'test'), + // Test that multiple expansions can be set + array('http://{var}/{var:2}{?keys*}', 'http://value/va?semi=%3B&dot=.&comma=%2C'), + // Test more complex query string stuff + array('http://www.test.com{+path}{?var,keys*}', 'http://www.test.com/foo/bar?var=value&semi=%3B&dot=.&comma=%2C') + )); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/UriTemplate/PeclUriTemplateTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/UriTemplate/PeclUriTemplateTest.php new file mode 100644 index 000000000..633c5d539 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/UriTemplate/PeclUriTemplateTest.php @@ -0,0 +1,27 @@ +markTestSkipped('uri_template PECL extension must be installed to test PeclUriTemplate'); + } + } + + /** + * @dataProvider templateProvider + */ + public function testExpandsUriTemplates($template, $expansion, $params) + { + $uri = new PeclUriTemplate($template); + $this->assertEquals($expansion, $uri->expand($template, $params)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/UriTemplate/UriTemplateTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/UriTemplate/UriTemplateTest.php new file mode 100644 index 000000000..5130d6f4b --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Parser/UriTemplate/UriTemplateTest.php @@ -0,0 +1,106 @@ +assertEquals($expansion, $uri->expand($template, $params)); + } + + public function expressionProvider() + { + return array( + array( + '{+var*}', array( + 'operator' => '+', + 'values' => array( + array('value' => 'var', 'modifier' => '*') + ) + ), + ), + array( + '{?keys,var,val}', array( + 'operator' => '?', + 'values' => array( + array('value' => 'keys', 'modifier' => ''), + array('value' => 'var', 'modifier' => ''), + array('value' => 'val', 'modifier' => '') + ) + ), + ), + array( + '{+x,hello,y}', array( + 'operator' => '+', + 'values' => array( + array('value' => 'x', 'modifier' => ''), + array('value' => 'hello', 'modifier' => ''), + array('value' => 'y', 'modifier' => '') + ) + ) + ) + ); + } + + /** + * @dataProvider expressionProvider + */ + public function testParsesExpressions($exp, $data) + { + $template = new UriTemplate($exp); + + // Access the config object + $class = new \ReflectionClass($template); + $method = $class->getMethod('parseExpression'); + $method->setAccessible(true); + + $exp = substr($exp, 1, -1); + $this->assertEquals($data, $method->invokeArgs($template, array($exp))); + } + + /** + * @ticket https://github.com/guzzle/guzzle/issues/90 + */ + public function testAllowsNestedArrayExpansion() + { + $template = new UriTemplate(); + + $result = $template->expand('http://example.com{+path}{/segments}{?query,data*,foo*}', array( + 'path' => '/foo/bar', + 'segments' => array('one', 'two'), + 'query' => 'test', + 'data' => array( + 'more' => array('fun', 'ice cream') + ), + 'foo' => array( + 'baz' => array( + 'bar' => 'fizz', + 'test' => 'buzz' + ), + 'bam' => 'boo' + ) + )); + + $this->assertEquals('http://example.com/foo/bar/one,two?query=test&more%5B0%5D=fun&more%5B1%5D=ice%20cream&baz%5Bbar%5D=fizz&baz%5Btest%5D=buzz&bam=boo', $result); + } + + /** + * @ticket https://github.com/guzzle/guzzle/issues/426 + */ + public function testSetRegex() + { + $template = new UriTemplate(); + $template->setRegex('/\<\$(.+)\>/'); + $this->assertSame('/foo', $template->expand('/<$a>', array('a' => 'foo'))); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Async/AsyncPluginTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Async/AsyncPluginTest.php new file mode 100644 index 000000000..16990a5a8 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Async/AsyncPluginTest.php @@ -0,0 +1,93 @@ +assertArrayHasKey('request.before_send', $events); + $this->assertArrayHasKey('request.exception', $events); + $this->assertArrayHasKey('curl.callback.progress', $events); + } + + public function testEnablesProgressCallbacks() + { + $p = new AsyncPlugin(); + $request = RequestFactory::getInstance()->create('PUT', 'http://www.example.com'); + $event = new Event(array( + 'request' => $request + )); + $p->onBeforeSend($event); + $this->assertEquals(true, $request->getCurlOptions()->get('progress')); + } + + public function testAddsTimesOutAfterSending() + { + $p = new AsyncPlugin(); + $request = RequestFactory::getInstance()->create('PUT', 'http://www.example.com'); + $handle = CurlHandle::factory($request); + $event = new Event(array( + 'request' => $request, + 'handle' => $handle->getHandle(), + 'uploaded' => 10, + 'upload_size' => 10, + 'downloaded' => 0 + )); + $p->onCurlProgress($event); + } + + public function testEnsuresRequestIsSet() + { + $p = new AsyncPlugin(); + $event = new Event(array( + 'uploaded' => 10, + 'upload_size' => 10, + 'downloaded' => 0 + )); + $p->onCurlProgress($event); + } + + public function testMasksCurlExceptions() + { + $p = new AsyncPlugin(); + $request = RequestFactory::getInstance()->create('PUT', 'http://www.example.com'); + $e = new CurlException('Error'); + $event = new Event(array( + 'request' => $request, + 'exception' => $e + )); + $p->onRequestTimeout($event); + $this->assertEquals(RequestInterface::STATE_COMPLETE, $request->getState()); + $this->assertEquals(200, $request->getResponse()->getStatusCode()); + $this->assertTrue($request->getResponse()->hasHeader('X-Guzzle-Async')); + } + + public function testEnsuresIntegration() + { + $this->getServer()->flush(); + $this->getServer()->enqueue("HTTP/1.1 204 FOO\r\nContent-Length: 4\r\n\r\ntest"); + $client = new Client($this->getServer()->getUrl()); + $request = $client->post('/', null, array( + 'foo' => 'bar' + )); + $request->getEventDispatcher()->addSubscriber(new AsyncPlugin()); + $request->send(); + $this->assertEquals('', $request->getResponse()->getBody(true)); + $this->assertTrue($request->getResponse()->hasHeader('X-Guzzle-Async')); + $received = $this->getServer()->getReceivedRequests(true); + $this->assertEquals('POST', $received[0]->getMethod()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/AbstractBackoffStrategyTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/AbstractBackoffStrategyTest.php new file mode 100644 index 000000000..72af26308 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/AbstractBackoffStrategyTest.php @@ -0,0 +1,86 @@ +getMockBuilder('Guzzle\Plugin\Backoff\AbstractBackoffStrategy') + ->setMethods(array('getDelay', 'makesDecision')) + ->getMockForAbstractClass(); + } + + public function testReturnsZeroWhenNoNextAndGotNull() + { + $request = new Request('GET', 'http://www.foo.com'); + $mock = $this->getMockStrategy(); + $mock->expects($this->atLeastOnce())->method('getDelay')->will($this->returnValue(null)); + $this->assertEquals(0, $mock->getBackoffPeriod(0, $request)); + } + + public function testReturnsFalse() + { + $request = new Request('GET', 'http://www.foo.com'); + $mock = $this->getMockStrategy(); + $mock->expects($this->atLeastOnce())->method('getDelay')->will($this->returnValue(false)); + $this->assertEquals(false, $mock->getBackoffPeriod(0, $request)); + } + + public function testReturnsNextValueWhenNullOrTrue() + { + $request = new Request('GET', 'http://www.foo.com'); + $mock = $this->getMockStrategy(); + $mock->expects($this->atLeastOnce())->method('getDelay')->will($this->returnValue(null)); + $mock->expects($this->any())->method('makesDecision')->will($this->returnValue(false)); + + $mock2 = $this->getMockStrategy(); + $mock2->expects($this->atLeastOnce())->method('getDelay')->will($this->returnValue(10)); + $mock2->expects($this->atLeastOnce())->method('makesDecision')->will($this->returnValue(true)); + $mock->setNext($mock2); + + $this->assertEquals(10, $mock->getBackoffPeriod(0, $request)); + } + + public function testReturnsFalseWhenNullAndNoNext() + { + $request = new Request('GET', 'http://www.foo.com'); + $s = new TruncatedBackoffStrategy(2); + $this->assertFalse($s->getBackoffPeriod(0, $request)); + } + + public function testHasNext() + { + $a = new TruncatedBackoffStrategy(2); + $b = new TruncatedBackoffStrategy(2); + $a->setNext($b); + $this->assertSame($b, $a->getNext()); + } + + public function testSkipsOtherDecisionsInChainWhenOneReturnsTrue() + { + $a = new CallbackBackoffStrategy(function () { return null; }, true); + $b = new CallbackBackoffStrategy(function () { return true; }, true); + $c = new CallbackBackoffStrategy(function () { return null; }, true); + $d = new CallbackBackoffStrategy(function () { return 10; }, false); + $a->setNext($b); + $b->setNext($c); + $c->setNext($d); + $this->assertEquals(10, $a->getBackoffPeriod(2, new Request('GET', 'http://www.foo.com'))); + } + + public function testReturnsZeroWhenDecisionMakerReturnsTrueButNoFurtherStrategiesAreInTheChain() + { + $a = new CallbackBackoffStrategy(function () { return null; }, true); + $b = new CallbackBackoffStrategy(function () { return true; }, true); + $a->setNext($b); + $this->assertSame(0, $a->getBackoffPeriod(2, new Request('GET', 'http://www.foo.com'))); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/BackoffLoggerTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/BackoffLoggerTest.php new file mode 100644 index 000000000..a64dd826e --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/BackoffLoggerTest.php @@ -0,0 +1,110 @@ +message = ''; + } + + public function testHasEventList() + { + $this->assertEquals(1, count(BackoffLogger::getSubscribedEvents())); + } + + public function testLogsEvents() + { + list($logPlugin, $request, $response) = $this->getMocks(); + + $response = $this->getMockBuilder('Guzzle\Http\Message\Response') + ->setConstructorArgs(array(503)) + ->setMethods(array('getInfo')) + ->getMock(); + + $response->expects($this->any()) + ->method('getInfo') + ->will($this->returnValue(2)); + + $handle = $this->getMockHandle(); + + $event = new Event(array( + 'request' => $request, + 'response' => $response, + 'retries' => 1, + 'delay' => 3, + 'handle' => $handle + )); + + $logPlugin->onRequestRetry($event); + $this->assertContains( + '] PUT http://www.example.com - 503 Service Unavailable - Retries: 1, Delay: 3, Time: 2, 2, cURL: 30 Foo', + $this->message + ); + } + + public function testCanSetTemplate() + { + $l = new BackoffLogger(new ClosureLogAdapter(function () {})); + $l->setTemplate('foo'); + $t = $this->readAttribute($l, 'formatter'); + $this->assertEquals('foo', $this->readAttribute($t, 'template')); + } + + /** + * @return array + */ + protected function getMocks() + { + $that = $this; + $logger = new ClosureLogAdapter(function ($message) use ($that) { + $that->message .= $message . "\n"; + }); + $logPlugin = new BackoffLogger($logger); + $response = new Response(503); + $request = RequestFactory::getInstance()->create('PUT', 'http://www.example.com', array( + 'Content-Length' => 3, + 'Foo' => 'Bar' + )); + + return array($logPlugin, $request, $response); + } + + /** + * @return CurlHandle + */ + protected function getMockHandle() + { + $handle = $this->getMockBuilder('Guzzle\Http\Curl\CurlHandle') + ->disableOriginalConstructor() + ->setMethods(array('getError', 'getErrorNo', 'getInfo')) + ->getMock(); + + $handle->expects($this->once()) + ->method('getError') + ->will($this->returnValue('Foo')); + + $handle->expects($this->once()) + ->method('getErrorNo') + ->will($this->returnValue(30)); + + $handle->expects($this->any()) + ->method('getInfo') + ->will($this->returnValue(2)); + + return $handle; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/BackoffPluginTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/BackoffPluginTest.php new file mode 100644 index 000000000..496e49eb2 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/BackoffPluginTest.php @@ -0,0 +1,297 @@ +retried = false; + } + + public static function getSubscribedEvents() + { + return array(BackoffPlugin::RETRY_EVENT => 'onRequestRetry'); + } + + public function onRequestRetry(Event $event) + { + $this->retried = $event; + } + + public function testHasEventList() + { + $this->assertEquals(1, count(BackoffPlugin::getAllEvents())); + } + + public function testCreatesDefaultExponentialBackoffPlugin() + { + $plugin = BackoffPlugin::getExponentialBackoff(3, array(204), array(10)); + $this->assertInstanceOf('Guzzle\Plugin\Backoff\BackoffPlugin', $plugin); + $strategy = $this->readAttribute($plugin, 'strategy'); + $this->assertInstanceOf('Guzzle\Plugin\Backoff\TruncatedBackoffStrategy', $strategy); + $this->assertEquals(3, $this->readAttribute($strategy, 'max')); + $strategy = $this->readAttribute($strategy, 'next'); + $this->assertInstanceOf('Guzzle\Plugin\Backoff\HttpBackoffStrategy', $strategy); + $this->assertEquals(array(204 => true), $this->readAttribute($strategy, 'errorCodes')); + $strategy = $this->readAttribute($strategy, 'next'); + $this->assertInstanceOf('Guzzle\Plugin\Backoff\CurlBackoffStrategy', $strategy); + $this->assertEquals(array(10 => true), $this->readAttribute($strategy, 'errorCodes')); + $strategy = $this->readAttribute($strategy, 'next'); + $this->assertInstanceOf('Guzzle\Plugin\Backoff\ExponentialBackoffStrategy', $strategy); + } + + public function testDoesNotRetryUnlessStrategyReturnsNumber() + { + $request = new Request('GET', 'http://www.example.com'); + $request->setState('transfer'); + + $mock = $this->getMockBuilder('Guzzle\Plugin\Backoff\BackoffStrategyInterface') + ->setMethods(array('getBackoffPeriod')) + ->getMockForAbstractClass(); + + $mock->expects($this->once()) + ->method('getBackoffPeriod') + ->will($this->returnValue(false)); + + $plugin = new BackoffPlugin($mock); + $plugin->addSubscriber($this); + $plugin->onRequestSent(new Event(array('request' => $request))); + $this->assertFalse($this->retried); + } + + public function testUpdatesRequestForRetry() + { + $request = new Request('GET', 'http://www.example.com'); + $request->setState('transfer'); + $response = new Response(500); + $handle = $this->getMockBuilder('Guzzle\Http\Curl\CurlHandle')->disableOriginalConstructor()->getMock(); + $e = new CurlException(); + $e->setCurlHandle($handle); + + $plugin = new BackoffPlugin(new ConstantBackoffStrategy(10)); + $plugin->addSubscriber($this); + + $event = new Event(array( + 'request' => $request, + 'response' => $response, + 'exception' => $e + )); + + $plugin->onRequestSent($event); + $this->assertEquals(array( + 'request' => $request, + 'response' => $response, + 'handle' => $handle, + 'retries' => 1, + 'delay' => 10 + ), $this->readAttribute($this->retried, 'context')); + + $plugin->onRequestSent($event); + $this->assertEquals(array( + 'request' => $request, + 'response' => $response, + 'handle' => $handle, + 'retries' => 2, + 'delay' => 10 + ), $this->readAttribute($this->retried, 'context')); + } + + public function testDoesNothingWhenNotRetryingAndPollingRequest() + { + $request = new Request('GET', 'http://www.foo.com'); + $plugin = new BackoffPlugin(new ConstantBackoffStrategy(10)); + $plugin->onRequestPoll(new Event(array('request' => $request))); + } + + public function testRetriesRequests() + { + // Create a script to return several 500 and 503 response codes + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndata" + )); + + $plugin = new BackoffPlugin( + new TruncatedBackoffStrategy(3, + new HttpBackoffStrategy(null, + new CurlBackoffStrategy(null, + new ConstantBackoffStrategy(0.05) + ) + ) + ) + ); + + $client = new Client($this->getServer()->getUrl()); + $client->getEventDispatcher()->addSubscriber($plugin); + $request = $client->get(); + $request->send(); + + // Make sure it eventually completed successfully + $this->assertEquals(200, $request->getResponse()->getStatusCode()); + $this->assertEquals('data', $request->getResponse()->getBody(true)); + + // Check that three requests were made to retry this request + $this->assertEquals(3, count($this->getServer()->getReceivedRequests(false))); + $this->assertEquals(2, $request->getParams()->get(BackoffPlugin::RETRY_PARAM)); + } + + /** + * @expectedException \Guzzle\Http\Exception\ServerErrorResponseException + */ + public function testFailsOnTruncation() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n" + )); + + $plugin = new BackoffPlugin( + new TruncatedBackoffStrategy(2, + new HttpBackoffStrategy(null, + new ConstantBackoffStrategy(0.05) + ) + ) + ); + + $client = new Client($this->getServer()->getUrl()); + $client->addSubscriber($plugin); + $client->get()->send(); + } + + public function testRetriesRequestsWhenInParallel() + { + // Create a script to return several 500 and 503 response codes + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndata", + "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndata", + "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndata", + "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndata", + "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndata" + )); + + $plugin = new BackoffPlugin( + new HttpBackoffStrategy(null, + new TruncatedBackoffStrategy(3, + new CurlBackoffStrategy(null, + new ConstantBackoffStrategy(0.1) + ) + ) + ) + ); + $client = new Client($this->getServer()->getUrl()); + $client->getEventDispatcher()->addSubscriber($plugin); + $requests = array(); + for ($i = 0; $i < 5; $i++) { + $requests[] = $client->get(); + } + $client->send($requests); + + $this->assertEquals(15, count($this->getServer()->getReceivedRequests(false))); + } + + /** + * @covers Guzzle\Plugin\Backoff\BackoffPlugin + * @covers Guzzle\Http\Curl\CurlMulti + */ + public function testRetriesPooledRequestsUsingDelayAndPollingEvent() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n", + "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndata" + )); + // Need to sleep for some time ensure that the polling works correctly in the observer + $plugin = new BackoffPlugin(new HttpBackoffStrategy(null, + new TruncatedBackoffStrategy(1, + new ConstantBackoffStrategy(0.5)))); + + $client = new Client($this->getServer()->getUrl()); + $client->getEventDispatcher()->addSubscriber($plugin); + $request = $client->get(); + $request->send(); + // Make sure it eventually completed successfully + $this->assertEquals('data', $request->getResponse()->getBody(true)); + // Check that two requests were made to retry this request + $this->assertEquals(2, count($this->getServer()->getReceivedRequests(false))); + } + + public function testSeeksToBeginningOfRequestBodyWhenRetrying() + { + // Create a request with a body + $request = new EntityEnclosingRequest('PUT', 'http://www.example.com'); + $request->setBody('abc'); + // Set the retry time to be something that will be retried always + $request->getParams()->set(BackoffPlugin::DELAY_PARAM, 2); + // Seek to the end of the stream + $request->getBody()->seek(3); + $this->assertEquals('', $request->getBody()->read(1)); + // Create a plugin that does not delay when retrying + $plugin = new BackoffPlugin(new ConstantBackoffStrategy(0)); + $plugin->onRequestPoll($this->getMockEvent($request)); + // Ensure that the stream was seeked to 0 + $this->assertEquals('a', $request->getBody()->read(1)); + } + + public function testDoesNotSeekOnRequestsWithNoBodyWhenRetrying() + { + // Create a request with a body + $request = new EntityEnclosingRequest('PUT', 'http://www.example.com'); + $request->getParams()->set(BackoffPlugin::DELAY_PARAM, 2); + $plugin = new BackoffPlugin(new ConstantBackoffStrategy(0)); + $plugin->onRequestPoll($this->getMockEvent($request)); + } + + protected function getMockEvent(RequestInterface $request) + { + // Create a mock curl multi object + $multi = $this->getMockBuilder('Guzzle\Http\Curl\CurlMulti') + ->setMethods(array('remove', 'add')) + ->getMock(); + + // Create an event that is expected for the Poll event + $event = new Event(array( + 'request' => $request, + 'curl_multi' => $multi + )); + $event->setName(CurlMultiInterface::POLLING_REQUEST); + + return $event; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/CallbackBackoffStrategyTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/CallbackBackoffStrategyTest.php new file mode 100644 index 000000000..c0ce10d5c --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/CallbackBackoffStrategyTest.php @@ -0,0 +1,31 @@ +getMock('Guzzle\Http\Message\Request', array(), array(), '', false); + $strategy = new CallbackBackoffStrategy(function () { return 10; }, true); + $this->assertTrue($strategy->makesDecision()); + $this->assertEquals(10, $strategy->getBackoffPeriod(0, $request)); + // Ensure it chains correctly when null is returned + $strategy = new CallbackBackoffStrategy(function () { return null; }, false); + $this->assertFalse($strategy->makesDecision()); + $this->assertFalse($strategy->getBackoffPeriod(0, $request)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/ConstantBackoffStrategyTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/ConstantBackoffStrategyTest.php new file mode 100644 index 000000000..703eb4a22 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/ConstantBackoffStrategyTest.php @@ -0,0 +1,20 @@ +assertFalse($strategy->makesDecision()); + $request = $this->getMock('Guzzle\Http\Message\Request', array(), array(), '', false); + $this->assertEquals(3.5, $strategy->getBackoffPeriod(0, $request)); + $this->assertEquals(3.5, $strategy->getBackoffPeriod(1, $request)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/CurlBackoffStrategyTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/CurlBackoffStrategyTest.php new file mode 100644 index 000000000..0a5c3e28d --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/CurlBackoffStrategyTest.php @@ -0,0 +1,36 @@ +assertNotEmpty(CurlBackoffStrategy::getDefaultFailureCodes()); + $strategy = new CurlBackoffStrategy(); + $this->assertTrue($strategy->makesDecision()); + $request = $this->getMock('Guzzle\Http\Message\Request', array(), array(), '', false); + $e = new CurlException(); + $e->setError('foo', CURLE_BAD_CALLING_ORDER); + $this->assertEquals(false, $strategy->getBackoffPeriod(0, $request, null, $e)); + + foreach (CurlBackoffStrategy::getDefaultFailureCodes() as $code) { + $this->assertEquals(0, $strategy->getBackoffPeriod(0, $request, null, $e->setError('foo', $code))); + } + } + + public function testIgnoresNonErrors() + { + $strategy = new CurlBackoffStrategy(); + $request = $this->getMock('Guzzle\Http\Message\Request', array(), array(), '', false); + $this->assertEquals(false, $strategy->getBackoffPeriod(0, $request, new Response(200))); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/ExponentialBackoffStrategyTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/ExponentialBackoffStrategyTest.php new file mode 100644 index 000000000..09965bcbf --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/ExponentialBackoffStrategyTest.php @@ -0,0 +1,23 @@ +assertFalse($strategy->makesDecision()); + $request = $this->getMock('Guzzle\Http\Message\Request', array(), array(), '', false); + $this->assertEquals(1, $strategy->getBackoffPeriod(0, $request)); + $this->assertEquals(2, $strategy->getBackoffPeriod(1, $request)); + $this->assertEquals(4, $strategy->getBackoffPeriod(2, $request)); + $this->assertEquals(8, $strategy->getBackoffPeriod(3, $request)); + $this->assertEquals(16, $strategy->getBackoffPeriod(4, $request)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/HttpBackoffStrategyTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/HttpBackoffStrategyTest.php new file mode 100644 index 000000000..ae68a4eb8 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/HttpBackoffStrategyTest.php @@ -0,0 +1,47 @@ +assertNotEmpty(HttpBackoffStrategy::getDefaultFailureCodes()); + $strategy = new HttpBackoffStrategy(); + $this->assertTrue($strategy->makesDecision()); + $request = $this->getMock('Guzzle\Http\Message\Request', array(), array(), '', false); + + $response = new Response(200); + $this->assertEquals(false, $strategy->getBackoffPeriod(0, $request, $response)); + $response->setStatus(400); + $this->assertEquals(false, $strategy->getBackoffPeriod(0, $request, $response)); + + foreach (HttpBackoffStrategy::getDefaultFailureCodes() as $code) { + $this->assertEquals(0, $strategy->getBackoffPeriod(0, $request, $response->setStatus($code))); + } + } + + public function testAllowsCustomCodes() + { + $strategy = new HttpBackoffStrategy(array(204)); + $request = $this->getMock('Guzzle\Http\Message\Request', array(), array(), '', false); + $response = new Response(204); + $this->assertEquals(0, $strategy->getBackoffPeriod(0, $request, $response)); + $response->setStatus(500); + $this->assertEquals(false, $strategy->getBackoffPeriod(0, $request, $response)); + } + + public function testIgnoresNonErrors() + { + $strategy = new HttpBackoffStrategy(); + $request = $this->getMock('Guzzle\Http\Message\Request', array(), array(), '', false); + $this->assertEquals(false, $strategy->getBackoffPeriod(0, $request)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/LinearBackoffStrategyTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/LinearBackoffStrategyTest.php new file mode 100644 index 000000000..b4ce8e4af --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/LinearBackoffStrategyTest.php @@ -0,0 +1,21 @@ +assertFalse($strategy->makesDecision()); + $request = $this->getMock('Guzzle\Http\Message\Request', array(), array(), '', false); + $this->assertEquals(0, $strategy->getBackoffPeriod(0, $request)); + $this->assertEquals(5, $strategy->getBackoffPeriod(1, $request)); + $this->assertEquals(10, $strategy->getBackoffPeriod(2, $request)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/ReasonPhraseBackoffStrategyTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/ReasonPhraseBackoffStrategyTest.php new file mode 100644 index 000000000..dea5a6878 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/ReasonPhraseBackoffStrategyTest.php @@ -0,0 +1,32 @@ +assertEmpty(ReasonPhraseBackoffStrategy::getDefaultFailureCodes()); + $strategy = new ReasonPhraseBackoffStrategy(array('Foo', 'Internal Server Error')); + $this->assertTrue($strategy->makesDecision()); + $request = $this->getMock('Guzzle\Http\Message\Request', array(), array(), '', false); + $response = new Response(200); + $this->assertEquals(false, $strategy->getBackoffPeriod(0, $request, $response)); + $response->setStatus(200, 'Foo'); + $this->assertEquals(0, $strategy->getBackoffPeriod(0, $request, $response)); + } + + public function testIgnoresNonErrors() + { + $strategy = new ReasonPhraseBackoffStrategy(); + $request = $this->getMock('Guzzle\Http\Message\Request', array(), array(), '', false); + $this->assertEquals(false, $strategy->getBackoffPeriod(0, $request)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/TruncatedBackoffStrategyTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/TruncatedBackoffStrategyTest.php new file mode 100644 index 000000000..5590dfb1c --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Backoff/TruncatedBackoffStrategyTest.php @@ -0,0 +1,30 @@ +assertTrue($strategy->makesDecision()); + $request = $this->getMock('Guzzle\Http\Message\Request', array(), array(), '', false); + $this->assertFalse($strategy->getBackoffPeriod(0, $request)); + $this->assertFalse($strategy->getBackoffPeriod(1, $request)); + $this->assertFalse($strategy->getBackoffPeriod(2, $request)); + + $response = new Response(500); + $strategy->setNext(new HttpBackoffStrategy(null, new ConstantBackoffStrategy(10))); + $this->assertEquals(10, $strategy->getBackoffPeriod(0, $request, $response)); + $this->assertEquals(10, $strategy->getBackoffPeriod(1, $request, $response)); + $this->assertFalse($strategy->getBackoffPeriod(2, $request, $response)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/CachePluginTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/CachePluginTest.php new file mode 100644 index 000000000..69da60a93 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/CachePluginTest.php @@ -0,0 +1,441 @@ +assertInstanceOf('Guzzle\Plugin\Cache\CacheStorageInterface', $this->readAttribute($plugin, 'storage')); + } + + public function testAddsDefaultCollaborators() + { + $this->assertNotEmpty(CachePlugin::getSubscribedEvents()); + $plugin = new CachePlugin(array( + 'storage' => $this->getMockBuilder('Guzzle\Plugin\Cache\CacheStorageInterface')->getMockForAbstractClass() + )); + $this->assertInstanceOf('Guzzle\Plugin\Cache\CacheStorageInterface', $this->readAttribute($plugin, 'storage')); + $this->assertInstanceOf( + 'Guzzle\Plugin\Cache\CanCacheStrategyInterface', + $this->readAttribute($plugin, 'canCache') + ); + $this->assertInstanceOf( + 'Guzzle\Plugin\Cache\RevalidationInterface', + $this->readAttribute($plugin, 'revalidation') + ); + } + + public function testAddsCallbackCollaborators() + { + $this->assertNotEmpty(CachePlugin::getSubscribedEvents()); + $plugin = new CachePlugin(array('can_cache' => function () {})); + $this->assertInstanceOf( + 'Guzzle\Plugin\Cache\CallbackCanCacheStrategy', + $this->readAttribute($plugin, 'canCache') + ); + } + + public function testCanPassCacheAsOnlyArgumentToConstructor() + { + $p = new CachePlugin(new DoctrineCacheAdapter(new ArrayCache())); + $p = new CachePlugin(new DefaultCacheStorage(new DoctrineCacheAdapter(new ArrayCache()))); + } + + public function testUsesCreatedCacheStorage() + { + $plugin = new CachePlugin(array( + 'adapter' => $this->getMockBuilder('Guzzle\Cache\CacheAdapterInterface')->getMockForAbstractClass() + )); + $this->assertInstanceOf('Guzzle\Plugin\Cache\CacheStorageInterface', $this->readAttribute($plugin, 'storage')); + } + + public function testUsesProvidedOptions() + { + $can = $this->getMockBuilder('Guzzle\Plugin\Cache\CanCacheStrategyInterface')->getMockForAbstractClass(); + $revalidate = $this->getMockBuilder('Guzzle\Plugin\Cache\RevalidationInterface')->getMockForAbstractClass(); + $plugin = new CachePlugin(array( + 'storage' => $this->getMockBuilder('Guzzle\Plugin\Cache\CacheStorageInterface')->getMockForAbstractClass(), + 'can_cache' => $can, + 'revalidation' => $revalidate + )); + $this->assertSame($can, $this->readAttribute($plugin, 'canCache')); + $this->assertSame($revalidate, $this->readAttribute($plugin, 'revalidation')); + } + + public function satisfyProvider() + { + $req1 = new Request('GET', 'http://foo.com', array('Cache-Control' => 'no-cache')); + + return array( + // The response is too old to satisfy the request + array(new Request('GET', 'http://foo.com', array('Cache-Control' => 'max-age=20')), new Response(200, array('Age' => 100)), false, false), + // The response cannot satisfy the request because it is stale + array(new Request('GET', 'http://foo.com'), new Response(200, array('Cache-Control' => 'max-age=10', 'Age' => 100)), false, false), + // Allows the expired response to satisfy the request because of the max-stale + array(new Request('GET', 'http://foo.com', array('Cache-Control' => 'max-stale=15')), new Response(200, array('Cache-Control' => 'max-age=90', 'Age' => 100)), true, false), + // Max stale is > than the allowed staleness + array(new Request('GET', 'http://foo.com', array('Cache-Control' => 'max-stale=5')), new Response(200, array('Cache-Control' => 'max-age=90', 'Age' => 100)), false, false), + // Performs cache revalidation + array($req1, new Response(200), true, true), + // Performs revalidation due to ETag on the response and no cache-control on the request + array(new Request('GET', 'http://foo.com'), new Response(200, array( + 'ETag' => 'ABC', + 'Expires' => date('c', strtotime('+1 year')) + )), true, true), + ); + } + + /** + * @dataProvider satisfyProvider + */ + public function testChecksIfResponseCanSatisfyRequest($request, $response, $can, $revalidates) + { + $didRevalidate = false; + $storage = $this->getMockBuilder('Guzzle\Plugin\Cache\CacheStorageInterface')->getMockForAbstractClass(); + $revalidate = $this->getMockBuilder('Guzzle\Plugin\Cache\DefaultRevalidation') + ->setMethods(array('revalidate')) + ->setConstructorArgs(array($storage)) + ->getMockForAbstractClass(); + + $revalidate->expects($this->any()) + ->method('revalidate') + ->will($this->returnCallback(function () use (&$didRevalidate) { + $didRevalidate = true; + return true; + })); + + $plugin = new CachePlugin(array( + 'storage' => $storage, + 'revalidation' => $revalidate + )); + + $this->assertEquals($can, $plugin->canResponseSatisfyRequest($request, $response)); + $this->assertEquals($didRevalidate, $revalidates); + } + + public function satisfyFailedProvider() + { + return array( + // Neither has stale-if-error + array(new Request('GET', 'http://foo.com', array()), new Response(200, array('Age' => 100)), false), + // Request has stale-if-error + array(new Request('GET', 'http://foo.com', array('Cache-Control' => 'stale-if-error')), new Response(200, array('Age' => 100, 'Cache-Control' => 'max-age=50')), true), + // Request has valid stale-if-error + array(new Request('GET', 'http://foo.com', array('Cache-Control' => 'stale-if-error=50')), new Response(200, array('Age' => 100, 'Cache-Control' => 'max-age=50')), true), + // Request has expired stale-if-error + array(new Request('GET', 'http://foo.com', array('Cache-Control' => 'stale-if-error=20')), new Response(200, array('Age' => 100, 'Cache-Control' => 'max-age=50')), false), + // Response has permanent stale-if-error + array(new Request('GET', 'http://foo.com', array()), new Response(200, array('Age' => 100, 'Cache-Control' => 'max-age=50, stale-if-error', )), true), + // Response has valid stale-if-error + array(new Request('GET', 'http://foo.com', array()), new Response(200, array('Age' => 100, 'Cache-Control' => 'max-age=50, stale-if-error=50')), true), + // Response has expired stale-if-error + array(new Request('GET', 'http://foo.com', array()), new Response(200, array('Age' => 100, 'Cache-Control' => 'max-age=50, stale-if-error=20')), false), + // Request has valid stale-if-error but response does not + array(new Request('GET', 'http://foo.com', array('Cache-Control' => 'stale-if-error=50')), new Response(200, array('Age' => 100, 'Cache-Control' => 'max-age=50, stale-if-error=20')), false), + // Response has valid stale-if-error but request does not + array(new Request('GET', 'http://foo.com', array('Cache-Control' => 'stale-if-error=20')), new Response(200, array('Age' => 100, 'Cache-Control' => 'max-age=50, stale-if-error=50')), false), + ); + } + + /** + * @dataProvider satisfyFailedProvider + */ + public function testChecksIfResponseCanSatisfyFailedRequest($request, $response, $can) + { + $plugin = new CachePlugin(); + + $this->assertEquals($can, $plugin->canResponseSatisfyFailedRequest($request, $response)); + } + + public function testDoesNothingWhenRequestIsNotCacheable() + { + $storage = $this->getMockBuilder('Guzzle\Plugin\Cache\CacheStorageInterface') + ->setMethods(array('fetch')) + ->getMockForAbstractClass(); + $storage->expects($this->never())->method('fetch'); + + $plugin = new CachePlugin(array( + 'storage' => $storage, + 'can_cache' => new CallbackCanCacheStrategy(function () { return false; }) + )); + + $plugin->onRequestBeforeSend(new Event(array( + 'request' => new Request('GET', 'http://foo.com') + ))); + } + + public function satisfiableProvider() + { + $date = new \DateTime('-10 seconds'); + + return array( + // Fresh response + array(new Response(200, array(), 'foo')), + // Stale response + array(new Response(200, array('Date' => $date->format('c'), 'Cache-Control' => 'max-age=5'), 'foo')) + ); + } + + /** + * @dataProvider satisfiableProvider + */ + public function testInjectsSatisfiableResponses($response) + { + $storage = $this->getMockBuilder('Guzzle\Plugin\Cache\CacheStorageInterface') + ->setMethods(array('fetch')) + ->getMockForAbstractClass(); + + $storage->expects($this->once())->method('fetch')->will($this->returnValue($response)); + $plugin = new CachePlugin(array('storage' => $storage)); + $request = new Request('GET', 'http://foo.com', array('Cache-Control' => 'max-stale')); + $plugin->onRequestBeforeSend(new Event(array('request' => $request))); + $plugin->onRequestSent(new Event(array('request' => $request, 'response' => $request->getResponse()))); + $this->assertEquals($response->getStatusCode(), $request->getResponse()->getStatusCode()); + $this->assertEquals((string) $response->getBody(), (string) $request->getResponse()->getBody()); + $this->assertTrue($request->getResponse()->hasHeader('Age')); + if ($request->getResponse()->isFresh() === false) { + $this->assertContains('110', (string) $request->getResponse()->getHeader('Warning')); + } + $this->assertSame( + sprintf('%s GuzzleCache/%s', $request->getProtocolVersion(), Version::VERSION), + (string) $request->getHeader('Via') + ); + $this->assertSame( + sprintf('%s GuzzleCache/%s',$request->getProtocolVersion(), Version::VERSION), + (string) $request->getResponse()->getHeader('Via') + ); + $this->assertTrue($request->getParams()->get('cache.lookup')); + $this->assertTrue($request->getParams()->get('cache.hit')); + $this->assertTrue($request->getResponse()->hasHeader('X-Cache-Lookup')); + $this->assertTrue($request->getResponse()->hasHeader('X-Cache')); + $this->assertEquals('HIT from GuzzleCache', (string) $request->getResponse()->getHeader('X-Cache')); + $this->assertEquals('HIT from GuzzleCache', (string) $request->getResponse()->getHeader('X-Cache-Lookup')); + } + + public function satisfiableOnErrorProvider() + { + $date = new \DateTime('-10 seconds'); + return array( + array( + new Response(200, array( + 'Date' => $date->format('c'), + 'Cache-Control' => 'max-age=5, stale-if-error' + ), 'foo'), + ) + ); + } + + /** + * @dataProvider satisfiableOnErrorProvider + */ + public function testInjectsSatisfiableResponsesOnError($cacheResponse) + { + $storage = $this->getMockBuilder('Guzzle\Plugin\Cache\CacheStorageInterface') + ->setMethods(array('fetch')) + ->getMockForAbstractClass(); + $storage->expects($this->exactly(2))->method('fetch')->will($this->returnValue($cacheResponse)); + $plugin = new CachePlugin(array('storage' => $storage)); + $request = new Request('GET', 'http://foo.com', array('Cache-Control' => 'max-stale')); + $plugin->onRequestBeforeSend(new Event(array('request' => $request))); + $plugin->onRequestError( + $event = new Event(array( + 'request' => $request, + 'response' => $request->getResponse(), + )) + ); + $response = $event['response']; + $this->assertEquals($cacheResponse->getStatusCode(), $response->getStatusCode()); + $this->assertEquals((string) $cacheResponse->getBody(), (string) $response->getBody()); + $this->assertTrue($response->hasHeader('Age')); + if ($response->isFresh() === false) { + $this->assertContains('110', (string) $response->getHeader('Warning')); + } + $this->assertSame(sprintf('%s GuzzleCache/%s', $request->getProtocolVersion(), Version::VERSION), (string) $request->getHeader('Via')); + $this->assertSame(sprintf('%s GuzzleCache/%s', $request->getProtocolVersion(), Version::VERSION), (string) $response->getHeader('Via')); + $this->assertTrue($request->getParams()->get('cache.lookup')); + $this->assertSame('error', $request->getParams()->get('cache.hit')); + $this->assertTrue($response->hasHeader('X-Cache-Lookup')); + $this->assertTrue($response->hasHeader('X-Cache')); + $this->assertEquals('HIT from GuzzleCache', (string) $response->getHeader('X-Cache-Lookup')); + $this->assertEquals('HIT_ERROR from GuzzleCache', (string) $response->getHeader('X-Cache')); + } + + /** + * @dataProvider satisfiableOnErrorProvider + */ + public function testInjectsSatisfiableResponsesOnException($cacheResponse) + { + $storage = $this->getMockBuilder('Guzzle\Plugin\Cache\CacheStorageInterface') + ->setMethods(array('fetch')) + ->getMockForAbstractClass(); + $storage->expects($this->exactly(2))->method('fetch')->will($this->returnValue($cacheResponse)); + $plugin = new CachePlugin(array('storage' => $storage)); + $request = new Request('GET', 'http://foo.com', array('Cache-Control' => 'max-stale')); + $plugin->onRequestBeforeSend(new Event(array( + 'request' => $request + ))); + $plugin->onRequestException( + new Event(array( + 'request' => $request, + 'response' => $request->getResponse(), + 'exception' => $this->getMock('Guzzle\Http\Exception\CurlException'), + )) + ); + $plugin->onRequestSent( + new Event(array( + 'request' => $request, + 'response' => $response = $request->getResponse(), + )) + ); + $this->assertEquals($cacheResponse->getStatusCode(), $response->getStatusCode()); + $this->assertEquals((string) $cacheResponse->getBody(), (string) $response->getBody()); + $this->assertTrue($response->hasHeader('Age')); + if ($response->isFresh() === false) { + $this->assertContains('110', (string) $response->getHeader('Warning')); + } + $this->assertSame(sprintf('%s GuzzleCache/%s', $request->getProtocolVersion(), Version::VERSION), (string) $request->getHeader('Via')); + $this->assertSame(sprintf('%s GuzzleCache/%s', $request->getProtocolVersion(), Version::VERSION), (string) $response->getHeader('Via')); + $this->assertTrue($request->getParams()->get('cache.lookup')); + $this->assertSame('error', $request->getParams()->get('cache.hit')); + $this->assertTrue($response->hasHeader('X-Cache-Lookup')); + $this->assertTrue($response->hasHeader('X-Cache')); + $this->assertEquals('HIT from GuzzleCache', (string) $response->getHeader('X-Cache-Lookup')); + $this->assertEquals('HIT_ERROR from GuzzleCache', (string) $response->getHeader('X-Cache')); + } + + public function unsatisfiableOnErrorProvider() + { + $date = new \DateTime('-10 seconds'); + + return array( + // no-store on request + array( + false, + array('Cache-Control' => 'no-store'), + new Response(200, array('Date' => $date->format('D, d M Y H:i:s T'), 'Cache-Control' => 'max-age=5, stale-if-error'), 'foo'), + ), + // request expired + array( + true, + array('Cache-Control' => 'stale-if-error=4'), + new Response(200, array('Date' => $date->format('D, d M Y H:i:s T'), 'Cache-Control' => 'max-age=5, stale-if-error'), 'foo'), + ), + // response expired + array( + true, + array('Cache-Control' => 'stale-if-error'), + new Response(200, array('Date' => $date->format('D, d M Y H:i:s T'), 'Cache-Control' => 'max-age=5, stale-if-error=4'), 'foo'), + ), + ); + } + + /** + * @dataProvider unsatisfiableOnErrorProvider + */ + public function testDoesNotInjectUnsatisfiableResponsesOnError($requestCanCache, $requestHeaders, $cacheResponse) + { + $storage = $this->getMockBuilder('Guzzle\Plugin\Cache\CacheStorageInterface') + ->setMethods(array('fetch')) + ->getMockForAbstractClass(); + $storage->expects($this->exactly($requestCanCache ? 2 : 0))->method('fetch')->will($this->returnValue($cacheResponse)); + $plugin = new CachePlugin(array('storage' => $storage)); + $request = new Request('GET', 'http://foo.com', $requestHeaders); + $plugin->onRequestBeforeSend(new Event(array( + 'request' => $request + ))); + $plugin->onRequestError( + $event = new Event(array( + 'request' => $request, + 'response' => $response = $request->getResponse(), + )) + ); + + $this->assertSame($response, $event['response']); + } + + /** + * @dataProvider unsatisfiableOnErrorProvider + */ + public function testDoesNotInjectUnsatisfiableResponsesOnException($requestCanCache, $requestHeaders, $responseParts) + { + $storage = $this->getMockBuilder('Guzzle\Plugin\Cache\CacheStorageInterface') + ->setMethods(array('fetch')) + ->getMockForAbstractClass(); + $storage->expects($this->exactly($requestCanCache ? 2 : 0))->method('fetch')->will($this->returnValue($responseParts)); + $plugin = new CachePlugin(array('storage' => $storage)); + $request = new Request('GET', 'http://foo.com', $requestHeaders); + $plugin->onRequestBeforeSend(new Event(array( + 'request' => $request + ))); + $plugin->onRequestException( + $event = new Event(array( + 'request' => $request, + 'response' => $response = $request->getResponse(), + 'exception' => $this->getMock('Guzzle\Http\Exception\CurlException'), + )) + ); + + $this->assertSame($response, $request->getResponse()); + } + + public function testCachesResponsesWhenCacheable() + { + $cache = new ArrayCache(); + $plugin = new CachePlugin($cache); + + $request = new Request('GET', 'http://foo.com'); + $response = new Response(200, array(), 'Foo'); + $plugin->onRequestBeforeSend(new Event(array( + 'request' => $request + ))); + $plugin->onRequestSent(new Event(array( + 'request' => $request, + 'response' => $response + ))); + $data = $this->readAttribute($cache, 'data'); + $this->assertNotEmpty($data); + } + + public function testPurgesRequests() + { + $storage = $this->getMockBuilder('Guzzle\Plugin\Cache\CacheStorageInterface') + ->setMethods(array('purge')) + ->getMockForAbstractClass(); + $storage->expects($this->atLeastOnce())->method('purge'); + $plugin = new CachePlugin(array('storage' => $storage)); + $request = new Request('GET', 'http://foo.com', array('X-Foo' => 'Bar')); + $plugin->purge($request); + } + + public function testAutoPurgesRequests() + { + $storage = $this->getMockBuilder('Guzzle\Plugin\Cache\CacheStorageInterface') + ->setMethods(array('purge')) + ->getMockForAbstractClass(); + $storage->expects($this->atLeastOnce())->method('purge'); + $plugin = new CachePlugin(array('storage' => $storage, 'auto_purge' => true)); + $client = new Client(); + $request = $client->put('http://foo.com', array('X-Foo' => 'Bar')); + $request->addSubscriber($plugin); + $request->setResponse(new Response(200), true); + $request->send(); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/CallbackCanCacheStrategyTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/CallbackCanCacheStrategyTest.php new file mode 100644 index 000000000..f3d9bafe2 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/CallbackCanCacheStrategyTest.php @@ -0,0 +1,72 @@ +assertTrue($c->canCacheRequest(new Request('DELETE', 'http://www.foo.com'))); + } + + /** + * The following is a bit of an integration test to ensure that the CachePlugin honors a + * custom can cache strategy. + */ + public function testIntegrationWithCachePlugin() + { + $c = new CallbackCanCacheStrategy( + function ($request) { return true; }, + function ($response) { return true; } + ); + + // Make a request and response that have no business being cached + $request = new Request('DELETE', 'http://www.foo.com'); + $response = Response::fromMessage( + "HTTP/1.1 200 OK\r\n" + . "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n" + . "Last-Modified: Wed, 09 Jan 2013 08:48:53 GMT\r\n" + . "Content-Length: 2\r\n" + . "Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0\r\n\r\n" + . "hi" + ); + + $this->assertTrue($c->canCacheRequest($request)); + $this->assertTrue($c->canCacheResponse($response)); + + $s = $this->getMockBuilder('Guzzle\Plugin\Cache\DefaultCacheStorage') + ->setConstructorArgs(array(new DoctrineCacheAdapter(new ArrayCache()))) + ->setMethods(array('fetch')) + ->getMockForAbstractClass(); + + $s->expects($this->once()) + ->method('fetch') + ->will($this->returnValue($response)); + + $plugin = new CachePlugin(array('can_cache' => $c, 'storage' => $s)); + $plugin->onRequestBeforeSend(new Event(array('request' => $request))); + + $this->assertEquals(200, $request->getResponse()->getStatusCode()); + $this->assertEquals('hi', $request->getResponse()->getBody(true)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/DefaultCacheStorageTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/DefaultCacheStorageTest.php new file mode 100644 index 000000000..701a0155f --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/DefaultCacheStorageTest.php @@ -0,0 +1,193 @@ + 'application/json')); + $response = new Response(200, array( + 'Content-Type' => 'application/json', + 'Connection' => 'close', + 'X-Foo' => 'Bar', + 'Vary' => 'Accept' + ), 'test'); + $s->cache($request, $response); + $data = $this->readAttribute($a, 'data'); + + return array( + 'cache' => $a, + 'adapter' => $c, + 'storage' => $s, + 'request' => $request, + 'response' => $response, + 'serialized' => end($data) + ); + } + + public function testReturnsNullForCacheMiss() + { + $cache = $this->getCache(); + $this->assertNull($cache['storage']->fetch(new Request('GET', 'http://test.com'))); + } + + public function testCachesRequests() + { + $cache = $this->getCache(); + $foundRequest = $foundBody = $bodyKey = false; + foreach ($this->readAttribute($cache['cache'], 'data') as $key => $v) { + if (strpos($v, 'foo.com')) { + $foundRequest = true; + $data = unserialize($v); + $bodyKey = $data[0][3]; + $this->assertInternalType('integer', $data[0][4]); + $this->assertFalse(isset($data[0][0]['connection'])); + $this->assertEquals('foo.com', $data[0][0]['host']); + } elseif ($v == 'test') { + $foundBody = $key; + } + } + $this->assertContains($bodyKey, $foundBody); + $this->assertTrue($foundRequest); + } + + public function testFetchesResponse() + { + $cache = $this->getCache(); + $response = $cache['storage']->fetch($cache['request']); + $this->assertEquals(200, $response->getStatusCode()); + $this->assertFalse($response->hasHeader('Connection')); + $this->assertEquals('Bar', (string) $response->getHeader('X-Foo')); + $this->assertEquals('test', (string) $response->getBody()); + $this->assertTrue(in_array($cache['serialized'], $this->readAttribute($cache['cache'], 'data'))); + } + + public function testDeletesRequestItemsAndBody() + { + $cache = $this->getCache(); + $cache['storage']->delete($cache['request']); + $this->assertFalse(in_array('test', $this->readAttribute($cache['cache'], 'data'))); + $this->assertFalse(in_array($cache['serialized'], $this->readAttribute($cache['cache'], 'data'))); + } + + public function testCachesMultipleRequestsWithVary() + { + $cache = $this->getCache(); + $cache['request']->setHeader('Accept', 'application/xml'); + $response = $cache['response']->setHeader('Content-Type', 'application/xml'); + $response->setBody('123'); + $cache['storage']->cache($cache['request'], $response); + $data = $this->readAttribute($cache['cache'], 'data'); + foreach ($data as $v) { + if (strpos($v, 'foo.com')) { + $u = unserialize($v); + $this->assertEquals(2, count($u)); + $this->assertEquals($u[0][0]['accept'], 'application/xml'); + $this->assertEquals($u[0][1]['content-type'], 'application/xml'); + $this->assertEquals($u[1][0]['accept'], 'application/json'); + $this->assertEquals($u[1][1]['content-type'], 'application/json'); + $this->assertNotSame($u[0][3], $u[1][3]); + break; + } + } + } + + public function testPurgeRemovesAllMethodCaches() + { + $cache = $this->getCache(); + foreach (array('HEAD', 'POST', 'PUT', 'DELETE') as $method) { + $request = RequestFactory::getInstance()->cloneRequestWithMethod($cache['request'], $method); + $cache['storage']->cache($request, $cache['response']); + } + $cache['storage']->purge('http://foo.com'); + $this->assertFalse(in_array('test', $this->readAttribute($cache['cache'], 'data'))); + $this->assertFalse(in_array($cache['serialized'], $this->readAttribute($cache['cache'], 'data'))); + $this->assertEquals( + array('DoctrineNamespaceCacheKey[]'), + array_keys($this->readAttribute($cache['cache'], 'data')) + ); + } + + public function testRemovesExpiredResponses() + { + $cache = $this->getCache(); + $request = new Request('GET', 'http://xyz.com'); + $response = new Response(200, array('Age' => 1000, 'Cache-Control' => 'max-age=-10000')); + $cache['storage']->cache($request, $response); + $this->assertNull($cache['storage']->fetch($request)); + $data = $this->readAttribute($cache['cache'], 'data'); + $this->assertFalse(in_array('xyz.com', $data)); + $this->assertTrue(in_array($cache['serialized'], $data)); + } + + public function testUsesVaryToDetermineResult() + { + $cache = $this->getCache(); + $this->assertInstanceOf('Guzzle\Http\Message\Response', $cache['storage']->fetch($cache['request'])); + $request = new Request('GET', 'http://foo.com', array('Accept' => 'application/xml')); + $this->assertNull($cache['storage']->fetch($request)); + } + + public function testEnsuresResponseIsStillPresent() + { + $cache = $this->getCache(); + $data = $this->readAttribute($cache['cache'], 'data'); + $key = array_search('test', $data); + $cache['cache']->delete(substr($key, 1, -4)); + $this->assertNull($cache['storage']->fetch($cache['request'])); + } + + public function staleProvider() + { + return array( + array( + new Request('GET', 'http://foo.com', array('Accept' => 'foo')), + new Response(200, array('Cache-Control' => 'stale-if-error=100', 'Vary' => 'Accept')) + ), + array( + new Request('GET', 'http://foo.com', array('Accept' => 'foo')), + new Response(200, array('Cache-Control' => 'stale-if-error', 'Vary' => 'Accept')) + ) + ); + } + + /** + * @dataProvider staleProvider + */ + public function testUsesStaleTimeDirectiveForTtd($request, $response) + { + $cache = $this->getCache(); + $cache['storage']->cache($request, $response); + $data = $this->readAttribute($cache['cache'], 'data'); + foreach ($data as $v) { + if (strpos($v, 'foo.com')) { + $u = unserialize($v); + $this->assertGreaterThan($u[1][4], $u[0][4]); + break; + } + } + } + + public function testCanFilterCacheKeys() + { + $cache = $this->getCache(); + $cache['request']->getQuery()->set('auth', 'foo'); + $this->assertNull($cache['storage']->fetch($cache['request'])); + $cache['request']->getParams()->set('cache.key_filter', 'auth'); + $this->assertNotNull($cache['storage']->fetch($cache['request'])); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/DefaultCanCacheStrategyTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/DefaultCanCacheStrategyTest.php new file mode 100644 index 000000000..de4d182a2 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/DefaultCanCacheStrategyTest.php @@ -0,0 +1,40 @@ +assertTrue($strategy->canCacheRequest($request)); + } + + public function testDoesNotCacheNoStore() + { + $strategy = new DefaultCanCacheStrategy(); + $request = new Request('GET', 'http://foo.com', array('cache-control' => 'no-store')); + $this->assertFalse($strategy->canCacheRequest($request)); + } + + public function testCanCacheResponse() + { + $response = $this->getMockBuilder('Guzzle\Http\Message\Response') + ->setMethods(array('canCache')) + ->setConstructorArgs(array(200)) + ->getMock(); + $response->expects($this->once()) + ->method('canCache') + ->will($this->returnValue(true)); + $strategy = new DefaultCanCacheStrategy(); + $this->assertTrue($strategy->canCacheResponse($response)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/DefaultRevalidationTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/DefaultRevalidationTest.php new file mode 100644 index 000000000..0699cb266 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/DefaultRevalidationTest.php @@ -0,0 +1,248 @@ +getHttpDate('-100 hours') . "\r\nContent-Length: 4\r\n\r\nData", + "HTTP/1.1 304 NOT MODIFIED\r\nCache-Control: max-age=2000000\r\nContent-Length: 0\r\n\r\n", + ), + // Forces revalidation that overwrites what is in cache + array( + false, + "\r\n", + "HTTP/1.1 200 OK\r\nCache-Control: must-revalidate, no-cache\r\nDate: " . $this->getHttpDate('-10 hours') . "\r\nContent-Length: 4\r\n\r\nData", + "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nDatas", + "HTTP/1.1 200 OK\r\nContent-Length: 5\r\nDate: " . $this->getHttpDate('now') . "\r\n\r\nDatas" + ), + // Throws an exception during revalidation + array( + false, + "\r\n", + "HTTP/1.1 200 OK\r\nCache-Control: no-cache\r\nDate: " . $this->getHttpDate('-3 hours') . "\r\n\r\nData", + "HTTP/1.1 500 INTERNAL SERVER ERROR\r\nContent-Length: 0\r\n\r\n" + ), + // ETag mismatch + array( + false, + "\r\n", + "HTTP/1.1 200 OK\r\nCache-Control: no-cache\r\nETag: \"123\"\r\nDate: " . $this->getHttpDate('-10 hours') . "\r\n\r\nData", + "HTTP/1.1 304 NOT MODIFIED\r\nETag: \"123456\"\r\n\r\n", + ), + ); + } + + /** + * @dataProvider cacheRevalidationDataProvider + */ + public function testRevalidatesResponsesAgainstOriginServer($can, $request, $response, $validate = null, $result = null) + { + // Send some responses to the test server for cache validation + $server = $this->getServer(); + $server->flush(); + + if ($validate) { + $server->enqueue($validate); + } + + $request = RequestFactory::getInstance()->fromMessage("GET / HTTP/1.1\r\nHost: 127.0.0.1:" . $server->getPort() . "\r\n" . $request); + $response = Response::fromMessage($response); + $request->setClient(new Client()); + + $plugin = new CachePlugin(new DoctrineCacheAdapter(new ArrayCache())); + $this->assertEquals( + $can, + $plugin->canResponseSatisfyRequest($request, $response), + '-> ' . $request . "\n" . $response + ); + + if ($result) { + $result = Response::fromMessage($result); + $result->removeHeader('Date'); + $request->getResponse()->removeHeader('Date'); + $request->getResponse()->removeHeader('Connection'); + // Get rid of dates + $this->assertEquals((string) $result, (string) $request->getResponse()); + } + + if ($validate) { + $this->assertEquals(1, count($server->getReceivedRequests())); + } + } + + public function testHandles404RevalidationResponses() + { + $request = new Request('GET', 'http://foo.com'); + $request->setClient(new Client()); + $badResponse = new Response(404, array(), 'Oh no!'); + $badRequest = clone $request; + $badRequest->setResponse($badResponse, true); + $response = new Response(200, array(), 'foo'); + + // Seed the cache + $s = new DefaultCacheStorage(new DoctrineCacheAdapter(new ArrayCache())); + $s->cache($request, $response); + $this->assertNotNull($s->fetch($request)); + + $rev = $this->getMockBuilder('Guzzle\Plugin\Cache\DefaultRevalidation') + ->setConstructorArgs(array($s)) + ->setMethods(array('createRevalidationRequest')) + ->getMock(); + + $rev->expects($this->once()) + ->method('createRevalidationRequest') + ->will($this->returnValue($badRequest)); + + try { + $rev->revalidate($request, $response); + $this->fail('Should have thrown an exception'); + } catch (BadResponseException $e) { + $this->assertSame($badResponse, $e->getResponse()); + $this->assertNull($s->fetch($request)); + } + } + + public function testCanRevalidateWithPlugin() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 200 OK\r\n" . + "Date: Mon, 12 Nov 2012 03:06:37 GMT\r\n" . + "Cache-Control: private, s-maxage=0, max-age=0, must-revalidate\r\n" . + "Last-Modified: Mon, 12 Nov 2012 02:53:38 GMT\r\n" . + "Content-Length: 2\r\n\r\nhi", + "HTTP/1.0 304 Not Modified\r\n" . + "Date: Mon, 12 Nov 2012 03:06:38 GMT\r\n" . + "Content-Type: text/html; charset=UTF-8\r\n" . + "Last-Modified: Mon, 12 Nov 2012 02:53:38 GMT\r\n" . + "Age: 6302\r\n\r\n", + "HTTP/1.0 304 Not Modified\r\n" . + "Date: Mon, 12 Nov 2012 03:06:38 GMT\r\n" . + "Content-Type: text/html; charset=UTF-8\r\n" . + "Last-Modified: Mon, 12 Nov 2012 02:53:38 GMT\r\n" . + "Age: 6302\r\n\r\n", + )); + $client = new Client($this->getServer()->getUrl()); + $client->addSubscriber(new CachePlugin()); + $this->assertEquals(200, $client->get()->send()->getStatusCode()); + $this->assertEquals(200, $client->get()->send()->getStatusCode()); + $this->assertEquals(200, $client->get()->send()->getStatusCode()); + $this->assertEquals(3, count($this->getServer()->getReceivedRequests())); + } + + public function testCanHandleRevalidationFailures() + { + $client = new Client($this->getServer()->getUrl()); + $lm = gmdate('c', time() - 60); + $mock = new MockPlugin(array( + new Response(200, array( + 'Date' => $lm, + 'Cache-Control' => 'max-age=100, must-revalidate, stale-if-error=9999', + 'Last-Modified' => $lm, + 'Content-Length' => 2 + ), 'hi'), + new CurlException('Bleh'), + new CurlException('Bleh') + )); + $client->addSubscriber(new CachePlugin()); + $client->addSubscriber($mock); + $client->get()->send(); + $response = $client->get()->send(); + $this->assertEquals(200, $response->getStatusCode()); + $this->assertEquals('hi', $response->getBody(true)); + $this->assertEquals(3, count($mock->getReceivedRequests())); + $this->assertEquals(0, count($mock->getQueue())); + } + + public function testCanHandleStaleIfErrorWhenRevalidating() + { + $lm = gmdate('c', time() - 60); + $mock = new MockPlugin(array( + new Response(200, array( + 'Date' => $lm, + 'Cache-Control' => 'must-revalidate, max-age=0, stale-if-error=1200', + 'Last-Modified' => $lm, + 'Content-Length' => 2 + ), 'hi'), + new CurlException('Oh no!'), + new CurlException('Oh no!') + )); + $cache = new CachePlugin(); + $client = new Client('http://www.example.com'); + $client->addSubscriber($cache); + $client->addSubscriber($mock); + $this->assertEquals(200, $client->get()->send()->getStatusCode()); + $response = $client->get()->send(); + $this->assertEquals(200, $response->getStatusCode()); + $this->assertCount(0, $mock); + $this->assertEquals('HIT from GuzzleCache', (string) $response->getHeader('X-Cache-Lookup')); + $this->assertEquals('HIT_ERROR from GuzzleCache', (string) $response->getHeader('X-Cache')); + } + + /** + * @group issue-437 + */ + public function testDoesNotTouchClosureListeners() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 200 OK\r\n" . + "Date: Mon, 12 Nov 2012 03:06:37 GMT\r\n" . + "Cache-Control: private, s-maxage=0, max-age=0, must-revalidate\r\n" . + "Last-Modified: Mon, 12 Nov 2012 02:53:38 GMT\r\n" . + "Content-Length: 2\r\n\r\nhi", + "HTTP/1.0 304 Not Modified\r\n" . + "Date: Mon, 12 Nov 2012 03:06:38 GMT\r\n" . + "Content-Type: text/html; charset=UTF-8\r\n" . + "Last-Modified: Mon, 12 Nov 2012 02:53:38 GMT\r\n" . + "Age: 6302\r\n\r\n", + "HTTP/1.0 304 Not Modified\r\n" . + "Date: Mon, 12 Nov 2012 03:06:38 GMT\r\n" . + "Content-Type: text/html; charset=UTF-8\r\n" . + "Last-Modified: Mon, 12 Nov 2012 02:53:38 GMT\r\n" . + "Age: 6302\r\n\r\n", + )); + $client = new Client($this->getServer()->getUrl()); + $client->addSubscriber(new CachePlugin()); + $client->getEventDispatcher()->addListener('command.after_send', function(){}); + $this->assertEquals(200, $client->get()->send()->getStatusCode()); + $this->assertEquals(200, $client->get()->send()->getStatusCode()); + $this->assertEquals(200, $client->get()->send()->getStatusCode()); + } + +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/DenyRevalidationTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/DenyRevalidationTest.php new file mode 100644 index 000000000..9af80f255 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/DenyRevalidationTest.php @@ -0,0 +1,19 @@ +assertFalse($deny->revalidate(new Request('GET', 'http://foo.com'), new Response(200))); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/SkipRevalidationTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/SkipRevalidationTest.php new file mode 100644 index 000000000..4bcc04bfa --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cache/SkipRevalidationTest.php @@ -0,0 +1,19 @@ +assertTrue($skip->revalidate(new Request('GET', 'http://foo.com'), new Response(200))); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cookie/CookieJar/ArrayCookieJarTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cookie/CookieJar/ArrayCookieJarTest.php new file mode 100644 index 000000000..5d0f668a6 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cookie/CookieJar/ArrayCookieJarTest.php @@ -0,0 +1,385 @@ +jar = new ArrayCookieJar(); + } + + protected function getTestCookies() + { + return array( + new Cookie(array('name' => 'foo', 'value' => 'bar', 'domain' => 'foo.com', 'path' => '/', 'discard' => true)), + new Cookie(array('name' => 'test', 'value' => '123', 'domain' => 'baz.com', 'path' => '/foo', 'expires' => 2)), + new Cookie(array('name' => 'you', 'value' => '123', 'domain' => 'bar.com', 'path' => '/boo', 'expires' => time() + 1000)) + ); + } + + /** + * Provides test data for cookie cookieJar retrieval + */ + public function getCookiesDataProvider() + { + return array( + array(array('foo', 'baz', 'test', 'muppet', 'googoo'), '', '', '', false), + array(array('foo', 'baz', 'muppet', 'googoo'), '', '', '', true), + array(array('googoo'), 'www.example.com', '', '', false), + array(array('muppet', 'googoo'), 'test.y.example.com', '', '', false), + array(array('foo', 'baz'), 'example.com', '', '', false), + array(array('muppet'), 'x.y.example.com', '/acme/', '', false), + array(array('muppet'), 'x.y.example.com', '/acme/test/', '', false), + array(array('googoo'), 'x.y.example.com', '/test/acme/test/', '', false), + array(array('foo', 'baz'), 'example.com', '', '', false), + array(array('baz'), 'example.com', '', 'baz', false), + ); + } + + public function testStoresAndRetrievesCookies() + { + $cookies = $this->getTestCookies(); + foreach ($cookies as $cookie) { + $this->assertTrue($this->jar->add($cookie)); + } + + $this->assertEquals(3, count($this->jar)); + $this->assertEquals(3, count($this->jar->getIterator())); + $this->assertEquals($cookies, $this->jar->all(null, null, null, false, false)); + } + + public function testRemovesExpiredCookies() + { + $cookies = $this->getTestCookies(); + foreach ($this->getTestCookies() as $cookie) { + $this->jar->add($cookie); + } + $this->jar->removeExpired(); + $this->assertEquals(array($cookies[0], $cookies[2]), $this->jar->all()); + } + + public function testRemovesTemporaryCookies() + { + $cookies = $this->getTestCookies(); + foreach ($this->getTestCookies() as $cookie) { + $this->jar->add($cookie); + } + $this->jar->removeTemporary(); + $this->assertEquals(array($cookies[2]), $this->jar->all()); + } + + public function testIsSerializable() + { + $this->assertEquals('[]', $this->jar->serialize()); + $this->jar->unserialize('[]'); + $this->assertEquals(array(), $this->jar->all()); + + $cookies = $this->getTestCookies(); + foreach ($this->getTestCookies() as $cookie) { + $this->jar->add($cookie); + } + + // Remove discard and expired cookies + $serialized = $this->jar->serialize(); + $data = json_decode($serialized, true); + $this->assertEquals(1, count($data)); + + $a = new ArrayCookieJar(); + $a->unserialize($serialized); + $this->assertEquals(1, count($a)); + } + + public function testRemovesSelectively() + { + $cookies = $this->getTestCookies(); + foreach ($this->getTestCookies() as $cookie) { + $this->jar->add($cookie); + } + + // Remove foo.com cookies + $this->jar->remove('foo.com'); + $this->assertEquals(2, count($this->jar)); + // Try again, removing no further cookies + $this->jar->remove('foo.com'); + $this->assertEquals(2, count($this->jar)); + + // Remove bar.com cookies with path of /boo + $this->jar->remove('bar.com', '/boo'); + $this->assertEquals(1, count($this->jar)); + + // Remove cookie by name + $this->jar->remove(null, null, 'test'); + $this->assertEquals(0, count($this->jar)); + } + + public function testDoesNotAddIncompleteCookies() + { + $this->assertEquals(false, $this->jar->add(new Cookie())); + $this->assertFalse($this->jar->add(new Cookie(array( + 'name' => 'foo' + )))); + $this->assertFalse($this->jar->add(new Cookie(array( + 'name' => false + )))); + $this->assertFalse($this->jar->add(new Cookie(array( + 'name' => true + )))); + $this->assertFalse($this->jar->add(new Cookie(array( + 'name' => 'foo', + 'domain' => 'foo.com' + )))); + } + + public function testDoesAddValidCookies() + { + $this->assertTrue($this->jar->add(new Cookie(array( + 'name' => 'foo', + 'domain' => 'foo.com', + 'value' => 0 + )))); + $this->assertTrue($this->jar->add(new Cookie(array( + 'name' => 'foo', + 'domain' => 'foo.com', + 'value' => 0.0 + )))); + $this->assertTrue($this->jar->add(new Cookie(array( + 'name' => 'foo', + 'domain' => 'foo.com', + 'value' => '0' + )))); + } + + public function testOverwritesCookiesThatAreOlderOrDiscardable() + { + $t = time() + 1000; + $data = array( + 'name' => 'foo', + 'value' => 'bar', + 'domain' => '.example.com', + 'path' => '/', + 'max_age' => '86400', + 'port' => array(80, 8080), + 'version' => '1', + 'secure' => true, + 'discard' => true, + 'expires' => $t + ); + + // Make sure that the discard cookie is overridden with the non-discard + $this->assertTrue($this->jar->add(new Cookie($data))); + + unset($data['discard']); + $this->assertTrue($this->jar->add(new Cookie($data))); + $this->assertEquals(1, count($this->jar)); + + $c = $this->jar->all(); + $this->assertEquals(false, $c[0]->getDiscard()); + + // Make sure it doesn't duplicate the cookie + $this->jar->add(new Cookie($data)); + $this->assertEquals(1, count($this->jar)); + + // Make sure the more future-ful expiration date supersede the other + $data['expires'] = time() + 2000; + $this->assertTrue($this->jar->add(new Cookie($data))); + $this->assertEquals(1, count($this->jar)); + $c = $this->jar->all(); + $this->assertNotEquals($t, $c[0]->getExpires()); + } + + public function testOverwritesCookiesThatHaveChanged() + { + $t = time() + 1000; + $data = array( + 'name' => 'foo', + 'value' => 'bar', + 'domain' => '.example.com', + 'path' => '/', + 'max_age' => '86400', + 'port' => array(80, 8080), + 'version' => '1', + 'secure' => true, + 'discard' => true, + 'expires' => $t + ); + + // Make sure that the discard cookie is overridden with the non-discard + $this->assertTrue($this->jar->add(new Cookie($data))); + + $data['value'] = 'boo'; + $this->assertTrue($this->jar->add(new Cookie($data))); + $this->assertEquals(1, count($this->jar)); + + // Changing the value plus a parameter also must overwrite the existing one + $data['value'] = 'zoo'; + $data['secure'] = false; + $this->assertTrue($this->jar->add(new Cookie($data))); + $this->assertEquals(1, count($this->jar)); + + $c = $this->jar->all(); + $this->assertEquals('zoo', $c[0]->getValue()); + } + + public function testAddsCookiesFromResponseWithNoRequest() + { + $response = new Response(200, array( + 'Set-Cookie' => array( + "fpc=d=.Hm.yh4.1XmJWjJfs4orLQzKzPImxklQoxXSHOZATHUSEFciRueW_7704iYUtsXNEXq0M92Px2glMdWypmJ7HIQl6XIUvrZimWjQ3vIdeuRbI.FNQMAfcxu_XN1zSx7l.AcPdKL6guHc2V7hIQFhnjRW0rxm2oHY1P4bGQxFNz7f.tHm12ZD3DbdMDiDy7TBXsuP4DM-&v=2; expires=Fri, 02-Mar-2019 02:17:40 GMT; path=/; domain=127.0.0.1", + "FPCK3=AgBNbvoQAGpGEABZLRAAbFsQAF1tEABkDhAAeO0=; expires=Sat, 02-Apr-2019 02:17:40 GMT; path=/; domain=127.0.0.1", + "CH=deleted; expires=Wed, 03-Mar-2010 02:17:39 GMT; path=/; domain=127.0.0.1", + "CH=AgBNbvoQAAEcEAApuhAAMJcQADQvEAAvGxAALe0QAD6uEAATwhAAC1AQAC8t; expires=Sat, 02-Apr-2019 02:17:40 GMT; path=/; domain=127.0.0.1" + ) + )); + + $this->jar->addCookiesFromResponse($response); + $this->assertEquals(3, count($this->jar)); + $this->assertEquals(1, count($this->jar->all(null, null, 'fpc'))); + $this->assertEquals(1, count($this->jar->all(null, null, 'FPCK3'))); + $this->assertEquals(1, count($this->jar->all(null, null, 'CH'))); + } + + public function testAddsCookiesFromResponseWithRequest() + { + $response = new Response(200, array( + 'Set-Cookie' => "fpc=d=.Hm.yh4.1XmJWjJfs4orLQzKzPImxklQoxXSHOZATHUSEFciRueW_7704iYUtsXNEXq0M92Px2glMdWypmJ7HIQl6XIUvrZimWjQ3vIdeuRbI.FNQMAfcxu_XN1zSx7l.AcPdKL6guHc2V7hIQFhnjRW0rxm2oHY1P4bGQxFNz7f.tHm12ZD3DbdMDiDy7TBXsuP4DM-&v=2; expires=Fri, 02-Mar-2019 02:17:40 GMT;" + )); + $request = new Request('GET', 'http://www.example.com'); + $this->jar->addCookiesFromResponse($response, $request); + $this->assertEquals(1, count($this->jar)); + } + + public function getMatchingCookiesDataProvider() + { + return array( + array('https://example.com', array(0)), + array('http://example.com', array()), + array('https://example.com:8912', array()), + array('https://foo.example.com', array(0)), + array('http://foo.example.com/test/acme/', array(4)) + ); + } + + /** + * @dataProvider getMatchingCookiesDataProvider + */ + public function testReturnsCookiesMatchingRequests($url, $cookies) + { + $bag = array( + new Cookie(array( + 'name' => 'foo', + 'value' => 'bar', + 'domain' => 'example.com', + 'path' => '/', + 'max_age' => '86400', + 'port' => array(443, 8080), + 'version' => '1', + 'secure' => true + )), + new Cookie(array( + 'name' => 'baz', + 'value' => 'foobar', + 'domain' => 'example.com', + 'path' => '/', + 'max_age' => '86400', + 'port' => array(80, 8080), + 'version' => '1', + 'secure' => true + )), + new Cookie(array( + 'name' => 'test', + 'value' => '123', + 'domain' => 'www.foobar.com', + 'path' => '/path/', + 'discard' => true + )), + new Cookie(array( + 'name' => 'muppet', + 'value' => 'cookie_monster', + 'domain' => '.y.example.com', + 'path' => '/acme/', + 'comment' => 'Comment goes here...', + 'expires' => time() + 86400 + )), + new Cookie(array( + 'name' => 'googoo', + 'value' => 'gaga', + 'domain' => '.example.com', + 'path' => '/test/acme/', + 'max_age' => 1500, + 'version' => 2 + )) + ); + + foreach ($bag as $cookie) { + $this->jar->add($cookie); + } + + $request = new Request('GET', $url); + $results = $this->jar->getMatchingCookies($request); + $this->assertEquals(count($cookies), count($results)); + foreach ($cookies as $i) { + $this->assertContains($bag[$i], $results); + } + } + + /** + * @expectedException \Guzzle\Plugin\Cookie\Exception\InvalidCookieException + * @expectedExceptionMessage The cookie name must not contain invalid characters: abc:@123 + */ + public function testThrowsExceptionWithStrictMode() + { + $a = new ArrayCookieJar(); + $a->setStrictMode(true); + $a->add(new Cookie(array( + 'name' => 'abc:@123', + 'value' => 'foo', + 'domain' => 'bar' + ))); + } + + public function testRemoveExistingCookieIfEmpty() + { + // Add a cookie that should not be affected + $a = new Cookie(array( + 'name' => 'foo', + 'value' => 'nope', + 'domain' => 'foo.com', + 'path' => '/abc' + )); + $this->jar->add($a); + + $data = array( + 'name' => 'foo', + 'value' => 'bar', + 'domain' => 'foo.com', + 'path' => '/' + ); + + $b = new Cookie($data); + $this->assertTrue($this->jar->add($b)); + $this->assertEquals(2, count($this->jar)); + + // Try to re-set the same cookie with no value: assert that cookie is not added + $data['value'] = null; + $this->assertFalse($this->jar->add(new Cookie($data))); + // assert that original cookie has been deleted + $cookies = $this->jar->all('foo.com'); + $this->assertTrue(in_array($a, $cookies, true)); + $this->assertFalse(in_array($b, $cookies, true)); + $this->assertEquals(1, count($this->jar)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cookie/CookieJar/FileCookieJarTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cookie/CookieJar/FileCookieJarTest.php new file mode 100644 index 000000000..ac9471fd8 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cookie/CookieJar/FileCookieJarTest.php @@ -0,0 +1,63 @@ +file = tempnam('/tmp', 'file-cookies'); + } + + public function testLoadsFromFileFile() + { + $jar = new FileCookieJar($this->file); + $this->assertEquals(array(), $jar->all()); + unlink($this->file); + } + + public function testPersistsToFileFile() + { + $jar = new FileCookieJar($this->file); + $jar->add(new Cookie(array( + 'name' => 'foo', + 'value' => 'bar', + 'domain' => 'foo.com', + 'expires' => time() + 1000 + ))); + $jar->add(new Cookie(array( + 'name' => 'baz', + 'value' => 'bar', + 'domain' => 'foo.com', + 'expires' => time() + 1000 + ))); + $jar->add(new Cookie(array( + 'name' => 'boo', + 'value' => 'bar', + 'domain' => 'foo.com', + ))); + + $this->assertEquals(3, count($jar)); + unset($jar); + + // Make sure it wrote to the file + $contents = file_get_contents($this->file); + $this->assertNotEmpty($contents); + + // Load the cookieJar from the file + $jar = new FileCookieJar($this->file); + + // Weeds out temporary and session cookies + $this->assertEquals(2, count($jar)); + unset($jar); + unlink($this->file); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cookie/CookiePluginTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cookie/CookiePluginTest.php new file mode 100644 index 000000000..f8c175cce --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cookie/CookiePluginTest.php @@ -0,0 +1,134 @@ +getMockBuilder('Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar') + ->setMethods(array('addCookiesFromResponse')) + ->getMock(); + + $mock->expects($this->exactly(1)) + ->method('addCookiesFromResponse') + ->with($response); + + $plugin = new CookiePlugin($mock); + $plugin->onRequestSent(new Event(array( + 'response' => $response + ))); + } + + public function testAddsCookiesToRequests() + { + $cookie = new Cookie(array( + 'name' => 'foo', + 'value' => 'bar' + )); + + $mock = $this->getMockBuilder('Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar') + ->setMethods(array('getMatchingCookies')) + ->getMock(); + + $mock->expects($this->once()) + ->method('getMatchingCookies') + ->will($this->returnValue(array($cookie))); + + $plugin = new CookiePlugin($mock); + + $client = new Client(); + $client->getEventDispatcher()->addSubscriber($plugin); + + $request = $client->get('http://www.example.com'); + $plugin->onRequestBeforeSend(new Event(array( + 'request' => $request + ))); + + $this->assertEquals('bar', $request->getCookie('foo')); + } + + public function testCookiesAreExtractedFromRedirectResponses() + { + $plugin = new CookiePlugin(new ArrayCookieJar()); + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 302 Moved Temporarily\r\n" . + "Set-Cookie: test=583551; expires=Wednesday, 23-Mar-2050 19:49:45 GMT; path=/\r\n" . + "Location: /redirect\r\n\r\n", + "HTTP/1.1 200 OK\r\n" . + "Content-Length: 0\r\n\r\n", + "HTTP/1.1 200 OK\r\n" . + "Content-Length: 0\r\n\r\n" + )); + + $client = new Client($this->getServer()->getUrl()); + $client->getEventDispatcher()->addSubscriber($plugin); + + $client->get()->send(); + $request = $client->get(); + $request->send(); + $this->assertEquals('test=583551', $request->getHeader('Cookie')); + + $requests = $this->getServer()->getReceivedRequests(true); + // Confirm subsequent requests have the cookie. + $this->assertEquals('test=583551', $requests[2]->getHeader('Cookie')); + // Confirm the redirected request has the cookie. + $this->assertEquals('test=583551', $requests[1]->getHeader('Cookie')); + } + + public function testCookiesAreNotAddedWhenParamIsSet() + { + $jar = new ArrayCookieJar(); + $plugin = new CookiePlugin($jar); + + $jar->add(new Cookie(array( + 'domain' => 'example.com', + 'path' => '/', + 'name' => 'test', + 'value' => 'hi', + 'expires' => time() + 3600 + ))); + + $client = new Client('http://example.com'); + $client->getEventDispatcher()->addSubscriber($plugin); + + // Ensure that it is normally added + $request = $client->get(); + $request->setResponse(new Response(200), true); + $request->send(); + $this->assertEquals('hi', $request->getCookie('test')); + + // Now ensure that it is not added + $request = $client->get(); + $request->getParams()->set('cookies.disable', true); + $request->setResponse(new Response(200), true); + $request->send(); + $this->assertNull($request->getCookie('test')); + } + + public function testProvidesCookieJar() + { + $jar = new ArrayCookieJar(); + $plugin = new CookiePlugin($jar); + $this->assertSame($jar, $plugin->getCookieJar()); + } + + public function testEscapesCookieDomains() + { + $cookie = new Cookie(array('domain' => '/foo/^$[A-Z]+/')); + $this->assertFalse($cookie->matchesDomain('foo')); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cookie/CookieTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cookie/CookieTest.php new file mode 100644 index 000000000..9fb0b4310 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Cookie/CookieTest.php @@ -0,0 +1,223 @@ +assertEquals('/', $cookie->getPath()); + $this->assertEquals(array(), $cookie->getPorts()); + } + + public function testConvertsDateTimeMaxAgeToUnixTimestamp() + { + $cookie = new Cookie(array( + 'expires' => 'November 20, 1984' + )); + $this->assertTrue(is_numeric($cookie->getExpires())); + } + + public function testAddsExpiresBasedOnMaxAge() + { + $t = time(); + $cookie = new Cookie(array( + 'max_age' => 100 + )); + $this->assertEquals($t + 100, $cookie->getExpires()); + } + + public function testHoldsValues() + { + $t = time(); + $data = array( + 'name' => 'foo', + 'value' => 'baz', + 'path' => '/bar', + 'domain' => 'baz.com', + 'expires' => $t, + 'max_age' => 100, + 'comment' => 'Hi', + 'comment_url' => 'foo.com', + 'port' => array(1, 2), + 'version' => 2, + 'secure' => true, + 'discard' => true, + 'http_only' => true, + 'data' => array( + 'foo' => 'baz', + 'bar' => 'bam' + ) + ); + + $cookie = new Cookie($data); + $this->assertEquals($data, $cookie->toArray()); + + $this->assertEquals('foo', $cookie->getName()); + $this->assertEquals('baz', $cookie->getValue()); + $this->assertEquals('baz.com', $cookie->getDomain()); + $this->assertEquals('/bar', $cookie->getPath()); + $this->assertEquals($t, $cookie->getExpires()); + $this->assertEquals(100, $cookie->getMaxAge()); + $this->assertEquals('Hi', $cookie->getComment()); + $this->assertEquals('foo.com', $cookie->getCommentUrl()); + $this->assertEquals(array(1, 2), $cookie->getPorts()); + $this->assertEquals(2, $cookie->getVersion()); + $this->assertTrue($cookie->getSecure()); + $this->assertTrue($cookie->getDiscard()); + $this->assertTrue($cookie->getHttpOnly()); + $this->assertEquals('baz', $cookie->getAttribute('foo')); + $this->assertEquals('bam', $cookie->getAttribute('bar')); + $this->assertEquals(array( + 'foo' => 'baz', + 'bar' => 'bam' + ), $cookie->getAttributes()); + + $cookie->setName('a') + ->setValue('b') + ->setPath('c') + ->setDomain('bar.com') + ->setExpires(10) + ->setMaxAge(200) + ->setComment('e') + ->setCommentUrl('f') + ->setPorts(array(80)) + ->setVersion(3) + ->setSecure(false) + ->setHttpOnly(false) + ->setDiscard(false) + ->setAttribute('snoop', 'dog'); + + $this->assertEquals('a', $cookie->getName()); + $this->assertEquals('b', $cookie->getValue()); + $this->assertEquals('c', $cookie->getPath()); + $this->assertEquals('bar.com', $cookie->getDomain()); + $this->assertEquals(10, $cookie->getExpires()); + $this->assertEquals(200, $cookie->getMaxAge()); + $this->assertEquals('e', $cookie->getComment()); + $this->assertEquals('f', $cookie->getCommentUrl()); + $this->assertEquals(array(80), $cookie->getPorts()); + $this->assertEquals(3, $cookie->getVersion()); + $this->assertFalse($cookie->getSecure()); + $this->assertFalse($cookie->getDiscard()); + $this->assertFalse($cookie->getHttpOnly()); + $this->assertEquals('dog', $cookie->getAttribute('snoop')); + } + + public function testDeterminesIfExpired() + { + $c = new Cookie(); + $c->setExpires(10); + $this->assertTrue($c->isExpired()); + $c->setExpires(time() + 10000); + $this->assertFalse($c->isExpired()); + } + + public function testMatchesPorts() + { + $cookie = new Cookie(); + // Always matches when nothing is set + $this->assertTrue($cookie->matchesPort(2)); + + $cookie->setPorts(array(1, 2)); + $this->assertTrue($cookie->matchesPort(2)); + $this->assertFalse($cookie->matchesPort(100)); + } + + public function testMatchesDomain() + { + $cookie = new Cookie(); + $this->assertTrue($cookie->matchesDomain('baz.com')); + + $cookie->setDomain('baz.com'); + $this->assertTrue($cookie->matchesDomain('baz.com')); + $this->assertFalse($cookie->matchesDomain('bar.com')); + + $cookie->setDomain('.baz.com'); + $this->assertTrue($cookie->matchesDomain('.baz.com')); + $this->assertTrue($cookie->matchesDomain('foo.baz.com')); + $this->assertFalse($cookie->matchesDomain('baz.bar.com')); + $this->assertTrue($cookie->matchesDomain('baz.com')); + + $cookie->setDomain('.127.0.0.1'); + $this->assertTrue($cookie->matchesDomain('127.0.0.1')); + + $cookie->setDomain('127.0.0.1'); + $this->assertTrue($cookie->matchesDomain('127.0.0.1')); + + $cookie->setDomain('.com.'); + $this->assertFalse($cookie->matchesDomain('baz.com')); + + $cookie->setDomain('.local'); + $this->assertTrue($cookie->matchesDomain('example.local')); + } + + public function testMatchesPath() + { + $cookie = new Cookie(); + $this->assertTrue($cookie->matchesPath('/foo')); + + $cookie->setPath('/foo'); + + // o The cookie-path and the request-path are identical. + $this->assertTrue($cookie->matchesPath('/foo')); + $this->assertFalse($cookie->matchesPath('/bar')); + + // o The cookie-path is a prefix of the request-path, and the first + // character of the request-path that is not included in the cookie- + // path is a %x2F ("/") character. + $this->assertTrue($cookie->matchesPath('/foo/bar')); + $this->assertFalse($cookie->matchesPath('/fooBar')); + + // o The cookie-path is a prefix of the request-path, and the last + // character of the cookie-path is %x2F ("/"). + $cookie->setPath('/foo/'); + $this->assertTrue($cookie->matchesPath('/foo/bar')); + $this->assertFalse($cookie->matchesPath('/fooBaz')); + $this->assertFalse($cookie->matchesPath('/foo')); + + } + + public function cookieValidateProvider() + { + return array( + array('foo', 'baz', 'bar', true), + array('0', '0', '0', true), + array('', 'baz', 'bar', 'The cookie name must not be empty'), + array('foo', '', 'bar', 'The cookie value must not be empty'), + array('foo', 'baz', '', 'The cookie domain must not be empty'), + array('foo\\', 'baz', '0', 'The cookie name must not contain invalid characters: foo\\'), + ); + } + + /** + * @dataProvider cookieValidateProvider + */ + public function testValidatesCookies($name, $value, $domain, $result) + { + $cookie = new Cookie(array( + 'name' => $name, + 'value' => $value, + 'domain' => $domain + )); + $this->assertSame($result, $cookie->validate()); + } + + public function testCreatesInvalidCharacterString() + { + $m = new \ReflectionMethod('Guzzle\Plugin\Cookie\Cookie', 'getInvalidCharacters'); + $m->setAccessible(true); + $p = new \ReflectionProperty('Guzzle\Plugin\Cookie\Cookie', 'invalidCharString'); + $p->setAccessible(true); + $p->setValue(''); + // Expects a string containing 51 invalid characters + $this->assertEquals(51, strlen($m->invoke($m))); + $this->assertContains('@', $m->invoke($m)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/CurlAuth/CurlAuthPluginTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/CurlAuth/CurlAuthPluginTest.php new file mode 100644 index 000000000..2a4b49eb6 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/CurlAuth/CurlAuthPluginTest.php @@ -0,0 +1,39 @@ +getEventDispatcher()->addSubscriber($plugin); + $request = $client->get('/'); + $this->assertEquals('michael', $request->getUsername()); + $this->assertEquals('test', $request->getPassword()); + Version::$emitWarnings = true; + } + + public function testAddsDigestAuthentication() + { + Version::$emitWarnings = false; + $plugin = new CurlAuthPlugin('julian', 'test', CURLAUTH_DIGEST); + $client = new Client('http://www.test.com/'); + $client->getEventDispatcher()->addSubscriber($plugin); + $request = $client->get('/'); + $this->assertEquals('julian', $request->getUsername()); + $this->assertEquals('test', $request->getPassword()); + $this->assertEquals('julian:test', $request->getCurlOptions()->get(CURLOPT_USERPWD)); + $this->assertEquals(CURLAUTH_DIGEST, $request->getCurlOptions()->get(CURLOPT_HTTPAUTH)); + Version::$emitWarnings = true; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/ErrorResponse/ErrorResponsePluginTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/ErrorResponse/ErrorResponsePluginTest.php new file mode 100644 index 000000000..6f94186b5 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/ErrorResponse/ErrorResponsePluginTest.php @@ -0,0 +1,137 @@ +flush(); + } + + public function setUp() + { + $mockError = 'Guzzle\Tests\Mock\ErrorResponseMock'; + $description = ServiceDescription::factory(array( + 'operations' => array( + 'works' => array( + 'httpMethod' => 'GET', + 'errorResponses' => array( + array('code' => 500, 'class' => $mockError), + array('code' => 503, 'reason' => 'foo', 'class' => $mockError), + array('code' => 200, 'reason' => 'Error!', 'class' => $mockError) + ) + ), + 'bad_class' => array( + 'httpMethod' => 'GET', + 'errorResponses' => array( + array('code' => 500, 'class' => 'Does\\Not\\Exist') + ) + ), + 'does_not_implement' => array( + 'httpMethod' => 'GET', + 'errorResponses' => array( + array('code' => 500, 'class' => __CLASS__) + ) + ), + 'no_errors' => array('httpMethod' => 'GET'), + 'no_class' => array( + 'httpMethod' => 'GET', + 'errorResponses' => array( + array('code' => 500) + ) + ), + ) + )); + $this->client = new Client($this->getServer()->getUrl()); + $this->client->setDescription($description); + } + + /** + * @expectedException \Guzzle\Http\Exception\ServerErrorResponseException + */ + public function testSkipsWhenErrorResponsesIsNotSet() + { + $this->getServer()->enqueue("HTTP/1.1 500 Foo\r\nContent-Length: 0\r\n\r\n"); + $this->client->addSubscriber(new ErrorResponsePlugin()); + $this->client->getCommand('no_errors')->execute(); + } + + public function testSkipsWhenErrorResponsesIsNotSetAndAllowsSuccess() + { + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + $this->client->addSubscriber(new ErrorResponsePlugin()); + $this->client->getCommand('no_errors')->execute(); + } + + /** + * @expectedException \Guzzle\Plugin\ErrorResponse\Exception\ErrorResponseException + * @expectedExceptionMessage Does\Not\Exist does not exist + */ + public function testEnsuresErrorResponseExists() + { + $this->getServer()->enqueue("HTTP/1.1 500 Foo\r\nContent-Length: 0\r\n\r\n"); + $this->client->addSubscriber(new ErrorResponsePlugin()); + $this->client->getCommand('bad_class')->execute(); + } + + /** + * @expectedException \Guzzle\Plugin\ErrorResponse\Exception\ErrorResponseException + * @expectedExceptionMessage must implement Guzzle\Plugin\ErrorResponse\ErrorResponseExceptionInterface + */ + public function testEnsuresErrorResponseImplementsInterface() + { + $this->getServer()->enqueue("HTTP/1.1 500 Foo\r\nContent-Length: 0\r\n\r\n"); + $this->client->addSubscriber(new ErrorResponsePlugin()); + $this->client->getCommand('does_not_implement')->execute(); + } + + public function testThrowsSpecificErrorResponseOnMatch() + { + try { + $this->getServer()->enqueue("HTTP/1.1 500 Foo\r\nContent-Length: 0\r\n\r\n"); + $this->client->addSubscriber(new ErrorResponsePlugin()); + $command = $this->client->getCommand('works'); + $command->execute(); + $this->fail('Exception not thrown'); + } catch (ErrorResponseMock $e) { + $this->assertSame($command, $e->command); + $this->assertEquals(500, $e->response->getStatusCode()); + } + } + + /** + * @expectedException \Guzzle\Tests\Mock\ErrorResponseMock + */ + public function testThrowsWhenCodeAndPhraseMatch() + { + $this->getServer()->enqueue("HTTP/1.1 200 Error!\r\nContent-Length: 0\r\n\r\n"); + $this->client->addSubscriber(new ErrorResponsePlugin()); + $this->client->getCommand('works')->execute(); + } + + public function testSkipsWhenReasonDoesNotMatch() + { + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + $this->client->addSubscriber(new ErrorResponsePlugin()); + $this->client->getCommand('works')->execute(); + } + + public function testSkipsWhenNoClassIsSet() + { + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + $this->client->addSubscriber(new ErrorResponsePlugin()); + $this->client->getCommand('no_class')->execute(); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/History/HistoryPluginTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/History/HistoryPluginTest.php new file mode 100644 index 000000000..41aa673fd --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/History/HistoryPluginTest.php @@ -0,0 +1,140 @@ +get(); + $requests[$i]->setResponse(new Response(200), true); + $requests[$i]->send(); + $h->add($requests[$i]); + } + + return $requests; + } + + public function testDescribesSubscribedEvents() + { + $this->assertInternalType('array', HistoryPlugin::getSubscribedEvents()); + } + + public function testMaintainsLimitValue() + { + $h = new HistoryPlugin(); + $this->assertSame($h, $h->setLimit(10)); + $this->assertEquals(10, $h->getLimit()); + } + + public function testAddsRequests() + { + $h = new HistoryPlugin(); + $requests = $this->addRequests($h, 1); + $this->assertEquals(1, count($h)); + $i = $h->getIterator(); + $this->assertEquals(1, count($i)); + $this->assertEquals($requests[0], $i[0]); + } + + /** + * @depends testAddsRequests + */ + public function testMaintainsLimit() + { + $h = new HistoryPlugin(); + $h->setLimit(2); + $requests = $this->addRequests($h, 3); + $this->assertEquals(2, count($h)); + $i = 0; + foreach ($h as $request) { + if ($i > 0) { + $this->assertSame($requests[$i], $request); + } + } + } + + public function testReturnsLastRequest() + { + $h = new HistoryPlugin(); + $requests = $this->addRequests($h, 5); + $this->assertSame(end($requests), $h->getLastRequest()); + } + + public function testReturnsLastResponse() + { + $h = new HistoryPlugin(); + $requests = $this->addRequests($h, 5); + $this->assertSame(end($requests)->getResponse(), $h->getLastResponse()); + } + + public function testClearsHistory() + { + $h = new HistoryPlugin(); + $requests = $this->addRequests($h, 5); + $this->assertEquals(5, count($h)); + $h->clear(); + $this->assertEquals(0, count($h)); + } + + /** + * @depends testAddsRequests + */ + public function testUpdatesAddRequests() + { + $h = new HistoryPlugin(); + $client = new Client('http://127.0.0.1/'); + $client->getEventDispatcher()->addSubscriber($h); + + $request = $client->get(); + $request->setResponse(new Response(200), true); + $request->send(); + + $this->assertSame($request, $h->getLastRequest()); + } + + public function testCanCastToString() + { + $client = new Client('http://127.0.0.1/'); + $h = new HistoryPlugin(); + $client->getEventDispatcher()->addSubscriber($h); + + $mock = new MockPlugin(array( + new Response(301, array('Location' => '/redirect1', 'Content-Length' => 0)), + new Response(307, array('Location' => '/redirect2', 'Content-Length' => 0)), + new Response(200, array('Content-Length' => '2'), 'HI') + )); + + $client->getEventDispatcher()->addSubscriber($mock); + $request = $client->get(); + $request->send(); + $this->assertEquals(3, count($h)); + $this->assertEquals(3, count($mock->getReceivedRequests())); + + $h = str_replace("\r", '', $h); + $this->assertContains("> GET / HTTP/1.1\nHost: 127.0.0.1\nUser-Agent:", $h); + $this->assertContains("< HTTP/1.1 301 Moved Permanently\nLocation: /redirect1", $h); + $this->assertContains("< HTTP/1.1 307 Temporary Redirect\nLocation: /redirect2", $h); + $this->assertContains("< HTTP/1.1 200 OK\nContent-Length: 2\n\nHI", $h); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Log/LogPluginTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Log/LogPluginTest.php new file mode 100644 index 000000000..ad663a53c --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Log/LogPluginTest.php @@ -0,0 +1,95 @@ +adapter = new ClosureLogAdapter(function ($message) { + echo $message; + }); + } + + public function testIgnoresCurlEventsWhenNotWiringBodies() + { + $p = new LogPlugin($this->adapter); + $this->assertNotEmpty($p->getSubscribedEvents()); + $event = new Event(array('request' => new Request('GET', 'http://foo.com'))); + $p->onCurlRead($event); + $p->onCurlWrite($event); + $p->onRequestBeforeSend($event); + } + + public function testLogsWhenComplete() + { + $output = ''; + $p = new LogPlugin(new ClosureLogAdapter(function ($message) use (&$output) { + $output = $message; + }), '{method} {resource} | {code} {res_body}'); + + $p->onRequestSent(new Event(array( + 'request' => new Request('GET', 'http://foo.com'), + 'response' => new Response(200, array(), 'Foo') + ))); + + $this->assertEquals('GET / | 200 Foo', $output); + } + + public function testWiresBodiesWhenNeeded() + { + $client = new Client($this->getServer()->getUrl()); + $plugin = new LogPlugin($this->adapter, '{req_body} | {res_body}', true); + $client->getEventDispatcher()->addSubscriber($plugin); + $request = $client->put(); + + // Send the response from the dummy server as the request body + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\nsend"); + $stream = fopen($this->getServer()->getUrl(), 'r'); + $request->setBody(EntityBody::factory($stream, 4)); + + $tmpFile = tempnam(sys_get_temp_dir(), 'non_repeatable'); + $request->setResponseBody(EntityBody::factory(fopen($tmpFile, 'w'))); + + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nresponse"); + + ob_start(); + $request->send(); + $message = ob_get_clean(); + + unlink($tmpFile); + $this->assertContains("send", $message); + $this->assertContains("response", $message); + } + + public function testHasHelpfulStaticFactoryMethod() + { + $s = fopen('php://temp', 'r+'); + $client = new Client(); + $client->addSubscriber(LogPlugin::getDebugPlugin(true, $s)); + $request = $client->put('http://foo.com', array('Content-Type' => 'Foo'), 'Bar'); + $request->setresponse(new Response(200), true); + $request->send(); + rewind($s); + $contents = stream_get_contents($s); + $this->assertContains('# Request:', $contents); + $this->assertContainsIns('PUT / HTTP/1.1', $contents); + $this->assertContains('# Response:', $contents); + $this->assertContainsIns('HTTP/1.1 200 OK', $contents); + $this->assertContains('# Errors:', $contents); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Md5/CommandContentMd5PluginTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Md5/CommandContentMd5PluginTest.php new file mode 100644 index 000000000..4bd411113 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Md5/CommandContentMd5PluginTest.php @@ -0,0 +1,97 @@ + array( + 'test' => array( + 'httpMethod' => 'PUT', + 'parameters' => array( + 'ContentMD5' => array(), + 'Body' => array( + 'location' => 'body' + ) + ) + ) + ) + )); + + $client = new Client(); + $client->setDescription($description); + + return $client; + } + + public function testHasEvents() + { + $this->assertNotEmpty(CommandContentMd5Plugin::getSubscribedEvents()); + } + + public function testValidatesMd5WhenParamExists() + { + $client = $this->getClient(); + $command = $client->getCommand('test', array( + 'Body' => 'Foo', + 'ContentMD5' => true + )); + $event = new Event(array('command' => $command)); + $request = $command->prepare(); + $plugin = new CommandContentMd5Plugin(); + $plugin->onCommandBeforeSend($event); + $this->assertEquals('E1bGfXrRY42Ba/uCLdLCXQ==', (string) $request->getHeader('Content-MD5')); + } + + public function testDoesNothingWhenNoPayloadExists() + { + $client = $this->getClient(); + $client->getDescription()->getOperation('test')->setHttpMethod('GET'); + $command = $client->getCommand('test'); + $event = new Event(array('command' => $command)); + $request = $command->prepare(); + $plugin = new CommandContentMd5Plugin(); + $plugin->onCommandBeforeSend($event); + $this->assertNull($request->getHeader('Content-MD5')); + } + + public function testAddsValidationToResponsesOfContentMd5() + { + $client = $this->getClient(); + $client->getDescription()->getOperation('test')->setHttpMethod('GET'); + $command = $client->getCommand('test', array( + 'ValidateMD5' => true + )); + $event = new Event(array('command' => $command)); + $request = $command->prepare(); + $plugin = new CommandContentMd5Plugin(); + $plugin->onCommandBeforeSend($event); + $listeners = $request->getEventDispatcher()->getListeners('request.complete'); + $this->assertNotEmpty($listeners); + } + + public function testIgnoresValidationWhenDisabled() + { + $client = $this->getClient(); + $client->getDescription()->getOperation('test')->setHttpMethod('GET'); + $command = $client->getCommand('test', array( + 'ValidateMD5' => false + )); + $event = new Event(array('command' => $command)); + $request = $command->prepare(); + $plugin = new CommandContentMd5Plugin(); + $plugin->onCommandBeforeSend($event); + $listeners = $request->getEventDispatcher()->getListeners('request.complete'); + $this->assertEmpty($listeners); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Md5/Md5ValidatorPluginTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Md5/Md5ValidatorPluginTest.php new file mode 100644 index 000000000..482e92b28 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Md5/Md5ValidatorPluginTest.php @@ -0,0 +1,120 @@ +create('GET', 'http://www.test.com/'); + $request->getEventDispatcher()->addSubscriber($plugin); + + $body = 'abc'; + $hash = md5($body); + $response = new Response(200, array( + 'Content-MD5' => $hash, + 'Content-Length' => 3 + ), 'abc'); + + $request->dispatch('request.complete', array( + 'response' => $response + )); + + // Try again with no Content-MD5 + $response->removeHeader('Content-MD5'); + $request->dispatch('request.complete', array( + 'response' => $response + )); + } + + /** + * @expectedException UnexpectedValueException + */ + public function testThrowsExceptionOnInvalidMd5() + { + $plugin = new Md5ValidatorPlugin(); + $request = RequestFactory::getInstance()->create('GET', 'http://www.test.com/'); + $request->getEventDispatcher()->addSubscriber($plugin); + + $request->dispatch('request.complete', array( + 'response' => new Response(200, array( + 'Content-MD5' => 'foobar', + 'Content-Length' => 3 + ), 'abc') + )); + } + + public function testSkipsWhenContentLengthIsTooLarge() + { + $plugin = new Md5ValidatorPlugin(false, 1); + $request = RequestFactory::getInstance()->create('GET', 'http://www.test.com/'); + $request->getEventDispatcher()->addSubscriber($plugin); + + $request->dispatch('request.complete', array( + 'response' => new Response(200, array( + 'Content-MD5' => 'foobar', + 'Content-Length' => 3 + ), 'abc') + )); + } + + public function testProperlyValidatesWhenUsingContentEncoding() + { + $plugin = new Md5ValidatorPlugin(true); + $request = RequestFactory::getInstance()->create('GET', 'http://www.test.com/'); + $request->getEventDispatcher()->addSubscriber($plugin); + + // Content-MD5 is the MD5 hash of the canonical content after all + // content-encoding has been applied. Because cURL will automatically + // decompress entity bodies, we need to re-compress it to calculate. + $body = EntityBody::factory('abc'); + $body->compress(); + $hash = $body->getContentMd5(); + $body->uncompress(); + + $response = new Response(200, array( + 'Content-MD5' => $hash, + 'Content-Encoding' => 'gzip' + ), 'abc'); + $request->dispatch('request.complete', array( + 'response' => $response + )); + $this->assertEquals('abc', $response->getBody(true)); + + // Try again with an unknown encoding + $response = new Response(200, array( + 'Content-MD5' => $hash, + 'Content-Encoding' => 'foobar' + ), 'abc'); + $request->dispatch('request.complete', array( + 'response' => $response + )); + + // Try again with compress + $body->compress('bzip2.compress'); + $response = new Response(200, array( + 'Content-MD5' => $body->getContentMd5(), + 'Content-Encoding' => 'compress' + ), 'abc'); + $request->dispatch('request.complete', array( + 'response' => $response + )); + + // Try again with encoding and disabled content-encoding checks + $request->getEventDispatcher()->removeSubscriber($plugin); + $plugin = new Md5ValidatorPlugin(false); + $request->getEventDispatcher()->addSubscriber($plugin); + $request->dispatch('request.complete', array( + 'response' => $response + )); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Mock/MockPluginTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Mock/MockPluginTest.php new file mode 100644 index 000000000..3af8fefcc --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Mock/MockPluginTest.php @@ -0,0 +1,199 @@ +assertInternalType('array', MockPlugin::getSubscribedEvents()); + } + + public function testDescribesEvents() + { + $this->assertInternalType('array', MockPlugin::getAllEvents()); + } + + public function testCanBeTemporary() + { + $plugin = new MockPlugin(); + $this->assertFalse($plugin->isTemporary()); + $plugin = new MockPlugin(null, true); + $this->assertTrue($plugin->isTemporary()); + } + + public function testIsCountable() + { + $plugin = new MockPlugin(); + $plugin->addResponse(Response::fromMessage("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")); + $this->assertEquals(1, count($plugin)); + } + + /** + * @depends testIsCountable + */ + public function testCanClearQueue() + { + $plugin = new MockPlugin(); + $plugin->addResponse(Response::fromMessage("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")); + $plugin->clearQueue(); + $this->assertEquals(0, count($plugin)); + } + + public function testCanInspectQueue() + { + $plugin = new MockPlugin(); + $this->assertInternalType('array', $plugin->getQueue()); + $plugin->addResponse(Response::fromMessage("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")); + $queue = $plugin->getQueue(); + $this->assertInternalType('array', $queue); + $this->assertEquals(1, count($queue)); + } + + public function testRetrievesResponsesFromFiles() + { + $response = MockPlugin::getMockFile(__DIR__ . '/../../TestData/mock_response'); + $this->assertInstanceOf('Guzzle\\Http\\Message\\Response', $response); + $this->assertEquals(200, $response->getStatusCode()); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testThrowsExceptionWhenResponseFileIsNotFound() + { + MockPlugin::getMockFile('missing/filename'); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testInvalidResponsesThrowAnException() + { + $p = new MockPlugin(); + $p->addResponse($this); + } + + public function testAddsResponseObjectsToQueue() + { + $p = new MockPlugin(); + $response = Response::fromMessage("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + $p->addResponse($response); + $this->assertEquals(array($response), $p->getQueue()); + } + + public function testAddsResponseFilesToQueue() + { + $p = new MockPlugin(); + $p->addResponse(__DIR__ . '/../../TestData/mock_response'); + $this->assertEquals(1, count($p)); + } + + /** + * @depends testAddsResponseFilesToQueue + */ + public function testAddsMockResponseToRequestFromClient() + { + $p = new MockPlugin(); + $response = MockPlugin::getMockFile(__DIR__ . '/../../TestData/mock_response'); + $p->addResponse($response); + + $client = new Client('http://127.0.0.1:123/'); + $client->getEventDispatcher()->addSubscriber($p, 9999); + $request = $client->get(); + $request->send(); + + $this->assertSame($response, $request->getResponse()); + $this->assertEquals(0, count($p)); + } + + /** + * @depends testAddsResponseFilesToQueue + * @expectedException \OutOfBoundsException + */ + public function testUpdateThrowsExceptionWhenEmpty() + { + $p = new MockPlugin(); + $p->onRequestBeforeSend(new Event()); + } + + /** + * @depends testAddsMockResponseToRequestFromClient + */ + public function testDetachesTemporaryWhenEmpty() + { + $p = new MockPlugin(null, true); + $p->addResponse(MockPlugin::getMockFile(__DIR__ . '/../../TestData/mock_response')); + $client = new Client('http://127.0.0.1:123/'); + $client->getEventDispatcher()->addSubscriber($p, 9999); + $request = $client->get(); + $request->send(); + + $this->assertFalse($this->hasSubscriber($client, $p)); + } + + public function testLoadsResponsesFromConstructor() + { + $p = new MockPlugin(array(new Response(200))); + $this->assertEquals(1, $p->count()); + } + + public function testStoresMockedRequests() + { + $p = new MockPlugin(array(new Response(200), new Response(200))); + $client = new Client('http://127.0.0.1:123/'); + $client->getEventDispatcher()->addSubscriber($p, 9999); + + $request1 = $client->get(); + $request1->send(); + $this->assertEquals(array($request1), $p->getReceivedRequests()); + + $request2 = $client->get(); + $request2->send(); + $this->assertEquals(array($request1, $request2), $p->getReceivedRequests()); + + $p->flush(); + $this->assertEquals(array(), $p->getReceivedRequests()); + } + + public function testReadsBodiesFromMockedRequests() + { + $p = new MockPlugin(array(new Response(200))); + $p->readBodies(true); + $client = new Client('http://127.0.0.1:123/'); + $client->getEventDispatcher()->addSubscriber($p, 9999); + + $body = EntityBody::factory('foo'); + $request = $client->put(); + $request->setBody($body); + $request->send(); + $this->assertEquals(3, $body->ftell()); + } + + public function testCanMockBadRequestExceptions() + { + $client = new Client('http://127.0.0.1:123/'); + $ex = new CurlException('Foo'); + $mock = new MockPlugin(array($ex)); + $client->addSubscriber($mock); + $request = $client->get('foo'); + + try { + $request->send(); + $this->fail('Did not dequeue an exception'); + } catch (CurlException $e) { + $this->assertSame($e, $ex); + $this->assertSame($request, $ex->getRequest()); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Oauth/OauthPluginTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Oauth/OauthPluginTest.php new file mode 100644 index 000000000..3892fb62b --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Plugin/Oauth/OauthPluginTest.php @@ -0,0 +1,345 @@ + 'foo', + 'consumer_secret' => 'bar', + 'token' => 'count', + 'token_secret' => 'dracula' + ); + + protected function getRequest() + { + return RequestFactory::getInstance()->create('POST', 'http://www.test.com/path?a=b&c=d', null, array( + 'e' => 'f' + )); + } + + public function testSubscribesToEvents() + { + $events = OauthPlugin::getSubscribedEvents(); + $this->assertArrayHasKey('request.before_send', $events); + } + + public function testAcceptsConfigurationData() + { + $p = new OauthPlugin($this->config); + + // Access the config object + $class = new \ReflectionClass($p); + $property = $class->getProperty('config'); + $property->setAccessible(true); + $config = $property->getValue($p); + + $this->assertEquals('foo', $config['consumer_key']); + $this->assertEquals('bar', $config['consumer_secret']); + $this->assertEquals('count', $config['token']); + $this->assertEquals('dracula', $config['token_secret']); + $this->assertEquals('1.0', $config['version']); + $this->assertEquals('HMAC-SHA1', $config['signature_method']); + $this->assertEquals('header', $config['request_method']); + } + + public function testCreatesStringToSignFromPostRequest() + { + $p = new OauthPlugin($this->config); + $request = $this->getRequest(); + $signString = $p->getStringToSign($request, self::TIMESTAMP, self::NONCE); + + $this->assertContains('&e=f', rawurldecode($signString)); + + $expectedSignString = + // Method and URL + 'POST&http%3A%2F%2Fwww.test.com%2Fpath' . + // Sorted parameters from query string and body + '&a%3Db%26c%3Dd%26e%3Df%26oauth_consumer_key%3Dfoo' . + '%26oauth_nonce%3De7aa11195ca58349bec8b5ebe351d3497eb9e603%26' . + 'oauth_signature_method%3DHMAC-SHA1' . + '%26oauth_timestamp%3D' . self::TIMESTAMP . '%26oauth_token%3Dcount%26oauth_version%3D1.0'; + + $this->assertEquals($expectedSignString, $signString); + } + + public function testCreatesStringToSignIgnoringPostFields() + { + $config = $this->config; + $config['disable_post_params'] = true; + $p = new OauthPlugin($config); + $request = $this->getRequest(); + $sts = rawurldecode($p->getStringToSign($request, self::TIMESTAMP, self::NONCE)); + $this->assertNotContains('&e=f', $sts); + } + + public function testCreatesStringToSignFromPostRequestWithCustomContentType() + { + $p = new OauthPlugin($this->config); + $request = $this->getRequest(); + $request->setHeader('Content-Type', 'Foo'); + $this->assertEquals( + // Method and URL + 'POST&http%3A%2F%2Fwww.test.com%2Fpath' . + // Sorted parameters from query string and body + '&a%3Db%26c%3Dd%26oauth_consumer_key%3Dfoo' . + '%26oauth_nonce%3D'. self::NONCE .'%26' . + 'oauth_signature_method%3DHMAC-SHA1' . + '%26oauth_timestamp%3D' . self::TIMESTAMP . '%26oauth_token%3Dcount%26oauth_version%3D1.0', + $p->getStringToSign($request, self::TIMESTAMP, self::NONCE) + ); + } + + /** + * @depends testCreatesStringToSignFromPostRequest + */ + public function testConvertsBooleansToStrings() + { + $p = new OauthPlugin($this->config); + $request = $this->getRequest(); + $request->getQuery()->set('a', true); + $request->getQuery()->set('c', false); + $this->assertContains('&a%3Dtrue%26c%3Dfalse', $p->getStringToSign($request, self::TIMESTAMP, self::NONCE)); + } + + public function testCreatesStringToSignFromPostRequestWithNullValues() + { + $config = array( + 'consumer_key' => 'foo', + 'consumer_secret' => 'bar', + 'token' => null, + 'token_secret' => 'dracula' + ); + + $p = new OauthPlugin($config); + $request = $this->getRequest(); + $signString = $p->getStringToSign($request, self::TIMESTAMP, self::NONCE); + + $this->assertContains('&e=f', rawurldecode($signString)); + + $expectedSignString = // Method and URL + 'POST&http%3A%2F%2Fwww.test.com%2Fpath' . + // Sorted parameters from query string and body + '&a%3Db%26c%3Dd%26e%3Df%26oauth_consumer_key%3Dfoo' . + '%26oauth_nonce%3De7aa11195ca58349bec8b5ebe351d3497eb9e603%26' . + 'oauth_signature_method%3DHMAC-SHA1' . + '%26oauth_timestamp%3D' . self::TIMESTAMP . '%26oauth_version%3D1.0'; + + $this->assertEquals($expectedSignString, $signString); + } + + /** + * @depends testCreatesStringToSignFromPostRequest + */ + public function testMultiDimensionalArray() + { + $p = new OauthPlugin($this->config); + $request = $this->getRequest(); + $request->getQuery()->set('a', array('b' => array('e' => 'f', 'c' => 'd'))); + $this->assertContains('a%255Bb%255D%255Bc%255D%3Dd%26a%255Bb%255D%255Be%255D%3Df%26c%3Dd%26e%3Df%26', $p->getStringToSign($request, self::TIMESTAMP, self::NONCE)); + } + + /** + * @depends testMultiDimensionalArray + */ + public function testMultiDimensionalArrayWithNonDefaultQueryAggregator() + { + $p = new OauthPlugin($this->config); + $request = $this->getRequest(); + $aggregator = new CommaAggregator(); + $query = $request->getQuery()->setAggregator($aggregator) + ->set('g', array('h', 'i', 'j')) + ->set('k', array('l')) + ->set('m', array('n', 'o')); + $this->assertContains('a%3Db%26c%3Dd%26e%3Df%26g%3Dh%2Ci%2Cj%26k%3Dl%26m%3Dn%2Co', $p->getStringToSign($request, self::TIMESTAMP, self::NONCE)); + } + + /** + * @depends testCreatesStringToSignFromPostRequest + */ + public function testSignsStrings() + { + $p = new OauthPlugin(array_merge($this->config, array( + 'signature_callback' => function($string, $key) { + return "_{$string}|{$key}_"; + } + ))); + $request = $this->getRequest(); + $sig = $p->getSignature($request, self::TIMESTAMP, self::NONCE); + $this->assertEquals( + '_POST&http%3A%2F%2Fwww.test.com%2Fpath&a%3Db%26c%3Dd%26e%3Df%26oauth_consumer_key%3Dfoo' . + '%26oauth_nonce%3D'. self::NONCE .'%26oauth_signature_method%3DHMAC-SHA1' . + '%26oauth_timestamp%3D' . self::TIMESTAMP . '%26oauth_token%3Dcount%26oauth_version%3D1.0|' . + 'bar&dracula_', + base64_decode($sig) + ); + } + + /** + * Test that the Oauth is signed correctly and that extra strings haven't been added + * to the authorization header. + */ + public function testSignsOauthRequests() + { + $p = new OauthPlugin($this->config); + $event = new Event(array( + 'request' => $this->getRequest(), + 'timestamp' => self::TIMESTAMP + )); + $params = $p->onRequestBeforeSend($event); + + $this->assertTrue($event['request']->hasHeader('Authorization')); + + $authorizationHeader = (string)$event['request']->getHeader('Authorization'); + + $this->assertStringStartsWith('OAuth ', $authorizationHeader); + + $stringsToCheck = array( + 'oauth_consumer_key="foo"', + 'oauth_nonce="'.urlencode($params['oauth_nonce']).'"', + 'oauth_signature="'.urlencode($params['oauth_signature']).'"', + 'oauth_signature_method="HMAC-SHA1"', + 'oauth_timestamp="' . self::TIMESTAMP . '"', + 'oauth_token="count"', + 'oauth_version="1.0"', + ); + + $totalLength = strlen('OAuth '); + + //Separator is not used before first parameter. + $separator = ''; + + foreach ($stringsToCheck as $stringToCheck) { + $this->assertContains($stringToCheck, $authorizationHeader); + $totalLength += strlen($separator); + $totalLength += strlen($stringToCheck); + $separator = ', '; + } + + // Technically this test is not universally valid. It would be allowable to have extra \n characters + // in the Authorization header. However Guzzle does not do this, so we just perform a simple check + // on length to validate the Authorization header is composed of only the strings above. + $this->assertEquals($totalLength, strlen($authorizationHeader), 'Authorization has extra characters i.e. contains extra elements compared to stringsToCheck.'); + } + + public function testSignsOauthQueryStringRequest() + { + $config = array_merge( + $this->config, + array('request_method' => OauthPlugin::REQUEST_METHOD_QUERY) + ); + + $p = new OauthPlugin($config); + $event = new Event(array( + 'request' => $this->getRequest(), + 'timestamp' => self::TIMESTAMP + )); + $params = $p->onRequestBeforeSend($event); + + $this->assertFalse($event['request']->hasHeader('Authorization')); + + $stringsToCheck = array( + 'a=b', + 'c=d', + 'oauth_consumer_key=foo', + 'oauth_nonce='.urlencode($params['oauth_nonce']), + 'oauth_signature='.urlencode($params['oauth_signature']), + 'oauth_signature_method=HMAC-SHA1', + 'oauth_timestamp='.self::TIMESTAMP, + 'oauth_token=count', + 'oauth_version=1.0', + ); + + $queryString = (string) $event['request']->getQuery(); + + $totalLength = strlen('?'); + + //Separator is not used before first parameter. + $separator = ''; + + foreach ($stringsToCheck as $stringToCheck) { + $this->assertContains($stringToCheck, $queryString); + $totalLength += strlen($separator); + $totalLength += strlen($stringToCheck); + $separator = '&'; + } + + // Removes the last query string separator '&' + $totalLength -= 1; + + $this->assertEquals($totalLength, strlen($queryString), 'Query string has extra characters i.e. contains extra elements compared to stringsToCheck.'); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testInvalidArgumentExceptionOnMethodError() + { + $config = array_merge( + $this->config, + array('request_method' => 'FakeMethod') + ); + + $p = new OauthPlugin($config); + $event = new Event(array( + 'request' => $this->getRequest(), + 'timestamp' => self::TIMESTAMP + )); + + $p->onRequestBeforeSend($event); + } + + public function testDoesNotAddFalseyValuesToAuthorization() + { + unset($this->config['token']); + $p = new OauthPlugin($this->config); + $event = new Event(array('request' => $this->getRequest(), 'timestamp' => self::TIMESTAMP)); + $p->onRequestBeforeSend($event); + $this->assertTrue($event['request']->hasHeader('Authorization')); + $this->assertNotContains('oauth_token=', (string) $event['request']->getHeader('Authorization')); + } + + public function testOptionalOauthParametersAreNotAutomaticallyAdded() + { + // The only required Oauth parameters are the consumer key and secret. That is enough credentials + // for signing oauth requests. + $config = array( + 'consumer_key' => 'foo', + 'consumer_secret' => 'bar', + ); + + $plugin = new OauthPlugin($config); + $event = new Event(array( + 'request' => $this->getRequest(), + 'timestamp' => self::TIMESTAMP + )); + + $timestamp = $plugin->getTimestamp($event); + $request = $event['request']; + $nonce = $plugin->generateNonce($request); + + $paramsToSign = $plugin->getParamsToSign($request, $timestamp, $nonce); + + $optionalParams = array( + 'callback' => 'oauth_callback', + 'token' => 'oauth_token', + 'verifier' => 'oauth_verifier', + 'token_secret' => 'token_secret' + ); + + foreach ($optionalParams as $optionName => $oauthName) { + $this->assertArrayNotHasKey($oauthName, $paramsToSign, "Optional Oauth param '$oauthName' was not set via config variable '$optionName', but it is listed in getParamsToSign()."); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/AbstractConfigLoaderTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/AbstractConfigLoaderTest.php new file mode 100644 index 000000000..8b42fb839 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/AbstractConfigLoaderTest.php @@ -0,0 +1,149 @@ +loader = $this->getMockBuilder('Guzzle\Service\AbstractConfigLoader') + ->setMethods(array('build')) + ->getMockForAbstractClass(); + } + + public function tearDown() + { + foreach ($this->cleanup as $file) { + unlink($file); + } + } + + /** + * @expectedException \Guzzle\Common\Exception\InvalidArgumentException + */ + public function testOnlyLoadsSupportedTypes() + { + $this->loader->load(new \stdClass()); + } + + /** + * @expectedException \Guzzle\Common\Exception\InvalidArgumentException + * @expectedExceptionMessage Unable to open fooooooo.json + */ + public function testFileMustBeReadable() + { + $this->loader->load('fooooooo.json'); + } + + /** + * @expectedException \Guzzle\Common\Exception\InvalidArgumentException + * @expectedExceptionMessage Unknown file extension + */ + public function testMustBeSupportedExtension() + { + $this->loader->load(dirname(__DIR__) . '/TestData/FileBody.txt'); + } + + /** + * @expectedException \Guzzle\Common\Exception\RuntimeException + * @expectedExceptionMessage Error loading JSON data from + */ + public function testJsonMustBeValue() + { + $filename = tempnam(sys_get_temp_dir(), 'json') . '.json'; + file_put_contents($filename, '{/{./{}foo'); + $this->cleanup[] = $filename; + $this->loader->load($filename); + } + + /** + * @expectedException \Guzzle\Common\Exception\InvalidArgumentException + * @expectedExceptionMessage PHP files must return an array + */ + public function testPhpFilesMustReturnAnArray() + { + $filename = tempnam(sys_get_temp_dir(), 'php') . '.php'; + file_put_contents($filename, 'cleanup[] = $filename; + $this->loader->load($filename); + } + + public function testLoadsPhpFileIncludes() + { + $filename = tempnam(sys_get_temp_dir(), 'php') . '.php'; + file_put_contents($filename, ' "bar");'); + $this->cleanup[] = $filename; + $this->loader->expects($this->exactly(1))->method('build')->will($this->returnArgument(0)); + $config = $this->loader->load($filename); + $this->assertEquals(array('foo' => 'bar'), $config); + } + + public function testCanCreateFromJson() + { + $file = dirname(__DIR__) . '/TestData/services/json1.json'; + // The build method will just return the config data + $this->loader->expects($this->exactly(1))->method('build')->will($this->returnArgument(0)); + $data = $this->loader->load($file); + // Ensure that the config files were merged using the includes directives + $this->assertArrayHasKey('includes', $data); + $this->assertArrayHasKey('services', $data); + $this->assertInternalType('array', $data['services']['foo']); + $this->assertInternalType('array', $data['services']['abstract']); + $this->assertInternalType('array', $data['services']['mock']); + $this->assertEquals('bar', $data['services']['foo']['params']['baz']); + } + + public function testUsesAliases() + { + $file = dirname(__DIR__) . '/TestData/services/json1.json'; + $this->loader->addAlias('foo', $file); + // The build method will just return the config data + $this->loader->expects($this->exactly(1))->method('build')->will($this->returnArgument(0)); + $data = $this->loader->load('foo'); + $this->assertEquals('bar', $data['services']['foo']['params']['baz']); + } + + /** + * @expectedException \Guzzle\Common\Exception\InvalidArgumentException + * @expectedExceptionMessage Unable to open foo.json + */ + public function testCanRemoveAliases() + { + $file = dirname(__DIR__) . '/TestData/services/json1.json'; + $this->loader->addAlias('foo.json', $file); + $this->loader->removeAlias('foo.json'); + $this->loader->load('foo.json'); + } + + public function testCanLoadArraysWithIncludes() + { + $file = dirname(__DIR__) . '/TestData/services/json1.json'; + $config = array('includes' => array($file)); + // The build method will just return the config data + $this->loader->expects($this->exactly(1))->method('build')->will($this->returnArgument(0)); + $data = $this->loader->load($config); + $this->assertEquals('bar', $data['services']['foo']['params']['baz']); + } + + public function testDoesNotEnterInfiniteLoop() + { + $prefix = $file = dirname(__DIR__) . '/TestData/description'; + $this->loader->load("{$prefix}/baz.json"); + $this->assertCount(4, $this->readAttribute($this->loader, 'loadedFiles')); + // Ensure that the internal list of loaded files is reset + $this->loader->load("{$prefix}/../test_service2.json"); + $this->assertCount(1, $this->readAttribute($this->loader, 'loadedFiles')); + // Ensure that previously loaded files will be reloaded when starting fresh + $this->loader->load("{$prefix}/baz.json"); + $this->assertCount(4, $this->readAttribute($this->loader, 'loadedFiles')); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Builder/ServiceBuilderLoaderTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Builder/ServiceBuilderLoaderTest.php new file mode 100644 index 000000000..f63070e38 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Builder/ServiceBuilderLoaderTest.php @@ -0,0 +1,177 @@ + array( + 'abstract' => array( + 'params' => array( + 'access_key' => 'xyz', + 'secret' => 'abc', + ), + ), + 'foo' => array( + 'extends' => 'abstract', + 'params' => array( + 'baz' => 'bar', + ), + ), + 'mock' => array( + 'extends' => 'abstract', + 'params' => array( + 'username' => 'foo', + 'password' => 'baz', + 'subdomain' => 'bar', + ) + ) + ) + ); + + $builder = $arrayFactory->load($data); + + // Ensure that services were parsed + $this->assertTrue(isset($builder['mock'])); + $this->assertTrue(isset($builder['abstract'])); + $this->assertTrue(isset($builder['foo'])); + $this->assertFalse(isset($builder['jimmy'])); + } + + /** + * @expectedException Guzzle\Service\Exception\ServiceNotFoundException + * @expectedExceptionMessage foo is trying to extend a non-existent service: abstract + */ + public function testThrowsExceptionWhenExtendingNonExistentService() + { + $arrayFactory = new ServiceBuilderLoader(); + + $data = array( + 'services' => array( + 'foo' => array( + 'extends' => 'abstract' + ) + ) + ); + + $builder = $arrayFactory->load($data); + } + + public function testAllowsGlobalParameterOverrides() + { + $arrayFactory = new ServiceBuilderLoader(); + + $data = array( + 'services' => array( + 'foo' => array( + 'params' => array( + 'foo' => 'baz', + 'bar' => 'boo' + ) + ) + ) + ); + + $builder = $arrayFactory->load($data, array( + 'bar' => 'jar', + 'far' => 'car' + )); + + $compiled = json_decode($builder->serialize(), true); + $this->assertEquals(array( + 'foo' => 'baz', + 'bar' => 'jar', + 'far' => 'car' + ), $compiled['foo']['params']); + } + + public function tstDoesNotErrorOnCircularReferences() + { + $arrayFactory = new ServiceBuilderLoader(); + $arrayFactory->load(array( + 'services' => array( + 'too' => array('extends' => 'ball'), + 'ball' => array('extends' => 'too'), + ) + )); + } + + public function configProvider() + { + $foo = array( + 'extends' => 'bar', + 'class' => 'stdClass', + 'params' => array('a' => 'test', 'b' => '456') + ); + + return array( + array( + // Does not extend the existing `foo` service but overwrites it + array( + 'services' => array( + 'foo' => $foo, + 'bar' => array('params' => array('baz' => '123')) + ) + ), + array( + 'services' => array( + 'foo' => array('class' => 'Baz') + ) + ), + array( + 'services' => array( + 'foo' => array('class' => 'Baz'), + 'bar' => array('params' => array('baz' => '123')) + ) + ) + ), + array( + // Extends the existing `foo` service + array( + 'services' => array( + 'foo' => $foo, + 'bar' => array('params' => array('baz' => '123')) + ) + ), + array( + 'services' => array( + 'foo' => array( + 'extends' => 'foo', + 'params' => array('b' => '123', 'c' => 'def') + ) + ) + ), + array( + 'services' => array( + 'foo' => array( + 'extends' => 'bar', + 'class' => 'stdClass', + 'params' => array('a' => 'test', 'b' => '123', 'c' => 'def') + ), + 'bar' => array('params' => array('baz' => '123')) + ) + ) + ) + ); + } + + /** + * @dataProvider configProvider + */ + public function testCombinesConfigs($a, $b, $c) + { + $l = new ServiceBuilderLoader(); + $m = new \ReflectionMethod($l, 'mergeData'); + $m->setAccessible(true); + $this->assertEquals($c, $m->invoke($l, $a, $b)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Builder/ServiceBuilderTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Builder/ServiceBuilderTest.php new file mode 100644 index 000000000..e1b3a1d49 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Builder/ServiceBuilderTest.php @@ -0,0 +1,317 @@ + array( + 'class' => 'Guzzle\Tests\Service\Mock\MockClient', + 'params' => array( + 'username' => 'michael', + 'password' => 'testing123', + 'subdomain' => 'michael', + ), + ), + 'billy.mock' => array( + 'alias' => 'Hello!', + 'class' => 'Guzzle\Tests\Service\Mock\MockClient', + 'params' => array( + 'username' => 'billy', + 'password' => 'passw0rd', + 'subdomain' => 'billy', + ), + ), + 'billy.testing' => array( + 'extends' => 'billy.mock', + 'params' => array( + 'subdomain' => 'test.billy', + ), + ), + 'missing_params' => array( + 'extends' => 'billy.mock' + ) + ); + + public function testAllowsSerialization() + { + $builder = ServiceBuilder::factory($this->arrayData); + $cached = unserialize(serialize($builder)); + $this->assertEquals($cached, $builder); + } + + public function testDelegatesFactoryMethodToAbstractFactory() + { + $builder = ServiceBuilder::factory($this->arrayData); + $c = $builder->get('michael.mock'); + $this->assertInstanceOf('Guzzle\Tests\Service\Mock\MockClient', $c); + } + + /** + * @expectedException Guzzle\Service\Exception\ServiceNotFoundException + * @expectedExceptionMessage No service is registered as foobar + */ + public function testThrowsExceptionWhenGettingInvalidClient() + { + ServiceBuilder::factory($this->arrayData)->get('foobar'); + } + + public function testStoresClientCopy() + { + $builder = ServiceBuilder::factory($this->arrayData); + $client = $builder->get('michael.mock'); + $this->assertInstanceOf('Guzzle\Tests\Service\Mock\MockClient', $client); + $this->assertEquals('http://127.0.0.1:8124/v1/michael', $client->getBaseUrl()); + $this->assertEquals($client, $builder->get('michael.mock')); + + // Get another client but throw this one away + $client2 = $builder->get('billy.mock', true); + $this->assertInstanceOf('Guzzle\Tests\Service\Mock\MockClient', $client2); + $this->assertEquals('http://127.0.0.1:8124/v1/billy', $client2->getBaseUrl()); + + // Make sure the original client is still there and set + $this->assertTrue($client === $builder->get('michael.mock')); + + // Create a new billy.mock client that is stored + $client3 = $builder->get('billy.mock'); + + // Make sure that the stored billy.mock client is equal to the other stored client + $this->assertTrue($client3 === $builder->get('billy.mock')); + + // Make sure that this client is not equal to the previous throwaway client + $this->assertFalse($client2 === $builder->get('billy.mock')); + } + + public function testBuildersPassOptionsThroughToClients() + { + $s = new ServiceBuilder(array( + 'michael.mock' => array( + 'class' => 'Guzzle\Tests\Service\Mock\MockClient', + 'params' => array( + 'base_url' => 'http://www.test.com/', + 'subdomain' => 'michael', + 'password' => 'test', + 'username' => 'michael', + 'curl.curlopt_proxyport' => 8080 + ) + ) + )); + + $c = $s->get('michael.mock'); + $this->assertEquals(8080, $c->getConfig('curl.curlopt_proxyport')); + } + + public function testUsesTheDefaultBuilderWhenNoBuilderIsSpecified() + { + $s = new ServiceBuilder(array( + 'michael.mock' => array( + 'class' => 'Guzzle\Tests\Service\Mock\MockClient', + 'params' => array( + 'base_url' => 'http://www.test.com/', + 'subdomain' => 'michael', + 'password' => 'test', + 'username' => 'michael', + 'curl.curlopt_proxyport' => 8080 + ) + ) + )); + + $c = $s->get('michael.mock'); + $this->assertInstanceOf('Guzzle\Tests\Service\Mock\MockClient', $c); + } + + public function testUsedAsArray() + { + $b = ServiceBuilder::factory($this->arrayData); + $this->assertTrue($b->offsetExists('michael.mock')); + $this->assertFalse($b->offsetExists('not_there')); + $this->assertInstanceOf('Guzzle\Service\Client', $b['michael.mock']); + + unset($b['michael.mock']); + $this->assertFalse($b->offsetExists('michael.mock')); + + $b['michael.mock'] = new Client('http://www.test.com/'); + $this->assertInstanceOf('Guzzle\Service\Client', $b['michael.mock']); + } + + public function testFactoryCanCreateFromJson() + { + $tmp = sys_get_temp_dir() . '/test.js'; + file_put_contents($tmp, json_encode($this->arrayData)); + $b = ServiceBuilder::factory($tmp); + unlink($tmp); + $s = $b->get('billy.testing'); + $this->assertEquals('test.billy', $s->getConfig('subdomain')); + $this->assertEquals('billy', $s->getConfig('username')); + } + + public function testFactoryCanCreateFromArray() + { + $b = ServiceBuilder::factory($this->arrayData); + $s = $b->get('billy.testing'); + $this->assertEquals('test.billy', $s->getConfig('subdomain')); + $this->assertEquals('billy', $s->getConfig('username')); + } + + public function testFactoryDoesNotRequireParams() + { + $b = ServiceBuilder::factory($this->arrayData); + $s = $b->get('missing_params'); + $this->assertEquals('billy', $s->getConfig('username')); + } + + public function testBuilderAllowsReferencesBetweenClients() + { + $builder = ServiceBuilder::factory(array( + 'a' => array( + 'class' => 'Guzzle\Tests\Service\Mock\MockClient', + 'params' => array( + 'other_client' => '{b}', + 'username' => 'x', + 'password' => 'y', + 'subdomain' => 'z' + ) + ), + 'b' => array( + 'class' => 'Guzzle\Tests\Service\Mock\MockClient', + 'params' => array( + 'username' => '1', + 'password' => '2', + 'subdomain' => '3' + ) + ) + )); + + $client = $builder['a']; + $this->assertEquals('x', $client->getConfig('username')); + $this->assertSame($builder['b'], $client->getConfig('other_client')); + $this->assertEquals('1', $builder['b']->getConfig('username')); + } + + public function testEmitsEventsWhenClientsAreCreated() + { + // Ensure that the client signals that it emits an event + $this->assertEquals(array('service_builder.create_client'), ServiceBuilder::getAllEvents()); + + // Create a test service builder + $builder = ServiceBuilder::factory(array( + 'a' => array( + 'class' => 'Guzzle\Tests\Service\Mock\MockClient', + 'params' => array( + 'username' => 'test', + 'password' => '123', + 'subdomain' => 'z' + ) + ) + )); + + // Add an event listener to pick up client creation events + $emits = 0; + $builder->getEventDispatcher()->addListener('service_builder.create_client', function($event) use (&$emits) { + $emits++; + }); + + // Get the 'a' client by name + $client = $builder->get('a'); + + // Ensure that the event was emitted once, and that the client was present + $this->assertEquals(1, $emits); + $this->assertInstanceOf('Guzzle\Tests\Service\Mock\MockClient', $client); + } + + public function testCanAddGlobalParametersToServicesOnLoad() + { + $builder = ServiceBuilder::factory($this->arrayData, array( + 'username' => 'fred', + 'new_value' => 'test' + )); + + $data = json_decode($builder->serialize(), true); + + foreach ($data as $service) { + $this->assertEquals('fred', $service['params']['username']); + $this->assertEquals('test', $service['params']['new_value']); + } + } + + public function testAddsGlobalPlugins() + { + $b = new ServiceBuilder($this->arrayData); + $b->addGlobalPlugin(new HistoryPlugin()); + $s = $b->get('michael.mock'); + $this->assertTrue($s->getEventDispatcher()->hasListeners('request.sent')); + } + + public function testCanGetData() + { + $b = new ServiceBuilder($this->arrayData); + $this->assertEquals($this->arrayData['michael.mock'], $b->getData('michael.mock')); + $this->assertNull($b->getData('ewofweoweofe')); + } + + public function testCanGetByAlias() + { + $b = new ServiceBuilder($this->arrayData); + $this->assertSame($b->get('billy.mock'), $b->get('Hello!')); + } + + public function testCanOverwriteParametersForThrowawayClients() + { + $b = new ServiceBuilder($this->arrayData); + + $c1 = $b->get('michael.mock'); + $this->assertEquals('michael', $c1->getConfig('username')); + + $c2 = $b->get('michael.mock', array('username' => 'jeremy')); + $this->assertEquals('jeremy', $c2->getConfig('username')); + } + + public function testGettingAThrowawayClientWithParametersDoesNotAffectGettingOtherClients() + { + $b = new ServiceBuilder($this->arrayData); + + $c1 = $b->get('michael.mock', array('username' => 'jeremy')); + $this->assertEquals('jeremy', $c1->getConfig('username')); + + $c2 = $b->get('michael.mock'); + $this->assertEquals('michael', $c2->getConfig('username')); + } + + public function testCanUseArbitraryData() + { + $b = new ServiceBuilder(); + $b['a'] = 'foo'; + $this->assertTrue(isset($b['a'])); + $this->assertEquals('foo', $b['a']); + unset($b['a']); + $this->assertFalse(isset($b['a'])); + } + + public function testCanRegisterServiceData() + { + $b = new ServiceBuilder(); + $b['a'] = array( + 'class' => 'Guzzle\Tests\Service\Mock\MockClient', + 'params' => array( + 'username' => 'billy', + 'password' => 'passw0rd', + 'subdomain' => 'billy', + ) + ); + $this->assertTrue(isset($b['a'])); + $this->assertInstanceOf('Guzzle\Tests\Service\Mock\MockClient', $b['a']); + $client = $b['a']; + unset($b['a']); + $this->assertFalse(isset($b['a'])); + // Ensure that instantiated clients can be registered + $b['mock'] = $client; + $this->assertSame($client, $b['mock']); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/CachingConfigLoaderTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/CachingConfigLoaderTest.php new file mode 100644 index 000000000..b8245ad58 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/CachingConfigLoaderTest.php @@ -0,0 +1,43 @@ +getMockBuilder('Guzzle\Service\ConfigLoaderInterface') + ->setMethods(array('load')) + ->getMockForAbstractClass(); + $data = array('foo' => 'bar'); + $loader->expects($this->once()) + ->method('load') + ->will($this->returnValue($data)); + $cache = new CachingConfigLoader($loader, $cache); + $this->assertEquals($data, $cache->load('foo')); + $this->assertEquals($data, $cache->load('foo')); + } + + public function testDoesNotCacheArrays() + { + $cache = new DoctrineCacheAdapter(new ArrayCache()); + $loader = $this->getMockBuilder('Guzzle\Service\ConfigLoaderInterface') + ->setMethods(array('load')) + ->getMockForAbstractClass(); + $data = array('foo' => 'bar'); + $loader->expects($this->exactly(2)) + ->method('load') + ->will($this->returnValue($data)); + $cache = new CachingConfigLoader($loader, $cache); + $this->assertEquals($data, $cache->load(array())); + $this->assertEquals($data, $cache->load(array())); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/ClientTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/ClientTest.php new file mode 100644 index 000000000..aee29ed8d --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/ClientTest.php @@ -0,0 +1,320 @@ +serviceTest = new ServiceDescription(array( + 'test_command' => new Operation(array( + 'doc' => 'documentationForCommand', + 'method' => 'DELETE', + 'class' => 'Guzzle\\Tests\\Service\\Mock\\Command\\MockCommand', + 'args' => array( + 'bucket' => array( + 'required' => true + ), + 'key' => array( + 'required' => true + ) + ) + )) + )); + + $this->service = ServiceDescription::factory(__DIR__ . '/../TestData/test_service.json'); + } + + public function testAllowsCustomClientParameters() + { + $client = new Mock\MockClient(null, array( + Client::COMMAND_PARAMS => array(AbstractCommand::RESPONSE_PROCESSING => 'foo') + )); + $command = $client->getCommand('mock_command'); + $this->assertEquals('foo', $command->get(AbstractCommand::RESPONSE_PROCESSING)); + } + + public function testFactoryCreatesClient() + { + $client = Client::factory(array( + 'base_url' => 'http://www.test.com/', + 'test' => '123' + )); + + $this->assertEquals('http://www.test.com/', $client->getBaseUrl()); + $this->assertEquals('123', $client->getConfig('test')); + } + + public function testFactoryDoesNotRequireBaseUrl() + { + $client = Client::factory(); + } + + public function testDescribesEvents() + { + $this->assertInternalType('array', Client::getAllEvents()); + } + + public function testExecutesCommands() + { + $this->getServer()->flush(); + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + + $client = new Client($this->getServer()->getUrl()); + $cmd = new MockCommand(); + $client->execute($cmd); + + $this->assertInstanceOf('Guzzle\\Http\\Message\\Response', $cmd->getResponse()); + $this->assertInstanceOf('Guzzle\\Http\\Message\\Response', $cmd->getResult()); + $this->assertEquals(1, count($this->getServer()->getReceivedRequests(false))); + } + + public function testExecutesCommandsWithArray() + { + $client = new Client('http://www.test.com/'); + $client->getEventDispatcher()->addSubscriber(new MockPlugin(array( + new Response(200), + new Response(200) + ))); + + // Create a command set and a command + $set = array(new MockCommand(), new MockCommand()); + $client->execute($set); + + // Make sure it sent + $this->assertTrue($set[0]->isExecuted()); + $this->assertTrue($set[1]->isExecuted()); + } + + /** + * @expectedException Guzzle\Common\Exception\InvalidArgumentException + */ + public function testThrowsExceptionWhenInvalidCommandIsExecuted() + { + $client = new Client(); + $client->execute(new \stdClass()); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testThrowsExceptionWhenMissingCommand() + { + $client = new Client(); + + $mock = $this->getMock('Guzzle\\Service\\Command\\Factory\\FactoryInterface'); + $mock->expects($this->any()) + ->method('factory') + ->with($this->equalTo('test')) + ->will($this->returnValue(null)); + + $client->setCommandFactory($mock); + $client->getCommand('test'); + } + + public function testCreatesCommandsUsingCommandFactory() + { + $mockCommand = new MockCommand(); + + $client = new Mock\MockClient(); + $mock = $this->getMock('Guzzle\\Service\\Command\\Factory\\FactoryInterface'); + $mock->expects($this->any()) + ->method('factory') + ->with($this->equalTo('foo')) + ->will($this->returnValue($mockCommand)); + + $client->setCommandFactory($mock); + + $command = $client->getCommand('foo', array('acl' => '123')); + $this->assertSame($mockCommand, $command); + $command = $client->getCommand('foo', array('acl' => '123')); + $this->assertSame($mockCommand, $command); + $this->assertSame($client, $command->getClient()); + } + + public function testOwnsServiceDescription() + { + $client = new Mock\MockClient(); + $this->assertNull($client->getDescription()); + + $description = $this->getMock('Guzzle\\Service\\Description\\ServiceDescription'); + $this->assertSame($client, $client->setDescription($description)); + $this->assertSame($description, $client->getDescription()); + } + + public function testOwnsResourceIteratorFactory() + { + $client = new Mock\MockClient(); + + $method = new \ReflectionMethod($client, 'getResourceIteratorFactory'); + $method->setAccessible(TRUE); + $rf1 = $method->invoke($client); + + $rf = $this->readAttribute($client, 'resourceIteratorFactory'); + $this->assertInstanceOf('Guzzle\\Service\\Resource\\ResourceIteratorClassFactory', $rf); + $this->assertSame($rf1, $rf); + + $rf = new ResourceIteratorClassFactory('Guzzle\Tests\Service\Mock'); + $client->setResourceIteratorFactory($rf); + $this->assertNotSame($rf1, $rf); + } + + public function testClientResetsRequestsBeforeExecutingCommands() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nHi", + "HTTP/1.1 200 OK\r\nContent-Length: 1\r\n\r\nI" + )); + + $client = new Mock\MockClient($this->getServer()->getUrl()); + + $command = $client->getCommand('mock_command'); + $client->execute($command); + $client->execute($command); + $this->assertEquals('I', $command->getResponse()->getBody(true)); + } + + public function testClientCreatesIterators() + { + $client = new Mock\MockClient(); + + $iterator = $client->getIterator('mock_command', array( + 'foo' => 'bar' + ), array( + 'limit' => 10 + )); + + $this->assertInstanceOf('Guzzle\Tests\Service\Mock\Model\MockCommandIterator', $iterator); + $this->assertEquals(10, $this->readAttribute($iterator, 'limit')); + + $command = $this->readAttribute($iterator, 'originalCommand'); + $this->assertEquals('bar', $command->get('foo')); + } + + public function testClientCreatesIteratorsWithNoOptions() + { + $client = new Mock\MockClient(); + $iterator = $client->getIterator('mock_command'); + $this->assertInstanceOf('Guzzle\Tests\Service\Mock\Model\MockCommandIterator', $iterator); + } + + public function testClientCreatesIteratorsWithCommands() + { + $client = new Mock\MockClient(); + $command = new MockCommand(); + $iterator = $client->getIterator($command); + $this->assertInstanceOf('Guzzle\Tests\Service\Mock\Model\MockCommandIterator', $iterator); + $iteratorCommand = $this->readAttribute($iterator, 'originalCommand'); + $this->assertSame($command, $iteratorCommand); + } + + public function testClientHoldsInflector() + { + $client = new Mock\MockClient(); + $this->assertInstanceOf('Guzzle\Inflection\MemoizingInflector', $client->getInflector()); + + $inflector = new Inflector(); + $client->setInflector($inflector); + $this->assertSame($inflector, $client->getInflector()); + } + + public function testClientAddsGlobalCommandOptions() + { + $client = new Mock\MockClient('http://www.foo.com', array( + Client::COMMAND_PARAMS => array( + 'mesa' => 'bar' + ) + )); + $command = $client->getCommand('mock_command'); + $this->assertEquals('bar', $command->get('mesa')); + } + + public function testSupportsServiceDescriptionBaseUrls() + { + $description = new ServiceDescription(array('baseUrl' => 'http://foo.com')); + $client = new Client(); + $client->setDescription($description); + $this->assertEquals('http://foo.com', $client->getBaseUrl()); + } + + public function testMergesDefaultCommandParamsCorrectly() + { + $client = new Mock\MockClient('http://www.foo.com', array( + Client::COMMAND_PARAMS => array( + 'mesa' => 'bar', + 'jar' => 'jar' + ) + )); + $command = $client->getCommand('mock_command', array('jar' => 'test')); + $this->assertEquals('bar', $command->get('mesa')); + $this->assertEquals('test', $command->get('jar')); + } + + /** + * @expectedException \Guzzle\Http\Exception\BadResponseException + */ + public function testWrapsSingleCommandExceptions() + { + $client = new Mock\MockClient('http://foobaz.com'); + $mock = new MockPlugin(array(new Response(401))); + $client->addSubscriber($mock); + $client->execute(new MockCommand()); + } + + public function testWrapsMultipleCommandExceptions() + { + $client = new Mock\MockClient('http://foobaz.com'); + $mock = new MockPlugin(array(new Response(200), new Response(200), new Response(404), new Response(500))); + $client->addSubscriber($mock); + + $cmds = array(new MockCommand(), new MockCommand(), new MockCommand(), new MockCommand()); + try { + $client->execute($cmds); + } catch (CommandTransferException $e) { + $this->assertEquals(2, count($e->getFailedRequests())); + $this->assertEquals(2, count($e->getSuccessfulRequests())); + $this->assertEquals(2, count($e->getFailedCommands())); + $this->assertEquals(2, count($e->getSuccessfulCommands())); + + foreach ($e->getSuccessfulCommands() as $c) { + $this->assertTrue($c->getResponse()->isSuccessful()); + } + + foreach ($e->getFailedCommands() as $c) { + $this->assertFalse($c->getRequest()->getResponse()->isSuccessful()); + } + } + } + + public function testGetCommandAfterTwoSetDescriptions() + { + $service1 = ServiceDescription::factory(__DIR__ . '/../TestData/test_service.json'); + $service2 = ServiceDescription::factory(__DIR__ . '/../TestData/test_service_3.json'); + + $client = new Mock\MockClient(); + + $client->setDescription($service1); + $client->getCommand('foo_bar'); + $client->setDescription($service2); + $client->getCommand('baz_qux'); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/AbstractCommandTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/AbstractCommandTest.php new file mode 100644 index 000000000..1004fae66 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/AbstractCommandTest.php @@ -0,0 +1,16 @@ +setDescription(ServiceDescription::factory(__DIR__ . '/../../TestData/test_service.json')); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/ClosureCommandTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/ClosureCommandTest.php new file mode 100644 index 000000000..d76224697 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/ClosureCommandTest.php @@ -0,0 +1,54 @@ + function($command, $api) { + $command->set('testing', '123'); + $request = RequestFactory::getInstance()->create('GET', 'http://www.test.com/'); + return $request; + } + )); + + $client = $this->getServiceBuilder()->get('mock'); + $c->setClient($client)->prepare(); + $this->assertEquals('123', $c->get('testing')); + $this->assertEquals('http://www.test.com/', $c->getRequest()->getUrl()); + } + + /** + * @expectedException UnexpectedValueException + * @expectedExceptionMessage Closure command did not return a RequestInterface object + */ + public function testMustReturnRequest() + { + $c = new ClosureCommand(array( + 'closure' => function($command, $api) { + return false; + } + )); + + $client = $this->getServiceBuilder()->get('mock'); + $c->setClient($client)->prepare(); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/CommandTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/CommandTest.php new file mode 100644 index 000000000..b7173d486 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/CommandTest.php @@ -0,0 +1,445 @@ +assertEquals('123', $command->get('test')); + $this->assertFalse($command->isPrepared()); + $this->assertFalse($command->isExecuted()); + } + + public function testDeterminesShortName() + { + $api = new Operation(array('name' => 'foobar')); + $command = new MockCommand(array(), $api); + $this->assertEquals('foobar', $command->getName()); + + $command = new MockCommand(); + $this->assertEquals('mock_command', $command->getName()); + + $command = new Sub(); + $this->assertEquals('sub.sub', $command->getName()); + } + + /** + * @expectedException RuntimeException + */ + public function testGetRequestThrowsExceptionBeforePreparation() + { + $command = new MockCommand(); + $command->getRequest(); + } + + public function testGetResponseExecutesCommandsWhenNeeded() + { + $response = new Response(200); + $client = $this->getClient(); + $this->setMockResponse($client, array($response)); + $command = new MockCommand(); + $command->setClient($client); + $this->assertSame($response, $command->getResponse()); + $this->assertSame($response, $command->getResponse()); + } + + public function testGetResultExecutesCommandsWhenNeeded() + { + $response = new Response(200); + $client = $this->getClient(); + $this->setMockResponse($client, array($response)); + $command = new MockCommand(); + $command->setClient($client); + $this->assertSame($response, $command->getResult()); + $this->assertSame($response, $command->getResult()); + } + + public function testSetClient() + { + $command = new MockCommand(); + $client = $this->getClient(); + + $command->setClient($client); + $this->assertEquals($client, $command->getClient()); + + unset($client); + unset($command); + + $command = new MockCommand(); + $client = $this->getClient(); + + $command->setClient($client)->prepare(); + $this->assertEquals($client, $command->getClient()); + $this->assertTrue($command->isPrepared()); + } + + public function testExecute() + { + $client = $this->getClient(); + $response = new Response(200, array( + 'Content-Type' => 'application/xml' + ), '123'); + $this->setMockResponse($client, array($response)); + $command = new MockCommand(); + $this->assertSame($command, $command->setClient($client)); + + // Returns the result of the command + $this->assertInstanceOf('SimpleXMLElement', $command->execute()); + + $this->assertTrue($command->isPrepared()); + $this->assertTrue($command->isExecuted()); + $this->assertSame($response, $command->getResponse()); + $this->assertInstanceOf('Guzzle\\Http\\Message\\Request', $command->getRequest()); + // Make sure that the result was automatically set to a SimpleXMLElement + $this->assertInstanceOf('SimpleXMLElement', $command->getResult()); + $this->assertEquals('123', (string) $command->getResult()->data); + } + + public function testConvertsJsonResponsesToArray() + { + $client = $this->getClient(); + $this->setMockResponse($client, array( + new \Guzzle\Http\Message\Response(200, array( + 'Content-Type' => 'application/json' + ), '{ "key": "Hi!" }' + ) + )); + $command = new MockCommand(); + $command->setClient($client); + $command->execute(); + $this->assertEquals(array( + 'key' => 'Hi!' + ), $command->getResult()); + } + + /** + * @expectedException \Guzzle\Common\Exception\RuntimeException + */ + public function testConvertsInvalidJsonResponsesToArray() + { + $json = '{ "key": "Hi!" }invalid'; + // Some implementations of php-json extension are not strict enough + // and allow to parse invalid json ignoring invalid parts + // See https://github.com/remicollet/pecl-json-c/issues/5 + if (json_decode($json) && JSON_ERROR_NONE === json_last_error()) { + $this->markTestSkipped('php-pecl-json library regression issues'); + } + + $client = $this->getClient(); + $this->setMockResponse($client, array( + new \Guzzle\Http\Message\Response(200, array( + 'Content-Type' => 'application/json' + ), $json + ) + )); + $command = new MockCommand(); + $command->setClient($client); + $command->execute(); + } + + public function testProcessResponseIsNotXml() + { + $client = $this->getClient(); + $this->setMockResponse($client, array( + new Response(200, array( + 'Content-Type' => 'application/octet-stream' + ), 'abc,def,ghi') + )); + $command = new MockCommand(); + $client->execute($command); + + // Make sure that the result was not converted to XML + $this->assertFalse($command->getResult() instanceof \SimpleXMLElement); + } + + /** + * @expectedException RuntimeException + */ + public function testExecuteThrowsExceptionWhenNoClientIsSet() + { + $command = new MockCommand(); + $command->execute(); + } + + /** + * @expectedException RuntimeException + */ + public function testPrepareThrowsExceptionWhenNoClientIsSet() + { + $command = new MockCommand(); + $command->prepare(); + } + + public function testCommandsAllowsCustomRequestHeaders() + { + $command = new MockCommand(); + $command->getRequestHeaders()->set('test', '123'); + $this->assertInstanceOf('Guzzle\Common\Collection', $command->getRequestHeaders()); + $this->assertEquals('123', $command->getRequestHeaders()->get('test')); + + $command->setClient($this->getClient())->prepare(); + $this->assertEquals('123', (string) $command->getRequest()->getHeader('test')); + } + + public function testCommandsAllowsCustomRequestHeadersAsArray() + { + $command = new MockCommand(array(AbstractCommand::HEADERS_OPTION => array('Foo' => 'Bar'))); + $this->assertInstanceOf('Guzzle\Common\Collection', $command->getRequestHeaders()); + $this->assertEquals('Bar', $command->getRequestHeaders()->get('Foo')); + } + + private function getOperation() + { + return new Operation(array( + 'name' => 'foobar', + 'httpMethod' => 'POST', + 'class' => 'Guzzle\\Tests\\Service\\Mock\\Command\\MockCommand', + 'parameters' => array( + 'test' => array( + 'default' => '123', + 'type' => 'string' + ) + ))); + } + + public function testCommandsUsesOperation() + { + $api = $this->getOperation(); + $command = new MockCommand(array(), $api); + $this->assertSame($api, $command->getOperation()); + $command->setClient($this->getClient())->prepare(); + $this->assertEquals('123', $command->get('test')); + $this->assertSame($api, $command->getOperation($api)); + } + + public function testCloneMakesNewRequest() + { + $client = $this->getClient(); + $command = new MockCommand(array(), $this->getOperation()); + $command->setClient($client); + + $command->prepare(); + $this->assertTrue($command->isPrepared()); + + $command2 = clone $command; + $this->assertFalse($command2->isPrepared()); + } + + public function testHasOnCompleteMethod() + { + $that = $this; + $called = 0; + + $testFunction = function($command) use (&$called, $that) { + $called++; + $that->assertInstanceOf('Guzzle\Service\Command\CommandInterface', $command); + }; + + $client = $this->getClient(); + $command = new MockCommand(array( + 'command.on_complete' => $testFunction + ), $this->getOperation()); + $command->setClient($client); + + $command->prepare()->setResponse(new Response(200), true); + $command->execute(); + $this->assertEquals(1, $called); + } + + /** + * @expectedException \Guzzle\Common\Exception\InvalidArgumentException + */ + public function testOnCompleteMustBeCallable() + { + $client = $this->getClient(); + $command = new MockCommand(); + $command->setOnComplete('foo'); + } + + public function testCanSetResultManually() + { + $client = $this->getClient(); + $client->getEventDispatcher()->addSubscriber(new MockPlugin(array( + new Response(200) + ))); + $command = new MockCommand(); + $client->execute($command); + $command->setResult('foo!'); + $this->assertEquals('foo!', $command->getResult()); + } + + public function testCanInitConfig() + { + $command = $this->getMockBuilder('Guzzle\\Service\\Command\\AbstractCommand') + ->setConstructorArgs(array(array( + 'foo' => 'bar' + ), new Operation(array( + 'parameters' => array( + 'baz' => new Parameter(array( + 'default' => 'baaar' + )) + ) + )))) + ->getMockForAbstractClass(); + + $this->assertEquals('bar', $command['foo']); + $this->assertEquals('baaar', $command['baz']); + } + + public function testAddsCurlOptionsToRequestsWhenPreparing() + { + $command = new MockCommand(array( + 'foo' => 'bar', + 'curl.options' => array('CURLOPT_PROXYPORT' => 8080) + )); + $client = new Client(); + $command->setClient($client); + $request = $command->prepare(); + $this->assertEquals(8080, $request->getCurlOptions()->get(CURLOPT_PROXYPORT)); + } + + public function testIsInvokable() + { + $client = $this->getClient(); + $response = new Response(200); + $this->setMockResponse($client, array($response)); + $command = new MockCommand(); + $command->setClient($client); + // Returns the result of the command + $this->assertSame($response, $command()); + } + + public function testCreatesDefaultOperation() + { + $command = $this->getMockBuilder('Guzzle\Service\Command\AbstractCommand')->getMockForAbstractClass(); + $this->assertInstanceOf('Guzzle\Service\Description\Operation', $command->getOperation()); + } + + public function testAllowsValidatorToBeInjected() + { + $command = $this->getMockBuilder('Guzzle\Service\Command\AbstractCommand')->getMockForAbstractClass(); + $v = new SchemaValidator(); + $command->setValidator($v); + $this->assertSame($v, $this->readAttribute($command, 'validator')); + } + + public function testCanDisableValidation() + { + $command = new MockCommand(); + $command->setClient(new \Guzzle\Service\Client()); + $v = $this->getMockBuilder('Guzzle\Service\Description\SchemaValidator') + ->setMethods(array('validate')) + ->getMock(); + $v->expects($this->never())->method('validate'); + $command->setValidator($v); + $command->set(AbstractCommand::DISABLE_VALIDATION, true); + $command->prepare(); + } + + public function testValidatorDoesNotUpdateNonDefaultValues() + { + $command = new MockCommand(array('test' => 123, 'foo' => 'bar')); + $command->setClient(new \Guzzle\Service\Client()); + $command->prepare(); + $this->assertEquals(123, $command->get('test')); + $this->assertEquals('bar', $command->get('foo')); + } + + public function testValidatorUpdatesDefaultValues() + { + $command = new MockCommand(); + $command->setClient(new \Guzzle\Service\Client()); + $command->prepare(); + $this->assertEquals(123, $command->get('test')); + $this->assertEquals('abc', $command->get('_internal')); + } + + /** + * @expectedException \Guzzle\Service\Exception\ValidationException + * @expectedExceptionMessage [Foo] Baz + */ + public function testValidatesCommandBeforeSending() + { + $command = new MockCommand(); + $command->setClient(new \Guzzle\Service\Client()); + $v = $this->getMockBuilder('Guzzle\Service\Description\SchemaValidator') + ->setMethods(array('validate', 'getErrors')) + ->getMock(); + $v->expects($this->any())->method('validate')->will($this->returnValue(false)); + $v->expects($this->any())->method('getErrors')->will($this->returnValue(array('[Foo] Baz', '[Bar] Boo'))); + $command->setValidator($v); + $command->prepare(); + } + + /** + * @expectedException \Guzzle\Service\Exception\ValidationException + * @expectedExceptionMessage Validation errors: [abc] must be of type string + */ + public function testValidatesAdditionalParameters() + { + $description = ServiceDescription::factory(array( + 'operations' => array( + 'foo' => array( + 'parameters' => array( + 'baz' => array('type' => 'integer') + ), + 'additionalParameters' => array( + 'type' => 'string' + ) + ) + ) + )); + + $client = new Client(); + $client->setDescription($description); + $command = $client->getCommand('foo', array( + 'abc' => false, + 'command.headers' => array('foo' => 'bar') + )); + $command->prepare(); + } + + public function testCanAccessValidationErrorsFromCommand() + { + $validationErrors = array('[Foo] Baz', '[Bar] Boo'); + $command = new MockCommand(); + $command->setClient(new \Guzzle\Service\Client()); + + $this->assertFalse($command->getValidationErrors()); + + $v = $this->getMockBuilder('Guzzle\Service\Description\SchemaValidator') + ->setMethods(array('validate', 'getErrors')) + ->getMock(); + $v->expects($this->any())->method('getErrors')->will($this->returnValue($validationErrors)); + $command->setValidator($v); + + $this->assertEquals($validationErrors, $command->getValidationErrors()); + } + + public function testCanChangeResponseBody() + { + $body = EntityBody::factory(); + $command = new MockCommand(); + $command->setClient(new \Guzzle\Service\Client()); + $command->set(AbstractCommand::RESPONSE_BODY, $body); + $request = $command->prepare(); + $this->assertSame($body, $this->readAttribute($request, 'responseBody')); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/DefaultRequestSerializerTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/DefaultRequestSerializerTest.php new file mode 100644 index 000000000..b7a4682fc --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/DefaultRequestSerializerTest.php @@ -0,0 +1,122 @@ +serializer = DefaultRequestSerializer::getInstance(); + $this->client = new Client('http://foo.com/baz'); + $this->operation = new Operation(array('httpMethod' => 'POST')); + $this->command = $this->getMockBuilder('Guzzle\Service\Command\AbstractCommand') + ->setConstructorArgs(array(array(), $this->operation)) + ->getMockForAbstractClass(); + $this->command->setClient($this->client); + } + + public function testAllowsCustomVisitor() + { + $this->serializer->addVisitor('custom', new HeaderVisitor()); + $this->command['test'] = '123'; + $this->operation->addParam(new Parameter(array('name' => 'test', 'location' => 'custom'))); + $request = $this->serializer->prepare($this->command); + $this->assertEquals('123', (string) $request->getHeader('test')); + } + + public function testUsesRelativePath() + { + $this->operation->setUri('bar'); + $request = $this->serializer->prepare($this->command); + $this->assertEquals('http://foo.com/baz/bar', (string) $request->getUrl()); + } + + public function testUsesRelativePathWithUriLocations() + { + $this->command['test'] = '123'; + $this->operation->setUri('bar/{test}'); + $this->operation->addParam(new Parameter(array('name' => 'test', 'location' => 'uri'))); + $request = $this->serializer->prepare($this->command); + $this->assertEquals('http://foo.com/baz/bar/123', (string) $request->getUrl()); + } + + public function testAllowsCustomFactory() + { + $f = new VisitorFlyweight(); + $serializer = new DefaultRequestSerializer($f); + $this->assertSame($f, $this->readAttribute($serializer, 'factory')); + } + + public function testMixedParams() + { + $this->operation->setUri('bar{?limit,fields}'); + $this->operation->addParam(new Parameter(array( + 'name' => 'limit', + 'location' => 'uri', + 'required' => false, + ))); + $this->operation->addParam(new Parameter(array( + 'name' => 'fields', + 'location' => 'uri', + 'required' => true, + ))); + + $this->command['fields'] = array('id', 'name'); + + $request = $this->serializer->prepare($this->command); + $this->assertEquals('http://foo.com/baz/bar?fields='.urlencode('id,name'), (string) $request->getUrl()); + } + + public function testValidatesAdditionalParameters() + { + $description = ServiceDescription::factory(array( + 'operations' => array( + 'foo' => array( + 'httpMethod' => 'PUT', + 'parameters' => array( + 'bar' => array('location' => 'header') + ), + 'additionalParameters' => array( + 'location' => 'json' + ) + ) + ) + )); + + $client = new Client(); + $client->setDescription($description); + $command = $client->getCommand('foo'); + $command['bar'] = 'test'; + $command['hello'] = 'abc'; + $request = $command->prepare(); + $this->assertEquals('test', (string) $request->getHeader('bar')); + $this->assertEquals('{"hello":"abc"}', (string) $request->getBody()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/DefaultResponseParserTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/DefaultResponseParserTest.php new file mode 100644 index 000000000..a6a02f951 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/DefaultResponseParserTest.php @@ -0,0 +1,59 @@ +setClient(new Client()); + $request = $op->prepare(); + $request->setResponse(new Response(200, array( + 'Content-Type' => 'application/xml' + ), 'Bar'), true); + $this->assertInstanceOf('SimpleXMLElement', $op->execute()); + } + + public function testParsesJsonResponses() + { + $op = new OperationCommand(array(), new Operation()); + $op->setClient(new Client()); + $request = $op->prepare(); + $request->setResponse(new Response(200, array( + 'Content-Type' => 'application/json' + ), '{"Baz":"Bar"}'), true); + $this->assertEquals(array('Baz' => 'Bar'), $op->execute()); + } + + /** + * @expectedException \Guzzle\Common\Exception\RuntimeException + */ + public function testThrowsExceptionWhenParsingJsonFails() + { + $op = new OperationCommand(array(), new Operation()); + $op->setClient(new Client()); + $request = $op->prepare(); + $request->setResponse(new Response(200, array('Content-Type' => 'application/json'), '{"Baz":ddw}'), true); + $op->execute(); + } + + public function testAddsContentTypeWhenExpectsIsSetOnCommand() + { + $op = new OperationCommand(array(), new Operation()); + $op['command.expects'] = 'application/json'; + $op->setClient(new Client()); + $request = $op->prepare(); + $request->setResponse(new Response(200, null, '{"Baz":"Bar"}'), true); + $this->assertEquals(array('Baz' => 'Bar'), $op->execute()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/AliasFactoryTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/AliasFactoryTest.php new file mode 100644 index 000000000..ab1041ad3 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/AliasFactoryTest.php @@ -0,0 +1,76 @@ +client = new Client(); + + $map = new MapFactory(array( + 'test' => 'Guzzle\Tests\Service\Mock\Command\MockCommand', + 'test1' => 'Guzzle\Tests\Service\Mock\Command\OtherCommand' + )); + + $this->factory = new AliasFactory($this->client, array( + 'foo' => 'test', + 'bar' => 'sub', + 'sub' => 'test1', + 'krull' => 'test3', + 'krull_2' => 'krull', + 'sub_2' => 'bar', + 'bad_link' => 'jarjar' + )); + + $map2 = new MapFactory(array( + 'test3' => 'Guzzle\Tests\Service\Mock\Command\Sub\Sub' + )); + + $this->client->setCommandFactory(new CompositeFactory(array($map, $this->factory, $map2))); + } + + public function aliasProvider() + { + return array( + array('foo', 'Guzzle\Tests\Service\Mock\Command\MockCommand', false), + array('bar', 'Guzzle\Tests\Service\Mock\Command\OtherCommand', false), + array('sub', 'Guzzle\Tests\Service\Mock\Command\OtherCommand', false), + array('sub_2', 'Guzzle\Tests\Service\Mock\Command\OtherCommand', false), + array('krull', 'Guzzle\Tests\Service\Mock\Command\Sub\Sub', false), + array('krull_2', 'Guzzle\Tests\Service\Mock\Command\Sub\Sub', false), + array('missing', null, true), + array('bad_link', null, true) + ); + } + + /** + * @dataProvider aliasProvider + */ + public function testAliasesCommands($key, $result, $exception) + { + try { + $command = $this->client->getCommand($key); + if (is_null($result)) { + $this->assertNull($command); + } else { + $this->assertInstanceof($result, $command); + } + } catch (\Exception $e) { + if (!$exception) { + $this->fail('Got exception when it was not expected'); + } + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/CompositeFactoryTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/CompositeFactoryTest.php new file mode 100644 index 000000000..b896dcfd6 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/CompositeFactoryTest.php @@ -0,0 +1,124 @@ +getMockBuilder($class) + ->disableOriginalConstructor() + ->getMock(); + } + + public function testIsIterable() + { + $factory = new CompositeFactory(array($this->getFactory(), $this->getFactory())); + $this->assertEquals(2, count($factory)); + $this->assertEquals(2, count(iterator_to_array($factory->getIterator()))); + } + + public function testFindsFactories() + { + $f1 = $this->getFactory(); + $f2 = $this->getFactory('Guzzle\\Service\\Command\\Factory\\CompositeFactory'); + $factory = new CompositeFactory(array($f1, $f2)); + $this->assertNull($factory->find('foo')); + $this->assertNull($factory->find($this->getFactory())); + $this->assertSame($f1, $factory->find('Guzzle\\Service\\Command\\Factory\\MapFactory')); + $this->assertSame($f2, $factory->find('Guzzle\\Service\\Command\\Factory\\CompositeFactory')); + $this->assertSame($f1, $factory->find($f1)); + $this->assertSame($f2, $factory->find($f2)); + + $this->assertFalse($factory->has('foo')); + $this->assertTrue($factory->has('Guzzle\\Service\\Command\\Factory\\MapFactory')); + $this->assertTrue($factory->has('Guzzle\\Service\\Command\\Factory\\CompositeFactory')); + } + + public function testCreatesCommands() + { + $factory = new CompositeFactory(); + $this->assertNull($factory->factory('foo')); + + $f1 = $this->getFactory(); + $mockCommand1 = $this->getMockForAbstractClass('Guzzle\\Service\\Command\\AbstractCommand'); + + $f1->expects($this->once()) + ->method('factory') + ->with($this->equalTo('foo')) + ->will($this->returnValue($mockCommand1)); + + $factory = new CompositeFactory(array($f1)); + $this->assertSame($mockCommand1, $factory->factory('foo')); + } + + public function testAllowsRemovalOfFactories() + { + $f1 = $this->getFactory(); + $f2 = $this->getFactory(); + $f3 = $this->getFactory('Guzzle\\Service\\Command\\Factory\\CompositeFactory'); + $factories = array($f1, $f2, $f3); + $factory = new CompositeFactory($factories); + + $factory->remove('foo'); + $this->assertEquals($factories, $factory->getIterator()->getArrayCopy()); + + $factory->remove($f1); + $this->assertEquals(array($f2, $f3), $factory->getIterator()->getArrayCopy()); + + $factory->remove('Guzzle\\Service\\Command\\Factory\\MapFactory'); + $this->assertEquals(array($f3), $factory->getIterator()->getArrayCopy()); + + $factory->remove('Guzzle\\Service\\Command\\Factory\\CompositeFactory'); + $this->assertEquals(array(), $factory->getIterator()->getArrayCopy()); + + $factory->remove('foo'); + $this->assertEquals(array(), $factory->getIterator()->getArrayCopy()); + } + + public function testAddsFactoriesBeforeAndAtEnd() + { + $f1 = $this->getFactory(); + $f2 = $this->getFactory(); + $f3 = $this->getFactory('Guzzle\\Service\\Command\\Factory\\CompositeFactory'); + $f4 = $this->getFactory(); + + $factory = new CompositeFactory(); + + $factory->add($f1); + $this->assertEquals(array($f1), $factory->getIterator()->getArrayCopy()); + + $factory->add($f2); + $this->assertEquals(array($f1, $f2), $factory->getIterator()->getArrayCopy()); + + $factory->add($f3, $f2); + $this->assertEquals(array($f1, $f3, $f2), $factory->getIterator()->getArrayCopy()); + + $factory->add($f4, 'Guzzle\\Service\\Command\\Factory\\CompositeFactory'); + $this->assertEquals(array($f1, $f4, $f3, $f2), $factory->getIterator()->getArrayCopy()); + } + + public function testProvidesDefaultChainForClients() + { + $client = $this->getMock('Guzzle\\Service\\Client'); + $chain = CompositeFactory::getDefaultChain($client); + $a = $chain->getIterator()->getArrayCopy(); + $this->assertEquals(1, count($a)); + $this->assertInstanceOf('Guzzle\\Service\\Command\\Factory\\ConcreteClassFactory', $a[0]); + + $description = $this->getMock('Guzzle\\Service\\Description\\ServiceDescription'); + $client->expects($this->once()) + ->method('getDescription') + ->will($this->returnValue($description)); + $chain = CompositeFactory::getDefaultChain($client); + $a = $chain->getIterator()->getArrayCopy(); + $this->assertEquals(2, count($a)); + $this->assertInstanceOf('Guzzle\\Service\\Command\\Factory\\ServiceDescriptionFactory', $a[0]); + $this->assertInstanceOf('Guzzle\\Service\\Command\\Factory\\ConcreteClassFactory', $a[1]); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/ConcreteClassFactoryTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/ConcreteClassFactoryTest.php new file mode 100644 index 000000000..766471822 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/ConcreteClassFactoryTest.php @@ -0,0 +1,49 @@ + $prefix + )); + } + + $factory = new ConcreteClassFactory($client); + + if (is_null($result)) { + $this->assertNull($factory->factory($key)); + } else { + $this->assertInstanceof($result, $factory->factory($key)); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/MapFactoryTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/MapFactoryTest.php new file mode 100644 index 000000000..ee720d1e7 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/MapFactoryTest.php @@ -0,0 +1,37 @@ + 'Guzzle\Tests\Service\Mock\Command\MockCommand', + 'test1' => 'Guzzle\Tests\Service\Mock\Command\OtherCommand' + )); + + if (is_null($result)) { + $this->assertNull($factory->factory($key)); + } else { + $this->assertInstanceof($result, $factory->factory($key)); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/ServiceDescriptionFactoryTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/ServiceDescriptionFactoryTest.php new file mode 100644 index 000000000..337263481 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/Factory/ServiceDescriptionFactoryTest.php @@ -0,0 +1,68 @@ +getDescription(); + + $factory = new ServiceDescriptionFactory($d); + $this->assertSame($d, $factory->getServiceDescription()); + + if (is_null($result)) { + $this->assertNull($factory->factory($key)); + } else { + $this->assertInstanceof($result, $factory->factory($key)); + } + } + + public function testUsesUcFirstIfNoExactMatch() + { + $d = $this->getDescription(); + $factory = new ServiceDescriptionFactory($d, new Inflector()); + $this->assertInstanceof('Guzzle\Tests\Service\Mock\Command\OtherCommand', $factory->factory('Test')); + $this->assertInstanceof('Guzzle\Tests\Service\Mock\Command\OtherCommand', $factory->factory('test')); + } + + public function testUsesInflectionIfNoExactMatch() + { + $d = $this->getDescription(); + $factory = new ServiceDescriptionFactory($d, new Inflector()); + $this->assertInstanceof('Guzzle\Tests\Service\Mock\Command\OtherCommand', $factory->factory('Binks')); + $this->assertInstanceof('Guzzle\Tests\Service\Mock\Command\OtherCommand', $factory->factory('binks')); + $this->assertInstanceof('Guzzle\Tests\Service\Mock\Command\MockCommand', $factory->factory('JarJar')); + $this->assertInstanceof('Guzzle\Tests\Service\Mock\Command\MockCommand', $factory->factory('jar_jar')); + } + + protected function getDescription() + { + return ServiceDescription::factory(array( + 'operations' => array( + 'jar_jar' => array('class' => 'Guzzle\Tests\Service\Mock\Command\MockCommand'), + 'binks' => array('class' => 'Guzzle\Tests\Service\Mock\Command\OtherCommand'), + 'Test' => array('class' => 'Guzzle\Tests\Service\Mock\Command\OtherCommand') + ) + )); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/AbstractVisitorTestCase.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/AbstractVisitorTestCase.php new file mode 100644 index 000000000..46b472eb5 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/AbstractVisitorTestCase.php @@ -0,0 +1,110 @@ +command = new MockCommand(); + $this->request = new EntityEnclosingRequest('POST', 'http://www.test.com/some/path.php'); + $this->validator = new SchemaValidator(); + } + + protected function getCommand($location) + { + $command = new OperationCommand(array(), $this->getNestedCommand($location)); + $command->setClient(new MockClient()); + + return $command; + } + + protected function getNestedCommand($location) + { + return new Operation(array( + 'httpMethod' => 'POST', + 'parameters' => array( + 'foo' => new Parameter(array( + 'type' => 'object', + 'location' => $location, + 'sentAs' => 'Foo', + 'required' => true, + 'properties' => array( + 'test' => array( + 'type' => 'object', + 'required' => true, + 'properties' => array( + 'baz' => array( + 'type' => 'boolean', + 'default' => true + ), + 'jenga' => array( + 'type' => 'string', + 'default' => 'hello', + 'sentAs' => 'Jenga_Yall!', + 'filters' => array('strtoupper') + ) + ) + ), + 'bar' => array('default' => 123) + ), + 'additionalProperties' => array( + 'type' => 'string', + 'filters' => array('strtoupper'), + 'location' => $location + ) + )), + 'arr' => new Parameter(array( + 'type' => 'array', + 'location' => $location, + 'items' => array( + 'type' => 'string', + 'filters' => array('strtoupper') + ) + )), + ) + )); + } + + protected function getCommandWithArrayParamAndFilters() + { + $operation = new Operation(array( + 'httpMethod' => 'POST', + 'parameters' => array( + 'foo' => new Parameter(array( + 'type' => 'string', + 'location' => 'query', + 'sentAs' => 'Foo', + 'required' => true, + 'default' => 'bar', + 'filters' => array('strtoupper') + )), + 'arr' => new Parameter(array( + 'type' => 'array', + 'location' => 'query', + 'sentAs' => 'Arr', + 'required' => true, + 'default' => array(123, 456, 789), + 'filters' => array(array('method' => 'implode', 'args' => array(',', '@value'))) + )) + ) + )); + $command = new OperationCommand(array(), $operation); + $command->setClient(new MockClient()); + + return $command; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/BodyVisitorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/BodyVisitorTest.php new file mode 100644 index 000000000..2a95c452a --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/BodyVisitorTest.php @@ -0,0 +1,63 @@ +getNestedCommand('body')->getParam('foo')->setSentAs('Foo'); + $visitor->visit($this->command, $this->request, $param, '123'); + $this->assertEquals('123', (string) $this->request->getBody()); + $this->assertNull($this->request->getHeader('Expect')); + } + + public function testAddsExpectHeaderWhenSetToTrue() + { + $visitor = new Visitor(); + $param = $this->getNestedCommand('body')->getParam('foo')->setSentAs('Foo'); + $param->setData('expect_header', true); + $visitor->visit($this->command, $this->request, $param, '123'); + $this->assertEquals('123', (string) $this->request->getBody()); + } + + public function testCanDisableExpectHeader() + { + $visitor = new Visitor(); + $param = $this->getNestedCommand('body')->getParam('foo')->setSentAs('Foo'); + $param->setData('expect_header', false); + $visitor->visit($this->command, $this->request, $param, '123'); + $this->assertNull($this->request->getHeader('Expect')); + } + + public function testCanSetExpectHeaderBasedOnSize() + { + $visitor = new Visitor(); + $param = $this->getNestedCommand('body')->getParam('foo')->setSentAs('Foo'); + // The body is less than the cutoff + $param->setData('expect_header', 5); + $visitor->visit($this->command, $this->request, $param, '123'); + $this->assertNull($this->request->getHeader('Expect')); + // Now check when the body is greater than the cutoff + $param->setData('expect_header', 2); + $visitor->visit($this->command, $this->request, $param, '123'); + $this->assertEquals('100-Continue', (string) $this->request->getHeader('Expect')); + } + + public function testAddsContentEncodingWhenSetOnBody() + { + $visitor = new Visitor(); + $param = $this->getNestedCommand('body')->getParam('foo')->setSentAs('Foo'); + $body = EntityBody::factory('foo'); + $body->compress(); + $visitor->visit($this->command, $this->request, $param, $body); + $this->assertEquals('gzip', (string) $this->request->getHeader('Content-Encoding')); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/HeaderVisitorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/HeaderVisitorTest.php new file mode 100644 index 000000000..7ea1ae913 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/HeaderVisitorTest.php @@ -0,0 +1,48 @@ +getNestedCommand('header')->getParam('foo')->setSentAs('test'); + $param->setAdditionalProperties(new Parameter(array())); + $visitor->visit($this->command, $this->request, $param, 'test'); + } + + public function testVisitsLocation() + { + $visitor = new Visitor(); + $param = $this->getNestedCommand('header')->getParam('foo')->setSentAs('test'); + $param->setAdditionalProperties(false); + $visitor->visit($this->command, $this->request, $param, '123'); + $this->assertEquals('123', (string) $this->request->getHeader('test')); + } + + public function testVisitsMappedPrefixHeaders() + { + $visitor = new Visitor(); + $param = $this->getNestedCommand('header')->getParam('foo')->setSentAs('test'); + $param->setSentAs('x-foo-'); + $param->setAdditionalProperties(new Parameter(array( + 'type' => 'string' + ))); + $visitor->visit($this->command, $this->request, $param, array( + 'bar' => 'test', + 'baz' => '123' + )); + $this->assertEquals('test', (string) $this->request->getHeader('x-foo-bar')); + $this->assertEquals('123', (string) $this->request->getHeader('x-foo-baz')); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/JsonVisitorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/JsonVisitorTest.php new file mode 100644 index 000000000..ea6782f53 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/JsonVisitorTest.php @@ -0,0 +1,60 @@ +after($this->command, $this->request); + + $param = $this->getNestedCommand('json')->getParam('foo'); + $visitor->visit($this->command, $this->request, $param->setSentAs('test'), '123'); + $visitor->visit($this->command, $this->request, $param->setSentAs('test2'), 'abc'); + $visitor->after($this->command, $this->request); + $this->assertEquals('{"test":"123","test2":"abc"}', (string) $this->request->getBody()); + } + + public function testAddsJsonHeader() + { + $visitor = new Visitor(); + $visitor->setContentTypeHeader('application/json-foo'); + $param = $this->getNestedCommand('json')->getParam('foo'); + $visitor->visit($this->command, $this->request, $param->setSentAs('test'), '123'); + $visitor->after($this->command, $this->request); + $this->assertEquals('application/json-foo', (string) $this->request->getHeader('Content-Type')); + } + + public function testRecursivelyBuildsJsonBodies() + { + $command = $this->getCommand('json'); + $request = $command->prepare(); + $this->assertEquals('{"Foo":{"test":{"baz":true,"Jenga_Yall!":"HELLO"},"bar":123}}', (string) $request->getBody()); + } + + public function testAppliesFiltersToAdditionalProperties() + { + $command = $this->getCommand('json'); + $command->set('foo', array('not_set' => 'abc')); + $request = $command->prepare(); + $result = json_decode($request->getBody(), true); + $this->assertEquals('ABC', $result['Foo']['not_set']); + } + + public function testAppliesFiltersToArrayItemValues() + { + $command = $this->getCommand('json'); + $command->set('arr', array('a', 'b')); + $request = $command->prepare(); + $result = json_decode($request->getBody(), true); + $this->assertEquals(array('A', 'B'), $result['arr']); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/PostFieldVisitorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/PostFieldVisitorTest.php new file mode 100644 index 000000000..540b41087 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/PostFieldVisitorTest.php @@ -0,0 +1,33 @@ +getNestedCommand('postField')->getParam('foo'); + $visitor->visit($this->command, $this->request, $param->setSentAs('test'), '123'); + $this->assertEquals('123', (string) $this->request->getPostField('test')); + } + + public function testRecursivelyBuildsPostFields() + { + $command = $this->getCommand('postField'); + $request = $command->prepare(); + $visitor = new Visitor(); + $param = $command->getOperation()->getParam('foo'); + $visitor->visit($command, $request, $param, $command['foo']); + $visitor->after($command, $request); + $this->assertEquals( + 'Foo[test][baz]=1&Foo[test][Jenga_Yall!]=HELLO&Foo[bar]=123', + rawurldecode((string) $request->getPostFields()) + ); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/PostFileVisitorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/PostFileVisitorTest.php new file mode 100644 index 000000000..21e3cec33 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/PostFileVisitorTest.php @@ -0,0 +1,54 @@ +getNestedCommand('postFile')->getParam('foo'); + + // Test using a path to a file + $visitor->visit($this->command, $this->request, $param->setSentAs('test_3'), __FILE__); + $this->assertInternalType('array', $this->request->getPostFile('test_3')); + + // Test with a PostFile + $visitor->visit($this->command, $this->request, $param->setSentAs(null), new PostFile('baz', __FILE__)); + $this->assertInternalType('array', $this->request->getPostFile('baz')); + } + + public function testVisitsLocationWithMultipleFiles() + { + $description = ServiceDescription::factory(array( + 'operations' => array( + 'DoPost' => array( + 'httpMethod' => 'POST', + 'parameters' => array( + 'foo' => array( + 'location' => 'postFile', + 'type' => array('string', 'array') + ) + ) + ) + ) + )); + $this->getServer()->flush(); + $this->getServer()->enqueue(array("HTTP/1.1 200 OK\r\nContent-Length:0\r\n\r\n")); + $client = new Client($this->getServer()->getUrl()); + $client->setDescription($description); + $command = $client->getCommand('DoPost', array('foo' => array(__FILE__, __FILE__))); + $command->execute(); + $received = $this->getServer()->getReceivedRequests(); + $this->assertContains('name="foo[0]";', $received[0]); + $this->assertContains('name="foo[1]";', $received[0]); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/QueryVisitorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/QueryVisitorTest.php new file mode 100644 index 000000000..607af7603 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/QueryVisitorTest.php @@ -0,0 +1,48 @@ +getNestedCommand('query')->getParam('foo')->setSentAs('test'); + $visitor->visit($this->command, $this->request, $param, '123'); + $this->assertEquals('123', $this->request->getQuery()->get('test')); + } + + /** + * @covers Guzzle\Service\Command\LocationVisitor\Request\QueryVisitor + * @covers Guzzle\Service\Command\LocationVisitor\Request\AbstractRequestVisitor::resolveRecursively + */ + public function testRecursivelyBuildsQueryStrings() + { + $command = $this->getCommand('query'); + $command->getOperation()->getParam('foo')->setSentAs('Foo'); + $request = $command->prepare(); + $this->assertEquals( + 'Foo[test][baz]=1&Foo[test][Jenga_Yall!]=HELLO&Foo[bar]=123', + rawurldecode($request->getQuery()) + ); + } + + /** + * @covers Guzzle\Service\Command\LocationVisitor\Request\AbstractRequestVisitor::resolveRecursively + */ + public function testFiltersAreAppliedToArrayParamType() + { + $command = $this->getCommandWithArrayParamAndFilters(); + $request = $command->prepare(); + $query = $request->getQuery(); + // param type 'string' + $this->assertEquals('BAR', $query->get('Foo')); + // param type 'array' + $this->assertEquals('123,456,789', $query->get('Arr')); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/ResponseBodyVisitorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/ResponseBodyVisitorTest.php new file mode 100644 index 000000000..ff8cec599 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/ResponseBodyVisitorTest.php @@ -0,0 +1,20 @@ +getNestedCommand('response_body')->getParam('foo'); + $visitor->visit($this->command, $this->request, $param, sys_get_temp_dir() . '/foo.txt'); + $body = $this->readAttribute($this->request, 'responseBody'); + $this->assertContains('/foo.txt', $body->getUri()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/XmlVisitorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/XmlVisitorTest.php new file mode 100644 index 000000000..beb58b00a --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Request/XmlVisitorTest.php @@ -0,0 +1,558 @@ + array( + 'xmlRoot' => array( + 'name' => 'test', + 'namespaces' => 'http://foo.com' + ) + ), + 'parameters' => array( + 'Foo' => array('location' => 'xml', 'type' => 'string'), + 'Baz' => array('location' => 'xml', 'type' => 'string') + ) + ), + array('Foo' => 'test', 'Baz' => 'bar'), + 'testbar' + ), + // Ensure that the content-type is not added + array(array('parameters' => array('Foo' => array('location' => 'xml', 'type' => 'string'))), array(), ''), + // Test with adding attributes and no namespace + array( + array( + 'data' => array( + 'xmlRoot' => array( + 'name' => 'test' + ) + ), + 'parameters' => array( + 'Foo' => array('location' => 'xml', 'type' => 'string', 'data' => array('xmlAttribute' => true)) + ) + ), + array('Foo' => 'test', 'Baz' => 'bar'), + '' + ), + // Test adding with an array + array( + array( + 'parameters' => array( + 'Foo' => array('location' => 'xml', 'type' => 'string'), + 'Baz' => array( + 'type' => 'array', + 'location' => 'xml', + 'items' => array( + 'type' => 'numeric', + 'sentAs' => 'Bar' + ) + ) + ) + ), + array('Foo' => 'test', 'Baz' => array(1, 2)), + 'test12' + ), + // Test adding an object + array( + array( + 'parameters' => array( + 'Foo' => array('location' => 'xml', 'type' => 'string'), + 'Baz' => array( + 'type' => 'object', + 'location' => 'xml', + 'properties' => array( + 'Bar' => array('type' => 'string'), + 'Bam' => array() + ) + ) + ) + ), + array('Foo' => 'test', 'Baz' => array('Bar' => 'abc', 'Bam' => 'foo')), + 'testabcfoo' + ), + // Add an array that contains an object + array( + array( + 'parameters' => array( + 'Baz' => array( + 'type' => 'array', + 'location' => 'xml', + 'items' => array( + 'type' => 'object', + 'sentAs' => 'Bar', + 'properties' => array('A' => array(), 'B' => array()) + ) + ) + ) + ), + array('Baz' => array( + array('A' => '1', 'B' => '2'), + array('A' => '3', 'B' => '4') + )), + '1234' + ), + // Add an object of attributes + array( + array( + 'parameters' => array( + 'Foo' => array('location' => 'xml', 'type' => 'string'), + 'Baz' => array( + 'type' => 'object', + 'location' => 'xml', + 'properties' => array( + 'Bar' => array('type' => 'string', 'data' => array('xmlAttribute' => true)), + 'Bam' => array() + ) + ) + ) + ), + array('Foo' => 'test', 'Baz' => array('Bar' => 'abc', 'Bam' => 'foo')), + 'testfoo' + ), + // Check order doesn't matter + array( + array( + 'parameters' => array( + 'Foo' => array('location' => 'xml', 'type' => 'string'), + 'Baz' => array( + 'type' => 'object', + 'location' => 'xml', + 'properties' => array( + 'Bar' => array('type' => 'string', 'data' => array('xmlAttribute' => true)), + 'Bam' => array() + ) + ) + ) + ), + array('Foo' => 'test', 'Baz' => array('Bam' => 'foo', 'Bar' => 'abc')), + 'testfoo' + ), + // Add values with custom namespaces + array( + array( + 'parameters' => array( + 'Foo' => array( + 'location' => 'xml', + 'type' => 'string', + 'data' => array( + 'xmlNamespace' => 'http://foo.com' + ) + ) + ) + ), + array('Foo' => 'test'), + 'test' + ), + // Add attributes with custom namespace prefix + array( + array( + 'parameters' => array( + 'Wrap' => array( + 'type' => 'object', + 'location' => 'xml', + 'properties' => array( + 'Foo' => array( + 'type' => 'string', + 'sentAs' => 'xsi:baz', + 'data' => array( + 'xmlNamespace' => 'http://foo.com', + 'xmlAttribute' => true + ) + ) + ) + ), + ) + ), + array('Wrap' => array( + 'Foo' => 'test' + )), + '' + ), + // Add nodes with custom namespace prefix + array( + array( + 'parameters' => array( + 'Wrap' => array( + 'type' => 'object', + 'location' => 'xml', + 'properties' => array( + 'Foo' => array( + 'type' => 'string', + 'sentAs' => 'xsi:Foo', + 'data' => array( + 'xmlNamespace' => 'http://foobar.com' + ) + ) + ) + ), + ) + ), + array('Wrap' => array( + 'Foo' => 'test' + )), + 'test' + ), + array( + array( + 'parameters' => array( + 'Foo' => array( + 'location' => 'xml', + 'type' => 'string', + 'data' => array( + 'xmlNamespace' => 'http://foo.com' + ) + ) + ) + ), + array('Foo' => '

    This is a title

    '), + 'This is a title]]>' + ), + // Flat array at top level + array( + array( + 'parameters' => array( + 'Bars' => array( + 'type' => 'array', + 'data' => array('xmlFlattened' => true), + 'location' => 'xml', + 'items' => array( + 'type' => 'object', + 'sentAs' => 'Bar', + 'properties' => array( + 'A' => array(), + 'B' => array() + ) + ) + ), + 'Boos' => array( + 'type' => 'array', + 'data' => array('xmlFlattened' => true), + 'location' => 'xml', + 'items' => array( + 'sentAs' => 'Boo', + 'type' => 'string' + ) + ) + ) + ), + array( + 'Bars' => array( + array('A' => '1', 'B' => '2'), + array('A' => '3', 'B' => '4') + ), + 'Boos' => array('test', '123') + ), + '1234test123' + ), + // Nested flat arrays + array( + array( + 'parameters' => array( + 'Delete' => array( + 'type' => 'object', + 'location' => 'xml', + 'properties' => array( + 'Items' => array( + 'type' => 'array', + 'data' => array('xmlFlattened' => true), + 'items' => array( + 'type' => 'object', + 'sentAs' => 'Item', + 'properties' => array( + 'A' => array(), + 'B' => array() + ) + ) + ) + ) + ) + ) + ), + array( + 'Delete' => array( + 'Items' => array( + array('A' => '1', 'B' => '2'), + array('A' => '3', 'B' => '4') + ) + ) + ), + '1234' + ) + ); + } + + /** + * @dataProvider xmlProvider + */ + public function testSerializesXml(array $operation, array $input, $xml) + { + $operation = new Operation($operation); + $command = $this->getMockBuilder('Guzzle\Service\Command\OperationCommand') + ->setConstructorArgs(array($input, $operation)) + ->getMockForAbstractClass(); + $command->setClient(new Client('http://www.test.com/some/path.php')); + $request = $command->prepare(); + if (!empty($input)) { + $this->assertEquals('application/xml', (string) $request->getHeader('Content-Type')); + } else { + $this->assertNull($request->getHeader('Content-Type')); + } + $body = str_replace(array("\n", ""), '', (string) $request->getBody()); + $this->assertEquals($xml, $body); + } + + public function testAddsContentTypeAndTopLevelValues() + { + $operation = new Operation(array( + 'data' => array( + 'xmlRoot' => array( + 'name' => 'test', + 'namespaces' => array( + 'xsi' => 'http://foo.com' + ) + ) + ), + 'parameters' => array( + 'Foo' => array('location' => 'xml', 'type' => 'string'), + 'Baz' => array('location' => 'xml', 'type' => 'string') + ) + )); + + $command = $this->getMockBuilder('Guzzle\Service\Command\OperationCommand') + ->setConstructorArgs(array(array( + 'Foo' => 'test', + 'Baz' => 'bar' + ), $operation)) + ->getMockForAbstractClass(); + + $command->setClient(new Client()); + $request = $command->prepare(); + $this->assertEquals('application/xml', (string) $request->getHeader('Content-Type')); + $this->assertEquals( + '' . "\n" + . 'testbar' . "\n", + (string) $request->getBody() + ); + } + + public function testCanChangeContentType() + { + $visitor = new XmlVisitor(); + $visitor->setContentTypeHeader('application/foo'); + $this->assertEquals('application/foo', $this->readAttribute($visitor, 'contentType')); + } + + public function testCanAddArrayOfSimpleTypes() + { + $request = new EntityEnclosingRequest('POST', 'http://foo.com'); + $visitor = new XmlVisitor(); + $param = new Parameter(array( + 'type' => 'object', + 'location' => 'xml', + 'name' => 'Out', + 'properties' => array( + 'Nodes' => array( + 'required' => true, + 'type' => 'array', + 'min' => 1, + 'items' => array('type' => 'string', 'sentAs' => 'Node') + ) + ) + )); + + $param->setParent(new Operation(array( + 'data' => array( + 'xmlRoot' => array( + 'name' => 'Test', + 'namespaces' => array( + 'https://foo/' + ) + ) + ) + ))); + + $value = array('Nodes' => array('foo', 'baz')); + $this->assertTrue($this->validator->validate($param, $value)); + $visitor->visit($this->command, $request, $param, $value); + $visitor->after($this->command, $request); + + $this->assertEquals( + "\n" + . "foobaz\n", + (string) $request->getBody() + ); + } + + public function testCanAddMultipleNamespacesToRoot() + { + $operation = new Operation(array( + 'data' => array( + 'xmlRoot' => array( + 'name' => 'Hi', + 'namespaces' => array( + 'xsi' => 'http://foo.com', + 'foo' => 'http://foobar.com' + ) + ) + ), + 'parameters' => array( + 'Foo' => array('location' => 'xml', 'type' => 'string') + ) + )); + + $command = $this->getMockBuilder('Guzzle\Service\Command\OperationCommand') + ->setConstructorArgs(array(array( + 'Foo' => 'test' + ), $operation)) + ->getMockForAbstractClass(); + + $command->setClient(new Client()); + $request = $command->prepare(); + $this->assertEquals('application/xml', (string) $request->getHeader('Content-Type')); + $this->assertEquals( + '' . "\n" + . 'test' . "\n", + (string) $request->getBody() + ); + } + + public function testValuesAreFiltered() + { + $operation = new Operation(array( + 'parameters' => array( + 'Foo' => array( + 'location' => 'xml', + 'type' => 'string', + 'filters' => array('strtoupper') + ), + 'Bar' => array( + 'location' => 'xml', + 'type' => 'object', + 'properties' => array( + 'Baz' => array( + 'filters' => array('strtoupper') + ) + ) + ) + ) + )); + + $command = $this->getMockBuilder('Guzzle\Service\Command\OperationCommand') + ->setConstructorArgs(array(array( + 'Foo' => 'test', + 'Bar' => array( + 'Baz' => 'abc' + ) + ), $operation)) + ->getMockForAbstractClass(); + + $command->setClient(new Client()); + $request = $command->prepare(); + $this->assertEquals( + '' . "\n" + . 'TESTABC' . "\n", + (string) $request->getBody() + ); + } + + public function testSkipsNullValues() + { + $operation = new Operation(array( + 'parameters' => array( + 'Foo' => array( + 'location' => 'xml', + 'type' => 'string' + ), + 'Bar' => array( + 'location' => 'xml', + 'type' => 'object', + 'properties' => array( + 'Baz' => array(), + 'Bam' => array(), + ) + ), + 'Arr' => array( + 'type' => 'array', + 'items' => array( + 'type' => 'string' + ) + ) + ) + )); + + $command = $this->getMockBuilder('Guzzle\Service\Command\OperationCommand') + ->setConstructorArgs(array(array( + 'Foo' => null, + 'Bar' => array( + 'Bar' => null, + 'Bam' => 'test' + ), + 'Arr' => array(null) + ), $operation)) + ->getMockForAbstractClass(); + + $command->setClient(new Client()); + $request = $command->prepare(); + $this->assertEquals( + '' . "\n" + . 'test' . "\n", + (string) $request->getBody() + ); + } + + public function testAllowsXmlEncoding() + { + $operation = new Operation(array( + 'data' => array( + 'xmlEncoding' => 'UTF-8' + ), + 'parameters' => array( + 'Foo' => array('location' => 'xml') + ) + )); + $command = $this->getMockBuilder('Guzzle\Service\Command\OperationCommand') + ->setConstructorArgs(array(array('Foo' => 'test'), $operation)) + ->getMockForAbstractClass(); + $command->setClient(new Client()); + $request = $command->prepare(); + $this->assertEquals( + '' . "\n" + . 'test' . "\n", + (string) $request->getBody() + ); + } + + public function testAllowsSendingXmlPayloadIfNoXmlParamsWereSet() + { + $operation = new Operation(array( + 'httpMethod' => 'POST', + 'data' => array('xmlAllowEmpty' => true), + 'parameters' => array('Foo' => array('location' => 'xml')) + )); + $command = $this->getMockBuilder('Guzzle\Service\Command\OperationCommand') + ->setConstructorArgs(array(array(), $operation)) + ->getMockForAbstractClass(); + $command->setClient(new Client('http://foo.com')); + $request = $command->prepare(); + $this->assertEquals( + '' . "\n" + . '' . "\n", + (string) $request->getBody() + ); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/AbstractResponseVisitorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/AbstractResponseVisitorTest.php new file mode 100644 index 000000000..7b8600342 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/AbstractResponseVisitorTest.php @@ -0,0 +1,29 @@ +value = array(); + $this->command = new MockCommand(); + $this->response = new Response(200, array( + 'X-Foo' => 'bar', + 'Content-Length' => 3, + 'Content-Type' => 'text/plain' + ), 'Foo'); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/BodyVisitorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/BodyVisitorTest.php new file mode 100644 index 000000000..932e39bff --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/BodyVisitorTest.php @@ -0,0 +1,21 @@ + 'body', 'name' => 'foo')); + $visitor->visit($this->command, $this->response, $param, $this->value); + $this->assertEquals('Foo', (string) $this->value['foo']); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/HeaderVisitorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/HeaderVisitorTest.php new file mode 100644 index 000000000..db54b1abb --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/HeaderVisitorTest.php @@ -0,0 +1,98 @@ + 'header', + 'name' => 'ContentType', + 'sentAs' => 'Content-Type' + )); + $visitor->visit($this->command, $this->response, $param, $this->value); + $this->assertEquals('text/plain', $this->value['ContentType']); + } + + public function testVisitsLocationWithFilters() + { + $visitor = new Visitor(); + $param = new Parameter(array( + 'location' => 'header', + 'name' => 'Content-Type', + 'filters' => array('strtoupper') + )); + $visitor->visit($this->command, $this->response, $param, $this->value); + $this->assertEquals('TEXT/PLAIN', $this->value['Content-Type']); + } + + public function testVisitsMappedPrefixHeaders() + { + $visitor = new Visitor(); + $param = new Parameter(array( + 'location' => 'header', + 'name' => 'Metadata', + 'sentAs' => 'X-Baz-', + 'type' => 'object', + 'additionalProperties' => array( + 'type' => 'string' + ) + )); + $response = new Response(200, array( + 'X-Baz-Test' => 'ABC', + 'X-Baz-Bar' => array('123', '456'), + 'Content-Length' => 3 + ), 'Foo'); + $visitor->visit($this->command, $response, $param, $this->value); + $this->assertEquals(array( + 'Metadata' => array( + 'Test' => 'ABC', + 'Bar' => array('123', '456') + ) + ), $this->value); + } + + /** + * @group issue-399 + * @link https://github.com/guzzle/guzzle/issues/399 + */ + public function testDiscardingUnknownHeaders() + { + $visitor = new Visitor(); + $param = new Parameter(array( + 'location' => 'header', + 'name' => 'Content-Type', + 'additionalParameters' => false + )); + $visitor->visit($this->command, $this->response, $param, $this->value); + $this->assertEquals('text/plain', $this->value['Content-Type']); + $this->assertArrayNotHasKey('X-Foo', $this->value); + } + + /** + * @group issue-399 + * @link https://github.com/guzzle/guzzle/issues/399 + */ + public function testDiscardingUnknownPropertiesWithAliasing() + { + $visitor = new Visitor(); + $param = new Parameter(array( + 'location' => 'header', + 'name' => 'ContentType', + 'sentAs' => 'Content-Type', + 'additionalParameters' => false + )); + $visitor->visit($this->command, $this->response, $param, $this->value); + $this->assertEquals('text/plain', $this->value['ContentType']); + $this->assertArrayNotHasKey('X-Foo', $this->value); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/JsonVisitorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/JsonVisitorTest.php new file mode 100644 index 000000000..4f8d30b1e --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/JsonVisitorTest.php @@ -0,0 +1,157 @@ +getMockBuilder('Guzzle\Service\Command\AbstractCommand') + ->setMethods(array('getResponse')) + ->getMockForAbstractClass(); + $command->expects($this->once()) + ->method('getResponse') + ->will($this->returnValue(new Response(200, null, '{"foo":"bar"}'))); + $result = array(); + $visitor->before($command, $result); + $this->assertEquals(array('foo' => 'bar'), $result); + } + + public function testVisitsLocation() + { + $visitor = new Visitor(); + $param = new Parameter(array( + 'name' => 'foo', + 'type' => 'array', + 'items' => array( + 'filters' => 'strtoupper', + 'type' => 'string' + ) + )); + $this->value = array('foo' => array('a', 'b', 'c')); + $visitor->visit($this->command, $this->response, $param, $this->value); + $this->assertEquals(array('A', 'B', 'C'), $this->value['foo']); + } + + public function testRenamesTopLevelValues() + { + $visitor = new Visitor(); + $param = new Parameter(array( + 'name' => 'foo', + 'sentAs' => 'Baz', + 'type' => 'string', + )); + $this->value = array('Baz' => 'test'); + $visitor->visit($this->command, $this->response, $param, $this->value); + $this->assertEquals(array('foo' => 'test'), $this->value); + } + + public function testRenamesDoesNotFailForNonExistentKey() + { + $visitor = new Visitor(); + $param = new Parameter(array( + 'name' => 'foo', + 'type' => 'object', + 'properties' => array( + 'bar' => array( + 'name' => 'bar', + 'sentAs' => 'baz', + ), + ), + )); + $this->value = array('foo' => array('unknown' => 'Unknown')); + $visitor->visit($this->command, $this->response, $param, $this->value); + $this->assertEquals(array('foo' => array('unknown' => 'Unknown')), $this->value); + } + + public function testTraversesObjectsAndAppliesFilters() + { + $visitor = new Visitor(); + $param = new Parameter(array( + 'name' => 'foo', + 'type' => 'object', + 'properties' => array( + 'foo' => array('filters' => 'strtoupper'), + 'bar' => array('filters' => 'strtolower') + ) + )); + $this->value = array('foo' => array('foo' => 'hello', 'bar' => 'THERE')); + $visitor->visit($this->command, $this->response, $param, $this->value); + $this->assertEquals(array('foo' => 'HELLO', 'bar' => 'there'), $this->value['foo']); + } + + /** + * @group issue-399 + * @link https://github.com/guzzle/guzzle/issues/399 + */ + public function testDiscardingUnknownProperties() + { + $visitor = new Visitor(); + $param = new Parameter(array( + 'name' => 'foo', + 'type' => 'object', + 'additionalProperties' => false, + 'properties' => array( + 'bar' => array( + 'type' => 'string', + 'name' => 'bar', + ), + ), + )); + $this->value = array('foo' => array('bar' => 15, 'unknown' => 'Unknown')); + $visitor->visit($this->command, $this->response, $param, $this->value); + $this->assertEquals(array('foo' => array('bar' => 15)), $this->value); + } + + /** + * @group issue-399 + * @link https://github.com/guzzle/guzzle/issues/399 + */ + public function testDiscardingUnknownPropertiesWithAliasing() + { + $visitor = new Visitor(); + $param = new Parameter(array( + 'name' => 'foo', + 'type' => 'object', + 'additionalProperties' => false, + 'properties' => array( + 'bar' => array( + 'name' => 'bar', + 'sentAs' => 'baz', + ), + ), + )); + $this->value = array('foo' => array('baz' => 15, 'unknown' => 'Unknown')); + $visitor->visit($this->command, $this->response, $param, $this->value); + $this->assertEquals(array('foo' => array('bar' => 15)), $this->value); + } + + public function testWalksAdditionalProperties() + { + $visitor = new Visitor(); + $param = new Parameter(array( + 'name' => 'foo', + 'type' => 'object', + 'additionalProperties' => array( + 'type' => 'object', + 'properties' => array( + 'bar' => array( + 'type' => 'string', + 'filters' => array('base64_decode') + ) + ), + ), + )); + $this->value = array('foo' => array('baz' => array('bar' => 'Zm9v'))); + $visitor->visit($this->command, $this->response, $param, $this->value); + $this->assertEquals('foo', $this->value['foo']['baz']['bar']); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/ReasonPhraseVisitorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/ReasonPhraseVisitorTest.php new file mode 100644 index 000000000..23cd40fed --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/ReasonPhraseVisitorTest.php @@ -0,0 +1,21 @@ + 'reasonPhrase', 'name' => 'phrase')); + $visitor->visit($this->command, $this->response, $param, $this->value); + $this->assertEquals('OK', $this->value['phrase']); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/StatusCodeVisitorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/StatusCodeVisitorTest.php new file mode 100644 index 000000000..7211a5801 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/StatusCodeVisitorTest.php @@ -0,0 +1,21 @@ + 'statusCode', 'name' => 'code')); + $visitor->visit($this->command, $this->response, $param, $this->value); + $this->assertEquals(200, $this->value['code']); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/XmlVisitorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/XmlVisitorTest.php new file mode 100644 index 000000000..f87cec7cd --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/Response/XmlVisitorTest.php @@ -0,0 +1,431 @@ +getMockBuilder('Guzzle\Service\Command\AbstractCommand') + ->setMethods(array('getResponse')) + ->getMockForAbstractClass(); + $command->expects($this->once()) + ->method('getResponse') + ->will($this->returnValue(new Response(200, null, 'test'))); + $result = array(); + $visitor->before($command, $result); + $this->assertEquals(array('Bar' => 'test'), $result); + } + + public function testBeforeMethodParsesXmlWithNamespace() + { + $this->markTestSkipped("Response/XmlVisitor cannot accept 'xmlns' in response, see #368 (http://git.io/USa1mA)."); + + $visitor = new Visitor(); + $command = $this->getMockBuilder('Guzzle\Service\Command\AbstractCommand') + ->setMethods(array('getResponse')) + ->getMockForAbstractClass(); + $command->expects($this->once()) + ->method('getResponse') + ->will($this->returnValue(new Response(200, null, 'test'))); + $result = array(); + $visitor->before($command, $result); + $this->assertEquals(array('Bar' => 'test'), $result); + } + + public function testBeforeMethodParsesNestedXml() + { + $visitor = new Visitor(); + $command = $this->getMockBuilder('Guzzle\Service\Command\AbstractCommand') + ->setMethods(array('getResponse')) + ->getMockForAbstractClass(); + $command->expects($this->once()) + ->method('getResponse') + ->will($this->returnValue(new Response(200, null, 'test'))); + $result = array(); + $visitor->before($command, $result); + $this->assertEquals(array('Items' => array('Bar' => 'test')), $result); + } + + public function testCanExtractAndRenameTopLevelXmlValues() + { + $visitor = new Visitor(); + $param = new Parameter(array( + 'location' => 'xml', + 'name' => 'foo', + 'sentAs' => 'Bar' + )); + $value = array('Bar' => 'test'); + $visitor->visit($this->command, $this->response, $param, $value); + $this->assertArrayHasKey('foo', $value); + $this->assertEquals('test', $value['foo']); + } + + public function testEnsuresRepeatedArraysAreInCorrectLocations() + { + $visitor = new Visitor(); + $param = new Parameter(array( + 'location' => 'xml', + 'name' => 'foo', + 'sentAs' => 'Foo', + 'type' => 'array', + 'items' => array( + 'type' => 'object', + 'properties' => array( + 'Bar' => array('type' => 'string'), + 'Baz' => array('type' => 'string'), + 'Bam' => array('type' => 'string') + ) + ) + )); + + $xml = new \SimpleXMLElement('12'); + $value = json_decode(json_encode($xml), true); + $visitor->visit($this->command, $this->response, $param, $value); + $this->assertEquals(array( + 'foo' => array( + array ( + 'Bar' => '1', + 'Baz' => '2' + ) + ) + ), $value); + } + + public function testEnsuresFlatArraysAreFlat() + { + $visitor = new Visitor(); + $param = new Parameter(array( + 'location' => 'xml', + 'name' => 'foo', + 'type' => 'array', + 'items' => array('type' => 'string') + )); + + $value = array('foo' => array('bar', 'baz')); + $visitor->visit($this->command, $this->response, $param, $value); + $this->assertEquals(array('foo' => array('bar', 'baz')), $value); + + $value = array('foo' => 'bar'); + $visitor->visit($this->command, $this->response, $param, $value); + $this->assertEquals(array('foo' => array('bar')), $value); + } + + public function xmlDataProvider() + { + $param = new Parameter(array( + 'location' => 'xml', + 'name' => 'Items', + 'type' => 'array', + 'items' => array( + 'type' => 'object', + 'name' => 'Item', + 'properties' => array( + 'Bar' => array('type' => 'string'), + 'Baz' => array('type' => 'string') + ) + ) + )); + + return array( + array($param, '12', array( + 'Items' => array( + array('Bar' => 1), + array('Bar' => 2) + ) + )), + array($param, '1', array( + 'Items' => array( + array('Bar' => 1) + ) + )), + array($param, '', array( + 'Items' => array() + )) + ); + } + + /** + * @dataProvider xmlDataProvider + */ + public function testEnsuresWrappedArraysAreInCorrectLocations($param, $xml, $result) + { + $visitor = new Visitor(); + $xml = new \SimpleXMLElement($xml); + $value = json_decode(json_encode($xml), true); + $visitor->visit($this->command, $this->response, $param, $value); + $this->assertEquals($result, $value); + } + + public function testCanRenameValues() + { + $visitor = new Visitor(); + $param = new Parameter(array( + 'name' => 'TerminatingInstances', + 'type' => 'array', + 'location' => 'xml', + 'sentAs' => 'instancesSet', + 'items' => array( + 'name' => 'item', + 'type' => 'object', + 'sentAs' => 'item', + 'properties' => array( + 'InstanceId' => array( + 'type' => 'string', + 'sentAs' => 'instanceId', + ), + 'CurrentState' => array( + 'type' => 'object', + 'sentAs' => 'currentState', + 'properties' => array( + 'Code' => array( + 'type' => 'numeric', + 'sentAs' => 'code', + ), + 'Name' => array( + 'type' => 'string', + 'sentAs' => 'name', + ), + ), + ), + 'PreviousState' => array( + 'type' => 'object', + 'sentAs' => 'previousState', + 'properties' => array( + 'Code' => array( + 'type' => 'numeric', + 'sentAs' => 'code', + ), + 'Name' => array( + 'type' => 'string', + 'sentAs' => 'name', + ), + ), + ), + ), + ) + )); + + $value = array( + 'instancesSet' => array ( + 'item' => array ( + 'instanceId' => 'i-3ea74257', + 'currentState' => array( + 'code' => '32', + 'name' => 'shutting-down', + ), + 'previousState' => array( + 'code' => '16', + 'name' => 'running', + ), + ), + ) + ); + + $visitor->visit($this->command, $this->response, $param, $value); + + $this->assertEquals(array( + 'TerminatingInstances' => array( + array( + 'InstanceId' => 'i-3ea74257', + 'CurrentState' => array( + 'Code' => '32', + 'Name' => 'shutting-down', + ), + 'PreviousState' => array( + 'Code' => '16', + 'Name' => 'running', + ) + ) + ) + ), $value); + } + + public function testCanRenameAttributes() + { + $visitor = new Visitor(); + $param = new Parameter(array( + 'name' => 'RunningQueues', + 'type' => 'array', + 'location' => 'xml', + 'items' => array( + 'type' => 'object', + 'sentAs' => 'item', + 'properties' => array( + 'QueueId' => array( + 'type' => 'string', + 'sentAs' => 'queue_id', + 'data' => array( + 'xmlAttribute' => true, + ), + ), + 'CurrentState' => array( + 'type' => 'object', + 'properties' => array( + 'Code' => array( + 'type' => 'numeric', + 'sentAs' => 'code', + 'data' => array( + 'xmlAttribute' => true, + ), + ), + 'Name' => array( + 'sentAs' => 'name', + 'data' => array( + 'xmlAttribute' => true, + ), + ), + ), + ), + 'PreviousState' => array( + 'type' => 'object', + 'properties' => array( + 'Code' => array( + 'type' => 'numeric', + 'sentAs' => 'code', + 'data' => array( + 'xmlAttribute' => true, + ), + ), + 'Name' => array( + 'sentAs' => 'name', + 'data' => array( + 'xmlAttribute' => true, + ), + ), + ), + ), + ), + ) + )); + + $xml = ''; + $value = json_decode(json_encode(new \SimpleXMLElement($xml)), true); + $visitor->visit($this->command, $this->response, $param, $value); + + $this->assertEquals(array( + 'RunningQueues' => array( + array( + 'QueueId' => 'q-3ea74257', + 'CurrentState' => array( + 'Code' => '32', + 'Name' => 'processing', + ), + 'PreviousState' => array( + 'Code' => '16', + 'Name' => 'wait', + ), + ), + ) + ), $value); + } + + public function testAddsEmptyArraysWhenValueIsMissing() + { + $visitor = new Visitor(); + $param = new Parameter(array( + 'name' => 'Foo', + 'type' => 'array', + 'location' => 'xml', + 'items' => array( + 'type' => 'object', + 'properties' => array( + 'Baz' => array('type' => 'array'), + 'Bar' => array( + 'type' => 'object', + 'properties' => array( + 'Baz' => array('type' => 'array'), + ) + ) + ) + ) + )); + + $value = array(); + $visitor->visit($this->command, $this->response, $param, $value); + + $value = array( + 'Foo' => array( + 'Bar' => array() + ) + ); + $visitor->visit($this->command, $this->response, $param, $value); + $this->assertEquals(array( + 'Foo' => array( + array( + 'Bar' => array() + ) + ) + ), $value); + } + + /** + * @group issue-399 + * @link https://github.com/guzzle/guzzle/issues/399 + */ + public function testDiscardingUnknownProperties() + { + $visitor = new Visitor(); + $param = new Parameter(array( + 'name' => 'foo', + 'type' => 'object', + 'additionalProperties' => false, + 'properties' => array( + 'bar' => array( + 'type' => 'string', + 'name' => 'bar', + ), + ), + )); + $this->value = array('foo' => array('bar' => 15, 'unknown' => 'Unknown')); + $visitor->visit($this->command, $this->response, $param, $this->value); + $this->assertEquals(array('foo' => array('bar' => 15)), $this->value); + } + + /** + * @group issue-399 + * @link https://github.com/guzzle/guzzle/issues/399 + */ + public function testDiscardingUnknownPropertiesWithAliasing() + { + $visitor = new Visitor(); + $param = new Parameter(array( + 'name' => 'foo', + 'type' => 'object', + 'additionalProperties' => false, + 'properties' => array( + 'bar' => array( + 'name' => 'bar', + 'sentAs' => 'baz', + ), + ), + )); + $this->value = array('foo' => array('baz' => 15, 'unknown' => 'Unknown')); + $visitor->visit($this->command, $this->response, $param, $this->value); + $this->assertEquals(array('foo' => array('bar' => 15)), $this->value); + } + + public function testProperlyHandlesEmptyStringValues() + { + $visitor = new Visitor(); + $param = new Parameter(array( + 'name' => 'foo', + 'type' => 'object', + 'properties' => array( + 'bar' => array('type' => 'string') + ), + )); + $xml = ''; + $value = json_decode(json_encode(new \SimpleXMLElement($xml)), true); + $visitor->visit($this->command, $this->response, $param, $value); + $this->assertEquals(array('foo' => array('bar' => '')), $value); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/VisitorFlyweightTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/VisitorFlyweightTest.php new file mode 100644 index 000000000..a252ffe60 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/LocationVisitor/VisitorFlyweightTest.php @@ -0,0 +1,53 @@ +assertInstanceOf('Guzzle\Service\Command\LocationVisitor\Request\JsonVisitor', $f->getRequestVisitor('json')); + $this->assertInstanceOf('Guzzle\Service\Command\LocationVisitor\Response\JsonVisitor', $f->getResponseVisitor('json')); + } + + public function testCanUseCustomMappings() + { + $f = new VisitorFlyweight(array()); + $this->assertEquals(array(), $this->readAttribute($f, 'mappings')); + } + + /** + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage No request visitor has been mapped for foo + */ + public function testThrowsExceptionWhenRetrievingUnknownVisitor() + { + VisitorFlyweight::getInstance()->getRequestVisitor('foo'); + } + + public function testCachesVisitors() + { + $f = new VisitorFlyweight(); + $v1 = $f->getRequestVisitor('json'); + $this->assertSame($v1, $f->getRequestVisitor('json')); + } + + public function testAllowsAddingVisitors() + { + $f = new VisitorFlyweight(); + $j1 = new JsonRequestVisitor(); + $j2 = new JsonResponseVisitor(); + $f->addRequestVisitor('json', $j1); + $f->addResponseVisitor('json', $j2); + $this->assertSame($j1, $f->getRequestVisitor('json')); + $this->assertSame($j2, $f->getResponseVisitor('json')); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/OperationCommandTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/OperationCommandTest.php new file mode 100644 index 000000000..95fb533af --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/OperationCommandTest.php @@ -0,0 +1,102 @@ +getRequestSerializer(); + $b = new DefaultRequestSerializer(VisitorFlyweight::getInstance()); + $operation->setRequestSerializer($b); + $this->assertNotSame($a, $operation->getRequestSerializer()); + } + + public function testPreparesRequestUsingSerializer() + { + $op = new OperationCommand(array(), new Operation()); + $op->setClient(new Client()); + $s = $this->getMockBuilder('Guzzle\Service\Command\RequestSerializerInterface') + ->setMethods(array('prepare')) + ->getMockForAbstractClass(); + $s->expects($this->once()) + ->method('prepare') + ->will($this->returnValue(new EntityEnclosingRequest('POST', 'http://foo.com'))); + $op->setRequestSerializer($s); + $op->prepare(); + } + + public function testParsesResponsesWithResponseParser() + { + $op = new OperationCommand(array(), new Operation()); + $p = $this->getMockBuilder('Guzzle\Service\Command\ResponseParserInterface') + ->setMethods(array('parse')) + ->getMockForAbstractClass(); + $p->expects($this->once()) + ->method('parse') + ->will($this->returnValue(array('foo' => 'bar'))); + $op->setResponseParser($p); + $op->setClient(new Client()); + $request = $op->prepare(); + $request->setResponse(new Response(200), true); + $this->assertEquals(array('foo' => 'bar'), $op->execute()); + } + + public function testParsesResponsesUsingModelParserWhenMatchingModelIsFound() + { + $description = ServiceDescription::factory(array( + 'operations' => array( + 'foo' => array('responseClass' => 'bar', 'responseType' => 'model') + ), + 'models' => array( + 'bar' => array( + 'type' => 'object', + 'properties' => array( + 'Baz' => array('type' => 'string', 'location' => 'xml') + ) + ) + ) + )); + + $op = new OperationCommand(array(), $description->getOperation('foo')); + $op->setClient(new Client()); + $request = $op->prepare(); + $request->setResponse(new Response(200, array( + 'Content-Type' => 'application/xml' + ), 'Bar'), true); + $result = $op->execute(); + $this->assertEquals(new Model(array('Baz' => 'Bar')), $result); + } + + public function testAllowsRawResponses() + { + $description = new ServiceDescription(array( + 'operations' => array('foo' => array('responseClass' => 'bar', 'responseType' => 'model')), + 'models' => array('bar' => array()) + )); + $op = new OperationCommand(array( + OperationCommand::RESPONSE_PROCESSING => OperationCommand::TYPE_RAW + ), $description->getOperation('foo')); + $op->setClient(new Client()); + $request = $op->prepare(); + $response = new Response(200, array( + 'Content-Type' => 'application/xml' + ), 'Bar'); + $request->setResponse($response, true); + $this->assertSame($response, $op->execute()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/OperationResponseParserTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/OperationResponseParserTest.php new file mode 100644 index 000000000..69ba1fcea --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Command/OperationResponseParserTest.php @@ -0,0 +1,335 @@ +addVisitor('foo', $visitor); + $this->assertSame($visitor, $this->readAttribute($p, 'factory')->getResponseVisitor('foo')); + } + + public function testUsesParentParser() + { + $p = new OperationResponseParser(new VisitorFlyweight()); + $operation = new Operation(); + $operation->setServiceDescription(new ServiceDescription()); + $op = new OperationCommand(array(), $operation); + $op->setResponseParser($p)->setClient(new Client()); + $op->prepare()->setResponse(new Response(200, array('Content-Type' => 'application/xml'), 'C'), true); + $this->assertInstanceOf('SimpleXMLElement', $op->execute()); + } + + public function testVisitsLocations() + { + $parser = new OperationResponseParser(new VisitorFlyweight(array())); + $parser->addVisitor('statusCode', new StatusCodeVisitor()); + $parser->addVisitor('reasonPhrase', new ReasonPhraseVisitor()); + $parser->addVisitor('json', new JsonVisitor()); + $op = new OperationCommand(array(), $this->getDescription()->getOperation('test')); + $op->setResponseParser($parser)->setClient(new Client()); + $op->prepare()->setResponse(new Response(201), true); + $result = $op->execute(); + $this->assertEquals(201, $result['code']); + $this->assertEquals('Created', $result['phrase']); + } + + public function testVisitsLocationsForJsonResponse() + { + $parser = OperationResponseParser::getInstance(); + $operation = $this->getDescription()->getOperation('test'); + $op = new OperationCommand(array(), $operation); + $op->setResponseParser($parser)->setClient(new Client()); + $op->prepare()->setResponse(new Response(200, array( + 'Content-Type' => 'application/json' + ), '{"baz":"bar","enigma":"123"}'), true); + $result = $op->execute(); + $this->assertEquals(array( + 'baz' => 'bar', + 'enigma' => '123', + 'code' => 200, + 'phrase' => 'OK' + ), $result->toArray()); + } + + public function testSkipsUnkownModels() + { + $parser = OperationResponseParser::getInstance(); + $operation = $this->getDescription()->getOperation('test'); + $operation->setResponseClass('Baz')->setResponseType('model'); + $op = new OperationCommand(array(), $operation); + $op->setResponseParser($parser)->setClient(new Client()); + $op->prepare()->setResponse(new Response(201), true); + $this->assertInstanceOf('Guzzle\Http\Message\Response', $op->execute()); + } + + public function testAllowsModelProcessingToBeDisabled() + { + $parser = OperationResponseParser::getInstance(); + $operation = $this->getDescription()->getOperation('test'); + $op = new OperationCommand(array('command.response_processing' => 'native'), $operation); + $op->setResponseParser($parser)->setClient(new Client()); + $op->prepare()->setResponse(new Response(200, array( + 'Content-Type' => 'application/json' + ), '{"baz":"bar","enigma":"123"}'), true); + $result = $op->execute(); + $this->assertInstanceOf('Guzzle\Service\Resource\Model', $result); + $this->assertEquals(array( + 'baz' => 'bar', + 'enigma' => '123' + ), $result->toArray()); + } + + public function testCanInjectModelSchemaIntoModels() + { + $parser = new OperationResponseParser(VisitorFlyweight::getInstance(), true); + $desc = $this->getDescription(); + $operation = $desc->getOperation('test'); + $op = new OperationCommand(array(), $operation); + $op->setResponseParser($parser)->setClient(new Client()); + $op->prepare()->setResponse(new Response(200, array( + 'Content-Type' => 'application/json' + ), '{"baz":"bar","enigma":"123"}'), true); + $result = $op->execute(); + $this->assertSame($result->getStructure(), $desc->getModel('Foo')); + } + + public function testDoesNotParseXmlWhenNotUsingXmlVisitor() + { + $parser = OperationResponseParser::getInstance(); + $description = ServiceDescription::factory(array( + 'operations' => array('test' => array('responseClass' => 'Foo')), + 'models' => array( + 'Foo' => array( + 'type' => 'object', + 'properties' => array('baz' => array('location' => 'body')) + ) + ) + )); + $operation = $description->getOperation('test'); + $op = new OperationCommand(array(), $operation); + $op->setResponseParser($parser)->setClient(new Client()); + $brokenXml = '<><><>>>>'; + $op->prepare()->setResponse(new Response(200, array( + 'Content-Type' => 'application/xml' + ), $brokenXml), true); + $result = $op->execute(); + $this->assertEquals(array('baz'), $result->getKeys()); + $this->assertEquals($brokenXml, (string) $result['baz']); + } + + public function testVisitsAdditionalProperties() + { + $parser = OperationResponseParser::getInstance(); + $description = ServiceDescription::factory(array( + 'operations' => array('test' => array('responseClass' => 'Foo')), + 'models' => array( + 'Foo' => array( + 'type' => 'object', + 'properties' => array( + 'code' => array('location' => 'statusCode') + ), + 'additionalProperties' => array( + 'location' => 'json', + 'type' => 'object', + 'properties' => array( + 'a' => array( + 'type' => 'string', + 'filters' => 'strtoupper' + ) + ) + ) + ) + ) + )); + + $operation = $description->getOperation('test'); + $op = new OperationCommand(array(), $operation); + $op->setResponseParser($parser)->setClient(new Client()); + $json = '[{"a":"test"},{"a":"baz"}]'; + $op->prepare()->setResponse(new Response(200, array('Content-Type' => 'application/json'), $json), true); + $result = $op->execute()->toArray(); + $this->assertEquals(array( + 'code' => 200, + array('a' => 'TEST'), + array('a' => 'BAZ') + ), $result); + } + + /** + * @group issue-399 + * @link https://github.com/guzzle/guzzle/issues/399 + */ + public function testAdditionalPropertiesDisabledDiscardsData() + { + $parser = OperationResponseParser::getInstance(); + $description = ServiceDescription::factory(array( + 'operations' => array('test' => array('responseClass' => 'Foo')), + 'models' => array( + 'Foo' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'properties' => array( + 'name' => array( + 'location' => 'json', + 'type' => 'string', + ), + 'nested' => array( + 'location' => 'json', + 'type' => 'object', + 'additionalProperties' => false, + 'properties' => array( + 'width' => array( + 'type' => 'integer' + ) + ), + ), + 'code' => array('location' => 'statusCode') + ), + + ) + ) + )); + + $operation = $description->getOperation('test'); + $op = new OperationCommand(array(), $operation); + $op->setResponseParser($parser)->setClient(new Client()); + $json = '{"name":"test", "volume":2.0, "nested":{"width":10,"bogus":1}}'; + $op->prepare()->setResponse(new Response(200, array('Content-Type' => 'application/json'), $json), true); + $result = $op->execute()->toArray(); + $this->assertEquals(array( + 'name' => 'test', + 'nested' => array( + 'width' => 10, + ), + 'code' => 200 + ), $result); + } + + public function testCreatesCustomResponseClassInterface() + { + $parser = OperationResponseParser::getInstance(); + $description = ServiceDescription::factory(array( + 'operations' => array('test' => array('responseClass' => 'Guzzle\Tests\Mock\CustomResponseModel')) + )); + $operation = $description->getOperation('test'); + $op = new OperationCommand(array(), $operation); + $op->setResponseParser($parser)->setClient(new Client()); + $op->prepare()->setResponse(new Response(200, array('Content-Type' => 'application/json'), 'hi!'), true); + $result = $op->execute(); + $this->assertInstanceOf('Guzzle\Tests\Mock\CustomResponseModel', $result); + $this->assertSame($op, $result->command); + } + + /** + * @expectedException \Guzzle\Service\Exception\ResponseClassException + * @expectedExceptionMessage must exist + */ + public function testEnsuresResponseClassExists() + { + $parser = OperationResponseParser::getInstance(); + $description = ServiceDescription::factory(array( + 'operations' => array('test' => array('responseClass' => 'Foo\Baz\Bar')) + )); + $operation = $description->getOperation('test'); + $op = new OperationCommand(array(), $operation); + $op->setResponseParser($parser)->setClient(new Client()); + $op->prepare()->setResponse(new Response(200, array('Content-Type' => 'application/json'), 'hi!'), true); + $op->execute(); + } + + /** + * @expectedException \Guzzle\Service\Exception\ResponseClassException + * @expectedExceptionMessage and implement + */ + public function testEnsuresResponseClassImplementsResponseClassInterface() + { + $parser = OperationResponseParser::getInstance(); + $description = ServiceDescription::factory(array( + 'operations' => array('test' => array('responseClass' => __CLASS__)) + )); + $operation = $description->getOperation('test'); + $op = new OperationCommand(array(), $operation); + $op->setResponseParser($parser)->setClient(new Client()); + $op->prepare()->setResponse(new Response(200, array('Content-Type' => 'application/json'), 'hi!'), true); + $op->execute(); + } + + protected function getDescription() + { + return ServiceDescription::factory(array( + 'operations' => array('test' => array('responseClass' => 'Foo')), + 'models' => array( + 'Foo' => array( + 'type' => 'object', + 'properties' => array( + 'baz' => array('type' => 'string', 'location' => 'json'), + 'code' => array('location' => 'statusCode'), + 'phrase' => array('location' => 'reasonPhrase'), + ) + ) + ) + )); + } + + public function testCanAddListenerToParseDomainObjects() + { + $client = new Client(); + $client->setDescription(ServiceDescription::factory(array( + 'operations' => array('test' => array('responseClass' => 'FooBazBar')) + ))); + $foo = new \stdClass(); + $client->getEventDispatcher()->addListener('command.parse_response', function ($e) use ($foo) { + $e['result'] = $foo; + }); + $command = $client->getCommand('test'); + $command->prepare()->setResponse(new Response(200), true); + $result = $command->execute(); + $this->assertSame($result, $foo); + } + + /** + * @group issue-399 + * @link https://github.com/guzzle/guzzle/issues/501 + */ + public function testAdditionalPropertiesWithRefAreResolved() + { + $parser = OperationResponseParser::getInstance(); + $description = ServiceDescription::factory(array( + 'operations' => array('test' => array('responseClass' => 'Foo')), + 'models' => array( + 'Baz' => array('type' => 'string'), + 'Foo' => array( + 'type' => 'object', + 'additionalProperties' => array('$ref' => 'Baz', 'location' => 'json') + ) + ) + )); + $operation = $description->getOperation('test'); + $op = new OperationCommand(array(), $operation); + $op->setResponseParser($parser)->setClient(new Client()); + $json = '{"a":"a","b":"b","c":"c"}'; + $op->prepare()->setResponse(new Response(200, array('Content-Type' => 'application/json'), $json), true); + $result = $op->execute()->toArray(); + $this->assertEquals(array('a' => 'a', 'b' => 'b', 'c' => 'c'), $result); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/OperationTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/OperationTest.php new file mode 100644 index 000000000..ae33b6925 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/OperationTest.php @@ -0,0 +1,308 @@ + 'test', + 'summary' => 'doc', + 'notes' => 'notes', + 'documentationUrl' => 'http://www.example.com', + 'httpMethod' => 'POST', + 'uri' => '/api/v1', + 'responseClass' => 'array', + 'responseNotes' => 'returns the json_decoded response', + 'deprecated' => true, + 'parameters' => array( + 'key' => array( + 'required' => true, + 'type' => 'string', + 'maxLength' => 10 + ), + 'key_2' => array( + 'required' => true, + 'type' => 'integer', + 'default' => 10 + ) + ) + )); + + $this->assertEquals('test', $c->getName()); + $this->assertEquals('doc', $c->getSummary()); + $this->assertEquals('http://www.example.com', $c->getDocumentationUrl()); + $this->assertEquals('POST', $c->getHttpMethod()); + $this->assertEquals('/api/v1', $c->getUri()); + $this->assertEquals('array', $c->getResponseClass()); + $this->assertEquals('returns the json_decoded response', $c->getResponseNotes()); + $this->assertTrue($c->getDeprecated()); + $this->assertEquals('Guzzle\\Service\\Command\\OperationCommand', $c->getClass()); + $this->assertEquals(array( + 'key' => new Parameter(array( + 'name' => 'key', + 'required' => true, + 'type' => 'string', + 'maxLength' => 10, + 'parent' => $c + )), + 'key_2' => new Parameter(array( + 'name' => 'key_2', + 'required' => true, + 'type' => 'integer', + 'default' => 10, + 'parent' => $c + )) + ), $c->getParams()); + + $this->assertEquals(new Parameter(array( + 'name' => 'key_2', + 'required' => true, + 'type' => 'integer', + 'default' => 10, + 'parent' => $c + )), $c->getParam('key_2')); + + $this->assertNull($c->getParam('afefwef')); + $this->assertArrayNotHasKey('parent', $c->getParam('key_2')->toArray()); + } + + public function testAllowsConcreteCommands() + { + $c = new Operation(array( + 'name' => 'test', + 'class' => 'Guzzle\\Service\\Command\ClosureCommand', + 'parameters' => array( + 'p' => new Parameter(array( + 'name' => 'foo' + )) + ) + )); + $this->assertEquals('Guzzle\\Service\\Command\ClosureCommand', $c->getClass()); + } + + public function testConvertsToArray() + { + $data = array( + 'name' => 'test', + 'class' => 'Guzzle\\Service\\Command\ClosureCommand', + 'summary' => 'test', + 'documentationUrl' => 'http://www.example.com', + 'httpMethod' => 'PUT', + 'uri' => '/', + 'parameters' => array('p' => array('name' => 'foo')) + ); + $c = new Operation($data); + $toArray = $c->toArray(); + unset($data['name']); + $this->assertArrayHasKey('parameters', $toArray); + $this->assertInternalType('array', $toArray['parameters']); + + // Normalize the array + unset($data['parameters']); + unset($toArray['parameters']); + + $data['responseType'] = 'primitive'; + $data['responseClass'] = 'array'; + $this->assertEquals($data, $toArray); + } + + public function testDeterminesIfHasParam() + { + $command = $this->getTestCommand(); + $this->assertTrue($command->hasParam('data')); + $this->assertFalse($command->hasParam('baz')); + } + + public function testReturnsParamNames() + { + $command = $this->getTestCommand(); + $this->assertEquals(array('data'), $command->getParamNames()); + } + + protected function getTestCommand() + { + return new Operation(array( + 'parameters' => array( + 'data' => new Parameter(array( + 'type' => 'string' + )) + ) + )); + } + + public function testCanBuildUpCommands() + { + $c = new Operation(array()); + $c->setName('foo') + ->setClass('Baz') + ->setDeprecated(false) + ->setSummary('summary') + ->setDocumentationUrl('http://www.foo.com') + ->setHttpMethod('PUT') + ->setResponseNotes('oh') + ->setResponseClass('string') + ->setUri('/foo/bar') + ->addParam(new Parameter(array( + 'name' => 'test' + ))); + + $this->assertEquals('foo', $c->getName()); + $this->assertEquals('Baz', $c->getClass()); + $this->assertEquals(false, $c->getDeprecated()); + $this->assertEquals('summary', $c->getSummary()); + $this->assertEquals('http://www.foo.com', $c->getDocumentationUrl()); + $this->assertEquals('PUT', $c->getHttpMethod()); + $this->assertEquals('oh', $c->getResponseNotes()); + $this->assertEquals('string', $c->getResponseClass()); + $this->assertEquals('/foo/bar', $c->getUri()); + $this->assertEquals(array('test'), $c->getParamNames()); + } + + public function testCanRemoveParams() + { + $c = new Operation(array()); + $c->addParam(new Parameter(array('name' => 'foo'))); + $this->assertTrue($c->hasParam('foo')); + $c->removeParam('foo'); + $this->assertFalse($c->hasParam('foo')); + } + + public function testAddsNameToParametersIfNeeded() + { + $command = new Operation(array('parameters' => array('foo' => new Parameter(array())))); + $this->assertEquals('foo', $command->getParam('foo')->getName()); + } + + public function testContainsApiErrorInformation() + { + $command = $this->getOperation(); + $this->assertEquals(1, count($command->getErrorResponses())); + $arr = $command->toArray(); + $this->assertEquals(1, count($arr['errorResponses'])); + $command->addErrorResponse(400, 'Foo', 'Baz\\Bar'); + $this->assertEquals(2, count($command->getErrorResponses())); + $command->setErrorResponses(array()); + $this->assertEquals(0, count($command->getErrorResponses())); + } + + public function testHasNotes() + { + $o = new Operation(array('notes' => 'foo')); + $this->assertEquals('foo', $o->getNotes()); + $o->setNotes('bar'); + $this->assertEquals('bar', $o->getNotes()); + } + + public function testHasData() + { + $o = new Operation(array('data' => array('foo' => 'baz', 'bar' => 123))); + $o->setData('test', false); + $this->assertEquals('baz', $o->getData('foo')); + $this->assertEquals(123, $o->getData('bar')); + $this->assertNull($o->getData('wfefwe')); + $this->assertEquals(array( + 'parameters' => array(), + 'class' => 'Guzzle\Service\Command\OperationCommand', + 'data' => array('foo' => 'baz', 'bar' => 123, 'test' => false), + 'responseClass' => 'array', + 'responseType' => 'primitive' + ), $o->toArray()); + } + + public function testHasServiceDescription() + { + $s = new ServiceDescription(); + $o = new Operation(array(), $s); + $this->assertSame($s, $o->getServiceDescription()); + } + + /** + * @expectedException Guzzle\Common\Exception\InvalidArgumentException + */ + public function testValidatesResponseType() + { + $o = new Operation(array('responseClass' => 'array', 'responseType' => 'foo')); + } + + public function testInfersResponseType() + { + $o = $this->getOperation(); + $o->setServiceDescription(new ServiceDescription(array('models' => array('Foo' => array())))); + $this->assertEquals('primitive', $o->getResponseType()); + $this->assertEquals('primitive', $o->setResponseClass('boolean')->getResponseType()); + $this->assertEquals('primitive', $o->setResponseClass('array')->getResponseType()); + $this->assertEquals('primitive', $o->setResponseClass('integer')->getResponseType()); + $this->assertEquals('primitive', $o->setResponseClass('string')->getResponseType()); + $this->assertEquals('class', $o->setResponseClass('foo')->getResponseType()); + $this->assertEquals('class', $o->setResponseClass(__CLASS__)->getResponseType()); + $this->assertEquals('model', $o->setResponseClass('Foo')->getResponseType()); + } + + public function testHasResponseType() + { + // infers in the constructor + $o = new Operation(array('responseClass' => 'array')); + $this->assertEquals('primitive', $o->getResponseType()); + // Infers when set + $o = new Operation(); + $this->assertEquals('primitive', $o->getResponseType()); + $this->assertEquals('model', $o->setResponseType('model')->getResponseType()); + } + + public function testHasAdditionalParameters() + { + $o = new Operation(array( + 'additionalParameters' => array( + 'type' => 'string', 'name' => 'binks' + ), + 'parameters' => array( + 'foo' => array('type' => 'integer') + ) + )); + $this->assertEquals('string', $o->getAdditionalParameters()->getType()); + $arr = $o->toArray(); + $this->assertEquals(array( + 'type' => 'string' + ), $arr['additionalParameters']); + } + + /** + * @return Operation + */ + protected function getOperation() + { + return new Operation(array( + 'name' => 'OperationTest', + 'class' => get_class($this), + 'parameters' => array( + 'test' => array('type' => 'object'), + 'bool_1' => array('default' => true, 'type' => 'boolean'), + 'bool_2' => array('default' => false), + 'float' => array('type' => 'numeric'), + 'int' => array('type' => 'integer'), + 'date' => array('type' => 'string'), + 'timestamp' => array('type' => 'string'), + 'string' => array('type' => 'string'), + 'username' => array('type' => 'string', 'required' => true, 'filters' => 'strtolower'), + 'test_function' => array('type' => 'string', 'filters' => __CLASS__ . '::strtoupper') + ), + 'errorResponses' => array( + array('code' => 503, 'reason' => 'InsufficientCapacity', 'class' => 'Guzzle\\Exception\\RuntimeException') + ) + )); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/ParameterTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/ParameterTest.php new file mode 100644 index 000000000..b9c162aae --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/ParameterTest.php @@ -0,0 +1,411 @@ + 'foo', + 'type' => 'bar', + 'required' => true, + 'default' => '123', + 'description' => '456', + 'minLength' => 2, + 'maxLength' => 5, + 'location' => 'body', + 'static' => 'static!', + 'filters' => array('trim', 'json_encode') + ); + + public function testCreatesParamFromArray() + { + $p = new Parameter($this->data); + $this->assertEquals('foo', $p->getName()); + $this->assertEquals('bar', $p->getType()); + $this->assertEquals(true, $p->getRequired()); + $this->assertEquals('123', $p->getDefault()); + $this->assertEquals('456', $p->getDescription()); + $this->assertEquals(2, $p->getMinLength()); + $this->assertEquals(5, $p->getMaxLength()); + $this->assertEquals('body', $p->getLocation()); + $this->assertEquals('static!', $p->getStatic()); + $this->assertEquals(array('trim', 'json_encode'), $p->getFilters()); + } + + public function testCanConvertToArray() + { + $p = new Parameter($this->data); + unset($this->data['name']); + $this->assertEquals($this->data, $p->toArray()); + } + + public function testUsesStatic() + { + $d = $this->data; + $d['default'] = 'booboo'; + $d['static'] = true; + $p = new Parameter($d); + $this->assertEquals('booboo', $p->getValue('bar')); + } + + public function testUsesDefault() + { + $d = $this->data; + $d['default'] = 'foo'; + $d['static'] = null; + $p = new Parameter($d); + $this->assertEquals('foo', $p->getValue(null)); + } + + public function testReturnsYourValue() + { + $d = $this->data; + $d['static'] = null; + $p = new Parameter($d); + $this->assertEquals('foo', $p->getValue('foo')); + } + + public function testZeroValueDoesNotCauseDefaultToBeReturned() + { + $d = $this->data; + $d['default'] = '1'; + $d['static'] = null; + $p = new Parameter($d); + $this->assertEquals('0', $p->getValue('0')); + } + + public function testFiltersValues() + { + $d = $this->data; + $d['static'] = null; + $d['filters'] = 'strtoupper'; + $p = new Parameter($d); + $this->assertEquals('FOO', $p->filter('foo')); + } + + public function testConvertsBooleans() + { + $p = new Parameter(array('type' => 'boolean')); + $this->assertEquals(true, $p->filter('true')); + $this->assertEquals(false, $p->filter('false')); + } + + public function testUsesArrayByDefaultForFilters() + { + $d = $this->data; + $d['filters'] = null; + $p = new Parameter($d); + $this->assertEquals(array(), $p->getFilters()); + } + + public function testAllowsSimpleLocationValue() + { + $p = new Parameter(array('name' => 'myname', 'location' => 'foo', 'sentAs' => 'Hello')); + $this->assertEquals('foo', $p->getLocation()); + $this->assertEquals('Hello', $p->getSentAs()); + } + + public function testParsesTypeValues() + { + $p = new Parameter(array('type' => 'foo')); + $this->assertEquals('foo', $p->getType()); + } + + /** + * @expectedException InvalidArgumentException + * @expectedExceptionMessage A [method] value must be specified for each complex filter + */ + public function testValidatesComplexFilters() + { + $p = new Parameter(array('filters' => array(array('args' => 'foo')))); + } + + public function testCanBuildUpParams() + { + $p = new Parameter(array()); + $p->setName('foo') + ->setDescription('c') + ->setFilters(array('d')) + ->setLocation('e') + ->setSentAs('f') + ->setMaxLength(1) + ->setMinLength(1) + ->setMinimum(2) + ->setMaximum(2) + ->setMinItems(3) + ->setMaxItems(3) + ->setRequired(true) + ->setStatic(true) + ->setDefault('h') + ->setType('i'); + + $p->addFilter('foo'); + + $this->assertEquals('foo', $p->getName()); + $this->assertEquals('h', $p->getDefault()); + $this->assertEquals('c', $p->getDescription()); + $this->assertEquals(array('d', 'foo'), $p->getFilters()); + $this->assertEquals('e', $p->getLocation()); + $this->assertEquals('f', $p->getSentAs()); + $this->assertEquals(1, $p->getMaxLength()); + $this->assertEquals(1, $p->getMinLength()); + $this->assertEquals(2, $p->getMaximum()); + $this->assertEquals(2, $p->getMinimum()); + $this->assertEquals(3, $p->getMaxItems()); + $this->assertEquals(3, $p->getMinItems()); + $this->assertEquals(true, $p->getRequired()); + $this->assertEquals(true, $p->getStatic()); + $this->assertEquals('i', $p->getType()); + } + + public function testAllowsNestedShape() + { + $command = $this->getServiceBuilder()->get('mock')->getCommand('mock_command')->getOperation(); + $param = new Parameter(array( + 'parent' => $command, + 'name' => 'foo', + 'type' => 'object', + 'location' => 'query', + 'properties' => array( + 'foo' => array( + 'type' => 'object', + 'required' => true, + 'properties' => array( + 'baz' => array( + 'name' => 'baz', + 'type' => 'bool', + ) + ) + ), + 'bar' => array( + 'name' => 'bar', + 'default' => '123' + ) + ) + )); + + $this->assertSame($command, $param->getParent()); + $this->assertNotEmpty($param->getProperties()); + $this->assertInstanceOf('Guzzle\Service\Description\Parameter', $param->getProperty('foo')); + $this->assertSame($param, $param->getProperty('foo')->getParent()); + $this->assertSame($param->getProperty('foo'), $param->getProperty('foo')->getProperty('baz')->getParent()); + $this->assertInstanceOf('Guzzle\Service\Description\Parameter', $param->getProperty('bar')); + $this->assertSame($param, $param->getProperty('bar')->getParent()); + + $array = $param->toArray(); + $this->assertInternalType('array', $array['properties']); + $this->assertArrayHasKey('foo', $array['properties']); + $this->assertArrayHasKey('bar', $array['properties']); + } + + public function testAllowsComplexFilters() + { + $that = $this; + $param = new Parameter(array()); + $param->setFilters(array(array('method' => function ($a, $b, $c, $d) use ($that, $param) { + $that->assertEquals('test', $a); + $that->assertEquals('my_value!', $b); + $that->assertEquals('bar', $c); + $that->assertSame($param, $d); + return 'abc' . $b; + }, 'args' => array('test', '@value', 'bar', '@api')))); + $this->assertEquals('abcmy_value!', $param->filter('my_value!')); + } + + public function testCanChangeParentOfNestedParameter() + { + $param1 = new Parameter(array('name' => 'parent')); + $param2 = new Parameter(array('name' => 'child')); + $param2->setParent($param1); + $this->assertSame($param1, $param2->getParent()); + } + + public function testCanRemoveFromNestedStructure() + { + $param1 = new Parameter(array('name' => 'parent')); + $param2 = new Parameter(array('name' => 'child')); + $param1->addProperty($param2); + $this->assertSame($param1, $param2->getParent()); + $this->assertSame($param2, $param1->getProperty('child')); + + // Remove a single child from the structure + $param1->removeProperty('child'); + $this->assertNull($param1->getProperty('child')); + // Remove the entire structure + $param1->addProperty($param2); + $param1->removeProperty('child'); + $this->assertNull($param1->getProperty('child')); + } + + public function testAddsAdditionalProperties() + { + $p = new Parameter(array( + 'type' => 'object', + 'additionalProperties' => array('type' => 'string') + )); + $this->assertInstanceOf('Guzzle\Service\Description\Parameter', $p->getAdditionalProperties()); + $this->assertNull($p->getAdditionalProperties()->getAdditionalProperties()); + $p = new Parameter(array('type' => 'object')); + $this->assertTrue($p->getAdditionalProperties()); + } + + public function testAddsItems() + { + $p = new Parameter(array( + 'type' => 'array', + 'items' => array('type' => 'string') + )); + $this->assertInstanceOf('Guzzle\Service\Description\Parameter', $p->getItems()); + $out = $p->toArray(); + $this->assertEquals('array', $out['type']); + $this->assertInternalType('array', $out['items']); + } + + public function testHasExtraProperties() + { + $p = new Parameter(); + $this->assertEquals(array(), $p->getData()); + $p->setData(array('foo' => 'bar')); + $this->assertEquals('bar', $p->getData('foo')); + $p->setData('baz', 'boo'); + $this->assertEquals(array('foo' => 'bar', 'baz' => 'boo'), $p->getData()); + } + + public function testCanRetrieveKnownPropertiesUsingDataMethod() + { + $p = new Parameter(); + $this->assertEquals(null, $p->getData('foo')); + $p->setName('test'); + $this->assertEquals('test', $p->getData('name')); + } + + public function testHasInstanceOf() + { + $p = new Parameter(); + $this->assertNull($p->getInstanceOf()); + $p->setInstanceOf('Foo'); + $this->assertEquals('Foo', $p->getInstanceOf()); + } + + public function testHasPattern() + { + $p = new Parameter(); + $this->assertNull($p->getPattern()); + $p->setPattern('/[0-9]+/'); + $this->assertEquals('/[0-9]+/', $p->getPattern()); + } + + public function testHasEnum() + { + $p = new Parameter(); + $this->assertNull($p->getEnum()); + $p->setEnum(array('foo', 'bar')); + $this->assertEquals(array('foo', 'bar'), $p->getEnum()); + } + + public function testSerializesItems() + { + $p = new Parameter(array( + 'type' => 'object', + 'additionalProperties' => array('type' => 'string') + )); + $this->assertEquals(array( + 'type' => 'object', + 'additionalProperties' => array('type' => 'string') + ), $p->toArray()); + } + + public function testResolvesRefKeysRecursively() + { + $description = new ServiceDescription(array( + 'models' => array( + 'JarJar' => array('type' => 'string', 'default' => 'Mesa address tha senate!'), + 'Anakin' => array('type' => 'array', 'items' => array('$ref' => 'JarJar')) + ) + )); + $p = new Parameter(array('$ref' => 'Anakin', 'description' => 'added'), $description); + $this->assertEquals(array( + 'type' => 'array', + 'items' => array('type' => 'string', 'default' => 'Mesa address tha senate!'), + 'description' => 'added' + ), $p->toArray()); + } + + public function testResolvesExtendsRecursively() + { + $jarJar = array('type' => 'string', 'default' => 'Mesa address tha senate!', 'description' => 'a'); + $anakin = array('type' => 'array', 'items' => array('extends' => 'JarJar', 'description' => 'b')); + $description = new ServiceDescription(array( + 'models' => array('JarJar' => $jarJar, 'Anakin' => $anakin) + )); + // Description attribute will be updated, and format added + $p = new Parameter(array('extends' => 'Anakin', 'format' => 'date'), $description); + $this->assertEquals(array( + 'type' => 'array', + 'format' => 'date', + 'items' => array( + 'type' => 'string', + 'default' => 'Mesa address tha senate!', + 'description' => 'b' + ) + ), $p->toArray()); + } + + public function testHasKeyMethod() + { + $p = new Parameter(array('name' => 'foo', 'sentAs' => 'bar')); + $this->assertEquals('bar', $p->getWireName()); + $p->setSentAs(null); + $this->assertEquals('foo', $p->getWireName()); + } + + public function testIncludesNameInToArrayWhenItemsAttributeHasName() + { + $p = new Parameter(array( + 'type' => 'array', + 'name' => 'Abc', + 'items' => array( + 'name' => 'Foo', + 'type' => 'object' + ) + )); + $result = $p->toArray(); + $this->assertEquals(array( + 'type' => 'array', + 'items' => array( + 'name' => 'Foo', + 'type' => 'object', + 'additionalProperties' => true + ) + ), $result); + } + + public function dateTimeProvider() + { + $d = 'October 13, 2012 16:15:46 UTC'; + + return array( + array($d, 'date-time', '2012-10-13T16:15:46Z'), + array($d, 'date', '2012-10-13'), + array($d, 'timestamp', strtotime($d)), + array(new \DateTime($d), 'timestamp', strtotime($d)) + ); + } + + /** + * @dataProvider dateTimeProvider + */ + public function testAppliesFormat($d, $format, $result) + { + $p = new Parameter(); + $p->setFormat($format); + $this->assertEquals($format, $p->getFormat()); + $this->assertEquals($result, $p->filter($d)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/SchemaFormatterTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/SchemaFormatterTest.php new file mode 100644 index 000000000..eb3619bea --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/SchemaFormatterTest.php @@ -0,0 +1,61 @@ +assertEquals($result, SchemaFormatter::format($format, $value)); + } + + /** + * @expectedException \Guzzle\Common\Exception\InvalidArgumentException + */ + public function testValidatesDateTimeInput() + { + SchemaFormatter::format('date-time', false); + } + + public function testEnsuresTimestampsAreIntegers() + { + $t = time(); + $result = SchemaFormatter::format('timestamp', $t); + $this->assertSame($t, $result); + $this->assertInternalType('int', $result); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/SchemaValidatorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/SchemaValidatorTest.php new file mode 100644 index 000000000..4d6cc8728 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/SchemaValidatorTest.php @@ -0,0 +1,326 @@ +validator = new SchemaValidator(); + } + + public function testValidatesArrayListsAreNumericallyIndexed() + { + $value = array(array(1)); + $this->assertFalse($this->validator->validate($this->getComplexParam(), $value)); + $this->assertEquals( + array('[Foo][0] must be an array of properties. Got a numerically indexed array.'), + $this->validator->getErrors() + ); + } + + public function testValidatesArrayListsContainProperItems() + { + $value = array(true); + $this->assertFalse($this->validator->validate($this->getComplexParam(), $value)); + $this->assertEquals( + array('[Foo][0] must be of type object'), + $this->validator->getErrors() + ); + } + + public function testAddsDefaultValuesInLists() + { + $value = array(array()); + $this->assertTrue($this->validator->validate($this->getComplexParam(), $value)); + $this->assertEquals(array(array('Bar' => true)), $value); + } + + public function testMergesDefaultValuesInLists() + { + $value = array( + array('Baz' => 'hello!'), + array('Bar' => false) + ); + $this->assertTrue($this->validator->validate($this->getComplexParam(), $value)); + $this->assertEquals(array( + array( + 'Baz' => 'hello!', + 'Bar' => true + ), + array('Bar' => false) + ), $value); + } + + public function testCorrectlyConvertsParametersToArrayWhenArraysArePresent() + { + $param = $this->getComplexParam(); + $result = $param->toArray(); + $this->assertInternalType('array', $result['items']); + $this->assertEquals('array', $result['type']); + $this->assertInstanceOf('Guzzle\Service\Description\Parameter', $param->getItems()); + } + + public function testAllowsInstanceOf() + { + $p = new Parameter(array( + 'name' => 'foo', + 'type' => 'object', + 'instanceOf' => get_class($this) + )); + $this->assertTrue($this->validator->validate($p, $this)); + $this->assertFalse($this->validator->validate($p, $p)); + $this->assertEquals(array('[foo] must be an instance of ' . __CLASS__), $this->validator->getErrors()); + } + + public function testEnforcesInstanceOfOnlyWhenObject() + { + $p = new Parameter(array( + 'name' => 'foo', + 'type' => array('object', 'string'), + 'instanceOf' => get_class($this) + )); + $this->assertTrue($this->validator->validate($p, $this)); + $s = 'test'; + $this->assertTrue($this->validator->validate($p, $s)); + } + + public function testConvertsObjectsToArraysWhenToArrayInterface() + { + $o = $this->getMockBuilder('Guzzle\Common\ToArrayInterface') + ->setMethods(array('toArray')) + ->getMockForAbstractClass(); + $o->expects($this->once()) + ->method('toArray') + ->will($this->returnValue(array( + 'foo' => 'bar' + ))); + $p = new Parameter(array( + 'name' => 'test', + 'type' => 'object', + 'properties' => array( + 'foo' => array('required' => 'true') + ) + )); + $this->assertTrue($this->validator->validate($p, $o)); + } + + public function testMergesValidationErrorsInPropertiesWithParent() + { + $p = new Parameter(array( + 'name' => 'foo', + 'type' => 'object', + 'properties' => array( + 'bar' => array('type' => 'string', 'required' => true, 'description' => 'This is what it does'), + 'test' => array('type' => 'string', 'minLength' => 2, 'maxLength' => 5), + 'test2' => array('type' => 'string', 'minLength' => 2, 'maxLength' => 2), + 'test3' => array('type' => 'integer', 'minimum' => 100), + 'test4' => array('type' => 'integer', 'maximum' => 10), + 'test5' => array('type' => 'array', 'maxItems' => 2), + 'test6' => array('type' => 'string', 'enum' => array('a', 'bc')), + 'test7' => array('type' => 'string', 'pattern' => '/[0-9]+/'), + 'test8' => array('type' => 'number'), + 'baz' => array( + 'type' => 'array', + 'minItems' => 2, + 'required' => true, + "items" => array("type" => "string") + ) + ) + )); + + $value = array( + 'test' => 'a', + 'test2' => 'abc', + 'baz' => array(false), + 'test3' => 10, + 'test4' => 100, + 'test5' => array(1, 3, 4), + 'test6' => 'Foo', + 'test7' => 'abc', + 'test8' => 'abc' + ); + + $this->assertFalse($this->validator->validate($p, $value)); + $this->assertEquals(array ( + '[foo][bar] is a required string: This is what it does', + '[foo][baz] must contain 2 or more elements', + '[foo][baz][0] must be of type string', + '[foo][test2] length must be less than or equal to 2', + '[foo][test3] must be greater than or equal to 100', + '[foo][test4] must be less than or equal to 10', + '[foo][test5] must contain 2 or fewer elements', + '[foo][test6] must be one of "a" or "bc"', + '[foo][test7] must match the following regular expression: /[0-9]+/', + '[foo][test8] must be of type number', + '[foo][test] length must be greater than or equal to 2', + ), $this->validator->getErrors()); + } + + public function testHandlesNullValuesInArraysWithDefaults() + { + $p = new Parameter(array( + 'name' => 'foo', + 'type' => 'object', + 'required' => true, + 'properties' => array( + 'bar' => array( + 'type' => 'object', + 'required' => true, + 'properties' => array( + 'foo' => array('default' => 'hi') + ) + ) + ) + )); + $value = array(); + $this->assertTrue($this->validator->validate($p, $value)); + $this->assertEquals(array('bar' => array('foo' => 'hi')), $value); + } + + public function testFailsWhenNullValuesInArraysWithNoDefaults() + { + $p = new Parameter(array( + 'name' => 'foo', + 'type' => 'object', + 'required' => true, + 'properties' => array( + 'bar' => array( + 'type' => 'object', + 'required' => true, + 'properties' => array('foo' => array('type' => 'string')) + ) + ) + )); + $value = array(); + $this->assertFalse($this->validator->validate($p, $value)); + $this->assertEquals(array('[foo][bar] is a required object'), $this->validator->getErrors()); + } + + public function testChecksTypes() + { + $p = new SchemaValidator(); + $r = new \ReflectionMethod($p, 'determineType'); + $r->setAccessible(true); + $this->assertEquals('any', $r->invoke($p, 'any', 'hello')); + $this->assertEquals(false, $r->invoke($p, 'foo', 'foo')); + $this->assertEquals('string', $r->invoke($p, 'string', 'hello')); + $this->assertEquals(false, $r->invoke($p, 'string', false)); + $this->assertEquals('integer', $r->invoke($p, 'integer', 1)); + $this->assertEquals(false, $r->invoke($p, 'integer', 'abc')); + $this->assertEquals('numeric', $r->invoke($p, 'numeric', 1)); + $this->assertEquals('numeric', $r->invoke($p, 'numeric', '1')); + $this->assertEquals('number', $r->invoke($p, 'number', 1)); + $this->assertEquals('number', $r->invoke($p, 'number', '1')); + $this->assertEquals(false, $r->invoke($p, 'numeric', 'a')); + $this->assertEquals('boolean', $r->invoke($p, 'boolean', true)); + $this->assertEquals('boolean', $r->invoke($p, 'boolean', false)); + $this->assertEquals(false, $r->invoke($p, 'boolean', 'false')); + $this->assertEquals('null', $r->invoke($p, 'null', null)); + $this->assertEquals(false, $r->invoke($p, 'null', 'abc')); + $this->assertEquals('array', $r->invoke($p, 'array', array())); + $this->assertEquals(false, $r->invoke($p, 'array', 'foo')); + } + + public function testValidatesFalseAdditionalProperties() + { + $param = new Parameter(array( + 'name' => 'foo', + 'type' => 'object', + 'properties' => array('bar' => array('type' => 'string')), + 'additionalProperties' => false + )); + $value = array('test' => '123'); + $this->assertFalse($this->validator->validate($param, $value)); + $this->assertEquals(array('[foo][test] is not an allowed property'), $this->validator->getErrors()); + $value = array('bar' => '123'); + $this->assertTrue($this->validator->validate($param, $value)); + } + + public function testAllowsUndefinedAdditionalProperties() + { + $param = new Parameter(array( + 'name' => 'foo', + 'type' => 'object', + 'properties' => array('bar' => array('type' => 'string')) + )); + $value = array('test' => '123'); + $this->assertTrue($this->validator->validate($param, $value)); + } + + public function testValidatesAdditionalProperties() + { + $param = new Parameter(array( + 'name' => 'foo', + 'type' => 'object', + 'properties' => array('bar' => array('type' => 'string')), + 'additionalProperties' => array('type' => 'integer') + )); + $value = array('test' => 'foo'); + $this->assertFalse($this->validator->validate($param, $value)); + $this->assertEquals(array('[foo][test] must be of type integer'), $this->validator->getErrors()); + } + + public function testValidatesAdditionalPropertiesThatArrayArrays() + { + $param = new Parameter(array( + 'name' => 'foo', + 'type' => 'object', + 'additionalProperties' => array( + 'type' => 'array', + 'items' => array('type' => 'string') + ) + )); + $value = array('test' => array(true)); + $this->assertFalse($this->validator->validate($param, $value)); + $this->assertEquals(array('[foo][test][0] must be of type string'), $this->validator->getErrors()); + } + + public function testIntegersCastToStringWhenTypeMismatch() + { + $param = new Parameter(array('name' => 'test', 'type' => 'string')); + $value = 12; + $this->assertTrue($this->validator->validate($param, $value)); + $this->assertEquals('12', $value); + } + + public function testRequiredMessageIncludesType() + { + $param = new Parameter(array('name' => 'test', 'type' => array('string', 'boolean'), 'required' => true)); + $value = null; + $this->assertFalse($this->validator->validate($param, $value)); + $this->assertEquals(array('[test] is a required string or boolean'), $this->validator->getErrors()); + } + + protected function getComplexParam() + { + return new Parameter(array( + 'name' => 'Foo', + 'type' => 'array', + 'required' => true, + 'min' => 1, + 'items' => array( + 'type' => 'object', + 'properties' => array( + 'Baz' => array( + 'type' => 'string', + ), + 'Bar' => array( + 'required' => true, + 'type' => 'boolean', + 'default' => true + ) + ) + ) + )); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/ServiceDescriptionLoaderTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/ServiceDescriptionLoaderTest.php new file mode 100644 index 000000000..bbfd1d6df --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/ServiceDescriptionLoaderTest.php @@ -0,0 +1,177 @@ + true, + 'baz' => array('bar'), + 'apiVersion' => '123', + 'operations' => array() + )); + + $this->assertEquals(true, $d->getData('foo')); + $this->assertEquals(array('bar'), $d->getData('baz')); + $this->assertEquals('123', $d->getApiVersion()); + } + + public function testAllowsDeepNestedInheritance() + { + $d = ServiceDescription::factory(array( + 'operations' => array( + 'abstract' => array( + 'httpMethod' => 'HEAD', + 'parameters' => array( + 'test' => array('type' => 'string', 'required' => true) + ) + ), + 'abstract2' => array('uri' => '/test', 'extends' => 'abstract'), + 'concrete' => array('extends' => 'abstract2'), + 'override' => array('extends' => 'abstract', 'httpMethod' => 'PUT'), + 'override2' => array('extends' => 'override', 'httpMethod' => 'POST', 'uri' => '/') + ) + )); + + $c = $d->getOperation('concrete'); + $this->assertEquals('/test', $c->getUri()); + $this->assertEquals('HEAD', $c->getHttpMethod()); + $params = $c->getParams(); + $param = $params['test']; + $this->assertEquals('string', $param->getType()); + $this->assertTrue($param->getRequired()); + + // Ensure that merging HTTP method does not make an array + $this->assertEquals('PUT', $d->getOperation('override')->getHttpMethod()); + $this->assertEquals('POST', $d->getOperation('override2')->getHttpMethod()); + $this->assertEquals('/', $d->getOperation('override2')->getUri()); + } + + /** + * @expectedException RuntimeException + */ + public function testThrowsExceptionWhenExtendingMissingCommand() + { + ServiceDescription::factory(array( + 'operations' => array( + 'concrete' => array( + 'extends' => 'missing' + ) + ) + )); + } + + public function testAllowsMultipleInheritance() + { + $description = ServiceDescription::factory(array( + 'operations' => array( + 'a' => array( + 'httpMethod' => 'GET', + 'parameters' => array( + 'a1' => array( + 'default' => 'foo', + 'required' => true, + 'prepend' => 'hi' + ) + ) + ), + 'b' => array( + 'extends' => 'a', + 'parameters' => array( + 'b2' => array() + ) + ), + 'c' => array( + 'parameters' => array( + 'a1' => array( + 'default' => 'bar', + 'required' => true, + 'description' => 'test' + ), + 'c3' => array() + ) + ), + 'd' => array( + 'httpMethod' => 'DELETE', + 'extends' => array('b', 'c'), + 'parameters' => array( + 'test' => array() + ) + ) + ) + )); + + $command = $description->getOperation('d'); + $this->assertEquals('DELETE', $command->getHttpMethod()); + $this->assertContains('a1', $command->getParamNames()); + $this->assertContains('b2', $command->getParamNames()); + $this->assertContains('c3', $command->getParamNames()); + $this->assertContains('test', $command->getParamNames()); + + $this->assertTrue($command->getParam('a1')->getRequired()); + $this->assertEquals('bar', $command->getParam('a1')->getDefault()); + $this->assertEquals('test', $command->getParam('a1')->getDescription()); + } + + public function testAddsOtherFields() + { + $description = ServiceDescription::factory(array( + 'operations' => array(), + 'description' => 'Foo', + 'apiVersion' => 'bar' + )); + $this->assertEquals('Foo', $description->getDescription()); + $this->assertEquals('bar', $description->getApiVersion()); + } + + public function testCanLoadNestedExtends() + { + $description = ServiceDescription::factory(array( + 'operations' => array( + 'root' => array( + 'class' => 'foo' + ), + 'foo' => array( + 'extends' => 'root', + 'parameters' => array( + 'baz' => array('type' => 'string') + ) + ), + 'foo_2' => array( + 'extends' => 'foo', + 'parameters' => array( + 'bar' => array('type' => 'string') + ) + ), + 'foo_3' => array( + 'class' => 'bar', + 'parameters' => array( + 'bar2' => array('type' => 'string') + ) + ), + 'foo_4' => array( + 'extends' => array('foo_2', 'foo_3'), + 'parameters' => array( + 'bar3' => array('type' => 'string') + ) + ) + ) + )); + + $this->assertTrue($description->hasOperation('foo_4')); + $foo4 = $description->getOperation('foo_4'); + $this->assertTrue($foo4->hasParam('baz')); + $this->assertTrue($foo4->hasParam('bar')); + $this->assertTrue($foo4->hasParam('bar2')); + $this->assertTrue($foo4->hasParam('bar3')); + $this->assertEquals('bar', $foo4->getClass()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/ServiceDescriptionTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/ServiceDescriptionTest.php new file mode 100644 index 000000000..ff2545235 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Description/ServiceDescriptionTest.php @@ -0,0 +1,240 @@ +serviceData = array( + 'test_command' => new Operation(array( + 'name' => 'test_command', + 'description' => 'documentationForCommand', + 'httpMethod' => 'DELETE', + 'class' => 'Guzzle\\Tests\\Service\\Mock\\Command\\MockCommand', + 'parameters' => array( + 'bucket' => array('required' => true), + 'key' => array('required' => true) + ) + )) + ); + } + + /** + * @covers Guzzle\Service\Description\ServiceDescription::factory + * @covers Guzzle\Service\Description\ServiceDescriptionLoader::build + */ + public function testFactoryDelegatesToConcreteFactories() + { + $jsonFile = __DIR__ . '/../../TestData/test_service.json'; + $this->assertInstanceOf('Guzzle\Service\Description\ServiceDescription', ServiceDescription::factory($jsonFile)); + } + + public function testConstructor() + { + $service = new ServiceDescription(array('operations' => $this->serviceData)); + $this->assertEquals(1, count($service->getOperations())); + $this->assertFalse($service->hasOperation('foobar')); + $this->assertTrue($service->hasOperation('test_command')); + } + + public function testIsSerializable() + { + $service = new ServiceDescription(array('operations' => $this->serviceData)); + $data = serialize($service); + $d2 = unserialize($data); + $this->assertEquals(serialize($service), serialize($d2)); + } + + public function testSerializesParameters() + { + $service = new ServiceDescription(array( + 'operations' => array( + 'foo' => new Operation(array('parameters' => array('foo' => array('type' => 'string')))) + ) + )); + $serialized = serialize($service); + $this->assertContains('"parameters":{"foo":', $serialized); + $service = unserialize($serialized); + $this->assertTrue($service->getOperation('foo')->hasParam('foo')); + } + + public function testAllowsForJsonBasedArrayParamsFunctionalTest() + { + $description = new ServiceDescription(array( + 'operations' => array( + 'test' => new Operation(array( + 'httpMethod' => 'PUT', + 'parameters' => array( + 'data' => array( + 'required' => true, + 'filters' => 'json_encode', + 'location' => 'body' + ) + ) + )) + ) + )); + $client = new Client(); + $client->setDescription($description); + $command = $client->getCommand('test', array( + 'data' => array( + 'foo' => 'bar' + ) + )); + + $request = $command->prepare(); + $this->assertEquals('{"foo":"bar"}', (string) $request->getBody()); + } + + public function testContainsModels() + { + $d = new ServiceDescription(array( + 'operations' => array('foo' => array()), + 'models' => array( + 'Tag' => array('type' => 'object'), + 'Person' => array('type' => 'object') + ) + )); + $this->assertTrue($d->hasModel('Tag')); + $this->assertTrue($d->hasModel('Person')); + $this->assertFalse($d->hasModel('Foo')); + $this->assertInstanceOf('Guzzle\Service\Description\Parameter', $d->getModel('Tag')); + $this->assertNull($d->getModel('Foo')); + $this->assertContains('"models":{', serialize($d)); + $this->assertEquals(array('Tag', 'Person'), array_keys($d->getModels())); + } + + public function testCanAddModels() + { + $d = new ServiceDescription(array()); + $this->assertFalse($d->hasModel('Foo')); + $d->addModel(new Parameter(array('name' => 'Foo'))); + $this->assertTrue($d->hasModel('Foo')); + } + + public function testHasAttributes() + { + $d = new ServiceDescription(array( + 'operations' => array(), + 'name' => 'Name', + 'description' => 'Description', + 'apiVersion' => '1.24' + )); + + $this->assertEquals('Name', $d->getName()); + $this->assertEquals('Description', $d->getDescription()); + $this->assertEquals('1.24', $d->getApiVersion()); + + $s = serialize($d); + $this->assertContains('"name":"Name"', $s); + $this->assertContains('"description":"Description"', $s); + $this->assertContains('"apiVersion":"1.24"', $s); + + $d = unserialize($s); + $this->assertEquals('Name', $d->getName()); + $this->assertEquals('Description', $d->getDescription()); + $this->assertEquals('1.24', $d->getApiVersion()); + } + + public function testPersistsCustomAttributes() + { + $data = array( + 'operations' => array('foo' => array('class' => 'foo', 'parameters' => array())), + 'name' => 'Name', + 'description' => 'Test', + 'apiVersion' => '1.24', + 'auth' => 'foo', + 'keyParam' => 'bar' + ); + $d = new ServiceDescription($data); + $d->setData('hello', 'baz'); + $this->assertEquals('foo', $d->getData('auth')); + $this->assertEquals('baz', $d->getData('hello')); + $this->assertEquals('bar', $d->getData('keyParam')); + // responseClass and responseType are added by default + $data['operations']['foo']['responseClass'] = 'array'; + $data['operations']['foo']['responseType'] = 'primitive'; + $this->assertEquals($data + array('hello' => 'baz'), json_decode($d->serialize(), true)); + } + + public function testHasToArray() + { + $data = array( + 'operations' => array(), + 'name' => 'Name', + 'description' => 'Test' + ); + $d = new ServiceDescription($data); + $arr = $d->toArray(); + $this->assertEquals('Name', $arr['name']); + $this->assertEquals('Test', $arr['description']); + } + + public function testReturnsNullWhenRetrievingMissingOperation() + { + $s = new ServiceDescription(array()); + $this->assertNull($s->getOperation('foo')); + } + + public function testCanAddOperations() + { + $s = new ServiceDescription(array()); + $this->assertFalse($s->hasOperation('Foo')); + $s->addOperation(new Operation(array('name' => 'Foo'))); + $this->assertTrue($s->hasOperation('Foo')); + } + + /** + * @expectedException Guzzle\Common\Exception\InvalidArgumentException + */ + public function testValidatesOperationTypes() + { + $s = new ServiceDescription(array( + 'operations' => array('foo' => new \stdClass()) + )); + } + + public function testHasBaseUrl() + { + $description = new ServiceDescription(array('baseUrl' => 'http://foo.com')); + $this->assertEquals('http://foo.com', $description->getBaseUrl()); + $description->setBaseUrl('http://foobar.com'); + $this->assertEquals('http://foobar.com', $description->getBaseUrl()); + } + + public function testCanUseBasePath() + { + $description = new ServiceDescription(array('basePath' => 'http://foo.com')); + $this->assertEquals('http://foo.com', $description->getBaseUrl()); + } + + public function testModelsHaveNames() + { + $desc = array( + 'models' => array( + 'date' => array('type' => 'string'), + 'user'=> array( + 'type' => 'object', + 'properties' => array( + 'dob' => array('$ref' => 'date') + ) + ) + ) + ); + + $s = ServiceDescription::factory($desc); + $this->assertEquals('date', $s->getModel('date')->getName()); + $this->assertEquals('dob', $s->getModel('user')->getProperty('dob')->getName()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Exception/CommandTransferExceptionTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Exception/CommandTransferExceptionTest.php new file mode 100644 index 000000000..be0d4ac8b --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Exception/CommandTransferExceptionTest.php @@ -0,0 +1,66 @@ +addSuccessfulCommand($c1)->addFailedCommand($c2); + $this->assertSame(array($c1), $e->getSuccessfulCommands()); + $this->assertSame(array($c2), $e->getFailedCommands()); + $this->assertSame(array($c1, $c2), $e->getAllCommands()); + } + + public function testConvertsMultiExceptionIntoCommandTransfer() + { + $r1 = new Request('GET', 'http://foo.com'); + $r2 = new Request('GET', 'http://foobaz.com'); + $e = new MultiTransferException('Test', 123); + $e->addSuccessfulRequest($r1)->addFailedRequest($r2); + $ce = CommandTransferException::fromMultiTransferException($e); + + $this->assertInstanceOf('Guzzle\Service\Exception\CommandTransferException', $ce); + $this->assertEquals('Test', $ce->getMessage()); + $this->assertEquals(123, $ce->getCode()); + $this->assertSame(array($r1), $ce->getSuccessfulRequests()); + $this->assertSame(array($r2), $ce->getFailedRequests()); + } + + public function testCanRetrieveExceptionForCommand() + { + $r1 = new Request('GET', 'http://foo.com'); + $e1 = new \Exception('foo'); + $c1 = $this->getMockBuilder('Guzzle\Tests\Service\Mock\Command\MockCommand') + ->setMethods(array('getRequest')) + ->getMock(); + $c1->expects($this->once())->method('getRequest')->will($this->returnValue($r1)); + + $e = new MultiTransferException('Test', 123); + $e->addFailedRequestWithException($r1, $e1); + $ce = CommandTransferException::fromMultiTransferException($e); + $ce->addFailedCommand($c1); + + $this->assertSame($e1, $ce->getExceptionForFailedCommand($c1)); + } + + public function testAddsNonRequestExceptions() + { + $e = new MultiTransferException(); + $e->add(new \Exception('bar')); + $e->addFailedRequestWithException(new Request('GET', 'http://www.foo.com'), new \Exception('foo')); + $ce = CommandTransferException::fromMultiTransferException($e); + $this->assertEquals(2, count($ce)); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Exception/InconsistentClientTransferExceptionTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Exception/InconsistentClientTransferExceptionTest.php new file mode 100644 index 000000000..6455295ad --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Exception/InconsistentClientTransferExceptionTest.php @@ -0,0 +1,15 @@ +assertEquals($items, $e->getCommands()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Exception/ValidationExceptionTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Exception/ValidationExceptionTest.php new file mode 100644 index 000000000..ef789d8a9 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Exception/ValidationExceptionTest.php @@ -0,0 +1,17 @@ +setErrors($errors); + $this->assertEquals($errors, $e->getErrors()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Command/IterableCommand.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Command/IterableCommand.php new file mode 100644 index 000000000..4ab423e85 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Command/IterableCommand.php @@ -0,0 +1,31 @@ + 'iterable_command', + 'parameters' => array( + 'page_size' => array('type' => 'integer'), + 'next_token' => array('type' => 'string') + ) + )); + } + + protected function build() + { + $this->request = $this->client->createRequest('GET'); + + // Add the next token and page size query string values + $this->request->getQuery()->set('next_token', $this->get('next_token')); + + if ($this->get('page_size')) { + $this->request->getQuery()->set('page_size', $this->get('page_size')); + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Command/MockCommand.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Command/MockCommand.php new file mode 100644 index 000000000..831a7e795 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Command/MockCommand.php @@ -0,0 +1,32 @@ + get_called_class() == __CLASS__ ? 'mock_command' : 'sub.sub', + 'httpMethod' => 'POST', + 'parameters' => array( + 'test' => array( + 'default' => 123, + 'required' => true, + 'doc' => 'Test argument' + ), + '_internal' => array( + 'default' => 'abc' + ), + 'foo' => array('filters' => array('strtoupper')) + ) + )); + } + + protected function build() + { + $this->request = $this->client->createRequest(); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Command/OtherCommand.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Command/OtherCommand.php new file mode 100644 index 000000000..72ae1f6a7 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Command/OtherCommand.php @@ -0,0 +1,30 @@ + 'other_command', + 'parameters' => array( + 'test' => array( + 'default' => '123', + 'required' => true, + 'doc' => 'Test argument' + ), + 'other' => array(), + 'arg' => array('type' => 'string'), + 'static' => array('static' => true, 'default' => 'this is static') + ) + )); + } + + protected function build() + { + $this->request = $this->client->getRequest('HEAD'); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Command/Sub/Sub.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Command/Sub/Sub.php new file mode 100644 index 000000000..d348480cf --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Command/Sub/Sub.php @@ -0,0 +1,7 @@ + '{scheme}://127.0.0.1:8124/{api_version}/{subdomain}', + 'scheme' => 'http', + 'api_version' => 'v1' + ), array('username', 'password', 'subdomain')); + + return new self($config->get('base_url'), $config); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Model/MockCommandIterator.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Model/MockCommandIterator.php new file mode 100644 index 000000000..8faf4123a --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Mock/Model/MockCommandIterator.php @@ -0,0 +1,42 @@ +nextToken) { + $this->command->set('next_token', $this->nextToken); + } + + $this->command->set('page_size', (int) $this->calculatePageSize()); + $this->command->execute(); + + $data = json_decode($this->command->getResponse()->getBody(true), true); + + $this->nextToken = $data['next_token']; + + return $data['resources']; + } + + public function next() + { + $this->calledNext++; + parent::next(); + } + + public function getResources() + { + return $this->resources; + } + + public function getIteratedCount() + { + return $this->iteratedCount; + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/CompositeResourceIteratorFactoryTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/CompositeResourceIteratorFactoryTest.php new file mode 100644 index 000000000..41c207372 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/CompositeResourceIteratorFactoryTest.php @@ -0,0 +1,37 @@ +assertFalse($factory->canBuild($cmd)); + $factory->build($cmd); + } + + public function testBuildsResourceIterators() + { + $f1 = new ResourceIteratorClassFactory('Guzzle\Tests\Service\Mock\Model'); + $factory = new CompositeResourceIteratorFactory(array()); + $factory->addFactory($f1); + $command = new MockCommand(); + $iterator = $factory->build($command, array('client.namespace' => 'Guzzle\Tests\Service\Mock')); + $this->assertInstanceOf('Guzzle\Tests\Service\Mock\Model\MockCommandIterator', $iterator); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/MapResourceIteratorFactoryTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/MapResourceIteratorFactoryTest.php new file mode 100644 index 000000000..d166e9261 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/MapResourceIteratorFactoryTest.php @@ -0,0 +1,40 @@ +build(new MockCommand()); + } + + public function testBuildsResourceIterators() + { + $factory = new MapResourceIteratorFactory(array( + 'mock_command' => 'Guzzle\Tests\Service\Mock\Model\MockCommandIterator' + )); + $iterator = $factory->build(new MockCommand()); + $this->assertInstanceOf('Guzzle\Tests\Service\Mock\Model\MockCommandIterator', $iterator); + } + + public function testUsesWildcardMappings() + { + $factory = new MapResourceIteratorFactory(array( + '*' => 'Guzzle\Tests\Service\Mock\Model\MockCommandIterator' + )); + $iterator = $factory->build(new MockCommand()); + $this->assertInstanceOf('Guzzle\Tests\Service\Mock\Model\MockCommandIterator', $iterator); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/ModelTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/ModelTest.php new file mode 100644 index 000000000..7214133e5 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/ModelTest.php @@ -0,0 +1,65 @@ + 'object')); + $model = new Model(array('foo' => 'bar'), $param); + $this->assertSame($param, $model->getStructure()); + $this->assertEquals('bar', $model->get('foo')); + $this->assertEquals('bar', $model['foo']); + } + + public function testCanBeUsedWithoutStructure() + { + $model = new Model(array( + 'Foo' => 'baz', + 'Bar' => array( + 'Boo' => 'Bam' + ) + )); + $transform = function ($key, $value) { + return ($value && is_array($value)) ? new Collection($value) : $value; + }; + $model = $model->map($transform); + $this->assertInstanceOf('Guzzle\Common\Collection', $model->getPath('Bar')); + } + + public function testAllowsFiltering() + { + $model = new Model(array( + 'Foo' => 'baz', + 'Bar' => 'a' + )); + $model = $model->filter(function ($i, $v) { + return $v[0] == 'a'; + }); + $this->assertEquals(array('Bar' => 'a'), $model->toArray()); + } + + public function testDoesNotIncludeEmptyStructureInString() + { + $model = new Model(array('Foo' => 'baz')); + $str = (string) $model; + $this->assertContains('Debug output of model', $str); + $this->assertNotContains('Model structure', $str); + } + + public function testDoesIncludeModelStructureInString() + { + $model = new Model(array('Foo' => 'baz'), new Parameter(array('name' => 'Foo'))); + $str = (string) $model; + $this->assertContains('Debug output of Foo model', $str); + $this->assertContains('Model structure', $str); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/ResourceIteratorClassFactoryTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/ResourceIteratorClassFactoryTest.php new file mode 100644 index 000000000..7b061b537 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/ResourceIteratorClassFactoryTest.php @@ -0,0 +1,41 @@ +registerNamespace('Baz'); + $command = new MockCommand(); + $factory->build($command); + } + + public function testBuildsResourceIterators() + { + $factory = new ResourceIteratorClassFactory('Guzzle\Tests\Service\Mock\Model'); + $command = new MockCommand(); + $iterator = $factory->build($command, array('client.namespace' => 'Guzzle\Tests\Service\Mock')); + $this->assertInstanceOf('Guzzle\Tests\Service\Mock\Model\MockCommandIterator', $iterator); + } + + public function testChecksIfCanBuild() + { + $factory = new ResourceIteratorClassFactory('Guzzle\Tests\Service'); + $this->assertFalse($factory->canBuild(new MockCommand())); + $factory = new ResourceIteratorClassFactory('Guzzle\Tests\Service\Mock\Model'); + $this->assertTrue($factory->canBuild(new MockCommand())); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/ResourceIteratorTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/ResourceIteratorTest.php new file mode 100644 index 000000000..573fb6d6e --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Service/Resource/ResourceIteratorTest.php @@ -0,0 +1,184 @@ +assertInternalType('array', ResourceIterator::getAllEvents()); + } + + public function testConstructorConfiguresDefaults() + { + $ri = $this->getMockForAbstractClass('Guzzle\\Service\\Resource\\ResourceIterator', array( + $this->getServiceBuilder()->get('mock')->getCommand('iterable_command'), + array( + 'limit' => 10, + 'page_size' => 3 + ) + ), 'MockIterator'); + + $this->assertEquals(false, $ri->getNextToken()); + $this->assertEquals(false, $ri->current()); + } + + public function testSendsRequestsForNextSetOfResources() + { + // Queue up an array of responses for iterating + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 200 OK\r\nContent-Length: 52\r\n\r\n{ \"next_token\": \"g\", \"resources\": [\"d\", \"e\", \"f\"] }", + "HTTP/1.1 200 OK\r\nContent-Length: 52\r\n\r\n{ \"next_token\": \"j\", \"resources\": [\"g\", \"h\", \"i\"] }", + "HTTP/1.1 200 OK\r\nContent-Length: 41\r\n\r\n{ \"next_token\": \"\", \"resources\": [\"j\"] }" + )); + + // Create a new resource iterator using the IterableCommand mock + $ri = new MockCommandIterator($this->getServiceBuilder()->get('mock')->getCommand('iterable_command'), array( + 'page_size' => 3 + )); + + // Ensure that no requests have been sent yet + $this->assertEquals(0, count($this->getServer()->getReceivedRequests(false))); + + //$this->assertEquals(array('d', 'e', 'f', 'g', 'h', 'i', 'j'), $ri->toArray()); + $ri->toArray(); + $requests = $this->getServer()->getReceivedRequests(true); + $this->assertEquals(3, count($requests)); + + $this->assertEquals(3, $requests[0]->getQuery()->get('page_size')); + $this->assertEquals(3, $requests[1]->getQuery()->get('page_size')); + $this->assertEquals(3, $requests[2]->getQuery()->get('page_size')); + + // Reset and resend + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 200 OK\r\nContent-Length: 52\r\n\r\n{ \"next_token\": \"g\", \"resources\": [\"d\", \"e\", \"f\"] }", + "HTTP/1.1 200 OK\r\nContent-Length: 52\r\n\r\n{ \"next_token\": \"j\", \"resources\": [\"g\", \"h\", \"i\"] }", + "HTTP/1.1 200 OK\r\nContent-Length: 41\r\n\r\n{ \"next_token\": \"\", \"resources\": [\"j\"] }", + )); + + $d = array(); + foreach ($ri as $data) { + $d[] = $data; + } + $this->assertEquals(array('d', 'e', 'f', 'g', 'h', 'i', 'j'), $d); + } + + public function testCalculatesPageSize() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 200 OK\r\nContent-Length: 52\r\n\r\n{ \"next_token\": \"g\", \"resources\": [\"d\", \"e\", \"f\"] }", + "HTTP/1.1 200 OK\r\nContent-Length: 52\r\n\r\n{ \"next_token\": \"j\", \"resources\": [\"g\", \"h\", \"i\"] }", + "HTTP/1.1 200 OK\r\nContent-Length: 52\r\n\r\n{ \"next_token\": \"j\", \"resources\": [\"j\", \"k\"] }" + )); + + $ri = new MockCommandIterator($this->getServiceBuilder()->get('mock')->getCommand('iterable_command'), array( + 'page_size' => 3, + 'limit' => 7 + )); + + $this->assertEquals(array('d', 'e', 'f', 'g', 'h', 'i', 'j'), $ri->toArray()); + $requests = $this->getServer()->getReceivedRequests(true); + $this->assertEquals(3, count($requests)); + $this->assertEquals(3, $requests[0]->getQuery()->get('page_size')); + $this->assertEquals(3, $requests[1]->getQuery()->get('page_size')); + $this->assertEquals(1, $requests[2]->getQuery()->get('page_size')); + } + + public function testUseAsArray() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 200 OK\r\nContent-Length: 52\r\n\r\n{ \"next_token\": \"g\", \"resources\": [\"d\", \"e\", \"f\"] }", + "HTTP/1.1 200 OK\r\nContent-Length: 52\r\n\r\n{ \"next_token\": \"\", \"resources\": [\"g\", \"h\", \"i\"] }" + )); + + $ri = new MockCommandIterator($this->getServiceBuilder()->get('mock')->getCommand('iterable_command')); + + // Ensure that the key is never < 0 + $this->assertEquals(0, $ri->key()); + $this->assertEquals(0, count($ri)); + + // Ensure that the iterator can be used as KVP array + $data = array(); + foreach ($ri as $key => $value) { + $data[$key] = $value; + } + + // Ensure that the iterate is countable + $this->assertEquals(6, count($ri)); + $this->assertEquals(array('d', 'e', 'f', 'g', 'h', 'i'), $data); + } + + public function testBailsWhenSendReturnsNoResults() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 200 OK\r\n\r\n{ \"next_token\": \"g\", \"resources\": [\"d\", \"e\", \"f\"] }", + "HTTP/1.1 200 OK\r\n\r\n{ \"next_token\": \"\", \"resources\": [] }" + )); + + $ri = new MockCommandIterator($this->getServiceBuilder()->get('mock')->getCommand('iterable_command')); + + // Ensure that the iterator can be used as KVP array + $data = $ri->toArray(); + + // Ensure that the iterate is countable + $this->assertEquals(3, count($ri)); + $this->assertEquals(array('d', 'e', 'f'), $data); + + $this->assertEquals(2, $ri->getRequestCount()); + } + + public function testHoldsDataOptions() + { + $ri = new MockCommandIterator($this->getServiceBuilder()->get('mock')->getCommand('iterable_command')); + $this->assertNull($ri->get('foo')); + $this->assertSame($ri, $ri->set('foo', 'bar')); + $this->assertEquals('bar', $ri->get('foo')); + } + + public function testSettingLimitOrPageSizeClearsData() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 200 OK\r\n\r\n{ \"next_token\": \"\", \"resources\": [\"d\", \"e\", \"f\"] }", + "HTTP/1.1 200 OK\r\n\r\n{ \"next_token\": \"\", \"resources\": [\"d\", \"e\", \"f\"] }", + "HTTP/1.1 200 OK\r\n\r\n{ \"next_token\": \"\", \"resources\": [\"d\", \"e\", \"f\"] }" + )); + + $ri = new MockCommandIterator($this->getServiceBuilder()->get('mock')->getCommand('iterable_command')); + $ri->toArray(); + $this->assertNotEmpty($this->readAttribute($ri, 'resources')); + + $ri->setLimit(10); + $this->assertEmpty($this->readAttribute($ri, 'resources')); + + $ri->toArray(); + $this->assertNotEmpty($this->readAttribute($ri, 'resources')); + $ri->setPageSize(10); + $this->assertEmpty($this->readAttribute($ri, 'resources')); + } + + public function testWorksWithCustomAppendIterator() + { + $this->getServer()->flush(); + $this->getServer()->enqueue(array( + "HTTP/1.1 200 OK\r\n\r\n{ \"next_token\": \"\", \"resources\": [\"d\", \"e\", \"f\"] }" + )); + $ri = new MockCommandIterator($this->getServiceBuilder()->get('mock')->getCommand('iterable_command')); + $a = new \Guzzle\Iterator\AppendIterator(); + $a->append($ri); + $results = iterator_to_array($a, false); + $this->assertEquals(4, $ri->calledNext); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Stream/PhpStreamRequestFactoryTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Stream/PhpStreamRequestFactoryTest.php new file mode 100644 index 000000000..083aaa0d9 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Stream/PhpStreamRequestFactoryTest.php @@ -0,0 +1,172 @@ +client = new Client($this->getServer()->getUrl()); + $this->factory = new PhpStreamRequestFactory(); + } + + public function testOpensValidStreamByCreatingContext() + { + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi"); + $request = $this->client->get('/'); + $stream = $this->factory->fromRequest($request); + $this->assertEquals('hi', (string) $stream); + $headers = $this->factory->getLastResponseHeaders(); + $this->assertContains('HTTP/1.1 200 OK', $headers); + $this->assertContains('Content-Length: 2', $headers); + $this->assertSame($headers, $stream->getCustomData('response_headers')); + $this->assertEquals(2, $stream->getSize()); + } + + public function testOpensValidStreamByPassingContextAndMerging() + { + $request = $this->client->get('/'); + $this->factory = $this->getMockBuilder('Guzzle\Stream\PhpStreamRequestFactory') + ->setMethods(array('createContext', 'createStream')) + ->getMock(); + $this->factory->expects($this->never()) + ->method('createContext'); + $this->factory->expects($this->once()) + ->method('createStream') + ->will($this->returnValue(new Stream(fopen('php://temp', 'r')))); + + $context = array('http' => array('method' => 'HEAD', 'ignore_errors' => false)); + $this->factory->fromRequest($request, stream_context_create($context)); + $options = stream_context_get_options($this->readAttribute($this->factory, 'context')); + $this->assertEquals('HEAD', $options['http']['method']); + $this->assertFalse($options['http']['ignore_errors']); + $this->assertEquals('1.1', $options['http']['protocol_version']); + } + + public function testAppliesProxySettings() + { + $request = $this->client->get('/'); + $request->getCurlOptions()->set(CURLOPT_PROXY, 'tcp://foo.com'); + $this->factory = $this->getMockBuilder('Guzzle\Stream\PhpStreamRequestFactory') + ->setMethods(array('createStream')) + ->getMock(); + $this->factory->expects($this->once()) + ->method('createStream') + ->will($this->returnValue(new Stream(fopen('php://temp', 'r')))); + $this->factory->fromRequest($request); + $options = stream_context_get_options($this->readAttribute($this->factory, 'context')); + $this->assertEquals('tcp://foo.com', $options['http']['proxy']); + } + + public function testAddsPostFields() + { + $this->getServer()->flush(); + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi"); + $request = $this->client->post('/', array('Foo' => 'Bar'), array('foo' => 'baz bar')); + $stream = $this->factory->fromRequest($request); + $this->assertEquals('hi', (string) $stream); + + $headers = $this->factory->getLastResponseHeaders(); + $this->assertContains('HTTP/1.1 200 OK', $headers); + $this->assertContains('Content-Length: 2', $headers); + $this->assertSame($headers, $stream->getCustomData('response_headers')); + + $received = $this->getServer()->getReceivedRequests(); + $this->assertEquals(1, count($received)); + $this->assertContains('POST / HTTP/1.1', $received[0]); + $this->assertContains('host: ', $received[0]); + $this->assertContains('user-agent: Guzzle/', $received[0]); + $this->assertContains('foo: Bar', $received[0]); + $this->assertContains('content-length: 13', $received[0]); + $this->assertContains('foo=baz%20bar', $received[0]); + } + + public function testAddsBody() + { + $this->getServer()->flush(); + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi"); + $request = $this->client->put('/', array('Foo' => 'Bar'), 'Testing...123'); + $stream = $this->factory->fromRequest($request); + $this->assertEquals('hi', (string) $stream); + + $headers = $this->factory->getLastResponseHeaders(); + $this->assertContains('HTTP/1.1 200 OK', $headers); + $this->assertContains('Content-Length: 2', $headers); + $this->assertSame($headers, $stream->getCustomData('response_headers')); + + $received = $this->getServer()->getReceivedRequests(); + $this->assertEquals(1, count($received)); + $this->assertContains('PUT / HTTP/1.1', $received[0]); + $this->assertContains('host: ', $received[0]); + $this->assertContains('user-agent: Guzzle/', $received[0]); + $this->assertContains('foo: Bar', $received[0]); + $this->assertContains('content-length: 13', $received[0]); + $this->assertContains('Testing...123', $received[0]); + } + + public function testCanDisableSslValidation() + { + $request = $this->client->get('/'); + $request->getCurlOptions()->set(CURLOPT_SSL_VERIFYPEER, false); + $this->factory = $this->getMockBuilder('Guzzle\Stream\PhpStreamRequestFactory') + ->setMethods(array('createStream')) + ->getMock(); + $this->factory->expects($this->once()) + ->method('createStream') + ->will($this->returnValue(new Stream(fopen('php://temp', 'r')))); + $this->factory->fromRequest($request); + $options = stream_context_get_options($this->readAttribute($this->factory, 'context')); + $this->assertFalse($options['ssl']['verify_peer']); + } + + public function testUsesSslValidationByDefault() + { + $request = $this->client->get('/'); + $this->factory = $this->getMockBuilder('Guzzle\Stream\PhpStreamRequestFactory') + ->setMethods(array('createStream')) + ->getMock(); + $this->factory->expects($this->once()) + ->method('createStream') + ->will($this->returnValue(new Stream(fopen('php://temp', 'r')))); + $this->factory->fromRequest($request); + $options = stream_context_get_options($this->readAttribute($this->factory, 'context')); + $this->assertTrue($options['ssl']['verify_peer']); + $this->assertSame($request->getCurlOptions()->get(CURLOPT_CAINFO), $options['ssl']['cafile']); + } + + public function testBasicAuthAddsUserAndPassToUrl() + { + $request = $this->client->get('/'); + $request->setAuth('Foo', 'Bar'); + $this->factory = $this->getMockBuilder('Guzzle\Stream\PhpStreamRequestFactory') + ->setMethods(array('createStream')) + ->getMock(); + $this->factory->expects($this->once()) + ->method('createStream') + ->will($this->returnValue(new Stream(fopen('php://temp', 'r')))); + $this->factory->fromRequest($request); + $this->assertContains('Foo:Bar@', (string) $this->readAttribute($this->factory, 'url')); + } + + public function testCanCreateCustomStreamClass() + { + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi"); + $request = $this->client->get('/'); + $stream = $this->factory->fromRequest($request, array(), array('stream_class' => 'Guzzle\Http\EntityBody')); + $this->assertInstanceOf('Guzzle\Http\EntityBody', $stream); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Stream/StreamTest.php b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Stream/StreamTest.php new file mode 100644 index 000000000..4973f252e --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/Stream/StreamTest.php @@ -0,0 +1,189 @@ +assertEquals($handle, $stream->getStream()); + $this->assertTrue($stream->isReadable()); + $this->assertTrue($stream->isWritable()); + $this->assertTrue($stream->isLocal()); + $this->assertTrue($stream->isSeekable()); + $this->assertEquals('PHP', $stream->getWrapper()); + $this->assertEquals('TEMP', $stream->getStreamType()); + $this->assertEquals(4, $stream->getSize()); + $this->assertEquals('php://temp', $stream->getUri()); + $this->assertEquals(array(), $stream->getWrapperData()); + $this->assertFalse($stream->isConsumed()); + unset($stream); + } + + public function testCanModifyStream() + { + $handle1 = fopen('php://temp', 'r+'); + $handle2 = fopen('php://temp', 'r+'); + $stream = new Stream($handle1); + $this->assertSame($handle1, $stream->getStream()); + $stream->setStream($handle2, 10); + $this->assertEquals(10, $stream->getSize()); + $this->assertSame($handle2, $stream->getStream()); + } + + public function testStreamClosesHandleOnDestruct() + { + $handle = fopen('php://temp', 'r'); + $stream = new Stream($handle); + unset($stream); + $this->assertFalse(is_resource($handle)); + } + + public function testConvertsToString() + { + $handle = fopen('php://temp', 'w+'); + fwrite($handle, 'data'); + $stream = new Stream($handle); + $this->assertEquals('data', (string) $stream); + unset($stream); + + $handle = fopen(__DIR__ . '/../TestData/FileBody.txt', 'r'); + $stream = new Stream($handle); + $this->assertEquals('', (string) $stream); + unset($stream); + } + + public function testConvertsToStringAndRestoresCursorPos() + { + $handle = fopen('php://temp', 'w+'); + $stream = new Stream($handle); + $stream->write('foobazbar'); + $stream->seek(3); + $this->assertEquals('foobazbar', (string) $stream); + $this->assertEquals(3, $stream->ftell()); + } + + public function testIsConsumed() + { + $handle = fopen('php://temp', 'w+'); + fwrite($handle, 'data'); + $stream = new Stream($handle); + $this->assertFalse($stream->isConsumed()); + $stream->read(4); + $this->assertTrue($stream->isConsumed()); + } + + public function testAllowsSettingManualSize() + { + $handle = fopen('php://temp', 'w+'); + fwrite($handle, 'data'); + $stream = new Stream($handle); + $stream->setSize(10); + $this->assertEquals(10, $stream->getSize()); + unset($stream); + } + + public function testWrapsStream() + { + $handle = fopen('php://temp', 'w+'); + fwrite($handle, 'data'); + $stream = new Stream($handle); + $this->assertTrue($stream->isSeekable()); + $this->assertTrue($stream->isReadable()); + $this->assertTrue($stream->seek(0)); + $this->assertEquals('da', $stream->read(2)); + $this->assertEquals('ta', $stream->read(2)); + $this->assertTrue($stream->seek(0)); + $this->assertEquals('data', $stream->read(4)); + $stream->write('_appended'); + $stream->seek(0); + $this->assertEquals('data_appended', $stream->read(13)); + } + + public function testGetSize() + { + $size = filesize(__DIR__ . '/../../../bootstrap.php'); + $handle = fopen(__DIR__ . '/../../../bootstrap.php', 'r'); + $stream = new Stream($handle); + $this->assertEquals($handle, $stream->getStream()); + $this->assertEquals($size, $stream->getSize()); + $this->assertEquals($size, $stream->getSize()); + unset($stream); + + // Make sure that false is returned when the size cannot be determined + $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + $handle = fopen('http://127.0.0.1:' . $this->getServer()->getPort(), 'r'); + $stream = new Stream($handle); + $this->assertEquals(false, $stream->getSize()); + unset($stream); + } + + public function testEnsuresSizeIsConsistent() + { + $h = fopen('php://temp', 'r+'); + fwrite($h, 'foo'); + $stream = new Stream($h); + $this->assertEquals(3, $stream->getSize()); + $stream->write('test'); + $this->assertEquals(7, $stream->getSize()); + fclose($h); + } + + public function testAbstractsMetaData() + { + $handle = fopen(__DIR__ . '/../../../bootstrap.php', 'r'); + $stream = new Stream($handle); + $this->assertEquals('plainfile', $stream->getMetaData('wrapper_type')); + $this->assertEquals(null, $stream->getMetaData('wrapper_data')); + $this->assertInternalType('array', $stream->getMetaData()); + } + + public function testDoesNotAttemptToWriteToReadonlyStream() + { + $handle = fopen(__DIR__ . '/../../../bootstrap.php', 'r'); + $stream = new Stream($handle); + $this->assertEquals(0, $stream->write('foo')); + } + + public function testProvidesStreamPosition() + { + $handle = fopen(__DIR__ . '/../../../bootstrap.php', 'r'); + $stream = new Stream($handle); + $stream->read(2); + $this->assertSame(ftell($handle), $stream->ftell()); + $this->assertEquals(2, $stream->ftell()); + } + + public function testRewindIsSeekZero() + { + $stream = new Stream(fopen('php://temp', 'w+')); + $stream->write('foobazbar'); + $this->assertTrue($stream->rewind()); + $this->assertEquals('foobazbar', $stream->read(9)); + } + + public function testCanDetachStream() + { + $r = fopen('php://temp', 'w+'); + $stream = new Stream($r); + $stream->detachStream(); + $this->assertNull($stream->getStream()); + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/FileBody.txt b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/FileBody.txt new file mode 100644 index 000000000..e69de29bb diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/description/bar.json b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/description/bar.json new file mode 100644 index 000000000..c354ed788 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/description/bar.json @@ -0,0 +1,3 @@ +{ + "includes": ["foo.json"] +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/description/baz.json b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/description/baz.json new file mode 100644 index 000000000..765237b3e --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/description/baz.json @@ -0,0 +1,3 @@ +{ + "includes": ["foo.json", "bar.json"] +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/description/foo.json b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/description/foo.json new file mode 100644 index 000000000..cee5005b8 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/description/foo.json @@ -0,0 +1,8 @@ +{ + "includes": ["recursive.json"], + "operations": { + "abstract": { + "httpMethod": "POST" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/description/recursive.json b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/description/recursive.json new file mode 100644 index 000000000..c354ed788 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/description/recursive.json @@ -0,0 +1,3 @@ +{ + "includes": ["foo.json"] +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/mock_response b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/mock_response new file mode 100644 index 000000000..b6938a28c --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/mock_response @@ -0,0 +1,3 @@ +HTTP/1.1 200 OK +Content-Length: 0 + diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/services/json1.json b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/services/json1.json new file mode 100644 index 000000000..7b2a9dad4 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/services/json1.json @@ -0,0 +1,18 @@ +{ + "includes": [ "json2.json" ], + "services": { + "abstract": { + "access_key": "xyz", + "secret": "abc" + }, + "mock": { + "class": "Guzzle\\Tests\\Service\\Mock\\MockClient", + "extends": "abstract", + "params": { + "username": "foo", + "password": "baz", + "subdomain": "bar" + } + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/services/json2.json b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/services/json2.json new file mode 100644 index 000000000..08e5566f0 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/services/json2.json @@ -0,0 +1,11 @@ +{ + "services": { + "foo": { + "class": "Guzzle\\Tests\\Service\\Mock\\MockClient", + "extends": "abstract", + "params": { + "baz": "bar" + } + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/services/services.json b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/services/services.json new file mode 100644 index 000000000..25452e4a4 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/services/services.json @@ -0,0 +1,71 @@ +{ + "abstract": { + "access_key": "xyz", + "secret": "abc" + }, + "mock": { + "class": "Guzzle\\Tests\\Service\\Mock\\MockClient", + "extends": "abstract", + "params": { + "username": "foo", + "password": "baz", + "subdomain": "bar" + } + }, + + "test.abstract.aws": { + "params": { + "access_key": "12345", + "secret_key": "abcd" + } + }, + + "test.s3": { + "class": "Guzzle\\Service\\Aws\\S3Client", + "extends": "test.abstract.aws", + "params": { + "devpay_product_token": "", + "devpay_user_token": "" + } + }, + + "test.simple_db": { + "class": "Guzzle\\Service\\Aws\\SimpleDb\\SimpleDbClient", + "extends": "test.abstract.aws" + }, + + "test.sqs": { + "class": "Guzzle\\Service\\Aws\\Sqs\\SqsClient", + "extends": "test.abstract.aws" + }, + + "test.centinel": { + "class": "Guzzle\\Service\\CardinalCommerce\\Centinel.CentinelClient", + "params": { + "password": "test", + "processor_id": "123", + "merchant_id": "456" + } + }, + + "test.mws": { + "class": "Guzzle\\Service\\Mws\\MwsClient", + "extends": "test.abstract.aws", + "params": { + "merchant_id": "ABCDE", + "marketplace_id": "FGHIJ", + "application_name": "GuzzleTest", + "application_version": "0.1", + "base_url": "https://mws.amazonservices.com" + } + }, + + "mock": { + "class": "Guzzle\\Tests\\Service\\Mock\\MockClient", + "params": { + "username": "test_user", + "password": "****", + "subdomain": "test" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/test_service.json b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/test_service.json new file mode 100644 index 000000000..01557ca11 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/test_service.json @@ -0,0 +1,40 @@ +{ + "includes": [ "test_service2.json" ], + "operations": { + "test": { + "uri": "/path" + }, + "concrete": { + "extends": "abstract" + }, + "foo_bar": { + "uri": "/testing", + "parameters": { + "other": { + "location": "json", + "location_key": "Other" + }, + "test": { + "type": "object", + "location": "json", + "properties": { + "baz": { + "type": "boolean", + "default": true + }, + "bar": { + "type": "string", + "filters": [ + { + "method": "strtolower", + "args": ["test", "@value"] + }, + "strtoupper" + ] + } + } + } + } + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/test_service2.json b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/test_service2.json new file mode 100644 index 000000000..66dd9ef7e --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/test_service2.json @@ -0,0 +1,7 @@ +{ + "operations": { + "abstract": { + "uri": "/abstract" + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/test_service_3.json b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/test_service_3.json new file mode 100644 index 000000000..ae2ae0bd4 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/Guzzle/Tests/TestData/test_service_3.json @@ -0,0 +1,40 @@ +{ + "includes": [ "test_service2.json" ], + "operations": { + "test": { + "uri": "/path" + }, + "concrete": { + "extends": "abstract" + }, + "baz_qux": { + "uri": "/testing", + "parameters": { + "other": { + "location": "json", + "location_key": "Other" + }, + "test": { + "type": "object", + "location": "json", + "properties": { + "baz": { + "type": "boolean", + "default": true + }, + "bar": { + "type": "string", + "filters": [ + { + "method": "strtolower", + "args": ["test", "@value"] + }, + "strtoupper" + ] + } + } + } + } + } + } +} diff --git a/src/bb-vendor/guzzle/guzzle/tests/bootstrap.php b/src/bb-vendor/guzzle/guzzle/tests/bootstrap.php new file mode 100644 index 000000000..28908d310 --- /dev/null +++ b/src/bb-vendor/guzzle/guzzle/tests/bootstrap.php @@ -0,0 +1,10 @@ + +All rights reserved. + +Based on Markdown +Copyright (c) 2003-2006 John Gruber + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +* Neither the name "Markdown" nor the names of its contributors may + be used to endorse or promote products derived from this software + without specific prior written permission. + +This software is provided by the copyright holders and contributors "as +is" and any express or implied warranties, including, but not limited +to, the implied warranties of merchantability and fitness for a +particular purpose are disclaimed. In no event shall the copyright owner +or contributors be liable for any direct, indirect, incidental, special, +exemplary, or consequential damages (including, but not limited to, +procurement of substitute goods or services; loss of use, data, or +profits; or business interruption) however caused and on any theory of +liability, whether in contract, strict liability, or tort (including +negligence or otherwise) arising in any way out of the use of this +software, even if advised of the possibility of such damage. diff --git a/src/bb-vendor/michelf/php-markdown/Michelf/Markdown.php b/src/bb-vendor/michelf/php-markdown/Michelf/Markdown.php new file mode 100644 index 000000000..c3eaf4464 --- /dev/null +++ b/src/bb-vendor/michelf/php-markdown/Michelf/Markdown.php @@ -0,0 +1,1896 @@ + + * @copyright 2004-2016 Michel Fortin + * @copyright (Original Markdown) 2004-2006 John Gruber + */ + +namespace Michelf; + +/** + * Markdown Parser Class + */ +class Markdown implements MarkdownInterface { + /** + * Define the package version + * @var string + */ + const MARKDOWNLIB_VERSION = "1.7.0"; + + /** + * Simple function interface - Initialize the parser and return the result + * of its transform method. This will work fine for derived classes too. + * + * @api + * + * @param string $text + * @return string + */ + public static function defaultTransform($text) { + // Take parser class on which this function was called. + $parser_class = \get_called_class(); + + // Try to take parser from the static parser list + static $parser_list; + $parser =& $parser_list[$parser_class]; + + // Create the parser it not already set + if (!$parser) { + $parser = new $parser_class; + } + + // Transform text using parser. + return $parser->transform($text); + } + + /** + * Configuration variables + */ + + /** + * Change to ">" for HTML output. + * @var string + */ + public $empty_element_suffix = " />"; + + /** + * The width of indentation of the output markup + * @var int + */ + public $tab_width = 4; + + /** + * Change to `true` to disallow markup or entities. + * @var boolean + */ + public $no_markup = false; + public $no_entities = false; + + + /** + * Change to `true` to enable line breaks on \n without two trailling spaces + * @var boolean + */ + public $hard_wrap = false; + + /** + * Predefined URLs and titles for reference links and images. + * @var array + */ + public $predef_urls = array(); + public $predef_titles = array(); + + /** + * Optional filter function for URLs + * @var callable + */ + public $url_filter_func = null; + + /** + * Optional header id="" generation callback function. + * @var callable + */ + public $header_id_func = null; + + /** + * Optional function for converting code block content to HTML + * @var callable + */ + public $code_block_content_func = null; + + /** + * Optional function for converting code span content to HTML. + * @var callable + */ + public $code_span_content_func = null; + + /** + * Class attribute to toggle "enhanced ordered list" behaviour + * setting this to true will allow ordered lists to start from the index + * number that is defined first. + * + * For example: + * 2. List item two + * 3. List item three + * + * Becomes: + *
      + *
    1. List item two
    2. + *
    3. List item three
    4. + *
    + * + * @var bool + */ + public $enhanced_ordered_list = false; + + /** + * Parser implementation + */ + + /** + * Regex to match balanced [brackets]. + * Needed to insert a maximum bracked depth while converting to PHP. + * @var int + */ + protected $nested_brackets_depth = 6; + protected $nested_brackets_re; + + protected $nested_url_parenthesis_depth = 4; + protected $nested_url_parenthesis_re; + + /** + * Table of hash values for escaped characters: + * @var string + */ + protected $escape_chars = '\`*_{}[]()>#+-.!'; + protected $escape_chars_re; + + /** + * Constructor function. Initialize appropriate member variables. + * @return void + */ + public function __construct() { + $this->_initDetab(); + $this->prepareItalicsAndBold(); + + $this->nested_brackets_re = + str_repeat('(?>[^\[\]]+|\[', $this->nested_brackets_depth). + str_repeat('\])*', $this->nested_brackets_depth); + + $this->nested_url_parenthesis_re = + str_repeat('(?>[^()\s]+|\(', $this->nested_url_parenthesis_depth). + str_repeat('(?>\)))*', $this->nested_url_parenthesis_depth); + + $this->escape_chars_re = '['.preg_quote($this->escape_chars).']'; + + // Sort document, block, and span gamut in ascendent priority order. + asort($this->document_gamut); + asort($this->block_gamut); + asort($this->span_gamut); + } + + + /** + * Internal hashes used during transformation. + * @var array + */ + protected $urls = array(); + protected $titles = array(); + protected $html_hashes = array(); + + /** + * Status flag to avoid invalid nesting. + * @var boolean + */ + protected $in_anchor = false; + + /** + * Called before the transformation process starts to setup parser states. + * @return void + */ + protected function setup() { + // Clear global hashes. + $this->urls = $this->predef_urls; + $this->titles = $this->predef_titles; + $this->html_hashes = array(); + $this->in_anchor = false; + } + + /** + * Called after the transformation process to clear any variable which may + * be taking up memory unnecessarly. + * @return void + */ + protected function teardown() { + $this->urls = array(); + $this->titles = array(); + $this->html_hashes = array(); + } + + /** + * Main function. Performs some preprocessing on the input text and pass + * it through the document gamut. + * + * @api + * + * @param string $text + * @return string + */ + public function transform($text) { + $this->setup(); + + # Remove UTF-8 BOM and marker character in input, if present. + $text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text); + + # Standardize line endings: + # DOS to Unix and Mac to Unix + $text = preg_replace('{\r\n?}', "\n", $text); + + # Make sure $text ends with a couple of newlines: + $text .= "\n\n"; + + # Convert all tabs to spaces. + $text = $this->detab($text); + + # Turn block-level HTML blocks into hash entries + $text = $this->hashHTMLBlocks($text); + + # Strip any lines consisting only of spaces and tabs. + # This makes subsequent regexen easier to write, because we can + # match consecutive blank lines with /\n+/ instead of something + # contorted like /[ ]*\n+/ . + $text = preg_replace('/^[ ]+$/m', '', $text); + + # Run document gamut methods. + foreach ($this->document_gamut as $method => $priority) { + $text = $this->$method($text); + } + + $this->teardown(); + + return $text . "\n"; + } + + /** + * Define the document gamut + * @var array + */ + protected $document_gamut = array( + // Strip link definitions, store in hashes. + "stripLinkDefinitions" => 20, + "runBasicBlockGamut" => 30, + ); + + /** + * Strips link definitions from text, stores the URLs and titles in + * hash references + * @param string $text + * @return string + */ + protected function stripLinkDefinitions($text) { + + $less_than_tab = $this->tab_width - 1; + + // Link defs are in the form: ^[id]: url "optional title" + $text = preg_replace_callback('{ + ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1 + [ ]* + \n? # maybe *one* newline + [ ]* + (?: + <(.+?)> # url = $2 + | + (\S+?) # url = $3 + ) + [ ]* + \n? # maybe one newline + [ ]* + (?: + (?<=\s) # lookbehind for whitespace + ["(] + (.*?) # title = $4 + [")] + [ ]* + )? # title is optional + (?:\n+|\Z) + }xm', + array($this, '_stripLinkDefinitions_callback'), + $text + ); + return $text; + } + + /** + * The callback to strip link definitions + * @param array $matches + * @return string + */ + protected function _stripLinkDefinitions_callback($matches) { + $link_id = strtolower($matches[1]); + $url = $matches[2] == '' ? $matches[3] : $matches[2]; + $this->urls[$link_id] = $url; + $this->titles[$link_id] =& $matches[4]; + return ''; // String that will replace the block + } + + /** + * Hashify HTML blocks + * @param string $text + * @return string + */ + protected function hashHTMLBlocks($text) { + if ($this->no_markup) { + return $text; + } + + $less_than_tab = $this->tab_width - 1; + + /** + * Hashify HTML blocks: + * + * We only want to do this for block-level HTML tags, such as headers, + * lists, and tables. That's because we still want to wrap

    s around + * "paragraphs" that are wrapped in non-block-level tags, such as + * anchors, phrase emphasis, and spans. The list of tags we're looking + * for is hard-coded: + * + * * List "a" is made of tags which can be both inline or block-level. + * These will be treated block-level when the start tag is alone on + * its line, otherwise they're not matched here and will be taken as + * inline later. + * * List "b" is made of tags which are always block-level; + */ + $block_tags_a_re = 'ins|del'; + $block_tags_b_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'. + 'script|noscript|style|form|fieldset|iframe|math|svg|'. + 'article|section|nav|aside|hgroup|header|footer|'. + 'figure'; + + // Regular expression for the content of a block tag. + $nested_tags_level = 4; + $attr = ' + (?> # optional tag attributes + \s # starts with whitespace + (?> + [^>"/]+ # text outside quotes + | + /+(?!>) # slash not followed by ">" + | + "[^"]*" # text inside double quotes (tolerate ">") + | + \'[^\']*\' # text inside single quotes (tolerate ">") + )* + )? + '; + $content = + str_repeat(' + (?> + [^<]+ # content without tag + | + <\2 # nested opening tag + '.$attr.' # attributes + (?> + /> + | + >', $nested_tags_level). // end of opening tag + '.*?'. // last level nested tag content + str_repeat(' + # closing nested tag + ) + | + <(?!/\2\s*> # other tags with a different name + ) + )*', + $nested_tags_level); + $content2 = str_replace('\2', '\3', $content); + + /** + * First, look for nested blocks, e.g.: + *

    + *
    + * tags for inner block must be indented. + *
    + *
    + * + * The outermost tags must start at the left margin for this to match, + * and the inner nested divs must be indented. + * We need to do this before the next, more liberal match, because the + * next match will start at the first `
    ` and stop at the + * first `
    `. + */ + $text = preg_replace_callback('{(?> + (?> + (?<=\n) # Starting on its own line + | # or + \A\n? # the at beginning of the doc + ) + ( # save in $1 + + # Match from `\n` to `\n`, handling nested tags + # in between. + + [ ]{0,'.$less_than_tab.'} + <('.$block_tags_b_re.')# start tag = $2 + '.$attr.'> # attributes followed by > and \n + '.$content.' # content, support nesting + # the matching end tag + [ ]* # trailing spaces/tabs + (?=\n+|\Z) # followed by a newline or end of document + + | # Special version for tags of group a. + + [ ]{0,'.$less_than_tab.'} + <('.$block_tags_a_re.')# start tag = $3 + '.$attr.'>[ ]*\n # attributes followed by > + '.$content2.' # content, support nesting + # the matching end tag + [ ]* # trailing spaces/tabs + (?=\n+|\Z) # followed by a newline or end of document + + | # Special case just for
    . It was easier to make a special + # case than to make the other regex more complicated. + + [ ]{0,'.$less_than_tab.'} + <(hr) # start tag = $2 + '.$attr.' # attributes + /?> # the matching end tag + [ ]* + (?=\n{2,}|\Z) # followed by a blank line or end of document + + | # Special case for standalone HTML comments: + + [ ]{0,'.$less_than_tab.'} + (?s: + + ) + [ ]* + (?=\n{2,}|\Z) # followed by a blank line or end of document + + | # PHP and ASP-style processor instructions ( + ) + [ ]* + (?=\n{2,}|\Z) # followed by a blank line or end of document + + ) + )}Sxmi', + array($this, '_hashHTMLBlocks_callback'), + $text + ); + + return $text; + } + + /** + * The callback for hashing HTML blocks + * @param string $matches + * @return string + */ + protected function _hashHTMLBlocks_callback($matches) { + $text = $matches[1]; + $key = $this->hashBlock($text); + return "\n\n$key\n\n"; + } + + /** + * Called whenever a tag must be hashed when a function insert an atomic + * element in the text stream. Passing $text to through this function gives + * a unique text-token which will be reverted back when calling unhash. + * + * The $boundary argument specify what character should be used to surround + * the token. By convension, "B" is used for block elements that needs not + * to be wrapped into paragraph tags at the end, ":" is used for elements + * that are word separators and "X" is used in the general case. + * + * @param string $text + * @param string $boundary + * @return string + */ + protected function hashPart($text, $boundary = 'X') { + // Swap back any tag hash found in $text so we do not have to `unhash` + // multiple times at the end. + $text = $this->unhash($text); + + // Then hash the block. + static $i = 0; + $key = "$boundary\x1A" . ++$i . $boundary; + $this->html_hashes[$key] = $text; + return $key; // String that will replace the tag. + } + + /** + * Shortcut function for hashPart with block-level boundaries. + * @param string $text + * @return string + */ + protected function hashBlock($text) { + return $this->hashPart($text, 'B'); + } + + /** + * Define the block gamut - these are all the transformations that form + * block-level tags like paragraphs, headers, and list items. + * @var array + */ + protected $block_gamut = array( + "doHeaders" => 10, + "doHorizontalRules" => 20, + "doLists" => 40, + "doCodeBlocks" => 50, + "doBlockQuotes" => 60, + ); + + /** + * Run block gamut tranformations. + * + * We need to escape raw HTML in Markdown source before doing anything + * else. This need to be done for each block, and not only at the + * begining in the Markdown function since hashed blocks can be part of + * list items and could have been indented. Indented blocks would have + * been seen as a code block in a previous pass of hashHTMLBlocks. + * + * @param string $text + * @return string + */ + protected function runBlockGamut($text) { + $text = $this->hashHTMLBlocks($text); + return $this->runBasicBlockGamut($text); + } + + /** + * Run block gamut tranformations, without hashing HTML blocks. This is + * useful when HTML blocks are known to be already hashed, like in the first + * whole-document pass. + * + * @param string $text + * @return string + */ + protected function runBasicBlockGamut($text) { + + foreach ($this->block_gamut as $method => $priority) { + $text = $this->$method($text); + } + + // Finally form paragraph and restore hashed blocks. + $text = $this->formParagraphs($text); + + return $text; + } + + /** + * Convert horizontal rules + * @param string $text + * @return string + */ + protected function doHorizontalRules($text) { + return preg_replace( + '{ + ^[ ]{0,3} # Leading space + ([-*_]) # $1: First marker + (?> # Repeated marker group + [ ]{0,2} # Zero, one, or two spaces. + \1 # Marker character + ){2,} # Group repeated at least twice + [ ]* # Tailing spaces + $ # End of line. + }mx', + "\n".$this->hashBlock("empty_element_suffix")."\n", + $text + ); + } + + /** + * These are all the transformations that occur *within* block-level + * tags like paragraphs, headers, and list items. + * @var array + */ + protected $span_gamut = array( + // Process character escapes, code spans, and inline HTML + // in one shot. + "parseSpan" => -30, + // Process anchor and image tags. Images must come first, + // because ![foo][f] looks like an anchor. + "doImages" => 10, + "doAnchors" => 20, + // Make links out of things like `` + // Must come after doAnchors, because you can use < and > + // delimiters in inline links like [this](). + "doAutoLinks" => 30, + "encodeAmpsAndAngles" => 40, + "doItalicsAndBold" => 50, + "doHardBreaks" => 60, + ); + + /** + * Run span gamut transformations + * @param string $text + * @return string + */ + protected function runSpanGamut($text) { + foreach ($this->span_gamut as $method => $priority) { + $text = $this->$method($text); + } + + return $text; + } + + /** + * Do hard breaks + * @param string $text + * @return string + */ + protected function doHardBreaks($text) { + if ($this->hard_wrap) { + return preg_replace_callback('/ *\n/', + array($this, '_doHardBreaks_callback'), $text); + } else { + return preg_replace_callback('/ {2,}\n/', + array($this, '_doHardBreaks_callback'), $text); + } + } + + /** + * Trigger part hashing for the hard break (callback method) + * @param array $matches + * @return string + */ + protected function _doHardBreaks_callback($matches) { + return $this->hashPart("empty_element_suffix\n"); + } + + /** + * Turn Markdown link shortcuts into XHTML tags. + * @param string $text + * @return string + */ + protected function doAnchors($text) { + if ($this->in_anchor) { + return $text; + } + $this->in_anchor = true; + + // First, handle reference-style links: [link text] [id] + $text = preg_replace_callback('{ + ( # wrap whole match in $1 + \[ + ('.$this->nested_brackets_re.') # link text = $2 + \] + + [ ]? # one optional space + (?:\n[ ]*)? # one optional newline followed by spaces + + \[ + (.*?) # id = $3 + \] + ) + }xs', + array($this, '_doAnchors_reference_callback'), $text); + + // Next, inline-style links: [link text](url "optional title") + $text = preg_replace_callback('{ + ( # wrap whole match in $1 + \[ + ('.$this->nested_brackets_re.') # link text = $2 + \] + \( # literal paren + [ \n]* + (?: + <(.+?)> # href = $3 + | + ('.$this->nested_url_parenthesis_re.') # href = $4 + ) + [ \n]* + ( # $5 + ([\'"]) # quote char = $6 + (.*?) # Title = $7 + \6 # matching quote + [ \n]* # ignore any spaces/tabs between closing quote and ) + )? # title is optional + \) + ) + }xs', + array($this, '_doAnchors_inline_callback'), $text); + + // Last, handle reference-style shortcuts: [link text] + // These must come last in case you've also got [link text][1] + // or [link text](/foo) + $text = preg_replace_callback('{ + ( # wrap whole match in $1 + \[ + ([^\[\]]+) # link text = $2; can\'t contain [ or ] + \] + ) + }xs', + array($this, '_doAnchors_reference_callback'), $text); + + $this->in_anchor = false; + return $text; + } + + /** + * Callback method to parse referenced anchors + * @param string $matches + * @return string + */ + protected function _doAnchors_reference_callback($matches) { + $whole_match = $matches[1]; + $link_text = $matches[2]; + $link_id =& $matches[3]; + + if ($link_id == "") { + // for shortcut links like [this][] or [this]. + $link_id = $link_text; + } + + // lower-case and turn embedded newlines into spaces + $link_id = strtolower($link_id); + $link_id = preg_replace('{[ ]?\n}', ' ', $link_id); + + if (isset($this->urls[$link_id])) { + $url = $this->urls[$link_id]; + $url = $this->encodeURLAttribute($url); + + $result = "titles[$link_id] ) ) { + $title = $this->titles[$link_id]; + $title = $this->encodeAttribute($title); + $result .= " title=\"$title\""; + } + + $link_text = $this->runSpanGamut($link_text); + $result .= ">$link_text"; + $result = $this->hashPart($result); + } else { + $result = $whole_match; + } + return $result; + } + + /** + * Callback method to parse inline anchors + * @param string $matches + * @return string + */ + protected function _doAnchors_inline_callback($matches) { + $whole_match = $matches[1]; + $link_text = $this->runSpanGamut($matches[2]); + $url = $matches[3] == '' ? $matches[4] : $matches[3]; + $title =& $matches[7]; + + // If the URL was of the form it got caught by the HTML + // tag parser and hashed. Need to reverse the process before using + // the URL. + $unhashed = $this->unhash($url); + if ($unhashed != $url) + $url = preg_replace('/^<(.*)>$/', '\1', $unhashed); + + $url = $this->encodeURLAttribute($url); + + $result = "encodeAttribute($title); + $result .= " title=\"$title\""; + } + + $link_text = $this->runSpanGamut($link_text); + $result .= ">$link_text"; + + return $this->hashPart($result); + } + + /** + * Turn Markdown image shortcuts into tags. + * @param string $text + * @return string + */ + protected function doImages($text) { + // First, handle reference-style labeled images: ![alt text][id] + $text = preg_replace_callback('{ + ( # wrap whole match in $1 + !\[ + ('.$this->nested_brackets_re.') # alt text = $2 + \] + + [ ]? # one optional space + (?:\n[ ]*)? # one optional newline followed by spaces + + \[ + (.*?) # id = $3 + \] + + ) + }xs', + array($this, '_doImages_reference_callback'), $text); + + // Next, handle inline images: ![alt text](url "optional title") + // Don't forget: encode * and _ + $text = preg_replace_callback('{ + ( # wrap whole match in $1 + !\[ + ('.$this->nested_brackets_re.') # alt text = $2 + \] + \s? # One optional whitespace character + \( # literal paren + [ \n]* + (?: + <(\S*)> # src url = $3 + | + ('.$this->nested_url_parenthesis_re.') # src url = $4 + ) + [ \n]* + ( # $5 + ([\'"]) # quote char = $6 + (.*?) # title = $7 + \6 # matching quote + [ \n]* + )? # title is optional + \) + ) + }xs', + array($this, '_doImages_inline_callback'), $text); + + return $text; + } + + /** + * Callback to parse references image tags + * @param array $matches + * @return string + */ + protected function _doImages_reference_callback($matches) { + $whole_match = $matches[1]; + $alt_text = $matches[2]; + $link_id = strtolower($matches[3]); + + if ($link_id == "") { + $link_id = strtolower($alt_text); // for shortcut links like ![this][]. + } + + $alt_text = $this->encodeAttribute($alt_text); + if (isset($this->urls[$link_id])) { + $url = $this->encodeURLAttribute($this->urls[$link_id]); + $result = "\"$alt_text\"";titles[$link_id])) { + $title = $this->titles[$link_id]; + $title = $this->encodeAttribute($title); + $result .= " title=\"$title\""; + } + $result .= $this->empty_element_suffix; + $result = $this->hashPart($result); + } else { + // If there's no such link ID, leave intact: + $result = $whole_match; + } + + return $result; + } + + /** + * Callback to parse inline image tags + * @param array $matches + * @return string + */ + protected function _doImages_inline_callback($matches) { + $whole_match = $matches[1]; + $alt_text = $matches[2]; + $url = $matches[3] == '' ? $matches[4] : $matches[3]; + $title =& $matches[7]; + + $alt_text = $this->encodeAttribute($alt_text); + $url = $this->encodeURLAttribute($url); + $result = "\"$alt_text\"";encodeAttribute($title); + $result .= " title=\"$title\""; // $title already quoted + } + $result .= $this->empty_element_suffix; + + return $this->hashPart($result); + } + + /** + * Parse Markdown heading elements to HTML + * @param string $text + * @return string + */ + protected function doHeaders($text) { + /** + * Setext-style headers: + * Header 1 + * ======== + * + * Header 2 + * -------- + */ + $text = preg_replace_callback('{ ^(.+?)[ ]*\n(=+|-+)[ ]*\n+ }mx', + array($this, '_doHeaders_callback_setext'), $text); + + /** + * atx-style headers: + * # Header 1 + * ## Header 2 + * ## Header 2 with closing hashes ## + * ... + * ###### Header 6 + */ + $text = preg_replace_callback('{ + ^(\#{1,6}) # $1 = string of #\'s + [ ]* + (.+?) # $2 = Header text + [ ]* + \#* # optional closing #\'s (not counted) + \n+ + }xm', + array($this, '_doHeaders_callback_atx'), $text); + + return $text; + } + + /** + * Setext header parsing callback + * @param array $matches + * @return string + */ + protected function _doHeaders_callback_setext($matches) { + // Terrible hack to check we haven't found an empty list item. + if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1])) { + return $matches[0]; + } + + $level = $matches[2]{0} == '=' ? 1 : 2; + + // ID attribute generation + $idAtt = $this->_generateIdFromHeaderValue($matches[1]); + + $block = "".$this->runSpanGamut($matches[1]).""; + return "\n" . $this->hashBlock($block) . "\n\n"; + } + + /** + * ATX header parsing callback + * @param array $matches + * @return string + */ + protected function _doHeaders_callback_atx($matches) { + // ID attribute generation + $idAtt = $this->_generateIdFromHeaderValue($matches[2]); + + $level = strlen($matches[1]); + $block = "".$this->runSpanGamut($matches[2]).""; + return "\n" . $this->hashBlock($block) . "\n\n"; + } + + /** + * If a header_id_func property is set, we can use it to automatically + * generate an id attribute. + * + * This method returns a string in the form id="foo", or an empty string + * otherwise. + * @param string $headerValue + * @return string + */ + protected function _generateIdFromHeaderValue($headerValue) { + if (!is_callable($this->header_id_func)) { + return ""; + } + + $idValue = call_user_func($this->header_id_func, $headerValue); + if (!$idValue) { + return ""; + } + + return ' id="' . $this->encodeAttribute($idValue) . '"'; + } + + /** + * Form HTML ordered (numbered) and unordered (bulleted) lists. + * @param string $text + * @return string + */ + protected function doLists($text) { + $less_than_tab = $this->tab_width - 1; + + // Re-usable patterns to match list item bullets and number markers: + $marker_ul_re = '[*+-]'; + $marker_ol_re = '\d+[\.]'; + + $markers_relist = array( + $marker_ul_re => $marker_ol_re, + $marker_ol_re => $marker_ul_re, + ); + + foreach ($markers_relist as $marker_re => $other_marker_re) { + // Re-usable pattern to match any entirel ul or ol list: + $whole_list_re = ' + ( # $1 = whole list + ( # $2 + ([ ]{0,'.$less_than_tab.'}) # $3 = number of spaces + ('.$marker_re.') # $4 = first list item marker + [ ]+ + ) + (?s:.+?) + ( # $5 + \z + | + \n{2,} + (?=\S) + (?! # Negative lookahead for another list item marker + [ ]* + '.$marker_re.'[ ]+ + ) + | + (?= # Lookahead for another kind of list + \n + \3 # Must have the same indentation + '.$other_marker_re.'[ ]+ + ) + ) + ) + '; // mx + + // We use a different prefix before nested lists than top-level lists. + //See extended comment in _ProcessListItems(). + + if ($this->list_level) { + $text = preg_replace_callback('{ + ^ + '.$whole_list_re.' + }mx', + array($this, '_doLists_callback'), $text); + } else { + $text = preg_replace_callback('{ + (?:(?<=\n)\n|\A\n?) # Must eat the newline + '.$whole_list_re.' + }mx', + array($this, '_doLists_callback'), $text); + } + } + + return $text; + } + + /** + * List parsing callback + * @param array $matches + * @return string + */ + protected function _doLists_callback($matches) { + // Re-usable patterns to match list item bullets and number markers: + $marker_ul_re = '[*+-]'; + $marker_ol_re = '\d+[\.]'; + $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)"; + $marker_ol_start_re = '[0-9]+'; + + $list = $matches[1]; + $list_type = preg_match("/$marker_ul_re/", $matches[4]) ? "ul" : "ol"; + + $marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re ); + + $list .= "\n"; + $result = $this->processListItems($list, $marker_any_re); + + $ol_start = 1; + if ($this->enhanced_ordered_list) { + // Get the start number for ordered list. + if ($list_type == 'ol') { + $ol_start_array = array(); + $ol_start_check = preg_match("/$marker_ol_start_re/", $matches[4], $ol_start_array); + if ($ol_start_check){ + $ol_start = $ol_start_array[0]; + } + } + } + + if ($ol_start > 1 && $list_type == 'ol'){ + $result = $this->hashBlock("<$list_type start=\"$ol_start\">\n" . $result . ""); + } else { + $result = $this->hashBlock("<$list_type>\n" . $result . ""); + } + return "\n". $result ."\n\n"; + } + + /** + * Nesting tracker for list levels + * @var integer + */ + protected $list_level = 0; + + /** + * Process the contents of a single ordered or unordered list, splitting it + * into individual list items. + * @param string $list_str + * @param string $marker_any_re + * @return string + */ + protected function processListItems($list_str, $marker_any_re) { + /** + * The $this->list_level global keeps track of when we're inside a list. + * Each time we enter a list, we increment it; when we leave a list, + * we decrement. If it's zero, we're not in a list anymore. + * + * We do this because when we're not inside a list, we want to treat + * something like this: + * + * I recommend upgrading to version + * 8. Oops, now this line is treated + * as a sub-list. + * + * As a single paragraph, despite the fact that the second line starts + * with a digit-period-space sequence. + * + * Whereas when we're inside a list (or sub-list), that line will be + * treated as the start of a sub-list. What a kludge, huh? This is + * an aspect of Markdown's syntax that's hard to parse perfectly + * without resorting to mind-reading. Perhaps the solution is to + * change the syntax rules such that sub-lists must start with a + * starting cardinal number; e.g. "1." or "a.". + */ + $this->list_level++; + + // Trim trailing blank lines: + $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str); + + $list_str = preg_replace_callback('{ + (\n)? # leading line = $1 + (^[ ]*) # leading whitespace = $2 + ('.$marker_any_re.' # list marker and space = $3 + (?:[ ]+|(?=\n)) # space only required if item is not empty + ) + ((?s:.*?)) # list item text = $4 + (?:(\n+(?=\n))|\n) # tailing blank line = $5 + (?= \n* (\z | \2 ('.$marker_any_re.') (?:[ ]+|(?=\n)))) + }xm', + array($this, '_processListItems_callback'), $list_str); + + $this->list_level--; + return $list_str; + } + + /** + * List item parsing callback + * @param array $matches + * @return string + */ + protected function _processListItems_callback($matches) { + $item = $matches[4]; + $leading_line =& $matches[1]; + $leading_space =& $matches[2]; + $marker_space = $matches[3]; + $tailing_blank_line =& $matches[5]; + + if ($leading_line || $tailing_blank_line || + preg_match('/\n{2,}/', $item)) + { + // Replace marker with the appropriate whitespace indentation + $item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item; + $item = $this->runBlockGamut($this->outdent($item)."\n"); + } else { + // Recursion for sub-lists: + $item = $this->doLists($this->outdent($item)); + $item = $this->formParagraphs($item, false); + } + + return "
  • " . $item . "
  • \n"; + } + + /** + * Process Markdown `
    ` blocks.
    +	 * @param  string $text
    +	 * @return string
    +	 */
    +	protected function doCodeBlocks($text) {
    +		$text = preg_replace_callback('{
    +				(?:\n\n|\A\n?)
    +				(	            # $1 = the code block -- one or more lines, starting with a space/tab
    +				  (?>
    +					[ ]{'.$this->tab_width.'}  # Lines must start with a tab or a tab-width of spaces
    +					.*\n+
    +				  )+
    +				)
    +				((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z)	# Lookahead for non-space at line-start, or end of doc
    +			}xm',
    +			array($this, '_doCodeBlocks_callback'), $text);
    +
    +		return $text;
    +	}
    +
    +	/**
    +	 * Code block parsing callback
    +	 * @param  array $matches
    +	 * @return string
    +	 */
    +	protected function _doCodeBlocks_callback($matches) {
    +		$codeblock = $matches[1];
    +
    +		$codeblock = $this->outdent($codeblock);
    +		if ($this->code_block_content_func) {
    +			$codeblock = call_user_func($this->code_block_content_func, $codeblock, "");
    +		} else {
    +			$codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
    +		}
    +
    +		# trim leading newlines and trailing newlines
    +		$codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock);
    +
    +		$codeblock = "
    $codeblock\n
    "; + return "\n\n" . $this->hashBlock($codeblock) . "\n\n"; + } + + /** + * Create a code span markup for $code. Called from handleSpanToken. + * @param string $code + * @return string + */ + protected function makeCodeSpan($code) { + if ($this->code_span_content_func) { + $code = call_user_func($this->code_span_content_func, $code); + } else { + $code = htmlspecialchars(trim($code), ENT_NOQUOTES); + } + return $this->hashPart("$code"); + } + + /** + * Define the emphasis operators with their regex matches + * @var array + */ + protected $em_relist = array( + '' => '(?:(? '(? '(? '(?:(? '(? '(? '(?:(? '(? '(?em_relist as $em => $em_re) { + foreach ($this->strong_relist as $strong => $strong_re) { + // Construct list of allowed token expressions. + $token_relist = array(); + if (isset($this->em_strong_relist["$em$strong"])) { + $token_relist[] = $this->em_strong_relist["$em$strong"]; + } + $token_relist[] = $em_re; + $token_relist[] = $strong_re; + + // Construct master expression from list. + $token_re = '{(' . implode('|', $token_relist) . ')}'; + $this->em_strong_prepared_relist["$em$strong"] = $token_re; + } + } + } + + /** + * Convert Markdown italics (emphasis) and bold (strong) to HTML + * @param string $text + * @return string + */ + protected function doItalicsAndBold($text) { + $token_stack = array(''); + $text_stack = array(''); + $em = ''; + $strong = ''; + $tree_char_em = false; + + while (1) { + // Get prepared regular expression for seraching emphasis tokens + // in current context. + $token_re = $this->em_strong_prepared_relist["$em$strong"]; + + // Each loop iteration search for the next emphasis token. + // Each token is then passed to handleSpanToken. + $parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE); + $text_stack[0] .= $parts[0]; + $token =& $parts[1]; + $text =& $parts[2]; + + if (empty($token)) { + // Reached end of text span: empty stack without emitting. + // any more emphasis. + while ($token_stack[0]) { + $text_stack[1] .= array_shift($token_stack); + $text_stack[0] .= array_shift($text_stack); + } + break; + } + + $token_len = strlen($token); + if ($tree_char_em) { + // Reached closing marker while inside a three-char emphasis. + if ($token_len == 3) { + // Three-char closing marker, close em and strong. + array_shift($token_stack); + $span = array_shift($text_stack); + $span = $this->runSpanGamut($span); + $span = "$span"; + $text_stack[0] .= $this->hashPart($span); + $em = ''; + $strong = ''; + } else { + // Other closing marker: close one em or strong and + // change current token state to match the other + $token_stack[0] = str_repeat($token{0}, 3-$token_len); + $tag = $token_len == 2 ? "strong" : "em"; + $span = $text_stack[0]; + $span = $this->runSpanGamut($span); + $span = "<$tag>$span"; + $text_stack[0] = $this->hashPart($span); + $$tag = ''; // $$tag stands for $em or $strong + } + $tree_char_em = false; + } else if ($token_len == 3) { + if ($em) { + // Reached closing marker for both em and strong. + // Closing strong marker: + for ($i = 0; $i < 2; ++$i) { + $shifted_token = array_shift($token_stack); + $tag = strlen($shifted_token) == 2 ? "strong" : "em"; + $span = array_shift($text_stack); + $span = $this->runSpanGamut($span); + $span = "<$tag>$span"; + $text_stack[0] .= $this->hashPart($span); + $$tag = ''; // $$tag stands for $em or $strong + } + } else { + // Reached opening three-char emphasis marker. Push on token + // stack; will be handled by the special condition above. + $em = $token{0}; + $strong = "$em$em"; + array_unshift($token_stack, $token); + array_unshift($text_stack, ''); + $tree_char_em = true; + } + } else if ($token_len == 2) { + if ($strong) { + // Unwind any dangling emphasis marker: + if (strlen($token_stack[0]) == 1) { + $text_stack[1] .= array_shift($token_stack); + $text_stack[0] .= array_shift($text_stack); + } + // Closing strong marker: + array_shift($token_stack); + $span = array_shift($text_stack); + $span = $this->runSpanGamut($span); + $span = "$span"; + $text_stack[0] .= $this->hashPart($span); + $strong = ''; + } else { + array_unshift($token_stack, $token); + array_unshift($text_stack, ''); + $strong = $token; + } + } else { + // Here $token_len == 1 + if ($em) { + if (strlen($token_stack[0]) == 1) { + // Closing emphasis marker: + array_shift($token_stack); + $span = array_shift($text_stack); + $span = $this->runSpanGamut($span); + $span = "$span"; + $text_stack[0] .= $this->hashPart($span); + $em = ''; + } else { + $text_stack[0] .= $token; + } + } else { + array_unshift($token_stack, $token); + array_unshift($text_stack, ''); + $em = $token; + } + } + } + return $text_stack[0]; + } + + /** + * Parse Markdown blockquotes to HTML + * @param string $text + * @return string + */ + protected function doBlockQuotes($text) { + $text = preg_replace_callback('/ + ( # Wrap whole match in $1 + (?> + ^[ ]*>[ ]? # ">" at the start of a line + .+\n # rest of the first line + (.+\n)* # subsequent consecutive lines + \n* # blanks + )+ + ) + /xm', + array($this, '_doBlockQuotes_callback'), $text); + + return $text; + } + + /** + * Blockquote parsing callback + * @param array $matches + * @return string + */ + protected function _doBlockQuotes_callback($matches) { + $bq = $matches[1]; + // trim one level of quoting - trim whitespace-only lines + $bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq); + $bq = $this->runBlockGamut($bq); // recurse + + $bq = preg_replace('/^/m', " ", $bq); + // These leading spaces cause problem with
     content, 
    +		// so we need to fix that:
    +		$bq = preg_replace_callback('{(\s*
    .+?
    )}sx', + array($this, '_doBlockQuotes_callback2'), $bq); + + return "\n" . $this->hashBlock("
    \n$bq\n
    ") . "\n\n"; + } + + /** + * Blockquote parsing callback + * @param array $matches + * @return string + */ + protected function _doBlockQuotes_callback2($matches) { + $pre = $matches[1]; + $pre = preg_replace('/^ /m', '', $pre); + return $pre; + } + + /** + * Parse paragraphs + * + * @param string $text String to process in paragraphs + * @param boolean $wrap_in_p Whether paragraphs should be wrapped in

    tags + * @return string + */ + protected function formParagraphs($text, $wrap_in_p = true) { + // Strip leading and trailing lines: + $text = preg_replace('/\A\n+|\n+\z/', '', $text); + + $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY); + + // Wrap

    tags and unhashify HTML blocks + foreach ($grafs as $key => $value) { + if (!preg_match('/^B\x1A[0-9]+B$/', $value)) { + // Is a paragraph. + $value = $this->runSpanGamut($value); + if ($wrap_in_p) { + $value = preg_replace('/^([ ]*)/', "

    ", $value); + $value .= "

    "; + } + $grafs[$key] = $this->unhash($value); + } else { + // Is a block. + // Modify elements of @grafs in-place... + $graf = $value; + $block = $this->html_hashes[$graf]; + $graf = $block; +// if (preg_match('{ +// \A +// ( # $1 =
    tag +//
    ]* +// \b +// markdown\s*=\s* ([\'"]) # $2 = attr quote char +// 1 +// \2 +// [^>]* +// > +// ) +// ( # $3 = contents +// .* +// ) +// (
    ) # $4 = closing tag +// \z +// }xs', $block, $matches)) +// { +// list(, $div_open, , $div_content, $div_close) = $matches; +// +// // We can't call Markdown(), because that resets the hash; +// // that initialization code should be pulled into its own sub, though. +// $div_content = $this->hashHTMLBlocks($div_content); +// +// // Run document gamut methods on the content. +// foreach ($this->document_gamut as $method => $priority) { +// $div_content = $this->$method($div_content); +// } +// +// $div_open = preg_replace( +// '{\smarkdown\s*=\s*([\'"]).+?\1}', '', $div_open); +// +// $graf = $div_open . "\n" . $div_content . "\n" . $div_close; +// } + $grafs[$key] = $graf; + } + } + + return implode("\n\n", $grafs); + } + + /** + * Encode text for a double-quoted HTML attribute. This function + * is *not* suitable for attributes enclosed in single quotes. + * @param string $text + * @return string + */ + protected function encodeAttribute($text) { + $text = $this->encodeAmpsAndAngles($text); + $text = str_replace('"', '"', $text); + return $text; + } + + /** + * Encode text for a double-quoted HTML attribute containing a URL, + * applying the URL filter if set. Also generates the textual + * representation for the URL (removing mailto: or tel:) storing it in $text. + * This function is *not* suitable for attributes enclosed in single quotes. + * + * @param string $url + * @param string &$text Passed by reference + * @return string URL + */ + protected function encodeURLAttribute($url, &$text = null) { + if ($this->url_filter_func) { + $url = call_user_func($this->url_filter_func, $url); + } + + if (preg_match('{^mailto:}i', $url)) { + $url = $this->encodeEntityObfuscatedAttribute($url, $text, 7); + } else if (preg_match('{^tel:}i', $url)) { + $url = $this->encodeAttribute($url); + $text = substr($url, 4); + } else { + $url = $this->encodeAttribute($url); + $text = $url; + } + + return $url; + } + + /** + * Smart processing for ampersands and angle brackets that need to + * be encoded. Valid character entities are left alone unless the + * no-entities mode is set. + * @param string $text + * @return string + */ + protected function encodeAmpsAndAngles($text) { + if ($this->no_entities) { + $text = str_replace('&', '&', $text); + } else { + // Ampersand-encoding based entirely on Nat Irons's Amputator + // MT plugin: + $text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/', + '&', $text); + } + // Encode remaining <'s + $text = str_replace('<', '<', $text); + + return $text; + } + + /** + * Parse Markdown automatic links to anchor HTML tags + * @param string $text + * @return string + */ + protected function doAutoLinks($text) { + $text = preg_replace_callback('{<((https?|ftp|dict|tel):[^\'">\s]+)>}i', + array($this, '_doAutoLinks_url_callback'), $text); + + // Email addresses: + $text = preg_replace_callback('{ + < + (?:mailto:)? + ( + (?: + [-!#$%&\'*+/=?^_`.{|}~\w\x80-\xFF]+ + | + ".*?" + ) + \@ + (?: + [-a-z0-9\x80-\xFF]+(\.[-a-z0-9\x80-\xFF]+)*\.[a-z]+ + | + \[[\d.a-fA-F:]+\] # IPv4 & IPv6 + ) + ) + > + }xi', + array($this, '_doAutoLinks_email_callback'), $text); + + return $text; + } + + /** + * Parse URL callback + * @param array $matches + * @return string + */ + protected function _doAutoLinks_url_callback($matches) { + $url = $this->encodeURLAttribute($matches[1], $text); + $link = "$text"; + return $this->hashPart($link); + } + + /** + * Parse email address callback + * @param array $matches + * @return string + */ + protected function _doAutoLinks_email_callback($matches) { + $addr = $matches[1]; + $url = $this->encodeURLAttribute("mailto:$addr", $text); + $link = "$text"; + return $this->hashPart($link); + } + + /** + * Input: some text to obfuscate, e.g. "mailto:foo@example.com" + * + * Output: the same text but with most characters encoded as either a + * decimal or hex entity, in the hopes of foiling most address + * harvesting spam bots. E.g.: + * + * mailto:foo + * @example.co + * m + * + * Note: the additional output $tail is assigned the same value as the + * ouput, minus the number of characters specified by $head_length. + * + * Based by a filter by Matthew Wickline, posted to BBEdit-Talk. + * With some optimizations by Milian Wolff. Forced encoding of HTML + * attribute special characters by Allan Odgaard. + * + * @param string $text + * @param string &$tail + * @param integer $head_length + * @return string + */ + protected function encodeEntityObfuscatedAttribute($text, &$tail = null, $head_length = 0) { + if ($text == "") { + return $tail = ""; + } + + $chars = preg_split('/(? $char) { + $ord = ord($char); + // Ignore non-ascii chars. + if ($ord < 128) { + $r = ($seed * (1 + $key)) % 100; // Pseudo-random function. + // roughly 10% raw, 45% hex, 45% dec + // '@' *must* be encoded. I insist. + // '"' and '>' have to be encoded inside the attribute + if ($r > 90 && strpos('@"&>', $char) === false) { + /* do nothing */ + } else if ($r < 45) { + $chars[$key] = '&#x'.dechex($ord).';'; + } else { + $chars[$key] = '&#'.$ord.';'; + } + } + } + + $text = implode('', $chars); + $tail = $head_length ? implode('', array_slice($chars, $head_length)) : $text; + + return $text; + } + + /** + * Take the string $str and parse it into tokens, hashing embeded HTML, + * escaped characters and handling code spans. + * @param string $str + * @return string + */ + protected function parseSpan($str) { + $output = ''; + + $span_re = '{ + ( + \\\\'.$this->escape_chars_re.' + | + (?no_markup ? '' : ' + | + # comment + | + <\?.*?\?> | <%.*?%> # processing instruction + | + <[!$]?[-a-zA-Z0-9:_]+ # regular tags + (?> + \s + (?>[^"\'>]+|"[^"]*"|\'[^\']*\')* + )? + > + | + <[-a-zA-Z0-9:_]+\s*/> # xml-style empty tag + | + # closing tag + ').' + ) + }xs'; + + while (1) { + // Each loop iteration seach for either the next tag, the next + // openning code span marker, or the next escaped character. + // Each token is then passed to handleSpanToken. + $parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE); + + // Create token from text preceding tag. + if ($parts[0] != "") { + $output .= $parts[0]; + } + + // Check if we reach the end. + if (isset($parts[1])) { + $output .= $this->handleSpanToken($parts[1], $parts[2]); + $str = $parts[2]; + } else { + break; + } + } + + return $output; + } + + /** + * Handle $token provided by parseSpan by determining its nature and + * returning the corresponding value that should replace it. + * @param string $token + * @param string &$str + * @return string + */ + protected function handleSpanToken($token, &$str) { + switch ($token{0}) { + case "\\": + return $this->hashPart("&#". ord($token{1}). ";"); + case "`": + // Search for end marker in remaining text. + if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm', + $str, $matches)) + { + $str = $matches[2]; + $codespan = $this->makeCodeSpan($matches[1]); + return $this->hashPart($codespan); + } + return $token; // Return as text since no ending marker found. + default: + return $this->hashPart($token); + } + } + + /** + * Remove one level of line-leading tabs or spaces + * @param string $text + * @return string + */ + protected function outdent($text) { + return preg_replace('/^(\t|[ ]{1,' . $this->tab_width . '})/m', '', $text); + } + + + /** + * String length function for detab. `_initDetab` will create a function to + * handle UTF-8 if the default function does not exist. + * @var string + */ + protected $utf8_strlen = 'mb_strlen'; + + /** + * Replace tabs with the appropriate amount of spaces. + * + * For each line we separate the line in blocks delemited by tab characters. + * Then we reconstruct every line by adding the appropriate number of space + * between each blocks. + * + * @param string $text + * @return string + */ + protected function detab($text) { + $text = preg_replace_callback('/^.*\t.*$/m', + array($this, '_detab_callback'), $text); + + return $text; + } + + /** + * Replace tabs callback + * @param string $matches + * @return string + */ + protected function _detab_callback($matches) { + $line = $matches[0]; + $strlen = $this->utf8_strlen; // strlen function for UTF-8. + + // Split in blocks. + $blocks = explode("\t", $line); + // Add each blocks to the line. + $line = $blocks[0]; + unset($blocks[0]); // Do not add first block twice. + foreach ($blocks as $block) { + // Calculate amount of space, insert spaces, insert block. + $amount = $this->tab_width - + $strlen($line, 'UTF-8') % $this->tab_width; + $line .= str_repeat(" ", $amount) . $block; + } + return $line; + } + + /** + * Check for the availability of the function in the `utf8_strlen` property + * (initially `mb_strlen`). If the function is not available, create a + * function that will loosely count the number of UTF-8 characters with a + * regular expression. + * @return void + */ + protected function _initDetab() { + + if (function_exists($this->utf8_strlen)) { + return; + } + + $this->utf8_strlen = create_function('$text', 'return preg_match_all( + "/[\\\\x00-\\\\xBF]|[\\\\xC0-\\\\xFF][\\\\x80-\\\\xBF]*/", + $text, $m);'); + } + + /** + * Swap back in all the tags hashed by _HashHTMLBlocks. + * @param string $text + * @return string + */ + protected function unhash($text) { + return preg_replace_callback('/(.)\x1A[0-9]+\1/', + array($this, '_unhash_callback'), $text); + } + + /** + * Unhashing callback + * @param array $matches + * @return string + */ + protected function _unhash_callback($matches) { + return $this->html_hashes[$matches[0]]; + } +} diff --git a/src/bb-vendor/michelf/php-markdown/Michelf/MarkdownExtra.php b/src/bb-vendor/michelf/php-markdown/Michelf/MarkdownExtra.php new file mode 100644 index 000000000..ac6b1b4f2 --- /dev/null +++ b/src/bb-vendor/michelf/php-markdown/Michelf/MarkdownExtra.php @@ -0,0 +1,1785 @@ + + * @copyright 2004-2016 Michel Fortin + * @copyright (Original Markdown) 2004-2006 John Gruber + */ + +namespace Michelf; + +/** + * Markdown Extra Parser Class + */ +class MarkdownExtra extends \Michelf\Markdown { + /** + * Configuration variables + */ + + /** + * Prefix for footnote ids. + * @var string + */ + public $fn_id_prefix = ""; + + /** + * Optional title attribute for footnote links and backlinks. + * @var string + */ + public $fn_link_title = ""; + public $fn_backlink_title = ""; + + /** + * Optional class attribute for footnote links and backlinks. + * @var string + */ + public $fn_link_class = "footnote-ref"; + public $fn_backlink_class = "footnote-backref"; + + /** + * Content to be displayed within footnote backlinks. The default is '↩'; + * the U+FE0E on the end is a Unicode variant selector used to prevent iOS + * from displaying the arrow character as an emoji. + * @var string + */ + public $fn_backlink_html = '↩︎'; + + /** + * Class name for table cell alignment (%% replaced left/center/right) + * For instance: 'go-%%' becomes 'go-left' or 'go-right' or 'go-center' + * If empty, the align attribute is used instead of a class name. + * @var string + */ + public $table_align_class_tmpl = ''; + + /** + * Optional class prefix for fenced code block. + * @var string + */ + public $code_class_prefix = ""; + + /** + * Class attribute for code blocks goes on the `code` tag; + * setting this to true will put attributes on the `pre` tag instead. + * @var boolean + */ + public $code_attr_on_pre = false; + + /** + * Predefined abbreviations. + * @var array + */ + public $predef_abbr = array(); + + /** + * Parser implementation + */ + + /** + * Constructor function. Initialize the parser object. + * @return void + */ + public function __construct() { + // Add extra escapable characters before parent constructor + // initialize the table. + $this->escape_chars .= ':|'; + + // Insert extra document, block, and span transformations. + // Parent constructor will do the sorting. + $this->document_gamut += array( + "doFencedCodeBlocks" => 5, + "stripFootnotes" => 15, + "stripAbbreviations" => 25, + "appendFootnotes" => 50, + ); + $this->block_gamut += array( + "doFencedCodeBlocks" => 5, + "doTables" => 15, + "doDefLists" => 45, + ); + $this->span_gamut += array( + "doFootnotes" => 5, + "doAbbreviations" => 70, + ); + + $this->enhanced_ordered_list = true; + parent::__construct(); + } + + + /** + * Extra variables used during extra transformations. + * @var array + */ + protected $footnotes = array(); + protected $footnotes_ordered = array(); + protected $footnotes_ref_count = array(); + protected $footnotes_numbers = array(); + protected $abbr_desciptions = array(); + /** @var @string */ + protected $abbr_word_re = ''; + + /** + * Give the current footnote number. + * @var integer + */ + protected $footnote_counter = 1; + + /** + * Setting up Extra-specific variables. + */ + protected function setup() { + parent::setup(); + + $this->footnotes = array(); + $this->footnotes_ordered = array(); + $this->footnotes_ref_count = array(); + $this->footnotes_numbers = array(); + $this->abbr_desciptions = array(); + $this->abbr_word_re = ''; + $this->footnote_counter = 1; + + foreach ($this->predef_abbr as $abbr_word => $abbr_desc) { + if ($this->abbr_word_re) + $this->abbr_word_re .= '|'; + $this->abbr_word_re .= preg_quote($abbr_word); + $this->abbr_desciptions[$abbr_word] = trim($abbr_desc); + } + } + + /** + * Clearing Extra-specific variables. + */ + protected function teardown() { + $this->footnotes = array(); + $this->footnotes_ordered = array(); + $this->footnotes_ref_count = array(); + $this->footnotes_numbers = array(); + $this->abbr_desciptions = array(); + $this->abbr_word_re = ''; + + parent::teardown(); + } + + + /** + * Extra attribute parser + */ + + /** + * Expression to use to catch attributes (includes the braces) + * @var string + */ + protected $id_class_attr_catch_re = '\{((?>[ ]*[#.a-z][-_:a-zA-Z0-9=]+){1,})[ ]*\}'; + + /** + * Expression to use when parsing in a context when no capture is desired + * @var string + */ + protected $id_class_attr_nocatch_re = '\{(?>[ ]*[#.a-z][-_:a-zA-Z0-9=]+){1,}[ ]*\}'; + + /** + * Parse attributes caught by the $this->id_class_attr_catch_re expression + * and return the HTML-formatted list of attributes. + * + * Currently supported attributes are .class and #id. + * + * In addition, this method also supports supplying a default Id value, + * which will be used to populate the id attribute in case it was not + * overridden. + * @param string $tag_name + * @param string $attr + * @param mixed $defaultIdValue + * @param array $classes + * @return string + */ + protected function doExtraAttributes($tag_name, $attr, $defaultIdValue = null, $classes = array()) { + if (empty($attr) && !$defaultIdValue && empty($classes)) return ""; + + // Split on components + preg_match_all('/[#.a-z][-_:a-zA-Z0-9=]+/', $attr, $matches); + $elements = $matches[0]; + + // Handle classes and IDs (only first ID taken into account) + $attributes = array(); + $id = false; + foreach ($elements as $element) { + if ($element{0} == '.') { + $classes[] = substr($element, 1); + } else if ($element{0} == '#') { + if ($id === false) $id = substr($element, 1); + } else if (strpos($element, '=') > 0) { + $parts = explode('=', $element, 2); + $attributes[] = $parts[0] . '="' . $parts[1] . '"'; + } + } + + if (!$id) $id = $defaultIdValue; + + // Compose attributes as string + $attr_str = ""; + if (!empty($id)) { + $attr_str .= ' id="'.$this->encodeAttribute($id) .'"'; + } + if (!empty($classes)) { + $attr_str .= ' class="'. implode(" ", $classes) . '"'; + } + if (!$this->no_markup && !empty($attributes)) { + $attr_str .= ' '.implode(" ", $attributes); + } + return $attr_str; + } + + /** + * Strips link definitions from text, stores the URLs and titles in + * hash references. + * @param string $text + * @return string + */ + protected function stripLinkDefinitions($text) { + $less_than_tab = $this->tab_width - 1; + + // Link defs are in the form: ^[id]: url "optional title" + $text = preg_replace_callback('{ + ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1 + [ ]* + \n? # maybe *one* newline + [ ]* + (?: + <(.+?)> # url = $2 + | + (\S+?) # url = $3 + ) + [ ]* + \n? # maybe one newline + [ ]* + (?: + (?<=\s) # lookbehind for whitespace + ["(] + (.*?) # title = $4 + [")] + [ ]* + )? # title is optional + (?:[ ]* '.$this->id_class_attr_catch_re.' )? # $5 = extra id & class attr + (?:\n+|\Z) + }xm', + array($this, '_stripLinkDefinitions_callback'), + $text); + return $text; + } + + /** + * Strip link definition callback + * @param array $matches + * @return string + */ + protected function _stripLinkDefinitions_callback($matches) { + $link_id = strtolower($matches[1]); + $url = $matches[2] == '' ? $matches[3] : $matches[2]; + $this->urls[$link_id] = $url; + $this->titles[$link_id] =& $matches[4]; + $this->ref_attr[$link_id] = $this->doExtraAttributes("", $dummy =& $matches[5]); + return ''; // String that will replace the block + } + + + /** + * HTML block parser + */ + + /** + * Tags that are always treated as block tags + * @var string + */ + protected $block_tags_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|form|fieldset|iframe|hr|legend|article|section|nav|aside|hgroup|header|footer|figcaption|figure'; + + /** + * Tags treated as block tags only if the opening tag is alone on its line + * @var string + */ + protected $context_block_tags_re = 'script|noscript|style|ins|del|iframe|object|source|track|param|math|svg|canvas|audio|video'; + + /** + * Tags where markdown="1" default to span mode: + * @var string + */ + protected $contain_span_tags_re = 'p|h[1-6]|li|dd|dt|td|th|legend|address'; + + /** + * Tags which must not have their contents modified, no matter where + * they appear + * @var string + */ + protected $clean_tags_re = 'script|style|math|svg'; + + /** + * Tags that do not need to be closed. + * @var string + */ + protected $auto_close_tags_re = 'hr|img|param|source|track'; + + /** + * Hashify HTML Blocks and "clean tags". + * + * We only want to do this for block-level HTML tags, such as headers, + * lists, and tables. That's because we still want to wrap

    s around + * "paragraphs" that are wrapped in non-block-level tags, such as anchors, + * phrase emphasis, and spans. The list of tags we're looking for is + * hard-coded. + * + * This works by calling _HashHTMLBlocks_InMarkdown, which then calls + * _HashHTMLBlocks_InHTML when it encounter block tags. When the markdown="1" + * attribute is found within a tag, _HashHTMLBlocks_InHTML calls back + * _HashHTMLBlocks_InMarkdown to handle the Markdown syntax within the tag. + * These two functions are calling each other. It's recursive! + * @param string $text + * @return string + */ + protected function hashHTMLBlocks($text) { + if ($this->no_markup) { + return $text; + } + + // Call the HTML-in-Markdown hasher. + list($text, ) = $this->_hashHTMLBlocks_inMarkdown($text); + + return $text; + } + + /** + * Parse markdown text, calling _HashHTMLBlocks_InHTML for block tags. + * + * * $indent is the number of space to be ignored when checking for code + * blocks. This is important because if we don't take the indent into + * account, something like this (which looks right) won't work as expected: + * + *

    + *
    + * Hello World. <-- Is this a Markdown code block or text? + *
    <-- Is this a Markdown code block or a real tag? + *
    + * + * If you don't like this, just don't indent the tag on which + * you apply the markdown="1" attribute. + * + * * If $enclosing_tag_re is not empty, stops at the first unmatched closing + * tag with that name. Nested tags supported. + * + * * If $span is true, text inside must treated as span. So any double + * newline will be replaced by a single newline so that it does not create + * paragraphs. + * + * Returns an array of that form: ( processed text , remaining text ) + * + * @param string $text + * @param integer $indent + * @param string $enclosing_tag_re + * @param boolean $span + * @return array + */ + protected function _hashHTMLBlocks_inMarkdown($text, $indent = 0, + $enclosing_tag_re = '', $span = false) + { + + if ($text === '') return array('', ''); + + // Regex to check for the presense of newlines around a block tag. + $newline_before_re = '/(?:^\n?|\n\n)*$/'; + $newline_after_re = + '{ + ^ # Start of text following the tag. + (?>[ ]*)? # Optional comment. + [ ]*\n # Must be followed by newline. + }xs'; + + // Regex to match any tag. + $block_tag_re = + '{ + ( # $2: Capture whole tag. + # Tag name. + ' . $this->block_tags_re . ' | + ' . $this->context_block_tags_re . ' | + ' . $this->clean_tags_re . ' | + (?!\s)'.$enclosing_tag_re . ' + ) + (?: + (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name. + (?> + ".*?" | # Double quotes (can contain `>`) + \'.*?\' | # Single quotes (can contain `>`) + .+? # Anything but quotes and `>`. + )*? + )? + > # End of tag. + | + # HTML Comment + | + <\?.*?\?> | <%.*?%> # Processing instruction + | + # CData Block + ' . ( !$span ? ' # If not in span. + | + # Indented code block + (?: ^[ ]*\n | ^ | \n[ ]*\n ) + [ ]{' . ($indent + 4) . '}[^\n]* \n + (?> + (?: [ ]{' . ($indent + 4) . '}[^\n]* | [ ]* ) \n + )* + | + # Fenced code block marker + (?<= ^ | \n ) + [ ]{0,' . ($indent + 3) . '}(?:~{3,}|`{3,}) + [ ]* + (?: \.?[-_:a-zA-Z0-9]+ )? # standalone class name + [ ]* + (?: ' . $this->id_class_attr_nocatch_re . ' )? # extra attributes + [ ]* + (?= \n ) + ' : '' ) . ' # End (if not is span). + | + # Code span marker + # Note, this regex needs to go after backtick fenced + # code blocks but it should also be kept outside of the + # "if not in span" condition adding backticks to the parser + `+ + ) + }xs'; + + + $depth = 0; // Current depth inside the tag tree. + $parsed = ""; // Parsed text that will be returned. + + // Loop through every tag until we find the closing tag of the parent + // or loop until reaching the end of text if no parent tag specified. + do { + // Split the text using the first $tag_match pattern found. + // Text before pattern will be first in the array, text after + // pattern will be at the end, and between will be any catches made + // by the pattern. + $parts = preg_split($block_tag_re, $text, 2, + PREG_SPLIT_DELIM_CAPTURE); + + // If in Markdown span mode, add a empty-string span-level hash + // after each newline to prevent triggering any block element. + if ($span) { + $void = $this->hashPart("", ':'); + $newline = "\n$void"; + $parts[0] = $void . str_replace("\n", $newline, $parts[0]) . $void; + } + + $parsed .= $parts[0]; // Text before current tag. + + // If end of $text has been reached. Stop loop. + if (count($parts) < 3) { + $text = ""; + break; + } + + $tag = $parts[1]; // Tag to handle. + $text = $parts[2]; // Remaining text after current tag. + $tag_re = preg_quote($tag); // For use in a regular expression. + + // Check for: Fenced code block marker. + // Note: need to recheck the whole tag to disambiguate backtick + // fences from code spans + if (preg_match('{^\n?([ ]{0,' . ($indent + 3) . '})(~{3,}|`{3,})[ ]*(?:\.?[-_:a-zA-Z0-9]+)?[ ]*(?:' . $this->id_class_attr_nocatch_re . ')?[ ]*\n?$}', $tag, $capture)) { + // Fenced code block marker: find matching end marker. + $fence_indent = strlen($capture[1]); // use captured indent in re + $fence_re = $capture[2]; // use captured fence in re + if (preg_match('{^(?>.*\n)*?[ ]{' . ($fence_indent) . '}' . $fence_re . '[ ]*(?:\n|$)}', $text, + $matches)) + { + // End marker found: pass text unchanged until marker. + $parsed .= $tag . $matches[0]; + $text = substr($text, strlen($matches[0])); + } + else { + // No end marker: just skip it. + $parsed .= $tag; + } + } + // Check for: Indented code block. + else if ($tag{0} == "\n" || $tag{0} == " ") { + // Indented code block: pass it unchanged, will be handled + // later. + $parsed .= $tag; + } + // Check for: Code span marker + // Note: need to check this after backtick fenced code blocks + else if ($tag{0} == "`") { + // Find corresponding end marker. + $tag_re = preg_quote($tag); + if (preg_match('{^(?>.+?|\n(?!\n))*?(?block_tags_re . ')\b}', $tag) || + ( preg_match('{^<(?:' . $this->context_block_tags_re . ')\b}', $tag) && + preg_match($newline_before_re, $parsed) && + preg_match($newline_after_re, $text) ) + ) + { + // Need to parse tag and following text using the HTML parser. + list($block_text, $text) = + $this->_hashHTMLBlocks_inHTML($tag . $text, "hashBlock", true); + + // Make sure it stays outside of any paragraph by adding newlines. + $parsed .= "\n\n$block_text\n\n"; + } + // Check for: Clean tag (like script, math) + // HTML Comments, processing instructions. + else if (preg_match('{^<(?:' . $this->clean_tags_re . ')\b}', $tag) || + $tag{1} == '!' || $tag{1} == '?') + { + // Need to parse tag and following text using the HTML parser. + // (don't check for markdown attribute) + list($block_text, $text) = + $this->_hashHTMLBlocks_inHTML($tag . $text, "hashClean", false); + + $parsed .= $block_text; + } + // Check for: Tag with same name as enclosing tag. + else if ($enclosing_tag_re !== '' && + // Same name as enclosing tag. + preg_match('{^= 0); + + return array($parsed, $text); + } + + /** + * Parse HTML, calling _HashHTMLBlocks_InMarkdown for block tags. + * + * * Calls $hash_method to convert any blocks. + * * Stops when the first opening tag closes. + * * $md_attr indicate if the use of the `markdown="1"` attribute is allowed. + * (it is not inside clean tags) + * + * Returns an array of that form: ( processed text , remaining text ) + * @param string $text + * @param string $hash_method + * @param string $md_attr + * @return array + */ + protected function _hashHTMLBlocks_inHTML($text, $hash_method, $md_attr) { + if ($text === '') return array('', ''); + + // Regex to match `markdown` attribute inside of a tag. + $markdown_attr_re = ' + { + \s* # Eat whitespace before the `markdown` attribute + markdown + \s*=\s* + (?> + (["\']) # $1: quote delimiter + (.*?) # $2: attribute value + \1 # matching delimiter + | + ([^\s>]*) # $3: unquoted attribute value + ) + () # $4: make $3 always defined (avoid warnings) + }xs'; + + // Regex to match any tag. + $tag_re = '{ + ( # $2: Capture whole tag. + + ".*?" | # Double quotes (can contain `>`) + \'.*?\' | # Single quotes (can contain `>`) + .+? # Anything but quotes and `>`. + )*? + )? + > # End of tag. + | + # HTML Comment + | + <\?.*?\?> | <%.*?%> # Processing instruction + | + # CData Block + ) + }xs'; + + $original_text = $text; // Save original text in case of faliure. + + $depth = 0; // Current depth inside the tag tree. + $block_text = ""; // Temporary text holder for current text. + $parsed = ""; // Parsed text that will be returned. + + // Get the name of the starting tag. + // (This pattern makes $base_tag_name_re safe without quoting.) + if (preg_match('/^<([\w:$]*)\b/', $text, $matches)) + $base_tag_name_re = $matches[1]; + + // Loop through every tag until we find the corresponding closing tag. + do { + // Split the text using the first $tag_match pattern found. + // Text before pattern will be first in the array, text after + // pattern will be at the end, and between will be any catches made + // by the pattern. + $parts = preg_split($tag_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE); + + if (count($parts) < 3) { + // End of $text reached with unbalenced tag(s). + // In that case, we return original text unchanged and pass the + // first character as filtered to prevent an infinite loop in the + // parent function. + return array($original_text{0}, substr($original_text, 1)); + } + + $block_text .= $parts[0]; // Text before current tag. + $tag = $parts[1]; // Tag to handle. + $text = $parts[2]; // Remaining text after current tag. + + // Check for: Auto-close tag (like
    ) + // Comments and Processing Instructions. + if (preg_match('{^auto_close_tags_re . ')\b}', $tag) || + $tag{1} == '!' || $tag{1} == '?') + { + // Just add the tag to the block as if it was text. + $block_text .= $tag; + } + else { + // Increase/decrease nested tag count. Only do so if + // the tag's name match base tag's. + if (preg_match('{^mode = $attr_m[2] . $attr_m[3]; + $span_mode = $this->mode == 'span' || $this->mode != 'block' && + preg_match('{^<(?:' . $this->contain_span_tags_re . ')\b}', $tag); + + // Calculate indent before tag. + if (preg_match('/(?:^|\n)( *?)(?! ).*?$/', $block_text, $matches)) { + $strlen = $this->utf8_strlen; + $indent = $strlen($matches[1], 'UTF-8'); + } else { + $indent = 0; + } + + // End preceding block with this tag. + $block_text .= $tag; + $parsed .= $this->$hash_method($block_text); + + // Get enclosing tag name for the ParseMarkdown function. + // (This pattern makes $tag_name_re safe without quoting.) + preg_match('/^<([\w:$]*)\b/', $tag, $matches); + $tag_name_re = $matches[1]; + + // Parse the content using the HTML-in-Markdown parser. + list ($block_text, $text) + = $this->_hashHTMLBlocks_inMarkdown($text, $indent, + $tag_name_re, $span_mode); + + // Outdent markdown text. + if ($indent > 0) { + $block_text = preg_replace("/^[ ]{1,$indent}/m", "", + $block_text); + } + + // Append tag content to parsed text. + if (!$span_mode) $parsed .= "\n\n$block_text\n\n"; + else $parsed .= "$block_text"; + + // Start over with a new block. + $block_text = ""; + } + else $block_text .= $tag; + } + + } while ($depth > 0); + + // Hash last block text that wasn't processed inside the loop. + $parsed .= $this->$hash_method($block_text); + + return array($parsed, $text); + } + + /** + * Called whenever a tag must be hashed when a function inserts a "clean" tag + * in $text, it passes through this function and is automaticaly escaped, + * blocking invalid nested overlap. + * @param string $text + * @return string + */ + protected function hashClean($text) { + return $this->hashPart($text, 'C'); + } + + /** + * Turn Markdown link shortcuts into XHTML tags. + * @param string $text + * @return string + */ + protected function doAnchors($text) { + if ($this->in_anchor) { + return $text; + } + $this->in_anchor = true; + + // First, handle reference-style links: [link text] [id] + $text = preg_replace_callback('{ + ( # wrap whole match in $1 + \[ + (' . $this->nested_brackets_re . ') # link text = $2 + \] + + [ ]? # one optional space + (?:\n[ ]*)? # one optional newline followed by spaces + + \[ + (.*?) # id = $3 + \] + ) + }xs', + array($this, '_doAnchors_reference_callback'), $text); + + // Next, inline-style links: [link text](url "optional title") + $text = preg_replace_callback('{ + ( # wrap whole match in $1 + \[ + (' . $this->nested_brackets_re . ') # link text = $2 + \] + \( # literal paren + [ \n]* + (?: + <(.+?)> # href = $3 + | + (' . $this->nested_url_parenthesis_re . ') # href = $4 + ) + [ \n]* + ( # $5 + ([\'"]) # quote char = $6 + (.*?) # Title = $7 + \6 # matching quote + [ \n]* # ignore any spaces/tabs between closing quote and ) + )? # title is optional + \) + (?:[ ]? ' . $this->id_class_attr_catch_re . ' )? # $8 = id/class attributes + ) + }xs', + array($this, '_doAnchors_inline_callback'), $text); + + // Last, handle reference-style shortcuts: [link text] + // These must come last in case you've also got [link text][1] + // or [link text](/foo) + $text = preg_replace_callback('{ + ( # wrap whole match in $1 + \[ + ([^\[\]]+) # link text = $2; can\'t contain [ or ] + \] + ) + }xs', + array($this, '_doAnchors_reference_callback'), $text); + + $this->in_anchor = false; + return $text; + } + + /** + * Callback for reference anchors + * @param array $matches + * @return string + */ + protected function _doAnchors_reference_callback($matches) { + $whole_match = $matches[1]; + $link_text = $matches[2]; + $link_id =& $matches[3]; + + if ($link_id == "") { + // for shortcut links like [this][] or [this]. + $link_id = $link_text; + } + + // lower-case and turn embedded newlines into spaces + $link_id = strtolower($link_id); + $link_id = preg_replace('{[ ]?\n}', ' ', $link_id); + + if (isset($this->urls[$link_id])) { + $url = $this->urls[$link_id]; + $url = $this->encodeURLAttribute($url); + + $result = "titles[$link_id] ) ) { + $title = $this->titles[$link_id]; + $title = $this->encodeAttribute($title); + $result .= " title=\"$title\""; + } + if (isset($this->ref_attr[$link_id])) + $result .= $this->ref_attr[$link_id]; + + $link_text = $this->runSpanGamut($link_text); + $result .= ">$link_text"; + $result = $this->hashPart($result); + } + else { + $result = $whole_match; + } + return $result; + } + + /** + * Callback for inline anchors + * @param array $matches + * @return string + */ + protected function _doAnchors_inline_callback($matches) { + $whole_match = $matches[1]; + $link_text = $this->runSpanGamut($matches[2]); + $url = $matches[3] == '' ? $matches[4] : $matches[3]; + $title =& $matches[7]; + $attr = $this->doExtraAttributes("a", $dummy =& $matches[8]); + + // if the URL was of the form it got caught by the HTML + // tag parser and hashed. Need to reverse the process before using the URL. + $unhashed = $this->unhash($url); + if ($unhashed != $url) + $url = preg_replace('/^<(.*)>$/', '\1', $unhashed); + + $url = $this->encodeURLAttribute($url); + + $result = "encodeAttribute($title); + $result .= " title=\"$title\""; + } + $result .= $attr; + + $link_text = $this->runSpanGamut($link_text); + $result .= ">$link_text"; + + return $this->hashPart($result); + } + + /** + * Turn Markdown image shortcuts into tags. + * @param string $text + * @return string + */ + protected function doImages($text) { + // First, handle reference-style labeled images: ![alt text][id] + $text = preg_replace_callback('{ + ( # wrap whole match in $1 + !\[ + (' . $this->nested_brackets_re . ') # alt text = $2 + \] + + [ ]? # one optional space + (?:\n[ ]*)? # one optional newline followed by spaces + + \[ + (.*?) # id = $3 + \] + + ) + }xs', + array($this, '_doImages_reference_callback'), $text); + + // Next, handle inline images: ![alt text](url "optional title") + // Don't forget: encode * and _ + $text = preg_replace_callback('{ + ( # wrap whole match in $1 + !\[ + (' . $this->nested_brackets_re . ') # alt text = $2 + \] + \s? # One optional whitespace character + \( # literal paren + [ \n]* + (?: + <(\S*)> # src url = $3 + | + (' . $this->nested_url_parenthesis_re . ') # src url = $4 + ) + [ \n]* + ( # $5 + ([\'"]) # quote char = $6 + (.*?) # title = $7 + \6 # matching quote + [ \n]* + )? # title is optional + \) + (?:[ ]? ' . $this->id_class_attr_catch_re . ' )? # $8 = id/class attributes + ) + }xs', + array($this, '_doImages_inline_callback'), $text); + + return $text; + } + + /** + * Callback for referenced images + * @param array $matches + * @return string + */ + protected function _doImages_reference_callback($matches) { + $whole_match = $matches[1]; + $alt_text = $matches[2]; + $link_id = strtolower($matches[3]); + + if ($link_id == "") { + $link_id = strtolower($alt_text); // for shortcut links like ![this][]. + } + + $alt_text = $this->encodeAttribute($alt_text); + if (isset($this->urls[$link_id])) { + $url = $this->encodeURLAttribute($this->urls[$link_id]); + $result = "\"$alt_text\"";titles[$link_id])) { + $title = $this->titles[$link_id]; + $title = $this->encodeAttribute($title); + $result .= " title=\"$title\""; + } + if (isset($this->ref_attr[$link_id])) + $result .= $this->ref_attr[$link_id]; + $result .= $this->empty_element_suffix; + $result = $this->hashPart($result); + } + else { + // If there's no such link ID, leave intact: + $result = $whole_match; + } + + return $result; + } + + /** + * Callback for inline images + * @param array $matches + * @return string + */ + protected function _doImages_inline_callback($matches) { + $whole_match = $matches[1]; + $alt_text = $matches[2]; + $url = $matches[3] == '' ? $matches[4] : $matches[3]; + $title =& $matches[7]; + $attr = $this->doExtraAttributes("img", $dummy =& $matches[8]); + + $alt_text = $this->encodeAttribute($alt_text); + $url = $this->encodeURLAttribute($url); + $result = "\"$alt_text\"";encodeAttribute($title); + $result .= " title=\"$title\""; // $title already quoted + } + $result .= $attr; + $result .= $this->empty_element_suffix; + + return $this->hashPart($result); + } + + /** + * Process markdown headers. Redefined to add ID and class attribute support. + * @param string $text + * @return string + */ + protected function doHeaders($text) { + // Setext-style headers: + // Header 1 {#header1} + // ======== + // + // Header 2 {#header2 .class1 .class2} + // -------- + // + $text = preg_replace_callback( + '{ + (^.+?) # $1: Header text + (?:[ ]+ ' . $this->id_class_attr_catch_re . ' )? # $3 = id/class attributes + [ ]*\n(=+|-+)[ ]*\n+ # $3: Header footer + }mx', + array($this, '_doHeaders_callback_setext'), $text); + + // atx-style headers: + // # Header 1 {#header1} + // ## Header 2 {#header2} + // ## Header 2 with closing hashes ## {#header3.class1.class2} + // ... + // ###### Header 6 {.class2} + // + $text = preg_replace_callback('{ + ^(\#{1,6}) # $1 = string of #\'s + [ ]* + (.+?) # $2 = Header text + [ ]* + \#* # optional closing #\'s (not counted) + (?:[ ]+ ' . $this->id_class_attr_catch_re . ' )? # $3 = id/class attributes + [ ]* + \n+ + }xm', + array($this, '_doHeaders_callback_atx'), $text); + + return $text; + } + + /** + * Callback for setext headers + * @param array $matches + * @return string + */ + protected function _doHeaders_callback_setext($matches) { + if ($matches[3] == '-' && preg_match('{^- }', $matches[1])) { + return $matches[0]; + } + + $level = $matches[3]{0} == '=' ? 1 : 2; + + $defaultId = is_callable($this->header_id_func) ? call_user_func($this->header_id_func, $matches[1]) : null; + + $attr = $this->doExtraAttributes("h$level", $dummy =& $matches[2], $defaultId); + $block = "" . $this->runSpanGamut($matches[1]) . ""; + return "\n" . $this->hashBlock($block) . "\n\n"; + } + + /** + * Callback for atx headers + * @param array $matches + * @return string + */ + protected function _doHeaders_callback_atx($matches) { + $level = strlen($matches[1]); + + $defaultId = is_callable($this->header_id_func) ? call_user_func($this->header_id_func, $matches[2]) : null; + $attr = $this->doExtraAttributes("h$level", $dummy =& $matches[3], $defaultId); + $block = "" . $this->runSpanGamut($matches[2]) . ""; + return "\n" . $this->hashBlock($block) . "\n\n"; + } + + /** + * Form HTML tables. + * @param string $text + * @return string + */ + protected function doTables($text) { + $less_than_tab = $this->tab_width - 1; + // Find tables with leading pipe. + // + // | Header 1 | Header 2 + // | -------- | -------- + // | Cell 1 | Cell 2 + // | Cell 3 | Cell 4 + $text = preg_replace_callback(' + { + ^ # Start of a line + [ ]{0,' . $less_than_tab . '} # Allowed whitespace. + [|] # Optional leading pipe (present) + (.+) \n # $1: Header row (at least one pipe) + + [ ]{0,' . $less_than_tab . '} # Allowed whitespace. + [|] ([ ]*[-:]+[-| :]*) \n # $2: Header underline + + ( # $3: Cells + (?> + [ ]* # Allowed whitespace. + [|] .* \n # Row content. + )* + ) + (?=\n|\Z) # Stop at final double newline. + }xm', + array($this, '_doTable_leadingPipe_callback'), $text); + + // Find tables without leading pipe. + // + // Header 1 | Header 2 + // -------- | -------- + // Cell 1 | Cell 2 + // Cell 3 | Cell 4 + $text = preg_replace_callback(' + { + ^ # Start of a line + [ ]{0,' . $less_than_tab . '} # Allowed whitespace. + (\S.*[|].*) \n # $1: Header row (at least one pipe) + + [ ]{0,' . $less_than_tab . '} # Allowed whitespace. + ([-:]+[ ]*[|][-| :]*) \n # $2: Header underline + + ( # $3: Cells + (?> + .* [|] .* \n # Row content + )* + ) + (?=\n|\Z) # Stop at final double newline. + }xm', + array($this, '_DoTable_callback'), $text); + + return $text; + } + + /** + * Callback for removing the leading pipe for each row + * @param array $matches + * @return string + */ + protected function _doTable_leadingPipe_callback($matches) { + $head = $matches[1]; + $underline = $matches[2]; + $content = $matches[3]; + + $content = preg_replace('/^ *[|]/m', '', $content); + + return $this->_doTable_callback(array($matches[0], $head, $underline, $content)); + } + + /** + * Make the align attribute in a table + * @param string $alignname + * @return string + */ + protected function _doTable_makeAlignAttr($alignname) + { + if (empty($this->table_align_class_tmpl)) { + return " align=\"$alignname\""; + } + + $classname = str_replace('%%', $alignname, $this->table_align_class_tmpl); + return " class=\"$classname\""; + } + + /** + * Calback for processing tables + * @param array $matches + * @return string + */ + protected function _doTable_callback($matches) { + $head = $matches[1]; + $underline = $matches[2]; + $content = $matches[3]; + + // Remove any tailing pipes for each line. + $head = preg_replace('/[|] *$/m', '', $head); + $underline = preg_replace('/[|] *$/m', '', $underline); + $content = preg_replace('/[|] *$/m', '', $content); + + // Reading alignement from header underline. + $separators = preg_split('/ *[|] */', $underline); + foreach ($separators as $n => $s) { + if (preg_match('/^ *-+: *$/', $s)) + $attr[$n] = $this->_doTable_makeAlignAttr('right'); + else if (preg_match('/^ *:-+: *$/', $s)) + $attr[$n] = $this->_doTable_makeAlignAttr('center'); + else if (preg_match('/^ *:-+ *$/', $s)) + $attr[$n] = $this->_doTable_makeAlignAttr('left'); + else + $attr[$n] = ''; + } + + // Parsing span elements, including code spans, character escapes, + // and inline HTML tags, so that pipes inside those gets ignored. + $head = $this->parseSpan($head); + $headers = preg_split('/ *[|] */', $head); + $col_count = count($headers); + $attr = array_pad($attr, $col_count, ''); + + // Write column headers. + $text = "\n"; + $text .= "\n"; + $text .= "\n"; + foreach ($headers as $n => $header) + $text .= " " . $this->runSpanGamut(trim($header)) . "\n"; + $text .= "\n"; + $text .= "\n"; + + // Split content by row. + $rows = explode("\n", trim($content, "\n")); + + $text .= "\n"; + foreach ($rows as $row) { + // Parsing span elements, including code spans, character escapes, + // and inline HTML tags, so that pipes inside those gets ignored. + $row = $this->parseSpan($row); + + // Split row by cell. + $row_cells = preg_split('/ *[|] */', $row, $col_count); + $row_cells = array_pad($row_cells, $col_count, ''); + + $text .= "\n"; + foreach ($row_cells as $n => $cell) + $text .= " " . $this->runSpanGamut(trim($cell)) . "\n"; + $text .= "\n"; + } + $text .= "\n"; + $text .= "
    "; + + return $this->hashBlock($text) . "\n"; + } + + /** + * Form HTML definition lists. + * @param string $text + * @return string + */ + protected function doDefLists($text) { + $less_than_tab = $this->tab_width - 1; + + // Re-usable pattern to match any entire dl list: + $whole_list_re = '(?> + ( # $1 = whole list + ( # $2 + [ ]{0,' . $less_than_tab . '} + ((?>.*\S.*\n)+) # $3 = defined term + \n? + [ ]{0,' . $less_than_tab . '}:[ ]+ # colon starting definition + ) + (?s:.+?) + ( # $4 + \z + | + \n{2,} + (?=\S) + (?! # Negative lookahead for another term + [ ]{0,' . $less_than_tab . '} + (?: \S.*\n )+? # defined term + \n? + [ ]{0,' . $less_than_tab . '}:[ ]+ # colon starting definition + ) + (?! # Negative lookahead for another definition + [ ]{0,' . $less_than_tab . '}:[ ]+ # colon starting definition + ) + ) + ) + )'; // mx + + $text = preg_replace_callback('{ + (?>\A\n?|(?<=\n\n)) + ' . $whole_list_re . ' + }mx', + array($this, '_doDefLists_callback'), $text); + + return $text; + } + + /** + * Callback for processing definition lists + * @param array $matches + * @return string + */ + protected function _doDefLists_callback($matches) { + // Re-usable patterns to match list item bullets and number markers: + $list = $matches[1]; + + // Turn double returns into triple returns, so that we can make a + // paragraph for the last item in a list, if necessary: + $result = trim($this->processDefListItems($list)); + $result = "
    \n" . $result . "\n
    "; + return $this->hashBlock($result) . "\n\n"; + } + + /** + * Process the contents of a single definition list, splitting it + * into individual term and definition list items. + * @param string $list_str + * @return string + */ + protected function processDefListItems($list_str) { + + $less_than_tab = $this->tab_width - 1; + + // Trim trailing blank lines: + $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str); + + // Process definition terms. + $list_str = preg_replace_callback('{ + (?>\A\n?|\n\n+) # leading line + ( # definition terms = $1 + [ ]{0,' . $less_than_tab . '} # leading whitespace + (?!\:[ ]|[ ]) # negative lookahead for a definition + # mark (colon) or more whitespace. + (?> \S.* \n)+? # actual term (not whitespace). + ) + (?=\n?[ ]{0,3}:[ ]) # lookahead for following line feed + # with a definition mark. + }xm', + array($this, '_processDefListItems_callback_dt'), $list_str); + + // Process actual definitions. + $list_str = preg_replace_callback('{ + \n(\n+)? # leading line = $1 + ( # marker space = $2 + [ ]{0,' . $less_than_tab . '} # whitespace before colon + \:[ ]+ # definition mark (colon) + ) + ((?s:.+?)) # definition text = $3 + (?= \n+ # stop at next definition mark, + (?: # next term or end of text + [ ]{0,' . $less_than_tab . '} \:[ ] | +
    | \z + ) + ) + }xm', + array($this, '_processDefListItems_callback_dd'), $list_str); + + return $list_str; + } + + /** + * Callback for
    elements in definition lists + * @param array $matches + * @return string + */ + protected function _processDefListItems_callback_dt($matches) { + $terms = explode("\n", trim($matches[1])); + $text = ''; + foreach ($terms as $term) { + $term = $this->runSpanGamut(trim($term)); + $text .= "\n
    " . $term . "
    "; + } + return $text . "\n"; + } + + /** + * Callback for
    elements in definition lists + * @param array $matches + * @return string + */ + protected function _processDefListItems_callback_dd($matches) { + $leading_line = $matches[1]; + $marker_space = $matches[2]; + $def = $matches[3]; + + if ($leading_line || preg_match('/\n{2,}/', $def)) { + // Replace marker with the appropriate whitespace indentation + $def = str_repeat(' ', strlen($marker_space)) . $def; + $def = $this->runBlockGamut($this->outdent($def . "\n\n")); + $def = "\n". $def ."\n"; + } + else { + $def = rtrim($def); + $def = $this->runSpanGamut($this->outdent($def)); + } + + return "\n
    " . $def . "
    \n"; + } + + /** + * Adding the fenced code block syntax to regular Markdown: + * + * ~~~ + * Code block + * ~~~ + * + * @param string $text + * @return string + */ + protected function doFencedCodeBlocks($text) { + + $less_than_tab = $this->tab_width; + + $text = preg_replace_callback('{ + (?:\n|\A) + # 1: Opening marker + ( + (?:~{3,}|`{3,}) # 3 or more tildes/backticks. + ) + [ ]* + (?: + \.?([-_:a-zA-Z0-9]+) # 2: standalone class name + )? + [ ]* + (?: + ' . $this->id_class_attr_catch_re . ' # 3: Extra attributes + )? + [ ]* \n # Whitespace and newline following marker. + + # 4: Content + ( + (?> + (?!\1 [ ]* \n) # Not a closing marker. + .*\n+ + )+ + ) + + # Closing marker. + \1 [ ]* (?= \n ) + }xm', + array($this, '_doFencedCodeBlocks_callback'), $text); + + return $text; + } + + /** + * Callback to process fenced code blocks + * @param array $matches + * @return string + */ + protected function _doFencedCodeBlocks_callback($matches) { + $classname =& $matches[2]; + $attrs =& $matches[3]; + $codeblock = $matches[4]; + + if ($this->code_block_content_func) { + $codeblock = call_user_func($this->code_block_content_func, $codeblock, $classname); + } else { + $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES); + } + + $codeblock = preg_replace_callback('/^\n+/', + array($this, '_doFencedCodeBlocks_newlines'), $codeblock); + + $classes = array(); + if ($classname != "") { + if ($classname{0} == '.') + $classname = substr($classname, 1); + $classes[] = $this->code_class_prefix . $classname; + } + $attr_str = $this->doExtraAttributes($this->code_attr_on_pre ? "pre" : "code", $attrs, null, $classes); + $pre_attr_str = $this->code_attr_on_pre ? $attr_str : ''; + $code_attr_str = $this->code_attr_on_pre ? '' : $attr_str; + $codeblock = "$codeblock
    "; + + return "\n\n".$this->hashBlock($codeblock)."\n\n"; + } + + /** + * Replace new lines in fenced code blocks + * @param array $matches + * @return string + */ + protected function _doFencedCodeBlocks_newlines($matches) { + return str_repeat("empty_element_suffix", + strlen($matches[0])); + } + + /** + * Redefining emphasis markers so that emphasis by underscore does not + * work in the middle of a word. + * @var array + */ + protected $em_relist = array( + '' => '(?:(? '(? '(? '(?:(? '(? '(? '(?:(? '(? '(? tags + * @return string HTML output + */ + protected function formParagraphs($text, $wrap_in_p = true) { + // Strip leading and trailing lines: + $text = preg_replace('/\A\n+|\n+\z/', '', $text); + + $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY); + + // Wrap

    tags and unhashify HTML blocks + foreach ($grafs as $key => $value) { + $value = trim($this->runSpanGamut($value)); + + // Check if this should be enclosed in a paragraph. + // Clean tag hashes & block tag hashes are left alone. + $is_p = $wrap_in_p && !preg_match('/^B\x1A[0-9]+B|^C\x1A[0-9]+C$/', $value); + + if ($is_p) { + $value = "

    $value

    "; + } + $grafs[$key] = $value; + } + + // Join grafs in one text, then unhash HTML tags. + $text = implode("\n\n", $grafs); + + // Finish by removing any tag hashes still present in $text. + $text = $this->unhash($text); + + return $text; + } + + + /** + * Footnotes - Strips link definitions from text, stores the URLs and + * titles in hash references. + * @param string $text + * @return string + */ + protected function stripFootnotes($text) { + $less_than_tab = $this->tab_width - 1; + + // Link defs are in the form: [^id]: url "optional title" + $text = preg_replace_callback('{ + ^[ ]{0,' . $less_than_tab . '}\[\^(.+?)\][ ]?: # note_id = $1 + [ ]* + \n? # maybe *one* newline + ( # text = $2 (no blank lines allowed) + (?: + .+ # actual text + | + \n # newlines but + (?!\[.+?\][ ]?:\s)# negative lookahead for footnote or link definition marker. + (?!\n+[ ]{0,3}\S)# ensure line is not blank and followed + # by non-indented content + )* + ) + }xm', + array($this, '_stripFootnotes_callback'), + $text); + return $text; + } + + /** + * Callback for stripping footnotes + * @param array $matches + * @return string + */ + protected function _stripFootnotes_callback($matches) { + $note_id = $this->fn_id_prefix . $matches[1]; + $this->footnotes[$note_id] = $this->outdent($matches[2]); + return ''; // String that will replace the block + } + + /** + * Replace footnote references in $text [^id] with a special text-token + * which will be replaced by the actual footnote marker in appendFootnotes. + * @param string $text + * @return string + */ + protected function doFootnotes($text) { + if (!$this->in_anchor) { + $text = preg_replace('{\[\^(.+?)\]}', "F\x1Afn:\\1\x1A:", $text); + } + return $text; + } + + /** + * Append footnote list to text + * @param string $text + * @return string + */ + protected function appendFootnotes($text) { + $text = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}', + array($this, '_appendFootnotes_callback'), $text); + + if (!empty($this->footnotes_ordered)) { + $text .= "\n\n"; + $text .= "
    \n"; + $text .= "empty_element_suffix . "\n"; + $text .= "
      \n\n"; + + $attr = ""; + if ($this->fn_backlink_class != "") { + $class = $this->fn_backlink_class; + $class = $this->encodeAttribute($class); + $attr .= " class=\"$class\""; + } + if ($this->fn_backlink_title != "") { + $title = $this->fn_backlink_title; + $title = $this->encodeAttribute($title); + $attr .= " title=\"$title\""; + } + $backlink_text = $this->fn_backlink_html; + $num = 0; + + while (!empty($this->footnotes_ordered)) { + $footnote = reset($this->footnotes_ordered); + $note_id = key($this->footnotes_ordered); + unset($this->footnotes_ordered[$note_id]); + $ref_count = $this->footnotes_ref_count[$note_id]; + unset($this->footnotes_ref_count[$note_id]); + unset($this->footnotes[$note_id]); + + $footnote .= "\n"; // Need to append newline before parsing. + $footnote = $this->runBlockGamut("$footnote\n"); + $footnote = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}', + array($this, '_appendFootnotes_callback'), $footnote); + + $attr = str_replace("%%", ++$num, $attr); + $note_id = $this->encodeAttribute($note_id); + + // Prepare backlink, multiple backlinks if multiple references + $backlink = "$backlink_text"; + for ($ref_num = 2; $ref_num <= $ref_count; ++$ref_num) { + $backlink .= " $backlink_text"; + } + // Add backlink to last paragraph; create new paragraph if needed. + if (preg_match('{

      $}', $footnote)) { + $footnote = substr($footnote, 0, -4) . " $backlink

      "; + } else { + $footnote .= "\n\n

      $backlink

      "; + } + + $text .= "
    1. \n"; + $text .= $footnote . "\n"; + $text .= "
    2. \n\n"; + } + + $text .= "
    \n"; + $text .= "
    "; + } + return $text; + } + + /** + * Callback for appending footnotes + * @param array $matches + * @return string + */ + protected function _appendFootnotes_callback($matches) { + $node_id = $this->fn_id_prefix . $matches[1]; + + // Create footnote marker only if it has a corresponding footnote *and* + // the footnote hasn't been used by another marker. + if (isset($this->footnotes[$node_id])) { + $num =& $this->footnotes_numbers[$node_id]; + if (!isset($num)) { + // Transfer footnote content to the ordered list and give it its + // number + $this->footnotes_ordered[$node_id] = $this->footnotes[$node_id]; + $this->footnotes_ref_count[$node_id] = 1; + $num = $this->footnote_counter++; + $ref_count_mark = ''; + } else { + $ref_count_mark = $this->footnotes_ref_count[$node_id] += 1; + } + + $attr = ""; + if ($this->fn_link_class != "") { + $class = $this->fn_link_class; + $class = $this->encodeAttribute($class); + $attr .= " class=\"$class\""; + } + if ($this->fn_link_title != "") { + $title = $this->fn_link_title; + $title = $this->encodeAttribute($title); + $attr .= " title=\"$title\""; + } + + $attr = str_replace("%%", $num, $attr); + $node_id = $this->encodeAttribute($node_id); + + return + "". + "$num". + ""; + } + + return "[^" . $matches[1] . "]"; + } + + + /** + * Abbreviations - strips abbreviations from text, stores titles in hash + * references. + * @param string $text + * @return string + */ + protected function stripAbbreviations($text) { + $less_than_tab = $this->tab_width - 1; + + // Link defs are in the form: [id]*: url "optional title" + $text = preg_replace_callback('{ + ^[ ]{0,' . $less_than_tab . '}\*\[(.+?)\][ ]?: # abbr_id = $1 + (.*) # text = $2 (no blank lines allowed) + }xm', + array($this, '_stripAbbreviations_callback'), + $text); + return $text; + } + + /** + * Callback for stripping abbreviations + * @param array $matches + * @return string + */ + protected function _stripAbbreviations_callback($matches) { + $abbr_word = $matches[1]; + $abbr_desc = $matches[2]; + if ($this->abbr_word_re) { + $this->abbr_word_re .= '|'; + } + $this->abbr_word_re .= preg_quote($abbr_word); + $this->abbr_desciptions[$abbr_word] = trim($abbr_desc); + return ''; // String that will replace the block + } + + /** + * Find defined abbreviations in text and wrap them in elements. + * @param string $text + * @return string + */ + protected function doAbbreviations($text) { + if ($this->abbr_word_re) { + // cannot use the /x modifier because abbr_word_re may + // contain significant spaces: + $text = preg_replace_callback('{' . + '(?abbr_word_re . ')' . + '(?![\w\x1A])' . + '}', + array($this, '_doAbbreviations_callback'), $text); + } + return $text; + } + + /** + * Callback for processing abbreviations + * @param array $matches + * @return string + */ + protected function _doAbbreviations_callback($matches) { + $abbr = $matches[0]; + if (isset($this->abbr_desciptions[$abbr])) { + $desc = $this->abbr_desciptions[$abbr]; + if (empty($desc)) { + return $this->hashPart("$abbr"); + } else { + $desc = $this->encodeAttribute($desc); + return $this->hashPart("$abbr"); + } + } else { + return $matches[0]; + } + } +} diff --git a/src/bb-vendor/michelf/php-markdown/Michelf/MarkdownInterface.php b/src/bb-vendor/michelf/php-markdown/Michelf/MarkdownInterface.php new file mode 100644 index 000000000..8512e3753 --- /dev/null +++ b/src/bb-vendor/michelf/php-markdown/Michelf/MarkdownInterface.php @@ -0,0 +1,38 @@ + + * @copyright 2004-2016 Michel Fortin + * @copyright (Original Markdown) 2004-2006 John Gruber + */ + +namespace Michelf; + +/** + * Markdown Parser Interface + */ +interface MarkdownInterface { + /** + * Initialize the parser and return the result of its transform method. + * This will work fine for derived classes too. + * + * @api + * + * @param string $text + * @return string + */ + public static function defaultTransform($text); + + /** + * Main function. Performs some preprocessing on the input text + * and pass it through the document gamut. + * + * @api + * + * @param string $text + * @return string + */ + public function transform($text); +} diff --git a/src/bb-vendor/michelf/php-markdown/Readme.md b/src/bb-vendor/michelf/php-markdown/Readme.md new file mode 100644 index 000000000..044407106 --- /dev/null +++ b/src/bb-vendor/michelf/php-markdown/Readme.md @@ -0,0 +1,384 @@ +PHP Markdown +============ + +PHP Markdown Lib 1.7.0 - 29 Oct 2016 + +by Michel Fortin + + +based on Markdown by John Gruber + + + +Introduction +------------ + +This is a library package that includes the PHP Markdown parser and its +sibling PHP Markdown Extra with additional features. + +Markdown is a text-to-HTML conversion tool for web writers. Markdown +allows you to write using an easy-to-read, easy-to-write plain text +format, then convert it to structurally valid XHTML (or HTML). + +"Markdown" is actually two things: a plain text markup syntax, and a +software tool, originally written in Perl, that converts the plain text +markup to HTML. PHP Markdown is a port to PHP of the original Markdown +program by John Gruber. + +* [Full documentation of the Markdown syntax]() + — Daring Fireball (John Gruber) +* [Markdown Extra syntax additions]() + — Michel Fortin + + +Requirement +----------- + +This library package requires PHP 5.3 or later. + +Note: The older plugin/library hybrid package for PHP Markdown and +PHP Markdown Extra is still maintained and will work with PHP 4.0.5 and later. + +Before PHP 5.3.7, pcre.backtrack_limit defaults to 100 000, which is too small +in many situations. You might need to set it to higher values. Later PHP +releases defaults to 1 000 000, which is usually fine. + + +Usage +----- + +This library package is meant to be used with class autoloading. For autoloading +to work, your project needs have setup a PSR-0-compatible autoloader. See the +included Readme.php file for a minimal autoloader setup. (If you cannot use +autoloading, see below.) + +With class autoloading in place, putting the 'Michelf' folder in your +include path should be enough for this to work: + + use \Michelf\Markdown; + $my_html = Markdown::defaultTransform($my_text); + +Markdown Extra syntax is also available the same way: + + use \Michelf\MarkdownExtra; + $my_html = MarkdownExtra::defaultTransform($my_text); + +If you wish to use PHP Markdown with another text filter function +built to parse HTML, you should filter the text *after* the `transform` +function call. This is an example with [PHP SmartyPants][psp]: + + use \Michelf\Markdown, \Michelf\SmartyPants; + $my_html = Markdown::defaultTransform($my_text); + $my_html = SmartyPants::defaultTransform($my_html); + +All these examples are using the static `defaultTransform` static function +found inside the parser class. If you want to customize the parser +configuration, you can also instantiate it directly and change some +configuration variables: + + use \Michelf\MarkdownExtra; + $parser = new MarkdownExtra; + $parser->fn_id_prefix = "post22-"; + $my_html = $parser->transform($my_text); + +To learn more, see the full list of [configuration variables]. + + [configuration variables]: https://michelf.ca/projects/php-markdown/configuration/ + + +### Usage without an autoloader + +If you cannot use class autoloading, you can still use `include` or `require` +to access the parser. To load the `\Michelf\Markdown` parser, do it this way: + + require_once 'Michelf/Markdown.inc.php'; + +Or, if you need the `\Michelf\MarkdownExtra` parser: + + require_once 'Michelf/MarkdownExtra.inc.php'; + +While the plain `.php` files depend on autoloading to work correctly, using the +`.inc.php` files instead will eagerly load the dependencies that would be +loaded on demand if you were using autoloading. + + +Public API and Versioning Policy +--------------------------------- + +Version numbers are of the form *major*.*minor*.*patch*. + +The public API of PHP Markdown consist of the two parser classes `Markdown` +and `MarkdownExtra`, their constructors, the `transform` and `defaultTransform` +functions and their configuration variables. The public API is stable for +a given major version number. It might get additions when the minor version +number increments. + +**Protected members are not considered public API.** This is unconventional +and deserves an explanation. Incrementing the major version number every time +the underlying implementation of something changes is going to give +nonessential version numbers for the vast majority of people who just use the +parser. Protected members are meant to create parser subclasses that behave in +different ways. Very few people create parser subclasses. I don't want to +discourage it by making everything private, but at the same time I can't +guarantee any stable hook between versions if you use protected members. + +**Syntax changes** will increment the minor number for new features, and the +patch number for small corrections. A *new feature* is something that needs a +change in the syntax documentation. Note that since PHP Markdown Lib includes +two parsers, a syntax change for either of them will increment the minor +number. Also note that there is nothing perfectly backward-compatible with the +Markdown syntax: all inputs are always valid, so new features always replace +something that was previously legal, although generally nonsensical to do. + + +Bugs +---- + +To file bug reports please send email to: + + +Please include with your report: (1) the example input; (2) the output you +expected; (3) the output PHP Markdown actually produced. + +If you have a problem where Markdown gives you an empty result, first check +that the backtrack limit is not too low by running `php --info | grep pcre`. +See Installation and Requirement above for details. + + +Development and Testing +----------------------- + +Pull requests for fixing bugs are welcome. Proposed new features are +going to be meticulously reviewed -- taking into account backward compatibility, +potential side effects, and future extensibility -- before deciding on +acceptance or rejection. + +If you make a pull request that includes changes to the parser please add +tests for what is being changed to [MDTest][] and make a pull request there +too. + + [MDTest]: https://github.com/michelf/mdtest/ + + +Donations +--------- + +If you wish to make a donation that will help me devote more time to +PHP Markdown, please visit [michelf.ca/donate] or send Bitcoin to +[1HiuX34czvVPPdhXbUAsAu7pZcesniDCGH]. + + [michelf.ca/donate]: https://michelf.ca/donate/#!Thanks%20for%20PHP%20Markdown + [1HiuX34czvVPPdhXbUAsAu7pZcesniDCGH]: bitcoin:1HiuX34czvVPPdhXbUAsAu7pZcesniDCGH + + +Version History +--------------- + +PHP Markdown Lib 1.7.0 (29 Oct 2016) + +* Added a `hard_wrap` configuration variable to make all newline characters + in the text become `
    ` tags in the HTML output. By default, according + to the standard Markdown syntax these newlines are ignored unless they a + preceded by two spaces. Thanks to Jonathan Cohlmeyer for the implementation. + +* Improved the parsing of list items to fix problematic cases that came to + light with the addition of `hard_wrap`. This should have no effect on the + output except span-level list items that ended with two spaces (and thus + ended with a line break). + +* Added a `code_span_content_func` configuration variable which takes a + function that will convert the content of the code span to HTML. This can + be useful to implement syntax highlighting. Although contrary to its + code block equivalent, there is no syntax for specifying a language. + Credits to styxit for the implementation. + +* Fixed a Markdwon Extra issue where two-space-at-end-of-line hard breaks + wouldn't work inside of HTML block elements such as `

    ` + where the element expects only span-level content. + +* In the parser code, switched to PHPDoc comment format. Thanks to + Robbie Averill for the help. + + +PHP Markdown Lib 1.6.0 (23 Dec 2015) + +Note: this version was incorrectly released as 1.5.1 on Dec 22, a number +that contradicted the versioning policy. + +* For fenced code blocks in Markdown Extra, can now set a class name for the + code block's language before the special attribute block. Previously, this + class name was only allowed in the absence of the special attribute block. + +* Added a `code_block_content_func` configuration variable which takes a + function that will convert the content of the code block to HTML. This is + most useful for syntax highlighting. For fenced code blocks in Markdown + Extra, the function has access to the language class name (the one outside + of the special attribute block). Credits to Mario Konrad for providing the + implementation. + +* The curled arrow character for the backlink in footnotes is now followed + by a Unicode variant selector to prevent it from being displayed in emoji + form on iOS. + + Note that in older browsers the variant selector is often interpreted as a + separate character, making it visible after the arrow. So there is now a + also a `fn_backlink_html` configuration variable that can be used to set + the link text to something else. Credits to Dana for providing the + implementation. + +* Fixed an issue in MarkdownExtra where long header lines followed by a + special attribute block would hit the backtrack limit an cause an empty + string to be returned. + + +PHP Markdown Lib 1.5.0 (1 Mar 2015) + +* Added the ability start ordered lists with a number different from 1 and + and have that reflected in the HTML output. This can be enabled with + the `enhanced_ordered_lists` configuration variable for the Markdown + parser; it is enabled by default for Markdown Extra. + Credits to Matt Gorle for providing the implementation. + +* Added the ability to insert custom HTML attributes with simple values + everywhere an extra attribute block is allowed (links, images, headers). + The value must be unquoted, cannot contains spaces and is limited to + alphanumeric ASCII characters. + Credits to Peter Droogmans for providing the implementation. + +* Added a `header_id_func` configuration variable which takes a function + that can generate an `id` attribute value from the header text. + Credits to Evert Pot for providing the implementation. + +* Added a `url_filter_func` configuration variable which takes a function + that can rewrite any link or image URL to something different. + + +PHP Markdown Lib 1.4.1 (4 May 2014) + +* The HTML block parser will now treat `

    ` as a block-level element + (as it should) and no longer wrap it in `

    ` or parse it's content with + the as Markdown syntax (although with Extra you can use `markdown="1"` + if you wish to use the Markdown syntax inside it). + +* The content of `'; + $html = str_replace('>'.$m[1][$i].'', $sub, $html); + } + } + + $html = preg_replace('//i', '', $html); + $html = preg_replace('/<\!\-\-.*?\-\->/s', ' ', $html); + + $match = 0; // no match for instance + $CSSext = []; + + // CSS inside external files + $regexp = '/]*rel=["\']stylesheet["\'][^>]*href=["\']([^>"\']*)["\'].*?>/si'; + $x = preg_match_all($regexp, $html, $cxt); + if ($x) { + $match += $x; + $CSSext = $cxt[1]; + } + $regexp = '/]*href=["\']([^>"\']*)["\'][^>]*?rel=["\']stylesheet["\'].*?>/si'; + $x = preg_match_all($regexp, $html, $cxt); + if ($x) { + $match += $x; + $CSSext = array_merge($CSSext, $cxt[1]); + } + + // look for @import stylesheets + // $regexp = '/@import url\([\'\"]{0,1}([^\)]*?\.css)[\'\"]{0,1}\)/si'; + // $regexp = '/@import url\([\'\"]{0,1}([^\)]*?\.css(\?\S+)?)[\'\"]{0,1}\)/si'; + $regexp = '/@import url\([\'\"]{0,1}(\S*?\.css(\?[^\s\'\"]+)?)[\'\"]{0,1}\)\;?/si'; + $x = preg_match_all($regexp, $html, $cxt); + if ($x) { + $match += $x; + $CSSext = array_merge($CSSext, $cxt[1]); + } + + // look for @import without the url() + // $regexp = '/@import [\'\"]{0,1}([^;]*?\.css)[\'\"]{0,1}/si'; + // $regexp = '/@import [\'\"]{0,1}([^;]*?\.css(\?\S+)?)[\'\"]{0,1}/si'; + $regexp = '/@import (?!url)[\'\"]{0,1}(\S*?\.css(\?[^\s\'\"]+)?)[\'\"]{0,1}\;?/si'; + $x = preg_match_all($regexp, $html, $cxt); + if ($x) { + $match += $x; + $CSSext = array_merge($CSSext, $cxt[1]); + } + + $ind = 0; + $CSSstr = ''; + + if (!is_array($this->cascadeCSS)) { + $this->cascadeCSS = []; + } + + while ($match) { + + $path = $CSSext[$ind]; + + $path = htmlspecialchars_decode($path); // mPDF 6 + + $this->mpdf->GetFullPath($path); + + $CSSextblock = $this->getFileContents($path); + if ($CSSextblock) { + // look for embedded @import stylesheets in other stylesheets + // and fix url paths (including background-images) relative to stylesheet + // $regexpem = '/@import url\([\'\"]{0,1}(.*?\.css)[\'\"]{0,1}\)/si'; + $regexpem = '/@import url\([\'\"]{0,1}(.*?\.css(\?\S+)?)[\'\"]{0,1}\)/si'; + $xem = preg_match_all($regexpem, $CSSextblock, $cxtem); + $cssBasePath = preg_replace('/\/[^\/]*$/', '', $path) . '/'; + if ($xem) { + foreach ($cxtem[1] as $cxtembedded) { + // path is relative to original stylesheet!! + $this->mpdf->GetFullPath($cxtembedded, $cssBasePath); + $match++; + $CSSext[] = $cxtembedded; + } + } + $regexpem = '/(background[^;]*url\s*\(\s*[\'\"]{0,1})([^\)\'\"]*)([\'\"]{0,1}\s*\))/si'; + $xem = preg_match_all($regexpem, $CSSextblock, $cxtem); + if ($xem) { + $count_cxtem = count($cxtem[0]); + for ($i = 0; $i < $count_cxtem; $i++) { + // path is relative to original stylesheet!! + $embedded = $cxtem[2][$i]; + if (!preg_match('/^data:image/i', $embedded)) { // mPDF 5.5.13 + $this->mpdf->GetFullPath($embedded, $cssBasePath); + $CSSextblock = str_replace($cxtem[0][$i], ($cxtem[1][$i] . $embedded . $cxtem[3][$i]), $CSSextblock); + } + } + } + $CSSstr .= ' ' . $CSSextblock; + } + $match--; + $ind++; + } + + // CSS as '); + } else { + throw new \Mpdf\MpdfException(sprintf('Unable to read default CSS file "%s"', $this->defaultCssFile)); + } + + if ($default_font == '') { + if ($this->onlyCoreFonts) { + if (in_array(strtolower($this->defaultCSS['BODY']['FONT-FAMILY']), $this->mono_fonts)) { + $default_font = 'ccourier'; + } elseif (in_array(strtolower($this->defaultCSS['BODY']['FONT-FAMILY']), $this->sans_fonts)) { + $default_font = 'chelvetica'; + } else { + $default_font = 'ctimes'; + } + } else { + $default_font = $this->defaultCSS['BODY']['FONT-FAMILY']; + } + } + if (!$default_font_size) { + $mmsize = $this->sizeConverter->convert($this->defaultCSS['BODY']['FONT-SIZE']); + $default_font_size = $mmsize * (Mpdf::SCALE); + } + + if ($default_font) { + $this->SetDefaultFont($default_font); + } + if ($default_font_size) { + $this->SetDefaultFontSize($default_font_size); + } + + $this->SetLineHeight(); // lineheight is in mm + + $this->SetFColor($this->colorConverter->convert(255, $this->PDFAXwarnings)); + $this->HREF = ''; + $this->oldy = -1; + $this->B = 0; + $this->I = 0; + + // mPDF 6 Lists + $this->listlvl = 0; + $this->listtype = []; + $this->listitem = []; + $this->listcounter = []; + + $this->tdbegin = false; + $this->table = []; + $this->cell = []; + $this->col = -1; + $this->row = -1; + $this->cellBorderBuffer = []; + + $this->divbegin = false; + // mPDF 6 + $this->cellTextAlign = ''; + $this->cellLineHeight = ''; + $this->cellLineStackingStrategy = ''; + $this->cellLineStackingShift = ''; + + $this->divwidth = 0; + $this->divheight = 0; + $this->spanbgcolor = false; + $this->spanborder = false; + $this->spanborddet = []; + + $this->blockjustfinished = false; + $this->ignorefollowingspaces = true; // in order to eliminate exceeding left-side spaces + $this->dash_on = false; + $this->dotted_on = false; + $this->textshadow = ''; + + $this->currentfontfamily = ''; + $this->currentfontsize = ''; + $this->currentfontstyle = ''; + $this->colorarray = ''; // mPDF 6 + $this->spanbgcolorarray = ''; // mPDF 6 + $this->textbuffer = []; + $this->internallink = []; + $this->basepath = ""; + + $this->SetBasePath(''); + + $this->textparam = []; + + $this->specialcontent = ''; + $this->selectoption = []; + } + + public function cleanup() + { + mb_internal_encoding($this->originalMbEnc); + @mb_regex_encoding($this->originalMbRegexEnc); + } + + /** + * @param \Psr\Log\LoggerInterface + * + * @return \Mpdf\Mpdf + */ + public function setLogger(LoggerInterface $logger) + { + $this->logger = $logger; + + foreach ($this->services as $name) { + if ($this->$name && $this->$name instanceof \Psr\Log\LoggerAwareInterface) { + $this->$name->setLogger($logger); + } + } + + return $this; + } + + private function initConfig(array $config) + { + $configObject = new ConfigVariables(); + $defaults = $configObject->getDefaults(); + $config = array_intersect_key($config + $defaults, $defaults); + + foreach ($config as $var => $val) { + $this->{$var} = $val; + } + + return $config; + } + + private function initConstructorParams(array $config) + { + $constructor = [ + 'mode' => '', + 'format' => 'A4', + 'default_font_size' => 0, + 'default_font' => '', + 'margin_left' => 15, + 'margin_right' => 15, + 'margin_top' => 16, + 'margin_bottom' => 16, + 'margin_header' => 9, + 'margin_footer' => 9, + 'orientation' => 'P', + ]; + + foreach ($constructor as $key => $val) { + if (isset($config[$key])) { + $constructor[$key] = $config[$key]; + } + } + + return array_values($constructor); + } + + private function initFontConfig(array $config) + { + $configObject = new FontVariables(); + $defaults = $configObject->getDefaults(); + $config = array_intersect_key($config + $defaults, $defaults); + foreach ($config as $var => $val) { + $this->{$var} = $val; + } + + return $config; + } + + function _setPageSize($format, &$orientation) + { + if (is_string($format)) { + + if (empty($format)) { + $format = 'A4'; + } + + // e.g. A4-L = A4 landscape, A4-P = A4 portrait + if (preg_match('/([0-9a-zA-Z]*)-([P,L])/i', $format, $m)) { + $format = $m[1]; + $orientation = $m[2]; + } elseif (empty($orientation)) { + $orientation = 'P'; + } + + $format = PageFormat::getSizeFromName($format); + + $this->fwPt = $format[0]; + $this->fhPt = $format[1]; + + } else { + + if (!$format[0] || !$format[1]) { + throw new \Mpdf\MpdfException('Invalid page format: ' . $format[0] . ' ' . $format[1]); + } + + $this->fwPt = $format[0] * Mpdf::SCALE; + $this->fhPt = $format[1] * Mpdf::SCALE; + } + + $this->fw = $this->fwPt / Mpdf::SCALE; + $this->fh = $this->fhPt / Mpdf::SCALE; + + // Page orientation + $orientation = strtolower($orientation); + if ($orientation === 'p' || $orientation == 'portrait') { + $orientation = 'P'; + $this->wPt = $this->fwPt; + $this->hPt = $this->fhPt; + } elseif ($orientation === 'l' || $orientation == 'landscape') { + $orientation = 'L'; + $this->wPt = $this->fhPt; + $this->hPt = $this->fwPt; + } else { + throw new \Mpdf\MpdfException('Incorrect orientation: ' . $orientation); + } + + $this->CurOrientation = $orientation; + + $this->w = $this->wPt / Mpdf::SCALE; + $this->h = $this->hPt / Mpdf::SCALE; + } + + function RestrictUnicodeFonts($res) + { + // $res = array of (Unicode) fonts to restrict to: e.g. norasi|norasiB - language specific + if (count($res)) { // Leave full list of available fonts if passed blank array + $this->available_unifonts = $res; + } else { + $this->available_unifonts = $this->default_available_fonts; + } + if (count($this->available_unifonts) == 0) { + $this->available_unifonts[] = $this->default_available_fonts[0]; + } + $this->available_unifonts = array_values($this->available_unifonts); + } + + function setMBencoding($enc) + { + if ($this->mb_enc != $enc) { + $this->mb_enc = $enc; + mb_internal_encoding($this->mb_enc); + } + } + + function SetMargins($left, $right, $top) + { + // Set left, top and right margins + $this->lMargin = $left; + $this->rMargin = $right; + $this->tMargin = $top; + } + + function ResetMargins() + { + // ReSet left, top margins + if (($this->forcePortraitHeaders || $this->forcePortraitMargins) && $this->DefOrientation == 'P' && $this->CurOrientation == 'L') { + if (($this->mirrorMargins) && (($this->page) % 2 == 0)) { // EVEN + $this->tMargin = $this->orig_rMargin; + $this->bMargin = $this->orig_lMargin; + } else { // ODD // OR NOT MIRRORING MARGINS/FOOTERS + $this->tMargin = $this->orig_lMargin; + $this->bMargin = $this->orig_rMargin; + } + $this->lMargin = $this->DeflMargin; + $this->rMargin = $this->DefrMargin; + $this->MarginCorrection = 0; + $this->PageBreakTrigger = $this->h - $this->bMargin; + } elseif (($this->mirrorMargins) && (($this->page) % 2 == 0)) { // EVEN + $this->lMargin = $this->DefrMargin; + $this->rMargin = $this->DeflMargin; + $this->MarginCorrection = $this->DefrMargin - $this->DeflMargin; + } else { // ODD // OR NOT MIRRORING MARGINS/FOOTERS + $this->lMargin = $this->DeflMargin; + $this->rMargin = $this->DefrMargin; + if ($this->mirrorMargins) { + $this->MarginCorrection = $this->DeflMargin - $this->DefrMargin; + } + } + $this->x = $this->lMargin; + } + + function SetLeftMargin($margin) + { + // Set left margin + $this->lMargin = $margin; + if ($this->page > 0 and $this->x < $margin) { + $this->x = $margin; + } + } + + function SetTopMargin($margin) + { + // Set top margin + $this->tMargin = $margin; + } + + function SetRightMargin($margin) + { + // Set right margin + $this->rMargin = $margin; + } + + function SetAutoPageBreak($auto, $margin = 0) + { + // Set auto page break mode and triggering margin + $this->autoPageBreak = $auto; + $this->bMargin = $margin; + $this->PageBreakTrigger = $this->h - $margin; + } + + function SetDisplayMode($zoom, $layout = 'continuous') + { + $allowedZoomModes = ['fullpage', 'fullwidth', 'real', 'default', 'none']; + + if (in_array($zoom, $allowedZoomModes, true) || is_numeric($zoom)) { + $this->ZoomMode = $zoom; + } else { + throw new \Mpdf\MpdfException('Incorrect zoom display mode: ' . $zoom); + } + + $allowedLayoutModes = ['single', 'continuous', 'two', 'twoleft', 'tworight', 'default']; + + if (in_array($layout, $allowedLayoutModes, true)) { + $this->LayoutMode = $layout; + } else { + throw new \Mpdf\MpdfException('Incorrect layout display mode: ' . $layout); + } + } + + function SetCompression($compress) + { + // Set page compression + if (function_exists('gzcompress')) { + $this->compress = $compress; + } else { + $this->compress = false; + } + } + + function SetTitle($title) + { + // Title of document // Arrives as UTF-8 + $this->title = $title; + } + + function SetSubject($subject) + { + // Subject of document + $this->subject = $subject; + } + + function SetAuthor($author) + { + // Author of document + $this->author = $author; + } + + function SetKeywords($keywords) + { + // Keywords of document + $this->keywords = $keywords; + } + + function SetCreator($creator) + { + // Creator of document + $this->creator = $creator; + } + + function AddCustomProperty($key, $value) + { + $this->customProperties[$key] = $value; + } + + /** + * Set one or multiple associated file ("/AF" as required by PDF/A-3) + * + * param $files is an array of hash containing: + * path: file path on FS + * content: file content + * name: file name (not necessarily the same as the file on FS) + * mime (optional): file mime type (will show up as /Subtype in the PDF) + * description (optional): file description + * AFRelationship (optional): PDF/A-3 AFRelationship (e.g. "Alternative") + * + * e.g. to associate 1 file: + * [[ + * 'path' => 'tmp/1234.xml', + * 'content' => 'file content', + * 'name' => 'public_name.xml', + * 'mime' => 'text/xml', + * 'description' => 'foo', + * 'AFRelationship' => 'Alternative', + * ]] + * + * @param mixed[] $files Array of arrays of associated files. See above + */ + function SetAssociatedFiles(array $files) + { + $this->associatedFiles = $files; + } + + function SetAdditionalXmpRdf($s) + { + $this->additionalXmpRdf = $s; + } + + function SetAnchor2Bookmark($x) + { + $this->anchor2Bookmark = $x; + } + + public function AliasNbPages($alias = '{nb}') + { + // Define an alias for total number of pages + $this->aliasNbPg = $alias; + } + + public function AliasNbPageGroups($alias = '{nbpg}') + { + // Define an alias for total number of pages in a group + $this->aliasNbPgGp = $alias; + } + + function SetAlpha($alpha, $bm = 'Normal', $return = false, $mode = 'B') + { + // alpha: real value from 0 (transparent) to 1 (opaque) + // bm: blend mode, one of the following: + // Normal, Multiply, Screen, Overlay, Darken, Lighten, ColorDodge, ColorBurn, + // HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity + // set alpha for stroking (CA) and non-stroking (ca) operations + // mode determines F (fill) S (stroke) B (both) + if (($this->PDFA || $this->PDFX) && $alpha != 1) { + if (($this->PDFA && !$this->PDFAauto) || ($this->PDFX && !$this->PDFXauto)) { + $this->PDFAXwarnings[] = "Image opacity must be 100% (Opacity changed to 100%)"; + } + $alpha = 1; + } + $a = ['BM' => '/' . $bm]; + if ($mode == 'F' || $mode == 'B') { + $a['ca'] = $alpha; // mPDF 5.7.2 + } + if ($mode == 'S' || $mode == 'B') { + $a['CA'] = $alpha; // mPDF 5.7.2 + } + $gs = $this->AddExtGState($a); + if ($return) { + return sprintf('/GS%d gs', $gs); + } else { + $this->writer->write(sprintf('/GS%d gs', $gs)); + } + } + + function AddExtGState($parms) + { + $n = count($this->extgstates); + // check if graphics state already exists + for ($i = 1; $i <= $n; $i++) { + if (count($this->extgstates[$i]['parms']) == count($parms)) { + $same = true; + foreach ($this->extgstates[$i]['parms'] as $k => $v) { + if (!isset($parms[$k]) || $parms[$k] != $v) { + $same = false; + break; + } + } + if ($same) { + return $i; + } + } + } + $n++; + $this->extgstates[$n]['parms'] = $parms; + return $n; + } + + function SetVisibility($v) + { + if (($this->PDFA || $this->PDFX) && $this->visibility != 'visible') { + $this->PDFAXwarnings[] = "Cannot set visibility to anything other than full when using PDFA or PDFX"; + return ''; + } elseif (!$this->PDFA && !$this->PDFX) { + $this->pdf_version = '1.5'; + } + if ($this->visibility != 'visible') { + $this->writer->write('EMC'); + $this->hasOC = intval($this->hasOC); + } + if ($v == 'printonly') { + $this->writer->write('/OC /OC1 BDC'); + $this->hasOC = ($this->hasOC | 1); + } elseif ($v == 'screenonly') { + $this->writer->write('/OC /OC2 BDC'); + $this->hasOC = ($this->hasOC | 2); + } elseif ($v == 'hidden') { + $this->writer->write('/OC /OC3 BDC'); + $this->hasOC = ($this->hasOC | 4); + } elseif ($v != 'visible') { + throw new \Mpdf\MpdfException('Incorrect visibility: ' . $v); + } + $this->visibility = $v; + } + + function Open() + { + // Begin document + if ($this->state == 0) { + // Was is function _begindoc() + // Start document + $this->state = 1; + $this->writer->write('%PDF-' . $this->pdf_version); + $this->writer->write('%' . chr(226) . chr(227) . chr(207) . chr(211)); // 4 chars > 128 to show binary file + } + } + + function Close() + { + // @log Closing last page + + // Terminate document + if ($this->state == 3) { + return; + } + if ($this->page == 0) { + $this->AddPage($this->CurOrientation); + } + if (count($this->cellBorderBuffer)) { + $this->printcellbuffer(); + } // *TABLES* + if ($this->tablebuffer) { + $this->printtablebuffer(); + } // *TABLES* + /* -- COLUMNS -- */ + + if ($this->ColActive) { + $this->SetColumns(0); + $this->ColActive = 0; + if (count($this->columnbuffer)) { + $this->printcolumnbuffer(); + } + } + /* -- END COLUMNS -- */ + + // BODY Backgrounds + $s = ''; + + $s .= $this->PrintBodyBackgrounds(); + $s .= $this->PrintPageBackgrounds(); + + $this->pages[$this->page] = preg_replace( + '/(___BACKGROUND___PATTERNS' . $this->uniqstr . ')/', + "\n" . $s . "\n" . '\\1', + $this->pages[$this->page] + ); + + $this->pageBackgrounds = []; + + if ($this->visibility != 'visible') { + $this->SetVisibility('visible'); + } + + $this->EndLayer(); + + if (!$this->tableOfContents->TOCmark) { // Page footer + $this->InFooter = true; + $this->Footer(); + $this->InFooter = false; + } + + if ($this->tableOfContents->TOCmark || count($this->tableOfContents->m_TOC)) { + $this->tableOfContents->insertTOC(); + } + + // *TOC* + // Close page + $this->_endpage(); + + // Close document + $this->_enddoc(); + } + + /* -- BACKGROUNDS -- */ + + function _resizeBackgroundImage($imw, $imh, $cw, $ch, $resize, $repx, $repy, $pba = [], $size = []) + { + // pba is background positioning area (from CSS background-origin) may not always be set [x,y,w,h] + // size is from CSS3 background-size - takes precendence over old resize + // $w - absolute length or % or auto or cover | contain + // $h - absolute length or % or auto or cover | contain + if (isset($pba['w'])) { + $cw = $pba['w']; + } + if (isset($pba['h'])) { + $ch = $pba['h']; + } + + $cw = $cw * Mpdf::SCALE; + $ch = $ch * Mpdf::SCALE; + if (empty($size) && !$resize) { + return [$imw, $imh, $repx, $repy]; + } + + if (isset($size['w']) && $size['w']) { + if ($size['w'] == 'contain') { + // Scale the image, while preserving its intrinsic aspect ratio (if any), + // to the largest size such that both its width and its height can fit inside the background positioning area. + // Same as resize==3 + $h = $imh * $cw / $imw; + $w = $cw; + if ($h > $ch) { + $w = $w * $ch / $h; + $h = $ch; + } + } elseif ($size['w'] == 'cover') { + // Scale the image, while preserving its intrinsic aspect ratio (if any), + // to the smallest size such that both its width and its height can completely cover the background positioning area. + $h = $imh * $cw / $imw; + $w = $cw; + if ($h < $ch) { + $w = $w * $h / $ch; + $h = $ch; + } + } else { + if (stristr($size['w'], '%')) { + $size['w'] = (float) $size['w']; + $size['w'] /= 100; + $size['w'] = ($cw * $size['w']); + } + if (stristr($size['h'], '%')) { + $size['h'] = (float) $size['h']; + $size['h'] /= 100; + $size['h'] = ($ch * $size['h']); + } + if ($size['w'] == 'auto' && $size['h'] == 'auto') { + $w = $imw; + $h = $imh; + } elseif ($size['w'] == 'auto' && $size['h'] != 'auto') { + $w = $imw * $size['h'] / $imh; + $h = $size['h']; + } elseif ($size['w'] != 'auto' && $size['h'] == 'auto') { + $h = $imh * $size['w'] / $imw; + $w = $size['w']; + } else { + $w = $size['w']; + $h = $size['h']; + } + } + return [$w, $h, $repx, $repy]; + } elseif ($resize == 1 && $imw > $cw) { + $h = $imh * $cw / $imw; + return [$cw, $h, $repx, $repy]; + } elseif ($resize == 2 && $imh > $ch) { + $w = $imw * $ch / $imh; + return [$w, $ch, $repx, $repy]; + } elseif ($resize == 3) { + $w = $imw; + $h = $imh; + if ($w > $cw) { + $h = $h * $cw / $w; + $w = $cw; + } + if ($h > $ch) { + $w = $w * $ch / $h; + $h = $ch; + } + return [$w, $h, $repx, $repy]; + } elseif ($resize == 4) { + $h = $imh * $cw / $imw; + return [$cw, $h, $repx, $repy]; + } elseif ($resize == 5) { + $w = $imw * $ch / $imh; + return [$w, $ch, $repx, $repy]; + } elseif ($resize == 6) { + return [$cw, $ch, $repx, $repy]; + } + return [$imw, $imh, $repx, $repy]; + } + + function SetBackground(&$properties, &$maxwidth) + { + if (isset($properties['BACKGROUND-ORIGIN']) && ($properties['BACKGROUND-ORIGIN'] == 'border-box' || $properties['BACKGROUND-ORIGIN'] == 'content-box')) { + $origin = $properties['BACKGROUND-ORIGIN']; + } else { + $origin = 'padding-box'; + } + + if (isset($properties['BACKGROUND-SIZE'])) { + if (stristr($properties['BACKGROUND-SIZE'], 'contain')) { + $bsw = $bsh = 'contain'; + } elseif (stristr($properties['BACKGROUND-SIZE'], 'cover')) { + $bsw = $bsh = 'cover'; + } else { + $bsw = $bsh = 'auto'; + $sz = preg_split('/\s+/', trim($properties['BACKGROUND-SIZE'])); + if (count($sz) == 2) { + $bsw = $sz[0]; + $bsh = $sz[1]; + } else { + $bsw = $sz[0]; + } + if (!stristr($bsw, '%') && !stristr($bsw, 'auto')) { + $bsw = $this->sizeConverter->convert($bsw, $maxwidth, $this->FontSize); + } + if (!stristr($bsh, '%') && !stristr($bsh, 'auto')) { + $bsh = $this->sizeConverter->convert($bsh, $maxwidth, $this->FontSize); + } + } + $size = ['w' => $bsw, 'h' => $bsh]; + } else { + $size = false; + } // mPDF 6 + if (preg_match('/(-moz-)*(repeating-)*(linear|radial)-gradient/', $properties['BACKGROUND-IMAGE'])) { + return ['gradient' => $properties['BACKGROUND-IMAGE'], 'origin' => $origin, 'size' => $size]; + } else { + $file = $properties['BACKGROUND-IMAGE']; + $sizesarray = $this->Image($file, 0, 0, 0, 0, '', '', false, false, false, false, true); + if (isset($sizesarray['IMAGE_ID'])) { + $image_id = $sizesarray['IMAGE_ID']; + $orig_w = $sizesarray['WIDTH'] * Mpdf::SCALE; // in user units i.e. mm + $orig_h = $sizesarray['HEIGHT'] * Mpdf::SCALE; // (using $this->img_dpi) + if (isset($properties['BACKGROUND-IMAGE-RESOLUTION'])) { + if (preg_match('/from-image/i', $properties['BACKGROUND-IMAGE-RESOLUTION']) && isset($sizesarray['set-dpi']) && $sizesarray['set-dpi'] > 0) { + $orig_w *= $this->img_dpi / $sizesarray['set-dpi']; + $orig_h *= $this->img_dpi / $sizesarray['set-dpi']; + } elseif (preg_match('/(\d+)dpi/i', $properties['BACKGROUND-IMAGE-RESOLUTION'], $m)) { + $dpi = $m[1]; + if ($dpi > 0) { + $orig_w *= $this->img_dpi / $dpi; + $orig_h *= $this->img_dpi / $dpi; + } + } + } + $x_repeat = true; + $y_repeat = true; + if (isset($properties['BACKGROUND-REPEAT'])) { + if ($properties['BACKGROUND-REPEAT'] == 'no-repeat' || $properties['BACKGROUND-REPEAT'] == 'repeat-x') { + $y_repeat = false; + } + if ($properties['BACKGROUND-REPEAT'] == 'no-repeat' || $properties['BACKGROUND-REPEAT'] == 'repeat-y') { + $x_repeat = false; + } + } + $x_pos = 0; + $y_pos = 0; + if (isset($properties['BACKGROUND-POSITION'])) { + $ppos = preg_split('/\s+/', $properties['BACKGROUND-POSITION']); + $x_pos = $ppos[0]; + $y_pos = $ppos[1]; + if (!stristr($x_pos, '%')) { + $x_pos = $this->sizeConverter->convert($x_pos, $maxwidth, $this->FontSize); + } + if (!stristr($y_pos, '%')) { + $y_pos = $this->sizeConverter->convert($y_pos, $maxwidth, $this->FontSize); + } + } + if (isset($properties['BACKGROUND-IMAGE-RESIZE'])) { + $resize = $properties['BACKGROUND-IMAGE-RESIZE']; + } else { + $resize = 0; + } + if (isset($properties['BACKGROUND-IMAGE-OPACITY'])) { + $opacity = $properties['BACKGROUND-IMAGE-OPACITY']; + } else { + $opacity = 1; + } + return ['image_id' => $image_id, 'orig_w' => $orig_w, 'orig_h' => $orig_h, 'x_pos' => $x_pos, 'y_pos' => $y_pos, 'x_repeat' => $x_repeat, 'y_repeat' => $y_repeat, 'resize' => $resize, 'opacity' => $opacity, 'itype' => $sizesarray['itype'], 'origin' => $origin, 'size' => $size]; + } + } + return false; + } + + /* -- END BACKGROUNDS -- */ + + function PrintBodyBackgrounds() + { + $s = ''; + $clx = 0; + $cly = 0; + $clw = $this->w; + $clh = $this->h; + // If using bleed and trim margins in paged media + if ($this->pageDim[$this->page]['outer_width_LR'] || $this->pageDim[$this->page]['outer_width_TB']) { + $clx = $this->pageDim[$this->page]['outer_width_LR'] - $this->pageDim[$this->page]['bleedMargin']; + $cly = $this->pageDim[$this->page]['outer_width_TB'] - $this->pageDim[$this->page]['bleedMargin']; + $clw = $this->w - 2 * $clx; + $clh = $this->h - 2 * $cly; + } + + if ($this->bodyBackgroundColor) { + $s .= 'q ' . $this->SetFColor($this->bodyBackgroundColor, true) . "\n"; + if ($this->bodyBackgroundColor[0] == 5) { // RGBa + $s .= $this->SetAlpha(ord($this->bodyBackgroundColor[4]) / 100, 'Normal', true, 'F') . "\n"; + } elseif ($this->bodyBackgroundColor[0] == 6) { // CMYKa + $s .= $this->SetAlpha(ord($this->bodyBackgroundColor[5]) / 100, 'Normal', true, 'F') . "\n"; + } + $s .= sprintf('%.3F %.3F %.3F %.3F re f Q', ($clx * Mpdf::SCALE), ($cly * Mpdf::SCALE), $clw * Mpdf::SCALE, $clh * Mpdf::SCALE) . "\n"; + } + + /* -- BACKGROUNDS -- */ + if ($this->bodyBackgroundGradient) { + $g = $this->gradient->parseBackgroundGradient($this->bodyBackgroundGradient); + if ($g) { + $s .= $this->gradient->Gradient($clx, $cly, $clw, $clh, (isset($g['gradtype']) ? $g['gradtype'] : null), $g['stops'], $g['colorspace'], $g['coords'], $g['extend'], true); + } + } + if ($this->bodyBackgroundImage) { + if (isset($this->bodyBackgroundImage['gradient']) && $this->bodyBackgroundImage['gradient'] && preg_match('/(-moz-)*(repeating-)*(linear|radial)-gradient/', $this->bodyBackgroundImage['gradient'])) { + $g = $this->gradient->parseMozGradient($this->bodyBackgroundImage['gradient']); + if ($g) { + $s .= $this->gradient->Gradient($clx, $cly, $clw, $clh, $g['type'], $g['stops'], $g['colorspace'], $g['coords'], $g['extend'], true); + } + } elseif ($this->bodyBackgroundImage['image_id']) { // Background pattern + $n = count($this->patterns) + 1; + // If using resize, uses TrimBox (not including the bleed) + list($orig_w, $orig_h, $x_repeat, $y_repeat) = $this->_resizeBackgroundImage($this->bodyBackgroundImage['orig_w'], $this->bodyBackgroundImage['orig_h'], $clw, $clh, $this->bodyBackgroundImage['resize'], $this->bodyBackgroundImage['x_repeat'], $this->bodyBackgroundImage['y_repeat']); + + $this->patterns[$n] = ['x' => $clx, 'y' => $cly, 'w' => $clw, 'h' => $clh, 'pgh' => $this->h, 'image_id' => $this->bodyBackgroundImage['image_id'], 'orig_w' => $orig_w, 'orig_h' => $orig_h, 'x_pos' => $this->bodyBackgroundImage['x_pos'], 'y_pos' => $this->bodyBackgroundImage['y_pos'], 'x_repeat' => $x_repeat, 'y_repeat' => $y_repeat, 'itype' => $this->bodyBackgroundImage['itype']]; + if (($this->bodyBackgroundImage['opacity'] > 0 || $this->bodyBackgroundImage['opacity'] === '0') && $this->bodyBackgroundImage['opacity'] < 1) { + $opac = $this->SetAlpha($this->bodyBackgroundImage['opacity'], 'Normal', true); + } else { + $opac = ''; + } + $s .= sprintf('q /Pattern cs /P%d scn %s %.3F %.3F %.3F %.3F re f Q', $n, $opac, ($clx * Mpdf::SCALE), ($cly * Mpdf::SCALE), $clw * Mpdf::SCALE, $clh * Mpdf::SCALE) . "\n"; + } + } + /* -- END BACKGROUNDS -- */ + return $s; + } + + function _setClippingPath($clx, $cly, $clw, $clh) + { + $s = ' q 0 w '; // Line width=0 + $s .= sprintf('%.3F %.3F m ', ($clx) * Mpdf::SCALE, ($this->h - ($cly)) * Mpdf::SCALE); // start point TL before the arc + $s .= sprintf('%.3F %.3F l ', ($clx) * Mpdf::SCALE, ($this->h - ($cly + $clh)) * Mpdf::SCALE); // line to BL + $s .= sprintf('%.3F %.3F l ', ($clx + $clw) * Mpdf::SCALE, ($this->h - ($cly + $clh)) * Mpdf::SCALE); // line to BR + $s .= sprintf('%.3F %.3F l ', ($clx + $clw) * Mpdf::SCALE, ($this->h - ($cly)) * Mpdf::SCALE); // line to TR + $s .= sprintf('%.3F %.3F l ', ($clx) * Mpdf::SCALE, ($this->h - ($cly)) * Mpdf::SCALE); // line to TL + $s .= ' W n '; // Ends path no-op & Sets the clipping path + return $s; + } + + function PrintPageBackgrounds($adjustmenty = 0) + { + $s = ''; + + ksort($this->pageBackgrounds); + + foreach ($this->pageBackgrounds as $bl => $pbs) { + + foreach ($pbs as $pb) { + + if ((!isset($pb['image_id']) && !isset($pb['gradient'])) || isset($pb['shadowonly'])) { // Background colour or boxshadow + + if ($pb['z-index'] > 0) { + $this->current_layer = $pb['z-index']; + $s .= "\n" . '/OCBZ-index /ZI' . $pb['z-index'] . ' BDC' . "\n"; + } + + if ($pb['visibility'] != 'visible') { + if ($pb['visibility'] == 'printonly') { + $s .= '/OC /OC1 BDC' . "\n"; + } elseif ($pb['visibility'] == 'screenonly') { + $s .= '/OC /OC2 BDC' . "\n"; + } elseif ($pb['visibility'] == 'hidden') { + $s .= '/OC /OC3 BDC' . "\n"; + } + } + + // Box shadow + if (isset($pb['shadow']) && $pb['shadow']) { + $s .= $pb['shadow'] . "\n"; + } + + if (isset($pb['clippath']) && $pb['clippath']) { + $s .= $pb['clippath'] . "\n"; + } + + $s .= 'q ' . $this->SetFColor($pb['col'], true) . "\n"; + + if ($pb['col'] && $pb['col'][0] === '5') { // RGBa + $s .= $this->SetAlpha(ord($pb['col'][4]) / 100, 'Normal', true, 'F') . "\n"; + } elseif ($pb['col'] && $pb['col'][0] === '6') { // CMYKa + $s .= $this->SetAlpha(ord($pb['col'][5]) / 100, 'Normal', true, 'F') . "\n"; + } + + $s .= sprintf('%.3F %.3F %.3F %.3F re f Q', $pb['x'] * Mpdf::SCALE, ($this->h - $pb['y']) * Mpdf::SCALE, $pb['w'] * Mpdf::SCALE, -$pb['h'] * Mpdf::SCALE) . "\n"; + + if (isset($pb['clippath']) && $pb['clippath']) { + $s .= 'Q' . "\n"; + } + + if ($pb['visibility'] != 'visible') { + $s .= 'EMC' . "\n"; + } + + if ($pb['z-index'] > 0) { + $s .= "\n" . 'EMCBZ-index' . "\n"; + $this->current_layer = 0; + } + } + } + + /* -- BACKGROUNDS -- */ + foreach ($pbs as $pb) { + + if ((isset($pb['gradient']) && $pb['gradient']) || (isset($pb['image_id']) && $pb['image_id'])) { + + if ($pb['z-index'] > 0) { + $this->current_layer = $pb['z-index']; + $s .= "\n" . '/OCGZ-index /ZI' . $pb['z-index'] . ' BDC' . "\n"; + } + + if ($pb['visibility'] != 'visible') { + if ($pb['visibility'] == 'printonly') { + $s .= '/OC /OC1 BDC' . "\n"; + } elseif ($pb['visibility'] == 'screenonly') { + $s .= '/OC /OC2 BDC' . "\n"; + } elseif ($pb['visibility'] == 'hidden') { + $s .= '/OC /OC3 BDC' . "\n"; + } + } + + } + + if (isset($pb['gradient']) && $pb['gradient']) { + + if (isset($pb['clippath']) && $pb['clippath']) { + $s .= $pb['clippath'] . "\n"; + } + + $s .= $this->gradient->Gradient($pb['x'], $pb['y'], $pb['w'], $pb['h'], $pb['gradtype'], $pb['stops'], $pb['colorspace'], $pb['coords'], $pb['extend'], true); + + if (isset($pb['clippath']) && $pb['clippath']) { + $s .= 'Q' . "\n"; + } + + } elseif (isset($pb['image_id']) && $pb['image_id']) { // Background Image + + $pb['y'] -= $adjustmenty; + $pb['h'] += $adjustmenty; + $n = count($this->patterns) + 1; + + list($orig_w, $orig_h, $x_repeat, $y_repeat) = $this->_resizeBackgroundImage($pb['orig_w'], $pb['orig_h'], $pb['w'], $pb['h'], $pb['resize'], $pb['x_repeat'], $pb['y_repeat'], $pb['bpa'], $pb['size']); + + $this->patterns[$n] = ['x' => $pb['x'], 'y' => $pb['y'], 'w' => $pb['w'], 'h' => $pb['h'], 'pgh' => $this->h, 'image_id' => $pb['image_id'], 'orig_w' => $orig_w, 'orig_h' => $orig_h, 'x_pos' => $pb['x_pos'], 'y_pos' => $pb['y_pos'], 'x_repeat' => $x_repeat, 'y_repeat' => $y_repeat, 'itype' => $pb['itype'], 'bpa' => $pb['bpa']]; + + $x = $pb['x'] * Mpdf::SCALE; + $y = ($this->h - $pb['y']) * Mpdf::SCALE; + $w = $pb['w'] * Mpdf::SCALE; + $h = -$pb['h'] * Mpdf::SCALE; + + if (isset($pb['clippath']) && $pb['clippath']) { + $s .= $pb['clippath'] . "\n"; + } + + if ($this->writingHTMLfooter || $this->writingHTMLheader) { // Write each (tiles) image rather than use as a pattern + + $iw = $pb['orig_w'] / Mpdf::SCALE; + $ih = $pb['orig_h'] / Mpdf::SCALE; + + $w = $pb['w']; + $h = $pb['h']; + $x0 = $pb['x']; + $y0 = $pb['y']; + + if (isset($pb['bpa']) && $pb['bpa']) { + $w = $pb['bpa']['w']; + $h = $pb['bpa']['h']; + $x0 = $pb['bpa']['x']; + $y0 = $pb['bpa']['y']; + } + + if (isset($pb['size']['w']) && $pb['size']['w']) { + $size = $pb['size']; + + if ($size['w'] == 'contain') { + // Scale the image, while preserving its intrinsic aspect ratio (if any), to the largest + // size such that both its width and its height can fit inside the background positioning area. + // Same as resize==3 + $ih = $ih * $pb['bpa']['w'] / $iw; + $iw = $pb['bpa']['w']; + if ($ih > $pb['bpa']['h']) { + $iw = $iw * $pb['bpa']['h'] / $ih; + $ih = $pb['bpa']['h']; + } + } elseif ($size['w'] == 'cover') { + // Scale the image, while preserving its intrinsic aspect ratio (if any), to the smallest + // size such that both its width and its height can completely cover the background positioning area. + $ih = $ih * $pb['bpa']['w'] / $iw; + $iw = $pb['bpa']['w']; + if ($ih < $pb['bpa']['h']) { + $iw = $iw * $ih / $pb['bpa']['h']; + $ih = $pb['bpa']['h']; + } + } else { + + if (NumericString::containsPercentChar($size['w'])) { + $size['w'] = NumericString::removePercentChar($size['w']); + $size['w'] /= 100; + $size['w'] = ($pb['bpa']['w'] * $size['w']); + } + + if (NumericString::containsPercentChar($size['h'])) { + $size['h'] = NumericString::removePercentChar($size['h']); + $size['h'] /= 100; + $size['h'] = ($pb['bpa']['h'] * $size['h']); + } + + if ($size['w'] == 'auto' && $size['h'] == 'auto') { + $iw = $iw; + $ih = $ih; + } elseif ($size['w'] == 'auto' && $size['h'] != 'auto') { + $iw = $iw * $size['h'] / $ih; + $ih = $size['h']; + } elseif ($size['w'] != 'auto' && $size['h'] == 'auto') { + $ih = $ih * $size['w'] / $iw; + $iw = $size['w']; + } else { + $iw = $size['w']; + $ih = $size['h']; + } + } + } + + // Number to repeat + if ($pb['x_repeat']) { + $nx = ceil($pb['w'] / $iw) + 1; + } else { + $nx = 1; + } + + if ($pb['y_repeat']) { + $ny = ceil($pb['h'] / $ih) + 1; + } else { + $ny = 1; + } + + $x_pos = $pb['x_pos']; + if (stristr($x_pos, '%')) { + $x_pos = (float) $x_pos; + $x_pos /= 100; + $x_pos = ($pb['bpa']['w'] * $x_pos) - ($iw * $x_pos); + } + + $y_pos = $pb['y_pos']; + + if (stristr($y_pos, '%')) { + $y_pos = (float) $y_pos; + $y_pos /= 100; + $y_pos = ($pb['bpa']['h'] * $y_pos) - ($ih * $y_pos); + } + + if ($nx > 1) { + while ($x_pos > ($pb['x'] - $pb['bpa']['x'])) { + $x_pos -= $iw; + } + } + + if ($ny > 1) { + while ($y_pos > ($pb['y'] - $pb['bpa']['y'])) { + $y_pos -= $ih; + } + } + + for ($xi = 0; $xi < $nx; $xi++) { + for ($yi = 0; $yi < $ny; $yi++) { + $x = $x0 + $x_pos + ($iw * $xi); + $y = $y0 + $y_pos + ($ih * $yi); + if ($pb['opacity'] > 0 && $pb['opacity'] < 1) { + $opac = $this->SetAlpha($pb['opacity'], 'Normal', true); + } else { + $opac = ''; + } + $s .= sprintf("q %s %.3F 0 0 %.3F %.3F %.3F cm /I%d Do Q", $opac, $iw * Mpdf::SCALE, $ih * Mpdf::SCALE, $x * Mpdf::SCALE, ($this->h - ($y + $ih)) * Mpdf::SCALE, $pb['image_id']) . "\n"; + } + } + + } else { + if (($pb['opacity'] > 0 || $pb['opacity'] === '0') && $pb['opacity'] < 1) { + $opac = $this->SetAlpha($pb['opacity'], 'Normal', true); + } else { + $opac = ''; + } + $s .= sprintf('q /Pattern cs /P%d scn %s %.3F %.3F %.3F %.3F re f Q', $n, $opac, $x, $y, $w, $h) . "\n"; + } + + if (isset($pb['clippath']) && $pb['clippath']) { + $s .= 'Q' . "\n"; + } + } + + if ((isset($pb['gradient']) && $pb['gradient']) || (isset($pb['image_id']) && $pb['image_id'])) { + if ($pb['visibility'] != 'visible') { + $s .= 'EMC' . "\n"; + } + + if ($pb['z-index'] > 0) { + $s .= "\n" . 'EMCGZ-index' . "\n"; + $this->current_layer = 0; + } + } + } + /* -- END BACKGROUNDS -- */ + } + + return $s; + } + + function PrintTableBackgrounds($adjustmenty = 0) + { + $s = ''; + /* -- BACKGROUNDS -- */ + ksort($this->tableBackgrounds); + foreach ($this->tableBackgrounds as $bl => $pbs) { + foreach ($pbs as $pb) { + if ((!isset($pb['gradient']) || !$pb['gradient']) && (!isset($pb['image_id']) || !$pb['image_id'])) { + $s .= 'q ' . $this->SetFColor($pb['col'], true) . "\n"; + if ($pb['col'][0] == 5) { // RGBa + $s .= $this->SetAlpha(ord($pb['col'][4]) / 100, 'Normal', true, 'F') . "\n"; + } elseif ($pb['col'][0] == 6) { // CMYKa + $s .= $this->SetAlpha(ord($pb['col'][5]) / 100, 'Normal', true, 'F') . "\n"; + } + $s .= sprintf('%.3F %.3F %.3F %.3F re %s Q', $pb['x'] * Mpdf::SCALE, ($this->h - $pb['y']) * Mpdf::SCALE, $pb['w'] * Mpdf::SCALE, -$pb['h'] * Mpdf::SCALE, 'f') . "\n"; + } + if (isset($pb['gradient']) && $pb['gradient']) { + if (isset($pb['clippath']) && $pb['clippath']) { + $s .= $pb['clippath'] . "\n"; + } + $s .= $this->gradient->Gradient($pb['x'], $pb['y'], $pb['w'], $pb['h'], $pb['gradtype'], $pb['stops'], $pb['colorspace'], $pb['coords'], $pb['extend'], true); + if (isset($pb['clippath']) && $pb['clippath']) { + $s .= 'Q' . "\n"; + } + } + if (isset($pb['image_id']) && $pb['image_id']) { // Background pattern + $pb['y'] -= $adjustmenty; + $pb['h'] += $adjustmenty; + $n = count($this->patterns) + 1; + list($orig_w, $orig_h, $x_repeat, $y_repeat) = $this->_resizeBackgroundImage($pb['orig_w'], $pb['orig_h'], $pb['w'], $pb['h'], $pb['resize'], $pb['x_repeat'], $pb['y_repeat']); + $this->patterns[$n] = ['x' => $pb['x'], 'y' => $pb['y'], 'w' => $pb['w'], 'h' => $pb['h'], 'pgh' => $this->h, 'image_id' => $pb['image_id'], 'orig_w' => $orig_w, 'orig_h' => $orig_h, 'x_pos' => $pb['x_pos'], 'y_pos' => $pb['y_pos'], 'x_repeat' => $x_repeat, 'y_repeat' => $y_repeat, 'itype' => $pb['itype']]; + $x = $pb['x'] * Mpdf::SCALE; + $y = ($this->h - $pb['y']) * Mpdf::SCALE; + $w = $pb['w'] * Mpdf::SCALE; + $h = -$pb['h'] * Mpdf::SCALE; + + // mPDF 5.7.3 + if (($this->writingHTMLfooter || $this->writingHTMLheader) && (!isset($pb['clippath']) || $pb['clippath'] == '')) { + // Set clipping path + $pb['clippath'] = sprintf(' q 0 w %.3F %.3F m %.3F %.3F l %.3F %.3F l %.3F %.3F l %.3F %.3F l W n ', $x, $y, $x, $y + $h, $x + $w, $y + $h, $x + $w, $y, $x, $y); + } + + if (isset($pb['clippath']) && $pb['clippath']) { + $s .= $pb['clippath'] . "\n"; + } + + // mPDF 5.7.3 + if ($this->writingHTMLfooter || $this->writingHTMLheader) { // Write each (tiles) image rather than use as a pattern + $iw = $pb['orig_w'] / Mpdf::SCALE; + $ih = $pb['orig_h'] / Mpdf::SCALE; + + $w = $pb['w']; + $h = $pb['h']; + $x0 = $pb['x']; + $y0 = $pb['y']; + + if (isset($pb['bpa']) && $pb['bpa']) { + $w = $pb['bpa']['w']; + $h = $pb['bpa']['h']; + $x0 = $pb['bpa']['x']; + $y0 = $pb['bpa']['y']; + } // At present 'bpa' (background page area) is not set for tablebackgrounds - only pagebackgrounds + // For now, just set it as: + else { + $pb['bpa'] = ['x' => $x0, 'y' => $y0, 'w' => $w, 'h' => $h]; + } + + if (isset($pb['size']['w']) && $pb['size']['w']) { + $size = $pb['size']; + + if ($size['w'] == 'contain') { + // Scale the image, while preserving its intrinsic aspect ratio (if any), to the largest size such that both its width and its height can fit inside the background positioning area. + // Same as resize==3 + $ih = $ih * $pb['bpa']['w'] / $iw; + $iw = $pb['bpa']['w']; + if ($ih > $pb['bpa']['h']) { + $iw = $iw * $pb['bpa']['h'] / $ih; + $ih = $pb['bpa']['h']; + } + } elseif ($size['w'] == 'cover') { + // Scale the image, while preserving its intrinsic aspect ratio (if any), to the smallest size such that both its width and its height can completely cover the background positioning area. + $ih = $ih * $pb['bpa']['w'] / $iw; + $iw = $pb['bpa']['w']; + if ($ih < $pb['bpa']['h']) { + $iw = $iw * $ih / $pb['bpa']['h']; + $ih = $pb['bpa']['h']; + } + } else { + if (NumericString::containsPercentChar($size['w'])) { + $size['w'] = NumericString::removePercentChar($size['w']); + $size['w'] /= 100; + $size['w'] = ($pb['bpa']['w'] * $size['w']); + } + if (NumericString::containsPercentChar($size['h'])) { + $size['h'] = NumericString::removePercentChar($size['h']); + $size['h'] /= 100; + $size['h'] = ($pb['bpa']['h'] * $size['h']); + } + if ($size['w'] == 'auto' && $size['h'] == 'auto') { + $iw = $iw; + $ih = $ih; + } elseif ($size['w'] == 'auto' && $size['h'] != 'auto') { + $iw = $iw * $size['h'] / $ih; + $ih = $size['h']; + } elseif ($size['w'] != 'auto' && $size['h'] == 'auto') { + $ih = $ih * $size['w'] / $iw; + $iw = $size['w']; + } else { + $iw = $size['w']; + $ih = $size['h']; + } + } + } + + // Number to repeat + if (isset($pb['x_repeat']) && $pb['x_repeat']) { + $nx = ceil($pb['w'] / $iw) + 1; + } else { + $nx = 1; + } + if (isset($pb['y_repeat']) && $pb['y_repeat']) { + $ny = ceil($pb['h'] / $ih) + 1; + } else { + $ny = 1; + } + + $x_pos = $pb['x_pos']; + if (NumericString::containsPercentChar($x_pos)) { + $x_pos = NumericString::removePercentChar($x_pos); + $x_pos /= 100; + $x_pos = ($pb['bpa']['w'] * $x_pos) - ($iw * $x_pos); + } + $y_pos = $pb['y_pos']; + if (NumericString::containsPercentChar($y_pos)) { + $y_pos = NumericString::removePercentChar($y_pos); + $y_pos /= 100; + $y_pos = ($pb['bpa']['h'] * $y_pos) - ($ih * $y_pos); + } + if ($nx > 1) { + while ($x_pos > ($pb['x'] - $pb['bpa']['x'])) { + $x_pos -= $iw; + } + } + if ($ny > 1) { + while ($y_pos > ($pb['y'] - $pb['bpa']['y'])) { + $y_pos -= $ih; + } + } + for ($xi = 0; $xi < $nx; $xi++) { + for ($yi = 0; $yi < $ny; $yi++) { + $x = $x0 + $x_pos + ($iw * $xi); + $y = $y0 + $y_pos + ($ih * $yi); + if ($pb['opacity'] > 0 && $pb['opacity'] < 1) { + $opac = $this->SetAlpha($pb['opacity'], 'Normal', true); + } else { + $opac = ''; + } + $s .= sprintf("q %s %.3F 0 0 %.3F %.3F %.3F cm /I%d Do Q", $opac, $iw * Mpdf::SCALE, $ih * Mpdf::SCALE, $x * Mpdf::SCALE, ($this->h - ($y + $ih)) * Mpdf::SCALE, $pb['image_id']) . "\n"; + } + } + } else { + if (($pb['opacity'] > 0 || $pb['opacity'] === '0') && $pb['opacity'] < 1) { + $opac = $this->SetAlpha($pb['opacity'], 'Normal', true); + } else { + $opac = ''; + } + $s .= sprintf('q /Pattern cs /P%d scn %s %.3F %.3F %.3F %.3F re f Q', $n, $opac, $x, $y, $w, $h) . "\n"; + } + + if (isset($pb['clippath']) && $pb['clippath']) { + $s .= 'Q' . "\n"; + } + } + } + } + /* -- END BACKGROUNDS -- */ + return $s; + } + + function BeginLayer($id) + { + if ($this->current_layer > 0) { + $this->EndLayer(); + } + if ($id < 1) { + return false; + } + if (!isset($this->layers[$id])) { + $this->layers[$id] = ['name' => 'Layer ' . ($id)]; + if (($this->PDFA || $this->PDFX)) { + $this->PDFAXwarnings[] = "Cannot use layers when using PDFA or PDFX"; + return ''; + } elseif (!$this->PDFA && !$this->PDFX) { + $this->pdf_version = '1.5'; + } + } + $this->current_layer = $id; + $this->writer->write('/OCZ-index /ZI' . $id . ' BDC'); + + $this->pageoutput[$this->page] = []; + } + + function EndLayer() + { + if ($this->current_layer > 0) { + $this->writer->write('EMCZ-index'); + $this->current_layer = 0; + } + } + + function AddPageByArray($a) + { + if (!is_array($a)) { + $a = []; + } + + $orientation = (isset($a['orientation']) ? $a['orientation'] : ''); + $condition = (isset($a['condition']) ? $a['condition'] : (isset($a['type']) ? $a['type'] : '')); + $resetpagenum = (isset($a['resetpagenum']) ? $a['resetpagenum'] : ''); + $pagenumstyle = (isset($a['pagenumstyle']) ? $a['pagenumstyle'] : ''); + $suppress = (isset($a['suppress']) ? $a['suppress'] : ''); + $mgl = (isset($a['mgl']) ? $a['mgl'] : (isset($a['margin-left']) ? $a['margin-left'] : '')); + $mgr = (isset($a['mgr']) ? $a['mgr'] : (isset($a['margin-right']) ? $a['margin-right'] : '')); + $mgt = (isset($a['mgt']) ? $a['mgt'] : (isset($a['margin-top']) ? $a['margin-top'] : '')); + $mgb = (isset($a['mgb']) ? $a['mgb'] : (isset($a['margin-bottom']) ? $a['margin-bottom'] : '')); + $mgh = (isset($a['mgh']) ? $a['mgh'] : (isset($a['margin-header']) ? $a['margin-header'] : '')); + $mgf = (isset($a['mgf']) ? $a['mgf'] : (isset($a['margin-footer']) ? $a['margin-footer'] : '')); + $ohname = (isset($a['ohname']) ? $a['ohname'] : (isset($a['odd-header-name']) ? $a['odd-header-name'] : '')); + $ehname = (isset($a['ehname']) ? $a['ehname'] : (isset($a['even-header-name']) ? $a['even-header-name'] : '')); + $ofname = (isset($a['ofname']) ? $a['ofname'] : (isset($a['odd-footer-name']) ? $a['odd-footer-name'] : '')); + $efname = (isset($a['efname']) ? $a['efname'] : (isset($a['even-footer-name']) ? $a['even-footer-name'] : '')); + $ohvalue = (isset($a['ohvalue']) ? $a['ohvalue'] : (isset($a['odd-header-value']) ? $a['odd-header-value'] : 0)); + $ehvalue = (isset($a['ehvalue']) ? $a['ehvalue'] : (isset($a['even-header-value']) ? $a['even-header-value'] : 0)); + $ofvalue = (isset($a['ofvalue']) ? $a['ofvalue'] : (isset($a['odd-footer-value']) ? $a['odd-footer-value'] : 0)); + $efvalue = (isset($a['efvalue']) ? $a['efvalue'] : (isset($a['even-footer-value']) ? $a['even-footer-value'] : 0)); + $pagesel = (isset($a['pagesel']) ? $a['pagesel'] : (isset($a['pageselector']) ? $a['pageselector'] : '')); + $newformat = (isset($a['newformat']) ? $a['newformat'] : (isset($a['sheet-size']) ? $a['sheet-size'] : '')); + + $this->AddPage($orientation, $condition, $resetpagenum, $pagenumstyle, $suppress, $mgl, $mgr, $mgt, $mgb, $mgh, $mgf, $ohname, $ehname, $ofname, $efname, $ohvalue, $ehvalue, $ofvalue, $efvalue, $pagesel, $newformat); + } + + // mPDF 6 pagebreaktype + function _preForcedPagebreak($pagebreaktype) + { + if ($pagebreaktype == 'cloneall') { + // Close any open block tags + $arr = []; + $ai = 0; + for ($b = $this->blklvl; $b > 0; $b--) { + $this->tag->CloseTag($this->blk[$b]['tag'], $arr, $ai); + } + if ($this->blklvl == 0 && !empty($this->textbuffer)) { // Output previously buffered content + $this->printbuffer($this->textbuffer, 1); + $this->textbuffer = []; + } + } elseif ($pagebreaktype == 'clonebycss') { + // Close open block tags whilst box-decoration-break==clone + $arr = []; + $ai = 0; + for ($b = $this->blklvl; $b > 0; $b--) { + if (isset($this->blk[$b]['box_decoration_break']) && $this->blk[$b]['box_decoration_break'] == 'clone') { + $this->tag->CloseTag($this->blk[$b]['tag'], $arr, $ai); + } else { + if ($b == $this->blklvl && !empty($this->textbuffer)) { // Output previously buffered content + $this->printbuffer($this->textbuffer, 1); + $this->textbuffer = []; + } + break; + } + } + } elseif (!empty($this->textbuffer)) { // Output previously buffered content + $this->printbuffer($this->textbuffer, 1); + $this->textbuffer = []; + } + } + + // mPDF 6 pagebreaktype + function _postForcedPagebreak($pagebreaktype, $startpage, $save_blk, $save_blklvl) + { + if ($pagebreaktype == 'cloneall') { + $this->blk = []; + $this->blk[0] = $save_blk[0]; + // Re-open block tags + $this->blklvl = 0; + $arr = []; + $i = 0; + for ($b = 1; $b <= $save_blklvl; $b++) { + $this->tag->OpenTag($save_blk[$b]['tag'], $save_blk[$b]['attr'], $arr, $i); + } + } elseif ($pagebreaktype == 'clonebycss') { + $this->blk = []; + $this->blk[0] = $save_blk[0]; + // Don't re-open tags for lowest level elements - so need to do some adjustments + for ($b = 1; $b <= $this->blklvl; $b++) { + $this->blk[$b] = $save_blk[$b]; + $this->blk[$b]['startpage'] = 0; + $this->blk[$b]['y0'] = $this->y; // ?? $this->tMargin + if (($this->page - $startpage) % 2) { + if (isset($this->blk[$b]['x0'])) { + $this->blk[$b]['x0'] += $this->MarginCorrection; + } else { + $this->blk[$b]['x0'] = $this->MarginCorrection; + } + } + // for Float DIV + $this->blk[$b]['marginCorrected'][$this->page] = true; + } + + // Re-open block tags for any that have box_decoration_break==clone + $arr = []; + $i = 0; + for ($b = $this->blklvl + 1; $b <= $save_blklvl; $b++) { + if ($b < $this->blklvl) { + $this->lastblocklevelchange = -1; + } + $this->tag->OpenTag($save_blk[$b]['tag'], $save_blk[$b]['attr'], $arr, $i); + } + if ($this->blk[$this->blklvl]['box_decoration_break'] != 'clone') { + $this->lastblocklevelchange = -1; + } + } else { + $this->lastblocklevelchange = -1; + } + } + + function AddPage( + $orientation = '', + $condition = '', + $resetpagenum = '', + $pagenumstyle = '', + $suppress = '', + $mgl = '', + $mgr = '', + $mgt = '', + $mgb = '', + $mgh = '', + $mgf = '', + $ohname = '', + $ehname = '', + $ofname = '', + $efname = '', + $ohvalue = 0, + $ehvalue = 0, + $ofvalue = 0, + $efvalue = 0, + $pagesel = '', + $newformat = '' + ) { + /* -- CSS-FLOAT -- */ + // Float DIV + // Cannot do with columns on, or if any change in page orientation/margins etc. + // If next page already exists - i.e background /headers and footers already written + if ($this->state > 0 && $this->page < count($this->pages)) { + $bak_cml = $this->cMarginL; + $bak_cmr = $this->cMarginR; + $bak_dw = $this->divwidth; + // Paint Div Border if necessary + if ($this->blklvl > 0) { + $save_tr = $this->table_rotate; // *TABLES* + $this->table_rotate = 0; // *TABLES* + if (isset($this->blk[$this->blklvl]['y0']) && $this->y == $this->blk[$this->blklvl]['y0']) { + $this->blk[$this->blklvl]['startpage'] ++; + } + if ((isset($this->blk[$this->blklvl]['y0']) && $this->y > $this->blk[$this->blklvl]['y0']) || $this->flowingBlockAttr['is_table']) { + $toplvl = $this->blklvl; + } else { + $toplvl = $this->blklvl - 1; + } + $sy = $this->y; + for ($bl = 1; $bl <= $toplvl; $bl++) { + $this->PaintDivBB('pagebottom', 0, $bl); + } + $this->y = $sy; + $this->table_rotate = $save_tr; // *TABLES* + } + $s = $this->PrintPageBackgrounds(); + + // Writes after the marker so not overwritten later by page background etc. + $this->pages[$this->page] = preg_replace( + '/(___BACKGROUND___PATTERNS' . $this->uniqstr . ')/', + '\\1' . "\n" . $s . "\n", + $this->pages[$this->page] + ); + + $this->pageBackgrounds = []; + $family = $this->FontFamily; + $style = $this->FontStyle; + $size = $this->FontSizePt; + $lw = $this->LineWidth; + $dc = $this->DrawColor; + $fc = $this->FillColor; + $tc = $this->TextColor; + $cf = $this->ColorFlag; + + $this->printfloatbuffer(); + + // Move to next page + $this->page++; + + $this->ResetMargins(); + $this->SetAutoPageBreak($this->autoPageBreak, $this->bMargin); + $this->x = $this->lMargin; + $this->y = $this->tMargin; + $this->FontFamily = ''; + $this->writer->write('2 J'); + $this->LineWidth = $lw; + $this->writer->write(sprintf('%.3F w', $lw * Mpdf::SCALE)); + + if ($family) { + $this->SetFont($family, $style, $size, true, true); + } + + $this->DrawColor = $dc; + + if ($dc != $this->defDrawColor) { + $this->writer->write($dc); + } + + $this->FillColor = $fc; + + if ($fc != $this->defFillColor) { + $this->writer->write($fc); + } + + $this->TextColor = $tc; + $this->ColorFlag = $cf; + + for ($bl = 1; $bl <= $this->blklvl; $bl++) { + $this->blk[$bl]['y0'] = $this->y; + // Don't correct more than once for background DIV containing a Float + if (!isset($this->blk[$bl]['marginCorrected'][$this->page])) { + if (isset($this->blk[$bl]['x0'])) { + $this->blk[$bl]['x0'] += $this->MarginCorrection; + } else { + $this->blk[$bl]['x0'] = $this->MarginCorrection; + } + } + $this->blk[$bl]['marginCorrected'][$this->page] = true; + } + + $this->cMarginL = $bak_cml; + $this->cMarginR = $bak_cmr; + $this->divwidth = $bak_dw; + + return ''; + } + /* -- END CSS-FLOAT -- */ + + // Start a new page + if ($this->state == 0) { + $this->Open(); + } + + $bak_cml = $this->cMarginL; + $bak_cmr = $this->cMarginR; + $bak_dw = $this->divwidth; + + $bak_lh = $this->lineheight; + + $orientation = substr(strtoupper($orientation), 0, 1); + $condition = strtoupper($condition); + + + if ($condition == 'E') { // only adds new page if needed to create an Even page + if (!$this->mirrorMargins || ($this->page) % 2 == 0) { + return false; + } + } elseif ($condition == 'O') { // only adds new page if needed to create an Odd page + if (!$this->mirrorMargins || ($this->page) % 2 == 1) { + return false; + } + } elseif ($condition == 'NEXT-EVEN') { // always adds at least one new page to create an Even page + if (!$this->mirrorMargins) { + $condition = ''; + } else { + if ($pagesel) { + $pbch = $pagesel; + $pagesel = ''; + } // *CSS-PAGE* + else { + $pbch = false; + } // *CSS-PAGE* + $this->AddPage($this->CurOrientation, 'O'); + $this->extrapagebreak = true; // mPDF 6 pagebreaktype + if ($pbch) { + $pagesel = $pbch; + } // *CSS-PAGE* + $condition = ''; + } + } elseif ($condition == 'NEXT-ODD') { // always adds at least one new page to create an Odd page + if (!$this->mirrorMargins) { + $condition = ''; + } else { + if ($pagesel) { + $pbch = $pagesel; + $pagesel = ''; + } // *CSS-PAGE* + else { + $pbch = false; + } // *CSS-PAGE* + $this->AddPage($this->CurOrientation, 'E'); + $this->extrapagebreak = true; // mPDF 6 pagebreaktype + if ($pbch) { + $pagesel = $pbch; + } // *CSS-PAGE* + $condition = ''; + } + } + + if ($resetpagenum || $pagenumstyle || $suppress) { + $this->PageNumSubstitutions[] = ['from' => ($this->page + 1), 'reset' => $resetpagenum, 'type' => $pagenumstyle, 'suppress' => $suppress]; + } + + $save_tr = $this->table_rotate; // *TABLES* + $this->table_rotate = 0; // *TABLES* + $save_kwt = $this->kwt; + $this->kwt = 0; + $save_layer = $this->current_layer; + $save_vis = $this->visibility; + + if ($this->visibility != 'visible') { + $this->SetVisibility('visible'); + } + + $this->EndLayer(); + + // Paint Div Border if necessary + // PAINTS BACKGROUND COLOUR OR BORDERS for DIV - DISABLED FOR COLUMNS (cf. AcceptPageBreak) AT PRESENT in ->PaintDivBB + if (!$this->ColActive && $this->blklvl > 0) { + if (isset($this->blk[$this->blklvl]['y0']) && $this->y == $this->blk[$this->blklvl]['y0'] && !$this->extrapagebreak) { // mPDF 6 pagebreaktype + if (isset($this->blk[$this->blklvl]['startpage'])) { + $this->blk[$this->blklvl]['startpage'] ++; + } else { + $this->blk[$this->blklvl]['startpage'] = 1; + } + } + if ((isset($this->blk[$this->blklvl]['y0']) && $this->y > $this->blk[$this->blklvl]['y0']) || $this->flowingBlockAttr['is_table'] || $this->extrapagebreak) { + $toplvl = $this->blklvl; + } // mPDF 6 pagebreaktype + else { + $toplvl = $this->blklvl - 1; + } + $sy = $this->y; + for ($bl = 1; $bl <= $toplvl; $bl++) { + if (isset($this->blk[$bl]['z-index']) && $this->blk[$bl]['z-index'] > 0) { + $this->BeginLayer($this->blk[$bl]['z-index']); + } + if (isset($this->blk[$bl]['visibility']) && $this->blk[$bl]['visibility'] && $this->blk[$bl]['visibility'] != 'visible') { + $this->SetVisibility($this->blk[$bl]['visibility']); + } + $this->PaintDivBB('pagebottom', 0, $bl); + } + $this->y = $sy; + // RESET block y0 and x0 - see below + } + $this->extrapagebreak = false; // mPDF 6 pagebreaktype + + if ($this->visibility != 'visible') { + $this->SetVisibility('visible'); + } + + $this->EndLayer(); + + // BODY Backgrounds + if ($this->page > 0) { + $s = ''; + $s .= $this->PrintBodyBackgrounds(); + + $s .= $this->PrintPageBackgrounds(); + $this->pages[$this->page] = preg_replace('/(___BACKGROUND___PATTERNS' . $this->uniqstr . ')/', "\n" . $s . "\n" . '\\1', $this->pages[$this->page]); + $this->pageBackgrounds = []; + } + + $save_kt = $this->keep_block_together; + $this->keep_block_together = 0; + + $save_cols = false; + + /* -- COLUMNS -- */ + if ($this->ColActive) { + $save_cols = true; + $save_nbcol = $this->NbCol; // other values of gap and vAlign will not change by setting Columns off + $this->SetColumns(0); + } + /* -- END COLUMNS -- */ + + $family = $this->FontFamily; + $style = $this->FontStyle; + $size = $this->FontSizePt; + $this->ColumnAdjust = true; // enables column height adjustment for the page + $lw = $this->LineWidth; + $dc = $this->DrawColor; + $fc = $this->FillColor; + $tc = $this->TextColor; + $cf = $this->ColorFlag; + if ($this->page > 0) { + // Page footer + $this->InFooter = true; + + $this->Reset(); + $this->pageoutput[$this->page] = []; + + $this->Footer(); + // Close page + $this->_endpage(); + } + + // Start new page + $this->_beginpage($orientation, $mgl, $mgr, $mgt, $mgb, $mgh, $mgf, $ohname, $ehname, $ofname, $efname, $ohvalue, $ehvalue, $ofvalue, $efvalue, $pagesel, $newformat); + + if ($this->docTemplate) { + $currentReaderId = $this->currentReaderId; + + $pagecount = $this->setSourceFile($this->docTemplate); + if (($this->page - $this->docTemplateStart) > $pagecount) { + if ($this->docTemplateContinue) { + $tplIdx = $this->importPage($pagecount); + $this->useTemplate($tplIdx); + } + } else { + $tplIdx = $this->importPage(($this->page - $this->docTemplateStart)); + $this->useTemplate($tplIdx); + } + + $this->currentReaderId = $currentReaderId; + } + + if ($this->pageTemplate) { + $this->useTemplate($this->pageTemplate); + } + + // Tiling Patterns + $this->writer->write('___PAGE___START' . $this->uniqstr); + $this->writer->write('___BACKGROUND___PATTERNS' . $this->uniqstr); + $this->writer->write('___HEADER___MARKER' . $this->uniqstr); + $this->pageBackgrounds = []; + + // Set line cap style to square + $this->SetLineCap(2); + // Set line width + $this->LineWidth = $lw; + $this->writer->write(sprintf('%.3F w', $lw * Mpdf::SCALE)); + // Set font + if ($family) { + $this->SetFont($family, $style, $size, true, true); // forces write + } + + // Set colors + $this->DrawColor = $dc; + if ($dc != $this->defDrawColor) { + $this->writer->write($dc); + } + $this->FillColor = $fc; + if ($fc != $this->defFillColor) { + $this->writer->write($fc); + } + $this->TextColor = $tc; + $this->ColorFlag = $cf; + + // Page header + $this->Header(); + + // Restore line width + if ($this->LineWidth != $lw) { + $this->LineWidth = $lw; + $this->writer->write(sprintf('%.3F w', $lw * Mpdf::SCALE)); + } + // Restore font + if ($family) { + $this->SetFont($family, $style, $size, true, true); // forces write + } + + // Restore colors + if ($this->DrawColor != $dc) { + $this->DrawColor = $dc; + $this->writer->write($dc); + } + if ($this->FillColor != $fc) { + $this->FillColor = $fc; + $this->writer->write($fc); + } + $this->TextColor = $tc; + $this->ColorFlag = $cf; + $this->InFooter = false; + + if ($save_layer > 0) { + $this->BeginLayer($save_layer); + } + + if ($save_vis != 'visible') { + $this->SetVisibility($save_vis); + } + + /* -- COLUMNS -- */ + if ($save_cols) { + // Restore columns + $this->SetColumns($save_nbcol, $this->colvAlign, $this->ColGap); + } + if ($this->ColActive) { + $this->SetCol(0); + } + /* -- END COLUMNS -- */ + + + // RESET BLOCK BORDER TOP + if (!$this->ColActive) { + for ($bl = 1; $bl <= $this->blklvl; $bl++) { + $this->blk[$bl]['y0'] = $this->y; + if (isset($this->blk[$bl]['x0'])) { + $this->blk[$bl]['x0'] += $this->MarginCorrection; + } else { + $this->blk[$bl]['x0'] = $this->MarginCorrection; + } + // Added mPDF 3.0 Float DIV + $this->blk[$bl]['marginCorrected'][$this->page] = true; + } + } + + + $this->table_rotate = $save_tr; // *TABLES* + $this->kwt = $save_kwt; + + $this->keep_block_together = $save_kt; + + $this->cMarginL = $bak_cml; + $this->cMarginR = $bak_cmr; + $this->divwidth = $bak_dw; + + $this->lineheight = $bak_lh; + } + + /** + * Get current page number + * + * @return int + */ + function PageNo() + { + return $this->page; + } + + function AddSpotColorsFromFile($file) + { + $colors = @file($file); + if (!$colors) { + throw new \Mpdf\MpdfException("Cannot load spot colors file - " . $file); + } + foreach ($colors as $sc) { + list($name, $c, $m, $y, $k) = preg_split("/\t/", $sc); + $c = intval($c); + $m = intval($m); + $y = intval($y); + $k = intval($k); + $this->AddSpotColor($name, $c, $m, $y, $k); + } + } + + function AddSpotColor($name, $c, $m, $y, $k) + { + $name = strtoupper(trim($name)); + if (!isset($this->spotColors[$name])) { + $i = count($this->spotColors) + 1; + $this->spotColors[$name] = ['i' => $i, 'c' => $c, 'm' => $m, 'y' => $y, 'k' => $k]; + $this->spotColorIDs[$i] = $name; + } + } + + function SetColor($col, $type = '') + { + $out = ''; + if (!$col) { + return ''; + } // mPDF 6 + if ($col[0] == 3 || $col[0] == 5) { // RGB / RGBa + $out = sprintf('%.3F %.3F %.3F rg', ord($col[1]) / 255, ord($col[2]) / 255, ord($col[3]) / 255); + } elseif ($col[0] == 1) { // GRAYSCALE + $out = sprintf('%.3F g', ord($col[1]) / 255); + } elseif ($col[0] == 2) { // SPOT COLOR + $out = sprintf('/CS%d cs %.3F scn', ord($col[1]), ord($col[2]) / 100); + } elseif ($col[0] == 4 || $col[0] == 6) { // CMYK / CMYKa + $out = sprintf('%.3F %.3F %.3F %.3F k', ord($col[1]) / 100, ord($col[2]) / 100, ord($col[3]) / 100, ord($col[4]) / 100); + } + if ($type == 'Draw') { + $out = strtoupper($out); + } // e.g. rg => RG + elseif ($type == 'CodeOnly') { + $out = preg_replace('/\s(rg|g|k)/', '', $out); + } + return $out; + } + + function SetDColor($col, $return = false) + { + $out = $this->SetColor($col, 'Draw'); + if ($return) { + return $out; + } + if ($out == '') { + return ''; + } + $this->DrawColor = $out; + if ($this->page > 0 && ((isset($this->pageoutput[$this->page]['DrawColor']) && $this->pageoutput[$this->page]['DrawColor'] != $this->DrawColor) || !isset($this->pageoutput[$this->page]['DrawColor']))) { + $this->writer->write($this->DrawColor); + } + $this->pageoutput[$this->page]['DrawColor'] = $this->DrawColor; + } + + function SetFColor($col, $return = false) + { + $out = $this->SetColor($col, 'Fill'); + if ($return) { + return $out; + } + if ($out == '') { + return ''; + } + $this->FillColor = $out; + $this->ColorFlag = ($out != $this->TextColor); + if ($this->page > 0 && ((isset($this->pageoutput[$this->page]['FillColor']) && $this->pageoutput[$this->page]['FillColor'] != $this->FillColor) || !isset($this->pageoutput[$this->page]['FillColor']))) { + $this->writer->write($this->FillColor); + } + $this->pageoutput[$this->page]['FillColor'] = $this->FillColor; + } + + function SetTColor($col, $return = false) + { + $out = $this->SetColor($col, 'Text'); + if ($return) { + return $out; + } + if ($out == '') { + return ''; + } + $this->TextColor = $out; + $this->ColorFlag = ($this->FillColor != $out); + } + + function SetDrawColor($r, $g = -1, $b = -1, $col4 = -1, $return = false) + { + // Set color for all stroking operations + $col = []; + if (($r == 0 and $g == 0 and $b == 0 && $col4 == -1) or $g == -1) { + $col = $this->colorConverter->convert($r, $this->PDFAXwarnings); + } elseif ($col4 == -1) { + $col = $this->colorConverter->convert('rgb(' . $r . ',' . $g . ',' . $b . ')', $this->PDFAXwarnings); + } else { + $col = $this->colorConverter->convert('cmyk(' . $r . ',' . $g . ',' . $b . ',' . $col4 . ')', $this->PDFAXwarnings); + } + $out = $this->SetDColor($col, $return); + return $out; + } + + function SetFillColor($r, $g = -1, $b = -1, $col4 = -1, $return = false) + { + // Set color for all filling operations + $col = []; + if (($r == 0 and $g == 0 and $b == 0 && $col4 == -1) or $g == -1) { + $col = $this->colorConverter->convert($r, $this->PDFAXwarnings); + } elseif ($col4 == -1) { + $col = $this->colorConverter->convert('rgb(' . $r . ',' . $g . ',' . $b . ')', $this->PDFAXwarnings); + } else { + $col = $this->colorConverter->convert('cmyk(' . $r . ',' . $g . ',' . $b . ',' . $col4 . ')', $this->PDFAXwarnings); + } + $out = $this->SetFColor($col, $return); + return $out; + } + + function SetTextColor($r, $g = -1, $b = -1, $col4 = -1, $return = false) + { + // Set color for text + $col = []; + if (($r == 0 and $g == 0 and $b == 0 && $col4 == -1) or $g == -1) { + $col = $this->colorConverter->convert($r, $this->PDFAXwarnings); + } elseif ($col4 == -1) { + $col = $this->colorConverter->convert('rgb(' . $r . ',' . $g . ',' . $b . ')', $this->PDFAXwarnings); + } else { + $col = $this->colorConverter->convert('cmyk(' . $r . ',' . $g . ',' . $b . ',' . $col4 . ')', $this->PDFAXwarnings); + } + $out = $this->SetTColor($col, $return); + return $out; + } + + function _getCharWidth(&$cw, $u, $isdef = true) + { + $w = 0; + + if ($u == 0) { + $w = false; + } elseif (isset($cw[$u * 2 + 1])) { + $w = (ord($cw[$u * 2]) << 8) + ord($cw[$u * 2 + 1]); + } + + if ($w == 65535) { + return 0; + } elseif ($w) { + return $w; + } elseif ($isdef) { + return false; + } else { + return 0; + } + } + + function _charDefined(&$cw, $u) + { + $w = 0; + if ($u == 0) { + return false; + } + if (isset($cw[$u * 2 + 1])) { + $w = (ord($cw[$u * 2]) << 8) + ord($cw[$u * 2 + 1]); + } + + return (bool) $w; + } + + function GetCharWidthCore($c) + { + // Get width of a single character in the current Core font + $c = (string) $c; + $w = 0; + // Soft Hyphens chr(173) + if ($c == chr(173) && $this->FontFamily != 'csymbol' && $this->FontFamily != 'czapfdingbats') { + return 0; + } elseif (($this->textvar & TextVars::FC_SMALLCAPS) && isset($this->upperCase[ord($c)])) { // mPDF 5.7.1 + $charw = $this->CurrentFont['cw'][chr($this->upperCase[ord($c)])]; + if ($charw !== false) { + $charw = $charw * $this->smCapsScale * $this->smCapsStretch / 100; + $w+=$charw; + } + } elseif (isset($this->CurrentFont['cw'][$c])) { + $w += $this->CurrentFont['cw'][$c]; + } elseif (isset($this->CurrentFont['cw'][ord($c)])) { + $w += $this->CurrentFont['cw'][ord($c)]; + } + $w *= ($this->FontSize / 1000); + if ($this->minwSpacing || $this->fixedlSpacing) { + if ($c == ' ') { + $nb_spaces = 1; + } else { + $nb_spaces = 0; + } + $w += $this->fixedlSpacing + ($nb_spaces * $this->minwSpacing); + } + return ($w); + } + + function GetCharWidthNonCore($c, $addSubset = true) + { + // Get width of a single character in the current Non-Core font + $c = (string) $c; + $w = 0; + $unicode = $this->UTF8StringToArray($c, $addSubset); + $char = $unicode[0]; + /* -- CJK-FONTS -- */ + if ($this->CurrentFont['type'] == 'Type0') { // CJK Adobe fonts + if ($char == 173) { + return 0; + } // Soft Hyphens + elseif (isset($this->CurrentFont['cw'][$char])) { + $w+=$this->CurrentFont['cw'][$char]; + } elseif (isset($this->CurrentFont['MissingWidth'])) { + $w += $this->CurrentFont['MissingWidth']; + } else { + $w += 500; + } + } else { + /* -- END CJK-FONTS -- */ + if ($char == 173) { + return 0; + } // Soft Hyphens + elseif (($this->textvar & TextVars::FC_SMALLCAPS) && isset($this->upperCase[$char])) { // mPDF 5.7.1 + $charw = $this->_getCharWidth($this->CurrentFont['cw'], $this->upperCase[$char]); + if ($charw !== false) { + $charw = $charw * $this->smCapsScale * $this->smCapsStretch / 100; + $w+=$charw; + } elseif (isset($this->CurrentFont['desc']['MissingWidth'])) { + $w += $this->CurrentFont['desc']['MissingWidth']; + } elseif (isset($this->CurrentFont['MissingWidth'])) { + $w += $this->CurrentFont['MissingWidth']; + } else { + $w += 500; + } + } else { + $charw = $this->_getCharWidth($this->CurrentFont['cw'], $char); + if ($charw !== false) { + $w+=$charw; + } elseif (isset($this->CurrentFont['desc']['MissingWidth'])) { + $w += $this->CurrentFont['desc']['MissingWidth']; + } elseif (isset($this->CurrentFont['MissingWidth'])) { + $w += $this->CurrentFont['MissingWidth']; + } else { + $w += 500; + } + } + } // *CJK-FONTS* + $w *= ($this->FontSize / 1000); + if ($this->minwSpacing || $this->fixedlSpacing) { + if ($c == ' ') { + $nb_spaces = 1; + } else { + $nb_spaces = 0; + } + $w += $this->fixedlSpacing + ($nb_spaces * $this->minwSpacing); + } + return ($w); + } + + function GetCharWidth($c, $addSubset = true) + { + if (!$this->usingCoreFont) { + return $this->GetCharWidthNonCore($c, $addSubset); + } else { + return $this->GetCharWidthCore($c); + } + } + + function GetStringWidth($s, $addSubset = true, $OTLdata = false, $textvar = 0, $includeKashida = false) + { + // mPDF 5.7.1 + // Get width of a string in the current font + $s = (string) $s; + $cw = &$this->CurrentFont['cw']; + $w = 0; + $kerning = 0; + $lastchar = 0; + $nb_carac = 0; + $nb_spaces = 0; + $kashida = 0; + // mPDF ITERATION + if ($this->iterationCounter) { + $s = preg_replace('/{iteration ([a-zA-Z0-9_]+)}/', '\\1', $s); + } + if (!$this->usingCoreFont) { + $discards = substr_count($s, "\xc2\xad"); // mPDF 6 soft hyphens [U+00AD] + $unicode = $this->UTF8StringToArray($s, $addSubset); + if ($this->minwSpacing || $this->fixedlSpacing) { + $nb_spaces = mb_substr_count($s, ' ', $this->mb_enc); + $nb_carac = count($unicode) - $discards; // mPDF 6 + // mPDF 5.7.1 + // Use GPOS OTL + if (isset($this->CurrentFont['useOTL']) && $this->CurrentFont['useOTL']) { + if (isset($OTLdata['group']) && $OTLdata['group']) { + $nb_carac -= substr_count($OTLdata['group'], 'M'); + } + } + } + /* -- CJK-FONTS -- */ + if ($this->CurrentFont['type'] == 'Type0') { // CJK Adobe fonts + foreach ($unicode as $char) { + if ($char == 0x00AD) { + continue; + } // mPDF 6 soft hyphens [U+00AD] + if (isset($cw[$char])) { + $w+=$cw[$char]; + } elseif (isset($this->CurrentFont['MissingWidth'])) { + $w += $this->CurrentFont['MissingWidth']; + } else { + $w += 500; + } + } + } else { + /* -- END CJK-FONTS -- */ + foreach ($unicode as $i => $char) { + if ($char == 0x00AD) { + continue; + } // mPDF 6 soft hyphens [U+00AD] + if (($textvar & TextVars::FC_SMALLCAPS) && isset($this->upperCase[$char])) { + $charw = $this->_getCharWidth($cw, $this->upperCase[$char]); + if ($charw !== false) { + $charw = $charw * $this->smCapsScale * $this->smCapsStretch / 100; + $w+=$charw; + } elseif (isset($this->CurrentFont['desc']['MissingWidth'])) { + $w += $this->CurrentFont['desc']['MissingWidth']; + } elseif (isset($this->CurrentFont['MissingWidth'])) { + $w += $this->CurrentFont['MissingWidth']; + } else { + $w += 500; + } + } else { + $charw = $this->_getCharWidth($cw, $char); + if ($charw !== false) { + $w+=$charw; + } elseif (isset($this->CurrentFont['desc']['MissingWidth'])) { + $w += $this->CurrentFont['desc']['MissingWidth']; + } elseif (isset($this->CurrentFont['MissingWidth'])) { + $w += $this->CurrentFont['MissingWidth']; + } else { + $w += 500; + } + // mPDF 5.7.1 + // Use GPOS OTL + // ...GetStringWidth... + if (isset($this->CurrentFont['useOTL']) && ($this->CurrentFont['useOTL'] & 0xFF) && !empty($OTLdata)) { + if (isset($OTLdata['GPOSinfo'][$i]['wDir']) && $OTLdata['GPOSinfo'][$i]['wDir'] == 'RTL') { + if (isset($OTLdata['GPOSinfo'][$i]['XAdvanceR']) && $OTLdata['GPOSinfo'][$i]['XAdvanceR']) { + $w += $OTLdata['GPOSinfo'][$i]['XAdvanceR'] * 1000 / $this->CurrentFont['unitsPerEm']; + } + } else { + if (isset($OTLdata['GPOSinfo'][$i]['XAdvanceL']) && $OTLdata['GPOSinfo'][$i]['XAdvanceL']) { + $w += $OTLdata['GPOSinfo'][$i]['XAdvanceL'] * 1000 / $this->CurrentFont['unitsPerEm']; + } + } + // Kashida from GPOS + // Kashida is set as an absolute length value (already set as a proportion based on useKashida %) + if ($includeKashida && isset($OTLdata['GPOSinfo'][$i]['kashida_space']) && $OTLdata['GPOSinfo'][$i]['kashida_space']) { + $kashida += $OTLdata['GPOSinfo'][$i]['kashida_space']; + } + } + if (($textvar & TextVars::FC_KERNING) && $lastchar) { + if (isset($this->CurrentFont['kerninfo'][$lastchar][$char])) { + $kerning += $this->CurrentFont['kerninfo'][$lastchar][$char]; + } + } + $lastchar = $char; + } + } + } // *CJK-FONTS* + } else { + if ($this->FontFamily != 'csymbol' && $this->FontFamily != 'czapfdingbats') { + $s = str_replace(chr(173), '', $s); + } + $nb_carac = $l = strlen($s); + if ($this->minwSpacing || $this->fixedlSpacing) { + $nb_spaces = substr_count($s, ' '); + } + for ($i = 0; $i < $l; $i++) { + if (($textvar & TextVars::FC_SMALLCAPS) && isset($this->upperCase[ord($s[$i])])) { // mPDF 5.7.1 + $charw = $cw[chr($this->upperCase[ord($s[$i])])]; + if ($charw !== false) { + $charw = $charw * $this->smCapsScale * $this->smCapsStretch / 100; + $w+=$charw; + } + } elseif (isset($cw[$s[$i]])) { + $w += $cw[$s[$i]]; + } elseif (isset($cw[ord($s[$i])])) { + $w += $cw[ord($s[$i])]; + } + if (($textvar & TextVars::FC_KERNING) && $i > 0) { // mPDF 5.7.1 + if (isset($this->CurrentFont['kerninfo'][$s[($i - 1)]][$s[$i]])) { + $kerning += $this->CurrentFont['kerninfo'][$s[($i - 1)]][$s[$i]]; + } + } + } + } + unset($cw); + if ($textvar & TextVars::FC_KERNING) { + $w += $kerning; + } // mPDF 5.7.1 + $w *= ($this->FontSize / 1000); + $w += (($nb_carac + $nb_spaces) * $this->fixedlSpacing) + ($nb_spaces * $this->minwSpacing); + $w += $kashida / Mpdf::SCALE; + + return ($w); + } + + function SetLineWidth($width) + { + // Set line width + $this->LineWidth = $width; + $lwout = (sprintf('%.3F w', $width * Mpdf::SCALE)); + if ($this->page > 0 && ((isset($this->pageoutput[$this->page]['LineWidth']) && $this->pageoutput[$this->page]['LineWidth'] != $lwout) || !isset($this->pageoutput[$this->page]['LineWidth']))) { + $this->writer->write($lwout); + } + $this->pageoutput[$this->page]['LineWidth'] = $lwout; + } + + function Line($x1, $y1, $x2, $y2) + { + // Draw a line + $this->writer->write(sprintf('%.3F %.3F m %.3F %.3F l S', $x1 * Mpdf::SCALE, ($this->h - $y1) * Mpdf::SCALE, $x2 * Mpdf::SCALE, ($this->h - $y2) * Mpdf::SCALE)); + } + + function Arrow($x1, $y1, $x2, $y2, $headsize = 3, $fill = 'B', $angle = 25) + { + // F == fill // S == stroke // B == stroke and fill + // angle = splay of arrowhead - 1 - 89 degrees + if ($fill == 'F') { + $fill = 'f'; + } elseif ($fill == 'FD' or $fill == 'DF' or $fill == 'B') { + $fill = 'B'; + } else { + $fill = 'S'; + } + $a = atan2(($y2 - $y1), ($x2 - $x1)); + $b = $a + deg2rad($angle); + $c = $a - deg2rad($angle); + $x3 = $x2 - ($headsize * cos($b)); + $y3 = $this->h - ($y2 - ($headsize * sin($b))); + $x4 = $x2 - ($headsize * cos($c)); + $y4 = $this->h - ($y2 - ($headsize * sin($c))); + + $x5 = $x3 - ($x3 - $x4) / 2; // mid point of base of arrowhead - to join arrow line to + $y5 = $y3 - ($y3 - $y4) / 2; + + $s = ''; + $s .= sprintf('%.3F %.3F m %.3F %.3F l S', $x1 * Mpdf::SCALE, ($this->h - $y1) * Mpdf::SCALE, $x5 * Mpdf::SCALE, $y5 * Mpdf::SCALE); + $this->writer->write($s); + + $s = ''; + $s .= sprintf('%.3F %.3F m %.3F %.3F l %.3F %.3F l %.3F %.3F l %.3F %.3F l ', $x5 * Mpdf::SCALE, $y5 * Mpdf::SCALE, $x3 * Mpdf::SCALE, $y3 * Mpdf::SCALE, $x2 * Mpdf::SCALE, ($this->h - $y2) * Mpdf::SCALE, $x4 * Mpdf::SCALE, $y4 * Mpdf::SCALE, $x5 * Mpdf::SCALE, $y5 * Mpdf::SCALE); + $s .= $fill; + $this->writer->write($s); + } + + function Rect($x, $y, $w, $h, $style = '') + { + // Draw a rectangle + if ($style == 'F') { + $op = 'f'; + } elseif ($style == 'FD' or $style == 'DF') { + $op = 'B'; + } else { + $op = 'S'; + } + $this->writer->write(sprintf('%.3F %.3F %.3F %.3F re %s', $x * Mpdf::SCALE, ($this->h - $y) * Mpdf::SCALE, $w * Mpdf::SCALE, -$h * Mpdf::SCALE, $op)); + } + + function AddFontDirectory($directory) + { + $this->fontDir[] = $directory; + $this->fontFileFinder->setDirectories($this->fontDir); + } + + function AddFont($family, $style = '') + { + if (empty($family)) { + return; + } + + $family = strtolower($family); + $style = strtoupper($style); + $style = str_replace('U', '', $style); + + if ($style == 'IB') { + $style = 'BI'; + } + + $fontkey = $family . $style; + + // check if the font has been already added + if (isset($this->fonts[$fontkey])) { + return; + } + + /* -- CJK-FONTS -- */ + if (in_array($family, $this->available_CJK_fonts)) { + if (empty($this->Big5_widths)) { + require __DIR__ . '/../data/CJKdata.php'; + } + $this->AddCJKFont($family); // don't need to add style + return; + } + /* -- END CJK-FONTS -- */ + + if ($this->usingCoreFont) { + throw new \Mpdf\MpdfException("mPDF Error - problem with Font management"); + } + + $stylekey = $style; + if (!$style) { + $stylekey = 'R'; + } + + if (!isset($this->fontdata[$family][$stylekey]) || !$this->fontdata[$family][$stylekey]) { + throw new \Mpdf\MpdfException(sprintf('Font "%s%s%s" is not supported', $family, $style ? ' - ' : '', $style)); + } + + /* Setup defaults */ + $font = [ + 'name' => '', + 'type' => '', + 'desc' => '', + 'panose' => '', + 'unitsPerEm' => '', + 'up' => '', + 'ut' => '', + 'strs' => '', + 'strp' => '', + 'sip' => false, + 'smp' => false, + 'useOTL' => 0, + 'fontmetrics' => '', + 'haskerninfo' => false, + 'haskernGPOS' => false, + 'hassmallcapsGSUB' => false, + 'BMPselected' => false, + 'GSUBScriptLang' => [], + 'GSUBFeatures' => [], + 'GSUBLookups' => [], + 'GPOSScriptLang' => [], + 'GPOSFeatures' => [], + 'GPOSLookups' => [], + 'rtlPUAstr' => '', + ]; + + $fontCacheFilename = $fontkey . '.mtx.json'; + if ($this->fontCache->jsonHas($fontCacheFilename)) { + $font = $this->fontCache->jsonLoad($fontCacheFilename); + } + + $ttffile = $this->fontFileFinder->findFontFile($this->fontdata[$family][$stylekey]); + $ttfstat = stat($ttffile); + + $TTCfontID = isset($this->fontdata[$family]['TTCfontID'][$stylekey]) ? isset($this->fontdata[$family]['TTCfontID'][$stylekey]) : 0; + $fontUseOTL = isset($this->fontdata[$family]['useOTL']) ? $this->fontdata[$family]['useOTL'] : false; + $BMPonly = in_array($family, $this->BMPonly) ? true : false; + + $regenerate = false; + if ($BMPonly && !$font['BMPselected']) { + $regenerate = true; + } elseif (!$BMPonly && $font['BMPselected']) { + $regenerate = true; + } + + if ($fontUseOTL && $font['useOTL'] != $fontUseOTL) { + $regenerate = true; + $font['useOTL'] = $fontUseOTL; + } elseif (!$fontUseOTL && $font['useOTL']) { + $regenerate = true; + $font['useOTL'] = 0; + } + + if ($this->fontDescriptor != $font['fontmetrics']) { + $regenerate = true; + } // mPDF 6 + + if (empty($font['name']) || $font['originalsize'] != $ttfstat['size'] || $regenerate) { + $generator = new MetricsGenerator($this->fontCache, $this->fontDescriptor); + + $generator->generateMetrics( + $ttffile, + $ttfstat, + $fontkey, + $TTCfontID, + $this->debugfonts, + $BMPonly, + $font['useOTL'], + $fontUseOTL + ); + + $font = $this->fontCache->jsonLoad($fontCacheFilename); + $cw = $this->fontCache->load($fontkey . '.cw.dat'); + $glyphIDtoUni = $this->fontCache->load($fontkey . '.gid.dat'); + } else { + if ($this->fontCache->has($fontkey . '.cw.dat')) { + $cw = $this->fontCache->load($fontkey . '.cw.dat'); + } + + if ($this->fontCache->has($fontkey . '.gid.dat')) { + $glyphIDtoUni = $this->fontCache->load($fontkey . '.gid.dat'); + } + } + + if (isset($this->fontdata[$family]['sip-ext']) && $this->fontdata[$family]['sip-ext']) { + $sipext = $this->fontdata[$family]['sip-ext']; + } else { + $sipext = ''; + } + + // Override with values from config_font.php + if (isset($this->fontdata[$family]['Ascent']) && $this->fontdata[$family]['Ascent']) { + $desc['Ascent'] = $this->fontdata[$family]['Ascent']; + } + if (isset($this->fontdata[$family]['Descent']) && $this->fontdata[$family]['Descent']) { + $desc['Descent'] = $this->fontdata[$family]['Descent']; + } + if (isset($this->fontdata[$family]['Leading']) && $this->fontdata[$family]['Leading']) { + $desc['Leading'] = $this->fontdata[$family]['Leading']; + } + + $i = count($this->fonts) + $this->extraFontSubsets + 1; + + $this->fonts[$fontkey] = [ + 'i' => $i, + 'name' => $font['name'], + 'type' => $font['type'], + 'desc' => $font['desc'], + 'panose' => $font['panose'], + 'unitsPerEm' => $font['unitsPerEm'], + 'up' => $font['up'], + 'ut' => $font['ut'], + 'strs' => $font['strs'], + 'strp' => $font['strp'], + 'cw' => $cw, + 'ttffile' => $ttffile, + 'fontkey' => $fontkey, + 'used' => false, + 'sip' => $font['sip'], + 'sipext' => $sipext, + 'smp' => $font['smp'], + 'TTCfontID' => $TTCfontID, + 'useOTL' => $fontUseOTL, + 'useKashida' => (isset($this->fontdata[$family]['useKashida']) ? $this->fontdata[$family]['useKashida'] : false), + 'GSUBScriptLang' => $font['GSUBScriptLang'], + 'GSUBFeatures' => $font['GSUBFeatures'], + 'GSUBLookups' => $font['GSUBLookups'], + 'GPOSScriptLang' => $font['GPOSScriptLang'], + 'GPOSFeatures' => $font['GPOSFeatures'], + 'GPOSLookups' => $font['GPOSLookups'], + 'rtlPUAstr' => $font['rtlPUAstr'], + 'glyphIDtoUni' => $glyphIDtoUni, + 'haskerninfo' => $font['haskerninfo'], + 'haskernGPOS' => $font['haskernGPOS'], + 'hassmallcapsGSUB' => $font['hassmallcapsGSUB'], + ]; + + + if (!$font['sip'] && !$font['smp']) { + $subsetRange = range(32, 127); + $this->fonts[$fontkey]['subset'] = array_combine($subsetRange, $subsetRange); + } else { + $this->fonts[$fontkey]['subsets'] = [0 => range(0, 127)]; + $this->fonts[$fontkey]['subsetfontids'] = [$i]; + } + + if ($font['haskerninfo']) { + $this->fonts[$fontkey]['kerninfo'] = $font['kerninfo']; + } + + $this->FontFiles[$fontkey] = [ + 'length1' => $font['originalsize'], + 'type' => 'TTF', + 'ttffile' => $ttffile, + 'sip' => $font['sip'], + 'smp' => $font['smp'], + ]; + + unset($cw); + } + + function SetFont($family, $style = '', $size = 0, $write = true, $forcewrite = false) + { + $family = strtolower($family); + + if (!$this->onlyCoreFonts) { + if ($family == 'sans' || $family == 'sans-serif') { + $family = $this->sans_fonts[0]; + } + if ($family == 'serif') { + $family = $this->serif_fonts[0]; + } + if ($family == 'mono' || $family == 'monospace') { + $family = $this->mono_fonts[0]; + } + } + + if (isset($this->fonttrans[$family]) && $this->fonttrans[$family]) { + $family = $this->fonttrans[$family]; + } + + if ($family == '') { + if ($this->FontFamily) { + $family = $this->FontFamily; + } elseif ($this->default_font) { + $family = $this->default_font; + } else { + throw new \Mpdf\MpdfException("No font or default font set!"); + } + } + + $this->ReqFontStyle = $style; // required or requested style - used later for artificial bold/italic + + if (($family == 'csymbol') || ($family == 'czapfdingbats') || ($family == 'ctimes') || ($family == 'ccourier') || ($family == 'chelvetica')) { + if ($this->PDFA || $this->PDFX) { + if ($family == 'csymbol' || $family == 'czapfdingbats') { + throw new \Mpdf\MpdfException("Symbol and Zapfdingbats cannot be embedded in mPDF (required for PDFA1-b or PDFX/1-a)."); + } + if ($family == 'ctimes' || $family == 'ccourier' || $family == 'chelvetica') { + if (($this->PDFA && !$this->PDFAauto) || ($this->PDFX && !$this->PDFXauto)) { + $this->PDFAXwarnings[] = "Core Adobe font " . ucfirst($family) . " cannot be embedded in mPDF, which is required for PDFA1-b or PDFX/1-a. (Embedded font will be substituted.)"; + } + if ($family == 'chelvetica') { + $family = 'sans'; + } + if ($family == 'ctimes') { + $family = 'serif'; + } + if ($family == 'ccourier') { + $family = 'mono'; + } + } + $this->usingCoreFont = false; + } else { + $this->usingCoreFont = true; + } + if ($family == 'csymbol' || $family == 'czapfdingbats') { + $style = ''; + } + } else { + $this->usingCoreFont = false; + } + + // mPDF 5.7.1 + if ($style) { + $style = strtoupper($style); + if ($style == 'IB') { + $style = 'BI'; + } + } + if ($size == 0) { + $size = $this->FontSizePt; + } + + $fontkey = $family . $style; + + $stylekey = $style; + if (!$stylekey) { + $stylekey = "R"; + } + + if (!$this->onlyCoreFonts && !$this->usingCoreFont) { + if (!isset($this->fonts[$fontkey]) || count($this->default_available_fonts) != count($this->available_unifonts)) { // not already added + + /* -- CJK-FONTS -- */ + if (in_array($fontkey, $this->available_CJK_fonts)) { + if (!isset($this->fonts[$fontkey])) { // already added + if (empty($this->Big5_widths)) { + require __DIR__ . '/../data/CJKdata.php'; + } + $this->AddCJKFont($family); // don't need to add style + } + } else { // Test to see if requested font/style is available - or substitute /* -- END CJK-FONTS -- */ + if (!in_array($fontkey, $this->available_unifonts)) { + // If font[nostyle] exists - set it + if (in_array($family, $this->available_unifonts)) { + $style = ''; + } // elseif only one font available - set it (assumes if only one font available it will not have a style) + elseif (count($this->available_unifonts) == 1) { + $family = $this->available_unifonts[0]; + $style = ''; + } else { + $found = 0; + // else substitute font of similar type + if (in_array($family, $this->sans_fonts)) { + $i = array_intersect($this->sans_fonts, $this->available_unifonts); + if (count($i)) { + $i = array_values($i); + // with requested style if possible + if (!in_array(($i[0] . $style), $this->available_unifonts)) { + $style = ''; + } + $family = $i[0]; + $found = 1; + } + } elseif (in_array($family, $this->serif_fonts)) { + $i = array_intersect($this->serif_fonts, $this->available_unifonts); + if (count($i)) { + $i = array_values($i); + // with requested style if possible + if (!in_array(($i[0] . $style), $this->available_unifonts)) { + $style = ''; + } + $family = $i[0]; + $found = 1; + } + } elseif (in_array($family, $this->mono_fonts)) { + $i = array_intersect($this->mono_fonts, $this->available_unifonts); + if (count($i)) { + $i = array_values($i); + // with requested style if possible + if (!in_array(($i[0] . $style), $this->available_unifonts)) { + $style = ''; + } + $family = $i[0]; + $found = 1; + } + } + + if (!$found) { + // set first available font + $fs = $this->available_unifonts[0]; + preg_match('/^([a-z_0-9\-]+)([BI]{0,2})$/', $fs, $fas); // Allow "-" + // with requested style if possible + $ws = $fas[1] . $style; + if (in_array($ws, $this->available_unifonts)) { + $family = $fas[1]; // leave $style as is + } elseif (in_array($fas[1], $this->available_unifonts)) { + // or without style + $family = $fas[1]; + $style = ''; + } else { + // or with the style specified + $family = $fas[1]; + $style = $fas[2]; + } + } + } + $fontkey = $family . $style; + } + } + } + + // try to add font (if not already added) + $this->AddFont($family, $style); + + // Test if font is already selected + if ($this->FontFamily == $family && $this->FontFamily == $this->currentfontfamily && $this->FontStyle == $style && $this->FontStyle == $this->currentfontstyle && $this->FontSizePt == $size && $this->FontSizePt == $this->currentfontsize && !$forcewrite) { + return $family; + } + + $fontkey = $family . $style; + + // Select it + $this->FontFamily = $family; + $this->FontStyle = $style; + $this->FontSizePt = $size; + $this->FontSize = $size / Mpdf::SCALE; + $this->CurrentFont = &$this->fonts[$fontkey]; + if ($write) { + $fontout = (sprintf('BT /F%d %.3F Tf ET', $this->CurrentFont['i'], $this->FontSizePt)); + if ($this->page > 0 && ((isset($this->pageoutput[$this->page]['Font']) && $this->pageoutput[$this->page]['Font'] != $fontout) || !isset($this->pageoutput[$this->page]['Font']))) { + $this->writer->write($fontout); + } + $this->pageoutput[$this->page]['Font'] = $fontout; + } + + // Added - currentfont (lowercase) used in HTML2PDF + $this->currentfontfamily = $family; + $this->currentfontsize = $size; + $this->currentfontstyle = $style; + $this->setMBencoding('UTF-8'); + } else { // if using core fonts + if ($this->PDFA || $this->PDFX) { + throw new \Mpdf\MpdfException('Core Adobe fonts cannot be embedded in mPDF (required for PDFA1-b or PDFX/1-a) - cannot use option to use core fonts.'); + } + $this->setMBencoding('windows-1252'); + + // Test if font is already selected + if (($this->FontFamily == $family) and ( $this->FontStyle == $style) and ( $this->FontSizePt == $size) && !$forcewrite) { + return $family; + } + + if (!isset($this->CoreFonts[$fontkey])) { + if (in_array($family, $this->serif_fonts)) { + $family = 'ctimes'; + } elseif (in_array($family, $this->mono_fonts)) { + $family = 'ccourier'; + } else { + $family = 'chelvetica'; + } + $this->usingCoreFont = true; + $fontkey = $family . $style; + } + + if (!isset($this->fonts[$fontkey])) { + // STANDARD CORE FONTS + if (isset($this->CoreFonts[$fontkey])) { + // Load metric file + $file = $family; + if ($family == 'ctimes' || $family == 'chelvetica' || $family == 'ccourier') { + $file .= strtolower($style); + } + require __DIR__ . '/../data/font/' . $file . '.php'; + if (!isset($cw)) { + throw new \Mpdf\MpdfException(sprintf('Could not include font metric file "%s"', $file)); + } + $i = count($this->fonts) + $this->extraFontSubsets + 1; + $this->fonts[$fontkey] = ['i' => $i, 'type' => 'core', 'name' => $this->CoreFonts[$fontkey], 'desc' => $desc, 'up' => $up, 'ut' => $ut, 'cw' => $cw]; + if ($this->useKerning && isset($kerninfo)) { + $this->fonts[$fontkey]['kerninfo'] = $kerninfo; + } + } else { + throw new \Mpdf\MpdfException(sprintf('Font %s not defined', $fontkey)); + } + } + + // Test if font is already selected + if (($this->FontFamily == $family) and ( $this->FontStyle == $style) and ( $this->FontSizePt == $size) && !$forcewrite) { + return $family; + } + // Select it + $this->FontFamily = $family; + $this->FontStyle = $style; + $this->FontSizePt = $size; + $this->FontSize = $size / Mpdf::SCALE; + $this->CurrentFont = &$this->fonts[$fontkey]; + if ($write) { + $fontout = (sprintf('BT /F%d %.3F Tf ET', $this->CurrentFont['i'], $this->FontSizePt)); + if ($this->page > 0 && ((isset($this->pageoutput[$this->page]['Font']) && $this->pageoutput[$this->page]['Font'] != $fontout) || !isset($this->pageoutput[$this->page]['Font']))) { + $this->writer->write($fontout); + } + $this->pageoutput[$this->page]['Font'] = $fontout; + } + // Added - currentfont (lowercase) used in HTML2PDF + $this->currentfontfamily = $family; + $this->currentfontsize = $size; + $this->currentfontstyle = $style; + } + + return $family; + } + + function SetFontSize($size, $write = true) + { + // Set font size in points + if ($this->FontSizePt == $size) { + return; + } + $this->FontSizePt = $size; + $this->FontSize = $size / Mpdf::SCALE; + $this->currentfontsize = $size; + if ($write) { + $fontout = (sprintf('BT /F%d %.3F Tf ET', $this->CurrentFont['i'], $this->FontSizePt)); + // Edited mPDF 3.0 + if ($this->page > 0 && ((isset($this->pageoutput[$this->page]['Font']) && $this->pageoutput[$this->page]['Font'] != $fontout) || !isset($this->pageoutput[$this->page]['Font']))) { + $this->writer->write($fontout); + } + $this->pageoutput[$this->page]['Font'] = $fontout; + } + } + + function AddLink() + { + // Create a new internal link + $n = count($this->links) + 1; + $this->links[$n] = [0, 0]; + return $n; + } + + function SetLink($link, $y = 0, $page = -1) + { + // Set destination of internal link + if ($y == -1) { + $y = $this->y; + } + if ($page == -1) { + $page = $this->page; + } + $this->links[$link] = [$page, $y]; + } + + function Link($x, $y, $w, $h, $link) + { + $l = [$x * Mpdf::SCALE, $this->hPt - $y * Mpdf::SCALE, $w * Mpdf::SCALE, $h * Mpdf::SCALE, $link]; + if ($this->keep_block_together) { // don't write yet + return; + } elseif ($this->table_rotate) { // *TABLES* + $this->tbrot_Links[$this->page][] = $l; // *TABLES* + return; // *TABLES* + } // *TABLES* + elseif ($this->kwt) { + $this->kwt_Links[$this->page][] = $l; + return; + } + + if ($this->writingHTMLheader || $this->writingHTMLfooter) { + $this->HTMLheaderPageLinks[] = $l; + return; + } + // Put a link on the page + $this->PageLinks[$this->page][] = $l; + // Save cross-reference to Column buffer + $ref = count($this->PageLinks[$this->page]) - 1; // *COLUMNS* + $this->columnLinks[$this->CurrCol][(int) $this->x][(int) $this->y] = $ref; // *COLUMNS* + } + + function Text($x, $y, $txt, $OTLdata = [], $textvar = 0, $aixextra = '', $coordsys = '', $return = false) + { + // Output (or return) a string + // Called (internally) by Watermark() & _tableWrite() [rotated cells] & TableHeaderFooter() & WriteText() + // Called also from classes/svg.php + // Expects Font to be set + // Expects input to be mb_encoded if necessary and RTL reversed & OTL processed + // ARTIFICIAL BOLD AND ITALIC + $s = 'q '; + if ($this->falseBoldWeight && strpos($this->ReqFontStyle, "B") !== false && strpos($this->FontStyle, "B") === false) { + $s .= '2 Tr 1 J 1 j '; + $s .= sprintf('%.3F w ', ($this->FontSize / 130) * Mpdf::SCALE * $this->falseBoldWeight); + $tc = strtoupper($this->TextColor); // change 0 0 0 rg to 0 0 0 RG + if ($this->FillColor != $tc) { + $s .= $tc . ' '; + } // stroke (outline) = same colour as text(fill) + } + if (strpos($this->ReqFontStyle, "I") !== false && strpos($this->FontStyle, "I") === false) { + $aix = '1 0 0.261799 1 %.3F %.3F Tm'; + } else { + $aix = '%.3F %.3F Td'; + } + + $aix = $aixextra . $aix; + + if ($this->ColorFlag) { + $s .= $this->TextColor . ' '; + } + + $this->CurrentFont['used'] = true; + + if ($this->usingCoreFont) { + $txt2 = str_replace(chr(160), chr(32), $txt); + } else { + $txt2 = str_replace(chr(194) . chr(160), chr(32), $txt); + } + + $px = $x; + $py = $y; + if ($coordsys != 'SVG') { + $px = $x * Mpdf::SCALE; + $py = ($this->h - $y) * Mpdf::SCALE; + } + + + /** ************** SIMILAR TO Cell() ************************ */ + + // IF corefonts AND NOT SmCaps AND NOT Kerning + // Just output text + if ($this->usingCoreFont && !($textvar & TextVars::FC_SMALLCAPS) && !($textvar & TextVars::FC_KERNING)) { + $txt2 = $this->writer->escape($txt2); + $s .= sprintf('BT ' . $aix . ' (%s) Tj ET', $px, $py, $txt2); + } // IF NOT corefonts [AND NO wordspacing] AND NOT SIP/SMP AND NOT SmCaps AND NOT Kerning AND NOT OTL + // Just output text + elseif (!$this->usingCoreFont && !($textvar & TextVars::FC_SMALLCAPS) && !($textvar & TextVars::FC_KERNING) && !(isset($this->CurrentFont['useOTL']) && ($this->CurrentFont['useOTL'] & 0xFF) && !empty($OTLdata['GPOSinfo']))) { + // IF SIP/SMP + if ($this->CurrentFont['sip'] || $this->CurrentFont['smp']) { + $txt2 = $this->UTF8toSubset($txt2); + $s .=sprintf('BT ' . $aix . ' %s Tj ET', $px, $py, $txt2); + } // NOT SIP/SMP + else { + $txt2 = $this->writer->utf8ToUtf16BigEndian($txt2, false); + $txt2 = $this->writer->escape($txt2); + $s .=sprintf('BT ' . $aix . ' (%s) Tj ET', $px, $py, $txt2); + } + } // IF NOT corefonts [AND IS wordspacing] AND NOT SIP AND NOT SmCaps AND NOT Kerning AND NOT OTL + // Not required here (cf. Cell() ) + // ELSE (IF SmCaps || Kerning || OTL) [corefonts or not corefonts; SIP or SMP or BMP] + else { + $s .= $this->applyGPOSpdf($txt2, $aix, $px, $py, $OTLdata, $textvar); + } + /* * ************** END ************************ */ + + $s .= ' '; + + if (($textvar & TextVars::FD_UNDERLINE) && $txt != '') { // mPDF 5.7.1 + $c = strtoupper($this->TextColor); // change 0 0 0 rg to 0 0 0 RG + if ($this->FillColor != $c) { + $s.= ' ' . $c . ' '; + } + if (isset($this->CurrentFont['up']) && $this->CurrentFont['up']) { + $up = $this->CurrentFont['up']; + } else { + $up = -100; + } + $adjusty = (-$up / 1000 * $this->FontSize); + if (isset($this->CurrentFont['ut']) && $this->CurrentFont['ut']) { + $ut = $this->CurrentFont['ut'] / 1000 * $this->FontSize; + } else { + $ut = 60 / 1000 * $this->FontSize; + } + $olw = $this->LineWidth; + $s .= ' ' . (sprintf(' %.3F w', $ut * Mpdf::SCALE)); + $s .= ' ' . $this->_dounderline($x, $y + $adjusty, $txt, $OTLdata, $textvar); + $s .= ' ' . (sprintf(' %.3F w', $olw * Mpdf::SCALE)); + if ($this->FillColor != $c) { + $s.= ' ' . $this->FillColor . ' '; + } + } + // STRIKETHROUGH + if (($textvar & TextVars::FD_LINETHROUGH) && $txt != '') { // mPDF 5.7.1 + $c = strtoupper($this->TextColor); // change 0 0 0 rg to 0 0 0 RG + if ($this->FillColor != $c) { + $s.= ' ' . $c . ' '; + } + // Superscript and Subscript Y coordinate adjustment (now for striked-through texts) + if (isset($this->CurrentFont['desc']['CapHeight']) && $this->CurrentFont['desc']['CapHeight']) { + $ch = $this->CurrentFont['desc']['CapHeight']; + } else { + $ch = 700; + } + $adjusty = (-$ch / 1000 * $this->FontSize) * 0.35; + if (isset($this->CurrentFont['ut']) && $this->CurrentFont['ut']) { + $ut = $this->CurrentFont['ut'] / 1000 * $this->FontSize; + } else { + $ut = 60 / 1000 * $this->FontSize; + } + $olw = $this->LineWidth; + $s .= ' ' . (sprintf(' %.3F w', $ut * Mpdf::SCALE)); + $s .= ' ' . $this->_dounderline($x, $y + $adjusty, $txt, $OTLdata, $textvar); + $s .= ' ' . (sprintf(' %.3F w', $olw * Mpdf::SCALE)); + if ($this->FillColor != $c) { + $s.= ' ' . $this->FillColor . ' '; + } + } + $s .= 'Q'; + + if ($return) { + return $s . " \n"; + } + $this->writer->write($s); + } + + /* -- DIRECTW -- */ + + function WriteText($x, $y, $txt) + { + // Output a string using Text() but does encoding and text reversing of RTL + $txt = $this->purify_utf8_text($txt); + if ($this->text_input_as_HTML) { + $txt = $this->all_entities_to_utf8($txt); + } + if ($this->usingCoreFont) { + $txt = mb_convert_encoding($txt, $this->mb_enc, 'UTF-8'); + } + + // DIRECTIONALITY + if (preg_match("/([" . $this->pregRTLchars . "])/u", $txt)) { + $this->biDirectional = true; + } // *OTL* + + $textvar = 0; + $save_OTLtags = $this->OTLtags; + $this->OTLtags = []; + if ($this->useKerning) { + if ($this->CurrentFont['haskernGPOS']) { + $this->OTLtags['Plus'] .= ' kern'; + } else { + $textvar = ($textvar | TextVars::FC_KERNING); + } + } + + /* -- OTL -- */ + // Use OTL OpenType Table Layout - GSUB & GPOS + if (isset($this->CurrentFont['useOTL']) && $this->CurrentFont['useOTL']) { + $txt = $this->otl->applyOTL($txt, $this->CurrentFont['useOTL']); + $OTLdata = $this->otl->OTLdata; + } + /* -- END OTL -- */ + $this->OTLtags = $save_OTLtags; + + $this->magic_reverse_dir($txt, $this->directionality, $OTLdata); + + $this->Text($x, $y, $txt, $OTLdata, $textvar); + } + + function WriteCell($w, $h = 0, $txt = '', $border = 0, $ln = 0, $align = '', $fill = 0, $link = '', $currentx = 0) + { + // Output a cell using Cell() but does encoding and text reversing of RTL + $txt = $this->purify_utf8_text($txt); + if ($this->text_input_as_HTML) { + $txt = $this->all_entities_to_utf8($txt); + } + if ($this->usingCoreFont) { + $txt = mb_convert_encoding($txt, $this->mb_enc, 'UTF-8'); + } + // DIRECTIONALITY + if (preg_match("/([" . $this->pregRTLchars . "])/u", $txt)) { + $this->biDirectional = true; + } // *OTL* + + $textvar = 0; + $save_OTLtags = $this->OTLtags; + $this->OTLtags = []; + if ($this->useKerning) { + if ($this->CurrentFont['haskernGPOS']) { + $this->OTLtags['Plus'] .= ' kern'; + } else { + $textvar = ($textvar | TextVars::FC_KERNING); + } + } + + /* -- OTL -- */ + // Use OTL OpenType Table Layout - GSUB & GPOS + if (isset($this->CurrentFont['useOTL']) && $this->CurrentFont['useOTL']) { + $txt = $this->otl->applyOTL($txt, $this->CurrentFont['useOTL']); + $OTLdata = $this->otl->OTLdata; + } + /* -- END OTL -- */ + $this->OTLtags = $save_OTLtags; + + $this->magic_reverse_dir($txt, $this->directionality, $OTLdata); + + $this->Cell($w, $h, $txt, $border, $ln, $align, $fill, $link, $currentx, 0, 0, 'M', 0, false, $OTLdata, $textvar); + } + + /* -- END DIRECTW -- */ + + function ResetSpacing() + { + if ($this->ws != 0) { + $this->writer->write('BT 0 Tw ET'); + } + $this->ws = 0; + if ($this->charspacing != 0) { + $this->writer->write('BT 0 Tc ET'); + } + $this->charspacing = 0; + } + + function SetSpacing($cs, $ws) + { + if (intval($cs * 1000) == 0) { + $cs = 0; + } + if ($cs) { + $this->writer->write(sprintf('BT %.3F Tc ET', $cs)); + } elseif ($this->charspacing != 0) { + $this->writer->write('BT 0 Tc ET'); + } + $this->charspacing = $cs; + if (intval($ws * 1000) == 0) { + $ws = 0; + } + if ($ws) { + $this->writer->write(sprintf('BT %.3F Tw ET', $ws)); + } elseif ($this->ws != 0) { + $this->writer->write('BT 0 Tw ET'); + } + $this->ws = $ws; + } + + // WORD SPACING + function GetJspacing($nc, $ns, $w, $inclCursive, &$cOTLdata) + { + $kashida_present = false; + $kashida_space = 0; + if ($w > 0 && $inclCursive && isset($this->CurrentFont['useKashida']) && $this->CurrentFont['useKashida'] && !empty($cOTLdata)) { + for ($c = 0; $c < count($cOTLdata); $c++) { + for ($i = 0; $i < strlen($cOTLdata[$c]['group']); $i++) { + if (isset($cOTLdata[$c]['GPOSinfo'][$i]['kashida']) && $cOTLdata[$c]['GPOSinfo'][$i]['kashida'] > 0) { + $kashida_present = true; + break 2; + } + } + } + } + + if ($kashida_present) { + $k_ctr = 0; // Number of kashida points + $k_total = 0; // Total of kashida values (priority) + // Reset word + $max_kashida_in_word = 0; + $last_kashida_in_word = -1; + + for ($c = 0; $c < count($cOTLdata); $c++) { + for ($i = 0; $i < strlen($cOTLdata[$c]['group']); $i++) { + if ($cOTLdata[$c]['group'][$i] == 'S') { + // Save from last word + if ($max_kashida_in_word) { + $k_ctr++; + $k_total = $max_kashida_in_word; + } + // Reset word + $max_kashida_in_word = 0; + $last_kashida_in_word = -1; + } + + if (isset($cOTLdata[$c]['GPOSinfo'][$i]['kashida']) && $cOTLdata[$c]['GPOSinfo'][$i]['kashida'] > 0) { + if ($max_kashida_in_word) { + if ($cOTLdata[$c]['GPOSinfo'][$i]['kashida'] > $max_kashida_in_word) { + $max_kashida_in_word = $cOTLdata[$c]['GPOSinfo'][$i]['kashida']; + $cOTLdata[$c]['GPOSinfo'][$last_kashida_in_word]['kashida'] = 0; + $last_kashida_in_word = $i; + } else { + $cOTLdata[$c]['GPOSinfo'][$i]['kashida'] = 0; + } + } else { + $max_kashida_in_word = $cOTLdata[$c]['GPOSinfo'][$i]['kashida']; + $last_kashida_in_word = $i; + } + } + } + } + // Save from last word + if ($max_kashida_in_word) { + $k_ctr++; + $k_total = $max_kashida_in_word; + } + + // Number of kashida points = $k_ctr + // $useKashida is a % value from CurrentFont/config_fonts.php + // % ratio divided between word-spacing and kashida-spacing + $kashida_space_ratio = intval($this->CurrentFont['useKashida']) / 100; + + + $kashida_space = $w * $kashida_space_ratio; + + $tatw = $this->_getCharWidth($this->CurrentFont['cw'], 0x0640); + // Only use kashida if each allocated kashida width is > 0.01 x width of a tatweel + // Otherwise fontstretch is too small and errors + // If not just leave to adjust word-spacing + if ($tatw && (($kashida_space / $k_ctr) / $tatw) > 0.01) { + for ($c = 0; $c < count($cOTLdata); $c++) { + for ($i = 0; $i < strlen($cOTLdata[$c]['group']); $i++) { + if (isset($cOTLdata[$c]['GPOSinfo'][$i]['kashida']) && $cOTLdata[$c]['GPOSinfo'][$i]['kashida'] > 0) { + // At this point kashida is a number representing priority (higher number - higher priority) + // We are now going to set it as an actual length + // This shares it equally amongst words: + $cOTLdata[$c]['GPOSinfo'][$i]['kashida_space'] = (1 / $k_ctr) * $kashida_space; + } + } + } + $w -= $kashida_space; + } + } + + $ws = 0; + $charspacing = 0; + $ww = $this->jSWord; + $ncx = $nc - 1; + if ($nc == 0) { + return [0, 0, 0]; + } // Only word spacing allowed / possible + elseif ($this->fixedlSpacing !== false || $inclCursive) { + if ($ns) { + $ws = $w / $ns; + } + } elseif ($nc == 1) { + $charspacing = $w; + } elseif (!$ns) { + $charspacing = $w / ($ncx ); + if (($this->jSmaxChar > 0) && ($charspacing > $this->jSmaxChar)) { + $charspacing = $this->jSmaxChar; + } + } elseif ($ns == ($ncx )) { + $charspacing = $w / $ns; + } else { + if ($this->usingCoreFont) { + $cs = ($w * (1 - $this->jSWord)) / ($ncx ); + if (($this->jSmaxChar > 0) && ($cs > $this->jSmaxChar)) { + $cs = $this->jSmaxChar; + $ww = 1 - (($cs * ($ncx )) / $w); + } + $charspacing = $cs; + $ws = ($w * ($ww) ) / $ns; + } else { + $cs = ($w * (1 - $this->jSWord)) / ($ncx - $ns); + if (($this->jSmaxChar > 0) && ($cs > $this->jSmaxChar)) { + $cs = $this->jSmaxChar; + $ww = 1 - (($cs * ($ncx - $ns)) / $w); + } + $charspacing = $cs; + $ws = (($w * ($ww) ) / $ns) - $charspacing; + } + } + return [$charspacing, $ws, $kashida_space]; + } + + /** + * Output a cell + * + * Expects input to be mb_encoded if necessary and RTL reversed + * + * @since mPDF 5.7.1 + */ + function Cell($w, $h = 0, $txt = '', $border = 0, $ln = 0, $align = '', $fill = 0, $link = '', $currentx = 0, $lcpaddingL = 0, $lcpaddingR = 0, $valign = 'M', $spanfill = 0, $exactWidth = false, $OTLdata = false, $textvar = 0, $lineBox = false) + { + // NON_BREAKING SPACE + if ($this->usingCoreFont) { + $txt = str_replace(chr(160), chr(32), $txt); + } else { + $txt = str_replace(chr(194) . chr(160), chr(32), $txt); + } + + $oldcolumn = $this->CurrCol; + + // Automatic page break + // Allows PAGE-BREAK-AFTER = avoid to work + if (isset($this->blk[$this->blklvl])) { + $bottom = $this->blk[$this->blklvl]['padding_bottom'] + $this->blk[$this->blklvl]['margin_bottom']; + } else { + $bottom = 0; + } + + if (!$this->tableLevel + && ( + ($this->y + $this->divheight > $this->PageBreakTrigger) + || ($this->y + $h > $this->PageBreakTrigger) + || ( + $this->y + ($h * 2) + $bottom > $this->PageBreakTrigger + && $this->blk[$this->blklvl]['page_break_after_avoid'] + ) + ) + && !$this->InFooter + && $this->AcceptPageBreak() + ) { // mPDF 5.7.2 + + $x = $this->x; // Current X position + + // WORD SPACING + $ws = $this->ws; // Word Spacing + $charspacing = $this->charspacing; // Character Spacing + $this->ResetSpacing(); + + $this->AddPage($this->CurOrientation); + + // Added to correct for OddEven Margins + $x += $this->MarginCorrection; + if ($currentx) { + $currentx += $this->MarginCorrection; + } + $this->x = $x; + // WORD SPACING + $this->SetSpacing($charspacing, $ws); + } + + // Test: to put line through centre of cell: $this->Line($this->x,$this->y+($h/2),$this->x+50,$this->y+($h/2)); + // Test: to put border around cell as it is specified: $border='LRTB'; + + /* -- COLUMNS -- */ + // COLS + // COLUMN CHANGE + if ($this->CurrCol != $oldcolumn) { + if ($currentx) { + $currentx += $this->ChangeColumn * ($this->ColWidth + $this->ColGap); + } + $this->x += $this->ChangeColumn * ($this->ColWidth + $this->ColGap); + } + + // COLUMNS Update/overwrite the lowest bottom of printing y value for a column + if ($this->ColActive) { + if ($h) { + $this->ColDetails[$this->CurrCol]['bottom_margin'] = $this->y + $h; + } else { + $this->ColDetails[$this->CurrCol]['bottom_margin'] = $this->y + $this->divheight; + } + } + /* -- END COLUMNS -- */ + + + if ($w == 0) { + $w = $this->w - $this->rMargin - $this->x; + } + + $s = ''; + if ($fill == 1 && $this->FillColor) { + if ((isset($this->pageoutput[$this->page]['FillColor']) && $this->pageoutput[$this->page]['FillColor'] != $this->FillColor) || !isset($this->pageoutput[$this->page]['FillColor'])) { + $s .= $this->FillColor . ' '; + } + $this->pageoutput[$this->page]['FillColor'] = $this->FillColor; + } + + if ($lineBox && isset($lineBox['boxtop']) && $txt) { // i.e. always from WriteFlowingBlock/finishFlowingBlock (but not objects - + // which only have $lineBox['top'] set) + $boxtop = $this->y + $lineBox['boxtop']; + $boxbottom = $this->y + $lineBox['boxbottom']; + $glyphYorigin = $lineBox['glyphYorigin']; + $baseline_shift = $lineBox['baseline-shift']; + $bord_boxtop = $bg_boxtop = $boxtop = $boxtop - $baseline_shift; + $bord_boxbottom = $bg_boxbottom = $boxbottom = $boxbottom - $baseline_shift; + $bord_boxheight = $bg_boxheight = $boxheight = $boxbottom - $boxtop; + + // If inline element BACKGROUND has bounding box set by parent element: + if (isset($lineBox['background-boxtop'])) { + $bg_boxtop = $this->y + $lineBox['background-boxtop'] - $lineBox['background-baseline-shift']; + $bg_boxbottom = $this->y + $lineBox['background-boxbottom'] - $lineBox['background-baseline-shift']; + $bg_boxheight = $bg_boxbottom - $bg_boxtop; + } + // If inline element BORDER has bounding box set by parent element: + if (isset($lineBox['border-boxtop'])) { + $bord_boxtop = $this->y + $lineBox['border-boxtop'] - $lineBox['border-baseline-shift']; + $bord_boxbottom = $this->y + $lineBox['border-boxbottom'] - $lineBox['border-baseline-shift']; + $bord_boxheight = $bord_boxbottom - $bord_boxtop; + } + + } else { + + $boxtop = $this->y; + $boxheight = $h; + $boxbottom = $this->y + $h; + $baseline_shift = 0; + + if ($txt != '') { + + // FONT SIZE - this determines the baseline caculation + $bfs = $this->FontSize; + // Calculate baseline Superscript and Subscript Y coordinate adjustment + $bfx = $this->baselineC; + $baseline = $bfx * $bfs; + + if ($textvar & TextVars::FA_SUPERSCRIPT) { + $baseline_shift = $this->textparam['text-baseline']; + } elseif ($textvar & TextVars::FA_SUBSCRIPT) { + $baseline_shift = $this->textparam['text-baseline']; + } elseif ($this->bullet) { + $baseline += ($bfx - 0.7) * $this->FontSize; + } + + // Vertical align (for Images) + if ($valign == 'T') { + $va = (0.5 * $bfs * $this->normalLineheight); + } elseif ($valign == 'B') { + $va = $h - (0.5 * $bfs * $this->normalLineheight); + } else { + $va = 0.5 * $h; + } // Middle + + // ONLY SET THESE IF WANT TO CONFINE BORDER +/- FILL TO FIT FONTSIZE - NOT FULL CELL AS IS ORIGINAL FUNCTION + // spanfill or spanborder are set in FlowingBlock functions + if ($spanfill || !empty($this->spanborddet) || $link != '') { + $exth = 0.2; // Add to fontsize to increase height of background / link / border + $boxtop = $this->y + $baseline + $va - ($this->FontSize * (1 + $exth / 2) * (0.5 + $bfx)); + $boxheight = $this->FontSize * (1 + $exth); + $boxbottom = $boxtop + $boxheight; + } + + $glyphYorigin = $baseline + $va; + } + + $boxtop -= $baseline_shift; + $boxbottom -= $baseline_shift; + $bord_boxtop = $bg_boxtop = $boxtop; + $bord_boxbottom = $bg_boxbottom = $boxbottom; + $bord_boxheight = $bg_boxheight = $boxheight = $boxbottom - $boxtop; + } + + $bbw = $tbw = $lbw = $rbw = 0; // Border widths + if (!empty($this->spanborddet)) { + + if (!isset($this->spanborddet['B'])) { + $this->spanborddet['B'] = ['s' => 0, 'style' => '', 'w' => 0]; + } + + if (!isset($this->spanborddet['T'])) { + $this->spanborddet['T'] = ['s' => 0, 'style' => '', 'w' => 0]; + } + + if (!isset($this->spanborddet['L'])) { + $this->spanborddet['L'] = ['s' => 0, 'style' => '', 'w' => 0]; + } + + if (!isset($this->spanborddet['R'])) { + $this->spanborddet['R'] = ['s' => 0, 'style' => '', 'w' => 0]; + } + + $bbw = $this->spanborddet['B']['w']; + $tbw = $this->spanborddet['T']['w']; + $lbw = $this->spanborddet['L']['w']; + $rbw = $this->spanborddet['R']['w']; + } + + if ($fill == 1 || $border == 1 || !empty($this->spanborddet)) { + + if (!empty($this->spanborddet)) { + + if ($fill == 1) { + $s .= sprintf('%.3F %.3F %.3F %.3F re f ', ($this->x - $lbw) * Mpdf::SCALE, ($this->h - $bg_boxtop + $tbw) * Mpdf::SCALE, ($w + $lbw + $rbw) * Mpdf::SCALE, (-$bg_boxheight - $tbw - $bbw) * Mpdf::SCALE); + } + + $s.= ' q '; + $dashon = 3; + $dashoff = 3.5; + $dot = 2.5; + + if ($tbw) { + $short = 0; + + if ($this->spanborddet['T']['style'] == 'dashed') { + $s .= sprintf(' 0 j 0 J [%.3F %.3F] 0 d ', $tbw * $dashon * Mpdf::SCALE, $tbw * $dashoff * Mpdf::SCALE); + } elseif ($this->spanborddet['T']['style'] == 'dotted') { + $s .= sprintf(' 1 j 1 J [%.3F %.3F] %.3F d ', 0.001, $tbw * $dot * Mpdf::SCALE, -$tbw / 2 * Mpdf::SCALE); + $short = $tbw / 2; + } else { + $s .= ' 0 j 0 J [] 0 d '; + } + + if ($this->spanborddet['T']['style'] != 'dotted') { + $s .= 'q '; + $s .= sprintf('%.3F %.3F m ', ($this->x - $lbw) * Mpdf::SCALE, ($this->h - $bord_boxtop + $tbw) * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F l ', ($this->x + $w + $rbw) * Mpdf::SCALE, ($this->h - $bord_boxtop + $tbw) * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F l ', ($this->x + $w) * Mpdf::SCALE, ($this->h - $bord_boxtop) * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F l ', ($this->x) * Mpdf::SCALE, ($this->h - $bord_boxtop) * Mpdf::SCALE); + $s .= ' h W n '; // Ends path no-op & Sets the clipping path + } + + $c = $this->SetDColor($this->spanborddet['T']['c'], true); + + if ($this->spanborddet['T']['style'] == 'double') { + $s .= sprintf(' %s %.3F w ', $c, $tbw / 3 * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F m %.3F %.3F l S ', ($this->x - $lbw) * Mpdf::SCALE, ($this->h - $bord_boxtop + $tbw * 5 / 6) * Mpdf::SCALE, ($this->x + $w + $rbw) * Mpdf::SCALE, ($this->h - $bord_boxtop + $tbw * 5 / 6) * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F m %.3F %.3F l S ', ($this->x - $lbw) * Mpdf::SCALE, ($this->h - $bord_boxtop + $tbw / 6) * Mpdf::SCALE, ($this->x + $w + $rbw) * Mpdf::SCALE, ($this->h - $bord_boxtop + $tbw / 6) * Mpdf::SCALE); + } elseif ($this->spanborddet['T']['style'] == 'dotted') { + $s .= sprintf(' %s %.3F w ', $c, $tbw * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F m %.3F %.3F l S ', ($this->x - $lbw) * Mpdf::SCALE, ($this->h - $bord_boxtop + $tbw / 2) * Mpdf::SCALE, ($this->x + $w + $rbw - $short) * Mpdf::SCALE, ($this->h - $bord_boxtop + $tbw / 2) * Mpdf::SCALE); + } else { + $s .= sprintf(' %s %.3F w ', $c, $tbw * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F m %.3F %.3F l S ', ($this->x - $lbw) * Mpdf::SCALE, ($this->h - $bord_boxtop + $tbw / 2) * Mpdf::SCALE, ($this->x + $w + $rbw - $short) * Mpdf::SCALE, ($this->h - $bord_boxtop + $tbw / 2) * Mpdf::SCALE); + } + + if ($this->spanborddet['T']['style'] != 'dotted') { + $s .= ' Q '; + } + } + if ($bbw) { + + $short = 0; + if ($this->spanborddet['B']['style'] == 'dashed') { + $s .= sprintf(' 0 j 0 J [%.3F %.3F] 0 d ', $bbw * $dashon * Mpdf::SCALE, $bbw * $dashoff * Mpdf::SCALE); + } elseif ($this->spanborddet['B']['style'] == 'dotted') { + $s .= sprintf(' 1 j 1 J [%.3F %.3F] %.3F d ', 0.001, $bbw * $dot * Mpdf::SCALE, -$bbw / 2 * Mpdf::SCALE); + $short = $bbw / 2; + } else { + $s .= ' 0 j 0 J [] 0 d '; + } + + if ($this->spanborddet['B']['style'] != 'dotted') { + $s .= 'q '; + $s .= sprintf('%.3F %.3F m ', ($this->x - $lbw) * Mpdf::SCALE, ($this->h - $bord_boxbottom - $bbw) * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F l ', ($this->x + $w + $rbw) * Mpdf::SCALE, ($this->h - $bord_boxbottom - $bbw) * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F l ', ($this->x + $w) * Mpdf::SCALE, ($this->h - $bord_boxbottom) * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F l ', ($this->x) * Mpdf::SCALE, ($this->h - $bord_boxbottom) * Mpdf::SCALE); + $s .= ' h W n '; // Ends path no-op & Sets the clipping path + } + + $c = $this->SetDColor($this->spanborddet['B']['c'], true); + + if ($this->spanborddet['B']['style'] == 'double') { + $s .= sprintf(' %s %.3F w ', $c, $bbw / 3 * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F m %.3F %.3F l S ', ($this->x - $lbw) * Mpdf::SCALE, ($this->h - $bord_boxbottom - $bbw / 6) * Mpdf::SCALE, ($this->x + $w + $rbw - $short) * Mpdf::SCALE, ($this->h - $bord_boxbottom - $bbw / 6) * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F m %.3F %.3F l S ', ($this->x - $lbw) * Mpdf::SCALE, ($this->h - $bord_boxbottom - $bbw * 5 / 6) * Mpdf::SCALE, ($this->x + $w + $rbw - $short) * Mpdf::SCALE, ($this->h - $bord_boxbottom - $bbw * 5 / 6) * Mpdf::SCALE); + } elseif ($this->spanborddet['B']['style'] == 'dotted') { + $s .= sprintf(' %s %.3F w ', $c, $bbw * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F m %.3F %.3F l S ', ($this->x - $lbw) * Mpdf::SCALE, ($this->h - $bord_boxbottom - $bbw / 2) * Mpdf::SCALE, ($this->x + $w + $rbw - $short) * Mpdf::SCALE, ($this->h - $bord_boxbottom - $bbw / 2) * Mpdf::SCALE); + } else { + $s .= sprintf(' %s %.3F w ', $c, $bbw * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F m %.3F %.3F l S ', ($this->x - $lbw) * Mpdf::SCALE, ($this->h - $bord_boxbottom - $bbw / 2) * Mpdf::SCALE, ($this->x + $w + $rbw - $short) * Mpdf::SCALE, ($this->h - $bord_boxbottom - $bbw / 2) * Mpdf::SCALE); + } + + if ($this->spanborddet['B']['style'] != 'dotted') { + $s .= ' Q '; + } + } + + if ($lbw) { + $short = 0; + if ($this->spanborddet['L']['style'] == 'dashed') { + $s .= sprintf(' 0 j 0 J [%.3F %.3F] 0 d ', $lbw * $dashon * Mpdf::SCALE, $lbw * $dashoff * Mpdf::SCALE); + } elseif ($this->spanborddet['L']['style'] == 'dotted') { + $s .= sprintf(' 1 j 1 J [%.3F %.3F] %.3F d ', 0.001, $lbw * $dot * Mpdf::SCALE, -$lbw / 2 * Mpdf::SCALE); + $short = $lbw / 2; + } else { + $s .= ' 0 j 0 J [] 0 d '; + } + + if ($this->spanborddet['L']['style'] != 'dotted') { + $s .= 'q '; + $s .= sprintf('%.3F %.3F m ', ($this->x - $lbw) * Mpdf::SCALE, ($this->h - $bord_boxbottom - $bbw) * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F l ', ($this->x) * Mpdf::SCALE, ($this->h - $bord_boxbottom) * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F l ', ($this->x) * Mpdf::SCALE, ($this->h - $bord_boxtop) * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F l ', ($this->x - $lbw) * Mpdf::SCALE, ($this->h - $bord_boxtop + $tbw) * Mpdf::SCALE); + $s .= ' h W n '; // Ends path no-op & Sets the clipping path + } + + $c = $this->SetDColor($this->spanborddet['L']['c'], true); + if ($this->spanborddet['L']['style'] == 'double') { + $s .= sprintf(' %s %.3F w ', $c, $lbw / 3 * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F m %.3F %.3F l S ', ($this->x - $lbw / 6) * Mpdf::SCALE, ($this->h - $bord_boxtop + $tbw) * Mpdf::SCALE, ($this->x - $lbw / 6) * Mpdf::SCALE, ($this->h - $bord_boxbottom - $bbw + $short) * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F m %.3F %.3F l S ', ($this->x - $lbw * 5 / 6) * Mpdf::SCALE, ($this->h - $bord_boxtop + $tbw) * Mpdf::SCALE, ($this->x - $lbw * 5 / 6) * Mpdf::SCALE, ($this->h - $bord_boxbottom - $bbw + $short) * Mpdf::SCALE); + } elseif ($this->spanborddet['L']['style'] == 'dotted') { + $s .= sprintf(' %s %.3F w ', $c, $lbw * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F m %.3F %.3F l S ', ($this->x - $lbw / 2) * Mpdf::SCALE, ($this->h - $bord_boxtop + $tbw) * Mpdf::SCALE, ($this->x - $lbw / 2) * Mpdf::SCALE, ($this->h - $bord_boxbottom - $bbw + $short) * Mpdf::SCALE); + } else { + $s .= sprintf(' %s %.3F w ', $c, $lbw * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F m %.3F %.3F l S ', ($this->x - $lbw / 2) * Mpdf::SCALE, ($this->h - $bord_boxtop + $tbw) * Mpdf::SCALE, ($this->x - $lbw / 2) * Mpdf::SCALE, ($this->h - $bord_boxbottom - $bbw + $short) * Mpdf::SCALE); + } + + if ($this->spanborddet['L']['style'] != 'dotted') { + $s .= ' Q '; + } + } + + if ($rbw) { + + $short = 0; + if ($this->spanborddet['R']['style'] == 'dashed') { + $s .= sprintf(' 0 j 0 J [%.3F %.3F] 0 d ', $rbw * $dashon * Mpdf::SCALE, $rbw * $dashoff * Mpdf::SCALE); + } elseif ($this->spanborddet['R']['style'] == 'dotted') { + $s .= sprintf(' 1 j 1 J [%.3F %.3F] %.3F d ', 0.001, $rbw * $dot * Mpdf::SCALE, -$rbw / 2 * Mpdf::SCALE); + $short = $rbw / 2; + } else { + $s .= ' 0 j 0 J [] 0 d '; + } + + if ($this->spanborddet['R']['style'] != 'dotted') { + $s .= 'q '; + $s .= sprintf('%.3F %.3F m ', ($this->x + $w + $rbw) * Mpdf::SCALE, ($this->h - $bord_boxbottom - $bbw) * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F l ', ($this->x + $w) * Mpdf::SCALE, ($this->h - $bord_boxbottom) * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F l ', ($this->x + $w) * Mpdf::SCALE, ($this->h - $bord_boxtop) * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F l ', ($this->x + $w + $rbw) * Mpdf::SCALE, ($this->h - $bord_boxtop + $tbw) * Mpdf::SCALE); + $s .= ' h W n '; // Ends path no-op & Sets the clipping path + } + + $c = $this->SetDColor($this->spanborddet['R']['c'], true); + if ($this->spanborddet['R']['style'] == 'double') { + $s .= sprintf(' %s %.3F w ', $c, $rbw / 3 * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F m %.3F %.3F l S ', ($this->x + $w + $rbw / 6) * Mpdf::SCALE, ($this->h - $bord_boxtop + $tbw) * Mpdf::SCALE, ($this->x + $w + $rbw / 6) * Mpdf::SCALE, ($this->h - $bord_boxbottom - $bbw + $short) * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F m %.3F %.3F l S ', ($this->x + $w + $rbw * 5 / 6) * Mpdf::SCALE, ($this->h - $bord_boxtop + $tbw) * Mpdf::SCALE, ($this->x + $w + $rbw * 5 / 6) * Mpdf::SCALE, ($this->h - $bord_boxbottom - $bbw + $short) * Mpdf::SCALE); + } elseif ($this->spanborddet['R']['style'] == 'dotted') { + $s .= sprintf(' %s %.3F w ', $c, $rbw * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F m %.3F %.3F l S ', ($this->x + $w + $rbw / 2) * Mpdf::SCALE, ($this->h - $bord_boxtop + $tbw) * Mpdf::SCALE, ($this->x + $w + $rbw / 2) * Mpdf::SCALE, ($this->h - $bord_boxbottom - $bbw + $short) * Mpdf::SCALE); + } else { + $s .= sprintf(' %s %.3F w ', $c, $rbw * Mpdf::SCALE); + $s .= sprintf('%.3F %.3F m %.3F %.3F l S ', ($this->x + $w + $rbw / 2) * Mpdf::SCALE, ($this->h - $bord_boxtop + $tbw) * Mpdf::SCALE, ($this->x + $w + $rbw / 2) * Mpdf::SCALE, ($this->h - $bord_boxbottom - $bbw + $short) * Mpdf::SCALE); + } + + if ($this->spanborddet['R']['style'] != 'dotted') { + $s .= ' Q '; + } + } + + $s.= ' Q '; + + } else { // If "border", does not come from WriteFlowingBlock or FinishFlowingBlock + + if ($fill == 1) { + $op = ($border == 1) ? 'B' : 'f'; + } else { + $op = 'S'; + } + + $s .= sprintf('%.3F %.3F %.3F %.3F re %s ', $this->x * Mpdf::SCALE, ($this->h - $bg_boxtop) * Mpdf::SCALE, $w * Mpdf::SCALE, -$bg_boxheight * Mpdf::SCALE, $op); + } + } + + if (is_string($border)) { // If "border", does not come from WriteFlowingBlock or FinishFlowingBlock + + $x = $this->x; + $y = $this->y; + + if (is_int(strpos($border, 'L'))) { + $s .= sprintf('%.3F %.3F m %.3F %.3F l S ', $x * Mpdf::SCALE, ($this->h - $bord_boxtop) * Mpdf::SCALE, $x * Mpdf::SCALE, ($this->h - ($bord_boxbottom)) * Mpdf::SCALE); + } + + if (is_int(strpos($border, 'T'))) { + $s .= sprintf('%.3F %.3F m %.3F %.3F l S ', $x * Mpdf::SCALE, ($this->h - $bord_boxtop) * Mpdf::SCALE, ($x + $w) * Mpdf::SCALE, ($this->h - $bord_boxtop) * Mpdf::SCALE); + } + + if (is_int(strpos($border, 'R'))) { + $s .= sprintf('%.3F %.3F m %.3F %.3F l S ', ($x + $w) * Mpdf::SCALE, ($this->h - $bord_boxtop) * Mpdf::SCALE, ($x + $w) * Mpdf::SCALE, ($this->h - ($bord_boxbottom)) * Mpdf::SCALE); + } + + if (is_int(strpos($border, 'B'))) { + $s .= sprintf('%.3F %.3F m %.3F %.3F l S ', $x * Mpdf::SCALE, ($this->h - ($bord_boxbottom)) * Mpdf::SCALE, ($x + $w) * Mpdf::SCALE, ($this->h - ($bord_boxbottom)) * Mpdf::SCALE); + } + } + + if ($txt != '') { + + if ($exactWidth) { + $stringWidth = $w; + } else { + $stringWidth = $this->GetStringWidth($txt, true, $OTLdata, $textvar) + ( $this->charspacing * mb_strlen($txt, $this->mb_enc) / Mpdf::SCALE ) + ( $this->ws * mb_substr_count($txt, ' ', $this->mb_enc) / Mpdf::SCALE ); + } + + // Set x OFFSET FOR PRINTING + if ($align == 'R') { + $dx = $w - $this->cMarginR - $stringWidth - $lcpaddingR; + } elseif ($align == 'C') { + $dx = (($w - $stringWidth ) / 2); + } elseif ($align == 'L' or $align == 'J') { + $dx = $this->cMarginL + $lcpaddingL; + } else { + $dx = 0; + } + + if ($this->ColorFlag) { + $s .='q ' . $this->TextColor . ' '; + } + + // OUTLINE + if (isset($this->textparam['outline-s']) && $this->textparam['outline-s'] && !($textvar & TextVars::FC_SMALLCAPS)) { // mPDF 5.7.1 + $s .=' ' . sprintf('%.3F w', $this->LineWidth * Mpdf::SCALE) . ' '; + $s .=" $this->DrawColor "; + $s .=" 2 Tr "; + } elseif ($this->falseBoldWeight && strpos($this->ReqFontStyle, "B") !== false && strpos($this->FontStyle, "B") === false && !($textvar & TextVars::FC_SMALLCAPS)) { // can't use together with OUTLINE or Small Caps // mPDF 5.7.1 ??? why not with SmallCaps ??? + $s .= ' 2 Tr 1 J 1 j '; + $s .= ' ' . sprintf('%.3F w', ($this->FontSize / 130) * Mpdf::SCALE * $this->falseBoldWeight) . ' '; + $tc = strtoupper($this->TextColor); // change 0 0 0 rg to 0 0 0 RG + if ($this->FillColor != $tc) { + $s .= ' ' . $tc . ' '; + } // stroke (outline) = same colour as text(fill) + } else { + $s .=" 0 Tr "; + } + + if (strpos($this->ReqFontStyle, "I") !== false && strpos($this->FontStyle, "I") === false) { // Artificial italic + $aix = '1 0 0.261799 1 %.3F %.3F Tm '; + } else { + $aix = '%.3F %.3F Td '; + } + + $px = ($this->x + $dx) * Mpdf::SCALE; + $py = ($this->h - ($this->y + $glyphYorigin - $baseline_shift)) * Mpdf::SCALE; + + // THE TEXT + $txt2 = $txt; + $sub = ''; + $this->CurrentFont['used'] = true; + + /* * ************** SIMILAR TO Text() ************************ */ + + // IF corefonts AND NOT SmCaps AND NOT Kerning + // Just output text; charspacing and wordspacing already set by charspacing (Tc) and ws (Tw) + if ($this->usingCoreFont && !($textvar & TextVars::FC_SMALLCAPS) && !($textvar & TextVars::FC_KERNING)) { + $txt2 = $this->writer->escape($txt2); + $sub .= sprintf('BT ' . $aix . ' (%s) Tj ET', $px, $py, $txt2); + } // IF NOT corefonts AND NO wordspacing AND NOT SIP/SMP AND NOT SmCaps AND NOT Kerning AND NOT OTL + // Just output text + elseif (!$this->usingCoreFont && !$this->ws && !($textvar & TextVars::FC_SMALLCAPS) && !($textvar & TextVars::FC_KERNING) && !(isset($this->CurrentFont['useOTL']) && ($this->CurrentFont['useOTL'] & 0xFF) && !empty($OTLdata['GPOSinfo']))) { + // IF SIP/SMP + if ((isset($this->CurrentFont['sip']) && $this->CurrentFont['sip']) || (isset($this->CurrentFont['smp']) && $this->CurrentFont['smp'])) { + $txt2 = $this->UTF8toSubset($txt2); + $sub .=sprintf('BT ' . $aix . ' %s Tj ET', $px, $py, $txt2); + } // NOT SIP/SMP + else { + $txt2 = $this->writer->utf8ToUtf16BigEndian($txt2, false); + $txt2 = $this->writer->escape($txt2); + $sub .=sprintf('BT ' . $aix . ' (%s) Tj ET', $px, $py, $txt2); + } + } // IF NOT corefonts AND IS wordspacing AND NOT SIP AND NOT SmCaps AND NOT Kerning AND NOT OTL + // Output text word by word with an adjustment to the intercharacter spacing for SPACEs to form word spacing + // IF multibyte - Tw has no effect - need to do word spacing using an adjustment before each space + elseif (!$this->usingCoreFont && $this->ws && !((isset($this->CurrentFont['sip']) && $this->CurrentFont['sip']) || (isset($this->CurrentFont['smp']) && $this->CurrentFont['smp'])) && !($textvar & TextVars::FC_SMALLCAPS) && !($textvar & TextVars::FC_KERNING) && !(isset($this->CurrentFont['useOTL']) && ($this->CurrentFont['useOTL'] & 0xFF) && (!empty($OTLdata['GPOSinfo']) || (strpos($OTLdata['group'], 'M') !== false && $this->charspacing)) )) { + $space = " "; + $space = $this->writer->utf8ToUtf16BigEndian($space, false); + $space = $this->writer->escape($space); + $sub .=sprintf('BT ' . $aix . ' %.3F Tc [', $px, $py, $this->charspacing); + $t = explode(' ', $txt2); + $numt = count($t); + for ($i = 0; $i < $numt; $i++) { + $tx = $t[$i]; + $tx = $this->writer->utf8ToUtf16BigEndian($tx, false); + $tx = $this->writer->escape($tx); + $sub .=sprintf('(%s) ', $tx); + if (($i + 1) < $numt) { + $adj = -($this->ws) * 1000 / $this->FontSizePt; + $sub .=sprintf('%d(%s) ', $adj, $space); + } + } + $sub .='] TJ '; + $sub .=' ET'; + } // ELSE (IF SmCaps || Kerning || OTL) [corefonts or not corefonts; SIP or SMP or BMP] + else { + $sub = $this->applyGPOSpdf($txt, $aix, $px, $py, $OTLdata, $textvar); + } + + /** ************** END SIMILAR TO Text() ************************ */ + + if ($this->shrin_k > 1) { + $shrin_k = $this->shrin_k; + } else { + $shrin_k = 1; + } + + // UNDERLINE + if ($textvar & TextVars::FD_UNDERLINE) { // mPDF 5.7.1 // mPDF 6 + + // mPDF 5.7.3 inline text-decoration parameters + + $c = isset($this->textparam['u-decoration']['color']) ? $this->textparam['u-decoration']['color'] : ''; + if ($this->FillColor != $c) { + $sub .= ' ' . $c . ' '; + } + + // mPDF 5.7.3 inline text-decoration parameters + $decorationfontkey = isset($this->textparam['u-decoration']['fontkey']) ? $this->textparam['u-decoration']['fontkey'] : ''; + $decorationfontsize = isset($this->textparam['u-decoration']['fontsize']) ? $this->textparam['u-decoration']['fontsize'] / $shrin_k : 0; + + if (isset($this->fonts[$decorationfontkey]['ut']) && $this->fonts[$decorationfontkey]['ut']) { + $ut = $this->fonts[$decorationfontkey]['ut'] / 1000 * $decorationfontsize; + } else { + $ut = 60 / 1000 * $decorationfontsize; + } + + if (isset($this->fonts[$decorationfontkey]['up']) && $this->fonts[$decorationfontkey]['up']) { + $up = $this->fonts[$decorationfontkey]['up']; + } else { + $up = -100; + } + + $adjusty = (-$up / 1000 * $decorationfontsize) + $ut / 2; + $ubaseline = isset($this->textparam['u-decoration']['baseline']) + ? $glyphYorigin - $this->textparam['u-decoration']['baseline'] / $shrin_k + : $glyphYorigin; + + $olw = $this->LineWidth; + + $sub .= ' ' . (sprintf(' %.3F w 0 j 0 J ', $ut * Mpdf::SCALE)); + $sub .= ' ' . $this->_dounderline($this->x + $dx, $this->y + $ubaseline + $adjusty, $txt, $OTLdata, $textvar); + $sub .= ' ' . (sprintf(' %.3F w 2 j 2 J ', $olw * Mpdf::SCALE)); + + if ($this->FillColor != $c) { + $sub .= ' ' . $this->FillColor . ' '; + } + } + + // STRIKETHROUGH + if ($textvar & TextVars::FD_LINETHROUGH) { // mPDF 5.7.1 // mPDF 6 + + // mPDF 5.7.3 inline text-decoration parameters + $c = $this->textparam['s-decoration']['color']; + + if ($this->FillColor != $c) { + $sub .= ' ' . $c . ' '; + } + + // mPDF 5.7.3 inline text-decoration parameters + $decorationfontkey = $this->textparam['s-decoration']['fontkey']; + $decorationfontsize = $this->textparam['s-decoration']['fontsize'] / $shrin_k; + + // Use yStrikeoutSize from OS/2 if available + if (isset($this->fonts[$decorationfontkey]['strs']) && $this->fonts[$decorationfontkey]['strs']) { + $ut = $this->fonts[$decorationfontkey]['strs'] / 1000 * $decorationfontsize; + } // else use underlineThickness from post if available + elseif (isset($this->fonts[$decorationfontkey]['ut']) && $this->fonts[$decorationfontkey]['ut']) { + $ut = $this->fonts[$decorationfontkey]['ut'] / 1000 * $decorationfontsize; + } else { + $ut = 50 / 1000 * $decorationfontsize; + } + + // Use yStrikeoutPosition from OS/2 if available + if (isset($this->fonts[$decorationfontkey]['strp']) && $this->fonts[$decorationfontkey]['strp']) { + $up = $this->fonts[$decorationfontkey]['strp']; + $adjusty = (-$up / 1000 * $decorationfontsize); + } // else use a fraction ($this->baselineS) of CapHeight + else { + if (isset($this->fonts[$decorationfontkey]['desc']['CapHeight']) && $this->fonts[$decorationfontkey]['desc']['CapHeight']) { + $ch = $this->fonts[$decorationfontkey]['desc']['CapHeight']; + } else { + $ch = 700; + } + $adjusty = (-$ch / 1000 * $decorationfontsize) * $this->baselineS; + } + + $sbaseline = $glyphYorigin - $this->textparam['s-decoration']['baseline'] / $shrin_k; + + $olw = $this->LineWidth; + + $sub .=' ' . (sprintf(' %.3F w 0 j 0 J ', $ut * Mpdf::SCALE)); + $sub .=' ' . $this->_dounderline($this->x + $dx, $this->y + $sbaseline + $adjusty, $txt, $OTLdata, $textvar); + $sub .=' ' . (sprintf(' %.3F w 2 j 2 J ', $olw * Mpdf::SCALE)); + + if ($this->FillColor != $c) { + $sub .= ' ' . $this->FillColor . ' '; + } + } + + // mPDF 5.7.3 inline text-decoration parameters + // OVERLINE + if ($textvar & TextVars::FD_OVERLINE) { // mPDF 5.7.1 // mPDF 6 + // mPDF 5.7.3 inline text-decoration parameters + $c = $this->textparam['o-decoration']['color']; + if ($this->FillColor != $c) { + $sub .= ' ' . $c . ' '; + } + + // mPDF 5.7.3 inline text-decoration parameters + $decorationfontkey = (int) (((float) $this->textparam['o-decoration']['fontkey']) / $shrin_k); + $decorationfontsize = $this->textparam['o-decoration']['fontsize']; + + if (isset($this->fonts[$decorationfontkey]['ut']) && $this->fonts[$decorationfontkey]['ut']) { + $ut = $this->fonts[$decorationfontkey]['ut'] / 1000 * $decorationfontsize; + } else { + $ut = 60 / 1000 * $decorationfontsize; + } + if (isset($this->fonts[$decorationfontkey]['desc']['CapHeight']) && $this->fonts[$decorationfontkey]['desc']['CapHeight']) { + $ch = $this->fonts[$decorationfontkey]['desc']['CapHeight']; + } else { + $ch = 700; + } + $adjusty = (-$ch / 1000 * $decorationfontsize) * $this->baselineO; + $obaseline = $glyphYorigin - $this->textparam['o-decoration']['baseline'] / $shrin_k; + $olw = $this->LineWidth; + $sub .=' ' . (sprintf(' %.3F w 0 j 0 J ', $ut * Mpdf::SCALE)); + $sub .=' ' . $this->_dounderline($this->x + $dx, $this->y + $obaseline + $adjusty, $txt, $OTLdata, $textvar); + $sub .=' ' . (sprintf(' %.3F w 2 j 2 J ', $olw * Mpdf::SCALE)); + if ($this->FillColor != $c) { + $sub .= ' ' . $this->FillColor . ' '; + } + } + + // TEXT SHADOW + if ($this->textshadow) { // First to process is last in CSS comma separated shadows + foreach ($this->textshadow as $ts) { + $s .= ' q '; + $s .= $this->SetTColor($ts['col'], true) . "\n"; + if ($ts['col'][0] == 5 && ord($ts['col'][4]) < 100) { // RGBa + $s .= $this->SetAlpha(ord($ts['col'][4]) / 100, 'Normal', true, 'F') . "\n"; + } elseif ($ts['col'][0] == 6 && ord($ts['col'][5]) < 100) { // CMYKa + $s .= $this->SetAlpha(ord($ts['col'][5]) / 100, 'Normal', true, 'F') . "\n"; + } elseif ($ts['col'][0] == 1 && $ts['col'][2] == 1 && ord($ts['col'][3]) < 100) { // Gray + $s .= $this->SetAlpha(ord($ts['col'][3]) / 100, 'Normal', true, 'F') . "\n"; + } + $s .= sprintf(' 1 0 0 1 %.4F %.4F cm', $ts['x'] * Mpdf::SCALE, -$ts['y'] * Mpdf::SCALE) . "\n"; + $s .= $sub; + $s .= ' Q '; + } + } + + $s .= $sub; + + // COLOR + if ($this->ColorFlag) { + $s .=' Q'; + } + + // LINK + if ($link != '') { + $this->Link($this->x, $boxtop, $w, $boxheight, $link); + } + } + if ($s) { + $this->writer->write($s); + } + + // WORD SPACING + if ($this->ws && !$this->usingCoreFont) { + $this->writer->write(sprintf('BT %.3F Tc ET', $this->charspacing)); + } + $this->lasth = $h; + if (strpos($txt, "\n") !== false) { + $ln = 1; // cell recognizes \n from
    tag + } + if ($ln > 0) { + // Go to next line + $this->y += $h; + if ($ln == 1) { + // Move to next line + if ($currentx != 0) { + $this->x = $currentx; + } else { + $this->x = $this->lMargin; + } + } + } else { + $this->x+=$w; + } + } + + function applyGPOSpdf($txt, $aix, $x, $y, $OTLdata, $textvar = 0) + { + // Generate PDF string + // ============================== + if ((isset($this->CurrentFont['sip']) && $this->CurrentFont['sip']) || (isset($this->CurrentFont['smp']) && $this->CurrentFont['smp'])) { + $sipset = true; + } else { + $sipset = false; + } + + if ($textvar & TextVars::FC_SMALLCAPS) { + $smcaps = true; + } // IF SmallCaps using transformation, NOT OTL + else { + $smcaps = false; + } + + if ($sipset) { + $fontid = $last_fontid = $original_fontid = $this->CurrentFont['subsetfontids'][0]; + } else { + $fontid = $last_fontid = $original_fontid = $this->CurrentFont['i']; + } + $SmallCapsON = false; // state: uppercase/not + $lastSmallCapsON = false; // state: uppercase/not + $last_fontsize = $fontsize = $this->FontSizePt; + $last_fontstretch = $fontstretch = 100; + $groupBreak = false; + + $unicode = $this->UTF8StringToArray($txt); + + $GPOSinfo = (isset($OTLdata['GPOSinfo']) ? $OTLdata['GPOSinfo'] : []); + $charspacing = ($this->charspacing * 1000 / $this->FontSizePt); + $wordspacing = ($this->ws * 1000 / $this->FontSizePt); + + $XshiftBefore = 0; + $XshiftAfter = 0; + $lastYPlacement = 0; + + if ($sipset) { + // mPDF 6 DELETED ******** + // $txt= preg_replace('/'.preg_quote($this->aliasNbPg,'/').'/', chr(7), $txt); // ? Need to adjust OTL info + // $txt= preg_replace('/'.preg_quote($this->aliasNbPgGp,'/').'/', chr(8), $txt); // ? Need to adjust OTL info + $tj = '<'; + } else { + $tj = '('; + } + + for ($i = 0; $i < count($unicode); $i++) { + $c = $unicode[$i]; + $tx = ''; + $XshiftBefore = $XshiftAfter; + $XshiftAfter = 0; + $YPlacement = 0; + $groupBreak = false; + $kashida = 0; + if (!empty($OTLdata)) { + // YPlacement from GPOS + if (isset($GPOSinfo[$i]['YPlacement']) && $GPOSinfo[$i]['YPlacement']) { + $YPlacement = $GPOSinfo[$i]['YPlacement'] * $this->FontSizePt / $this->CurrentFont['unitsPerEm']; + $groupBreak = true; + } + // XPlacement from GPOS + if (isset($GPOSinfo[$i]['XPlacement']) && $GPOSinfo[$i]['XPlacement']) { + if (!isset($GPOSinfo[$i]['wDir']) || $GPOSinfo[$i]['wDir'] != 'RTL') { + if (isset($GPOSinfo[$i]['BaseWidth'])) { + $GPOSinfo[$i]['XPlacement'] -= $GPOSinfo[$i]['BaseWidth']; + } + } + + // Convert to PDF Text space (thousandths of a unit ); + $XshiftBefore += $GPOSinfo[$i]['XPlacement'] * 1000 / $this->CurrentFont['unitsPerEm']; + $XshiftAfter += -$GPOSinfo[$i]['XPlacement'] * 1000 / $this->CurrentFont['unitsPerEm']; + } + + // Kashida from GPOS + // Kashida is set as an absolute length value, but to adjust text needs to be converted to + // font-related size + if (isset($GPOSinfo[$i]['kashida_space']) && $GPOSinfo[$i]['kashida_space']) { + $kashida = $GPOSinfo[$i]['kashida_space']; + } + + if ($c == 32) { // word spacing + $XshiftAfter += $wordspacing; + } + + if (substr($OTLdata['group'], ($i + 1), 1) != 'M') { // Don't add inter-character spacing before Marks + $XshiftAfter += $charspacing; + } + + // ...applyGPOSpdf... + // XAdvance from GPOS - Convert to PDF Text space (thousandths of a unit ); + if (((isset($GPOSinfo[$i]['wDir']) && $GPOSinfo[$i]['wDir'] != 'RTL') || !isset($GPOSinfo[$i]['wDir'])) && isset($GPOSinfo[$i]['XAdvanceL']) && $GPOSinfo[$i]['XAdvanceL']) { + $XshiftAfter += $GPOSinfo[$i]['XAdvanceL'] * 1000 / $this->CurrentFont['unitsPerEm']; + } elseif (isset($GPOSinfo[$i]['wDir']) && $GPOSinfo[$i]['wDir'] == 'RTL' && isset($GPOSinfo[$i]['XAdvanceR']) && $GPOSinfo[$i]['XAdvanceR']) { + $XshiftAfter += $GPOSinfo[$i]['XAdvanceR'] * 1000 / $this->CurrentFont['unitsPerEm']; + } + } // Character & Word spacing - if NOT OTL + else { + $XshiftAfter += $charspacing; + if ($c == 32) { + $XshiftAfter += $wordspacing; + } + } + + // IF Kerning done using pairs rather than OTL + if ($textvar & TextVars::FC_KERNING) { + if ($i > 0 && isset($this->CurrentFont['kerninfo'][$unicode[($i - 1)]][$unicode[$i]])) { + $XshiftBefore += $this->CurrentFont['kerninfo'][$unicode[($i - 1)]][$unicode[$i]]; + } + } + + if ($YPlacement != $lastYPlacement) { + $groupBreak = true; + } + + if ($XshiftBefore) { // +ve value in PDF moves to the left + // If Fontstretch is ongoing, need to adjust X adjustments because these will be stretched out. + $XshiftBefore *= 100 / $last_fontstretch; + if ($sipset) { + $tj .= sprintf('>%d<', (-$XshiftBefore)); + } else { + $tj .= sprintf(')%d(', (-$XshiftBefore)); + } + } + + // Small-Caps + if ($smcaps) { + if (isset($this->upperCase[$c])) { + $c = $this->upperCase[$c]; + // $this->CurrentFont['subset'][$this->upperCase[$c]] = $this->upperCase[$c]; // add the CAP to subset + $SmallCapsON = true; + // For $sipset + if (!$lastSmallCapsON) { // Turn ON SmallCaps + $groupBreak = true; + $fontstretch = $this->smCapsStretch; + $fontsize = $this->FontSizePt * $this->smCapsScale; + } + } else { + $SmallCapsON = false; + if ($lastSmallCapsON) { // Turn OFF SmallCaps + $groupBreak = true; + $fontstretch = 100; + $fontsize = $this->FontSizePt; + } + } + } + + // Prepare Text and Select Font ID + if ($sipset) { + // mPDF 6 DELETED ******** + // if ($c == 7 || $c == 8) { + // if ($original_fontid != $last_fontid) { + // $groupBreak = true; + // $fontid = $original_fontid; + // } + // if ($c == 7) { $tj .= $this->aliasNbPgHex; } + // else { $tj .= $this->aliasNbPgGpHex; } + // continue; + // } + for ($j = 0; $j < 99; $j++) { + $init = array_search($c, $this->CurrentFont['subsets'][$j]); + if ($init !== false) { + if ($this->CurrentFont['subsetfontids'][$j] != $last_fontid) { + $groupBreak = true; + $fontid = $this->CurrentFont['subsetfontids'][$j]; + } + $tx = sprintf("%02s", strtoupper(dechex($init))); + break; + } elseif (count($this->CurrentFont['subsets'][$j]) < 255) { + $n = count($this->CurrentFont['subsets'][$j]); + $this->CurrentFont['subsets'][$j][$n] = $c; + if ($this->CurrentFont['subsetfontids'][$j] != $last_fontid) { + $groupBreak = true; + $fontid = $this->CurrentFont['subsetfontids'][$j]; + } + $tx = sprintf("%02s", strtoupper(dechex($n))); + break; + } elseif (!isset($this->CurrentFont['subsets'][($j + 1)])) { + $this->CurrentFont['subsets'][($j + 1)] = [0 => 0]; + $this->CurrentFont['subsetfontids'][($j + 1)] = count($this->fonts) + $this->extraFontSubsets + 1; + $this->extraFontSubsets++; + } + } + } else { + $tx = UtfString::code2utf($c); + if ($this->usingCoreFont) { + $tx = utf8_decode($tx); + } else { + $tx = $this->writer->utf8ToUtf16BigEndian($tx, false); + } + $tx = $this->writer->escape($tx); + } + + // If any settings require a new Text Group + if ($groupBreak || $fontstretch != $last_fontstretch) { + if ($sipset) { + $tj .= '>] TJ '; + } else { + $tj .= ')] TJ '; + } + if ($fontid != $last_fontid || $fontsize != $last_fontsize) { + $tj .= sprintf(' /F%d %.3F Tf ', $fontid, $fontsize); + } + if ($fontstretch != $last_fontstretch) { + $tj .= sprintf('%d Tz ', $fontstretch); + } + if ($YPlacement != $lastYPlacement) { + $tj .= sprintf('%.3F Ts ', $YPlacement); + } + if ($sipset) { + $tj .= '[<'; + } else { + $tj .= '[('; + } + } + + // Output the code for the txt character + $tj .= $tx; + $lastSmallCapsON = $SmallCapsON; + $last_fontid = $fontid; + $last_fontsize = $fontsize; + $last_fontstretch = $fontstretch; + + // Kashida + if ($kashida) { + $c = 0x0640; // add the Tatweel U+0640 + if (isset($this->CurrentFont['subset'])) { + $this->CurrentFont['subset'][$c] = $c; + } + $kashida *= 1000 / $this->FontSizePt; + $tatw = $this->_getCharWidth($this->CurrentFont['cw'], 0x0640); + + // Get YPlacement from next Base character + $nextbase = $i + 1; + while ($OTLdata['group'][$nextbase] != 'C') { + $nextbase++; + } + if (isset($GPOSinfo[$nextbase]) && isset($GPOSinfo[$nextbase]['YPlacement']) && $GPOSinfo[$nextbase]['YPlacement']) { + $YPlacement = $GPOSinfo[$nextbase]['YPlacement'] * $this->FontSizePt / $this->CurrentFont['unitsPerEm']; + } + + // Prepare Text and Select Font ID + if ($sipset) { + for ($j = 0; $j < 99; $j++) { + $init = array_search($c, $this->CurrentFont['subsets'][$j]); + if ($init !== false) { + if ($this->CurrentFont['subsetfontids'][$j] != $last_fontid) { + $fontid = $this->CurrentFont['subsetfontids'][$j]; + } + $tx = sprintf("%02s", strtoupper(dechex($init))); + break; + } elseif (count($this->CurrentFont['subsets'][$j]) < 255) { + $n = count($this->CurrentFont['subsets'][$j]); + $this->CurrentFont['subsets'][$j][$n] = $c; + if ($this->CurrentFont['subsetfontids'][$j] != $last_fontid) { + $fontid = $this->CurrentFont['subsetfontids'][$j]; + } + $tx = sprintf("%02s", strtoupper(dechex($n))); + break; + } elseif (!isset($this->CurrentFont['subsets'][($j + 1)])) { + $this->CurrentFont['subsets'][($j + 1)] = [0 => 0]; + $this->CurrentFont['subsetfontids'][($j + 1)] = count($this->fonts) + $this->extraFontSubsets + 1; + $this->extraFontSubsets++; + } + } + } else { + $tx = UtfString::code2utf($c); + $tx = $this->writer->utf8ToUtf16BigEndian($tx, false); + $tx = $this->writer->escape($tx); + } + + if ($kashida > $tatw) { + // Insert multiple tatweel characters, repositioning the last one to give correct total length + $fontstretch = 100; + $nt = intval($kashida / $tatw); + $nudgeback = (($nt + 1) * $tatw) - $kashida; + $optx = str_repeat($tx, $nt); + if ($sipset) { + $optx .= sprintf('>%d<', ($nudgeback)); + } else { + $optx .= sprintf(')%d(', ($nudgeback)); + } + $optx .= $tx; // #last + } else { + // Insert single tatweel character and use fontstretch to get correct length + $fontstretch = ($kashida / $tatw) * 100; + $optx = $tx; + } + + if ($sipset) { + $tj .= '>] TJ '; + } else { + $tj .= ')] TJ '; + } + if ($fontid != $last_fontid || $fontsize != $last_fontsize) { + $tj .= sprintf(' /F%d %.3F Tf ', $fontid, $fontsize); + } + if ($fontstretch != $last_fontstretch) { + $tj .= sprintf('%d Tz ', $fontstretch); + } + $tj .= sprintf('%.3F Ts ', $YPlacement); + if ($sipset) { + $tj .= '[<'; + } else { + $tj .= '[('; + } + + // Output the code for the txt character(s) + $tj .= $optx; + $last_fontid = $fontid; + $last_fontstretch = $fontstretch; + $fontstretch = 100; + } + + $lastYPlacement = $YPlacement; + } + + + // Finish up + if ($sipset) { + $tj .= '>'; + if ($XshiftAfter) { + $tj .= sprintf('%d', (-$XshiftAfter)); + } + if ($last_fontid != $original_fontid) { + $tj .= '] TJ '; + $tj .= sprintf(' /F%d %.3F Tf ', $original_fontid, $fontsize); + $tj .= '['; + } + $tj = preg_replace('/([^\\\])<>/', '\\1 ', $tj); + } else { + $tj .= ')'; + if ($XshiftAfter) { + $tj .= sprintf('%d', (-$XshiftAfter)); + } + if ($last_fontid != $original_fontid) { + $tj .= '] TJ '; + $tj .= sprintf(' /F%d %.3F Tf ', $original_fontid, $fontsize); + $tj .= '['; + } + $tj = preg_replace('/([^\\\])\(\)/', '\\1 ', $tj); + } + + $s = sprintf(' BT ' . $aix . ' 0 Tc 0 Tw [%s] TJ ET ', $x, $y, $tj); + + // echo $s."\n\n"; // exit; + + return $s; + } + + function _kern($txt, $mode, $aix, $x, $y) + { + if ($mode == 'MBTw') { // Multibyte requiring word spacing + $space = ' '; + // Convert string to UTF-16BE without BOM + $space = $this->writer->utf8ToUtf16BigEndian($space, false); + $space = $this->writer->escape($space); + $s = sprintf(' BT ' . $aix, $x * Mpdf::SCALE, ($this->h - $y) * Mpdf::SCALE); + $t = explode(' ', $txt); + for ($i = 0; $i < count($t); $i++) { + $tx = $t[$i]; + + $tj = '('; + $unicode = $this->UTF8StringToArray($tx); + for ($ti = 0; $ti < count($unicode); $ti++) { + if ($ti > 0 && isset($this->CurrentFont['kerninfo'][$unicode[($ti - 1)]][$unicode[$ti]])) { + $kern = -$this->CurrentFont['kerninfo'][$unicode[($ti - 1)]][$unicode[$ti]]; + $tj .= sprintf(')%d(', $kern); + } + $tc = UtfString::code2utf($unicode[$ti]); + $tc = $this->writer->utf8ToUtf16BigEndian($tc, false); + $tj .= $this->writer->escape($tc); + } + $tj .= ')'; + $s .= sprintf(' %.3F Tc [%s] TJ', $this->charspacing, $tj); + + + if (($i + 1) < count($t)) { + $s .= sprintf(' %.3F Tc (%s) Tj', $this->ws + $this->charspacing, $space); + } + } + $s .= ' ET '; + } elseif (!$this->usingCoreFont) { + $s = ''; + $tj = '('; + $unicode = $this->UTF8StringToArray($txt); + for ($i = 0; $i < count($unicode); $i++) { + if ($i > 0 && isset($this->CurrentFont['kerninfo'][$unicode[($i - 1)]][$unicode[$i]])) { + $kern = -$this->CurrentFont['kerninfo'][$unicode[($i - 1)]][$unicode[$i]]; + $tj .= sprintf(')%d(', $kern); + } + $tx = UtfString::code2utf($unicode[$i]); + $tx = $this->writer->utf8ToUtf16BigEndian($tx, false); + $tj .= $this->writer->escape($tx); + } + $tj .= ')'; + $s .= sprintf(' BT ' . $aix . ' [%s] TJ ET ', $x * Mpdf::SCALE, ($this->h - $y) * Mpdf::SCALE, $tj); + } else { // CORE Font + $s = ''; + $tj = '('; + $l = strlen($txt); + for ($i = 0; $i < $l; $i++) { + if ($i > 0 && isset($this->CurrentFont['kerninfo'][$txt[($i - 1)]][$txt[$i]])) { + $kern = -$this->CurrentFont['kerninfo'][$txt[($i - 1)]][$txt[$i]]; + $tj .= sprintf(')%d(', $kern); + } + $tj .= $this->writer->escape($txt[$i]); + } + $tj .= ')'; + $s .= sprintf(' BT ' . $aix . ' [%s] TJ ET ', $x * Mpdf::SCALE, ($this->h - $y) * Mpdf::SCALE, $tj); + } + + return $s; + } + + function MultiCell($w, $h, $txt, $border = 0, $align = '', $fill = 0, $link = '', $directionality = 'ltr', $encoded = false, $OTLdata = false, $maxrows = false) + { + // maxrows is called from mpdfform->TEXTAREA + // Parameter (pre-)encoded - When called internally from form::textarea - mb_encoding already done and OTL - but not reverse RTL + if (!$encoded) { + $txt = $this->purify_utf8_text($txt); + if ($this->text_input_as_HTML) { + $txt = $this->all_entities_to_utf8($txt); + } + if ($this->usingCoreFont) { + $txt = mb_convert_encoding($txt, $this->mb_enc, 'UTF-8'); + } + if (preg_match("/([" . $this->pregRTLchars . "])/u", $txt)) { + $this->biDirectional = true; + } // *OTL* + /* -- OTL -- */ + $OTLdata = []; + // Use OTL OpenType Table Layout - GSUB & GPOS + if (isset($this->CurrentFont['useOTL']) && $this->CurrentFont['useOTL']) { + $txt = $this->otl->applyOTL($txt, $this->CurrentFont['useOTL']); + $OTLdata = $this->otl->OTLdata; + } + if ($directionality == 'rtl' || $this->biDirectional) { + if (!isset($OTLdata)) { + $unicode = $this->UTF8StringToArray($txt, false); + $is_strong = false; + $this->getBasicOTLdata($OTLdata, $unicode, $is_strong); + } + } + /* -- END OTL -- */ + } + if (!$align) { + $align = $this->defaultAlign; + } + + // Output text with automatic or explicit line breaks + $cw = &$this->CurrentFont['cw']; + if ($w == 0) { + $w = $this->w - $this->rMargin - $this->x; + } + + $wmax = ($w - ($this->cMarginL + $this->cMarginR)); + if ($this->usingCoreFont) { + $s = str_replace("\r", '', $txt); + $nb = strlen($s); + while ($nb > 0 and $s[$nb - 1] == "\n") { + $nb--; + } + } else { + $s = str_replace("\r", '', $txt); + $nb = mb_strlen($s, $this->mb_enc); + while ($nb > 0 and mb_substr($s, $nb - 1, 1, $this->mb_enc) == "\n") { + $nb--; + } + } + $b = 0; + if ($border) { + if ($border == 1) { + $border = 'LTRB'; + $b = 'LRT'; + $b2 = 'LR'; + } else { + $b2 = ''; + if (is_int(strpos($border, 'L'))) { + $b2 .= 'L'; + } + if (is_int(strpos($border, 'R'))) { + $b2 .= 'R'; + } + $b = is_int(strpos($border, 'T')) ? $b2 . 'T' : $b2; + } + } + $sep = -1; + $i = 0; + $j = 0; + $l = 0; + $ns = 0; + $nl = 1; + + $rows = 0; + $start_y = $this->y; + + if (!$this->usingCoreFont) { + $inclCursive = false; + if (preg_match("/([" . $this->pregCURSchars . "])/u", $s)) { + $inclCursive = true; + } + while ($i < $nb) { + // Get next character + $c = mb_substr($s, $i, 1, $this->mb_enc); + if ($c == "\n") { + // Explicit line break + // WORD SPACING + $this->ResetSpacing(); + $tmp = rtrim(mb_substr($s, $j, $i - $j, $this->mb_enc)); + $tmpOTLdata = false; + /* -- OTL -- */ + if (isset($OTLdata)) { + $tmpOTLdata = $this->otl->sliceOTLdata($OTLdata, $j, $i - $j); + $this->otl->trimOTLdata($tmpOTLdata, false, true); + $this->magic_reverse_dir($tmp, $directionality, $tmpOTLdata); + } + /* -- END OTL -- */ + $this->Cell($w, $h, $tmp, $b, 2, $align, $fill, $link, 0, 0, 0, 'M', 0, false, $tmpOTLdata); + if ($maxrows != false && isset($this->form) && ($this->y - $start_y) / $h > $maxrows) { + return false; + } + $i++; + $sep = -1; + $j = $i; + $l = 0; + $ns = 0; + $nl++; + if ($border and $nl == 2) { + $b = $b2; + } + continue; + } + if ($c == " ") { + $sep = $i; + $ls = $l; + $ns++; + } + + $l += $this->GetCharWidthNonCore($c); + + if ($l > $wmax) { + // Automatic line break + if ($sep == -1) { // Only one word + if ($i == $j) { + $i++; + } + // WORD SPACING + $this->ResetSpacing(); + $tmp = rtrim(mb_substr($s, $j, $i - $j, $this->mb_enc)); + $tmpOTLdata = false; + /* -- OTL -- */ + if (isset($OTLdata)) { + $tmpOTLdata = $this->otl->sliceOTLdata($OTLdata, $j, $i - $j); + $this->otl->trimOTLdata($tmpOTLdata, false, true); + $this->magic_reverse_dir($tmp, $directionality, $tmpOTLdata); + } + /* -- END OTL -- */ + $this->Cell($w, $h, $tmp, $b, 2, $align, $fill, $link, 0, 0, 0, 'M', 0, false, $tmpOTLdata); + } else { + $tmp = rtrim(mb_substr($s, $j, $sep - $j, $this->mb_enc)); + $tmpOTLdata = false; + /* -- OTL -- */ + if (isset($OTLdata)) { + $tmpOTLdata = $this->otl->sliceOTLdata($OTLdata, $j, $sep - $j); + $this->otl->trimOTLdata($tmpOTLdata, false, true); + } + /* -- END OTL -- */ + if ($align == 'J') { + ////////////////////////////////////////// + // JUSTIFY J using Unicode fonts (Word spacing doesn't work) + // WORD SPACING UNICODE + // Change NON_BREAKING SPACE to spaces so they are 'spaced' properly + $tmp = str_replace(chr(194) . chr(160), chr(32), $tmp); + $len_ligne = $this->GetStringWidth($tmp, false, $tmpOTLdata); + $nb_carac = mb_strlen($tmp, $this->mb_enc); + $nb_spaces = mb_substr_count($tmp, ' ', $this->mb_enc); + // Take off number of Marks + // Use GPOS OTL + if (isset($this->CurrentFont['useOTL']) && ($this->CurrentFont['useOTL'])) { + if (isset($tmpOTLdata['group']) && $tmpOTLdata['group']) { + $nb_carac -= substr_count($tmpOTLdata['group'], 'M'); + } + } + + list($charspacing, $ws, $kashida) = $this->GetJspacing($nb_carac, $nb_spaces, ((($wmax) - $len_ligne) * Mpdf::SCALE), $inclCursive, $tmpOTLdata); + $this->SetSpacing($charspacing, $ws); + ////////////////////////////////////////// + } + if (isset($OTLdata)) { + $this->magic_reverse_dir($tmp, $directionality, $tmpOTLdata); + } + $this->Cell($w, $h, $tmp, $b, 2, $align, $fill, $link, 0, 0, 0, 'M', 0, false, $tmpOTLdata); + $i = $sep + 1; + } + if ($maxrows != false && isset($this->form) && ($this->y - $start_y) / $h > $maxrows) { + return false; + } + $sep = -1; + $j = $i; + $l = 0; + $ns = 0; + $nl++; + if ($border and $nl == 2) { + $b = $b2; + } + } else { + $i++; + } + } + // Last chunk + // WORD SPACING + + $this->ResetSpacing(); + } else { + while ($i < $nb) { + // Get next character + $c = $s[$i]; + if ($c == "\n") { + // Explicit line break + // WORD SPACING + $this->ResetSpacing(); + $this->Cell($w, $h, substr($s, $j, $i - $j), $b, 2, $align, $fill, $link); + if ($maxrows != false && isset($this->form) && ($this->y - $start_y) / $h > $maxrows) { + return false; + } + $i++; + $sep = -1; + $j = $i; + $l = 0; + $ns = 0; + $nl++; + if ($border and $nl == 2) { + $b = $b2; + } + continue; + } + if ($c == " ") { + $sep = $i; + $ls = $l; + $ns++; + } + + $l += $this->GetCharWidthCore($c); + if ($l > $wmax) { + // Automatic line break + if ($sep == -1) { + if ($i == $j) { + $i++; + } + // WORD SPACING + $this->ResetSpacing(); + $this->Cell($w, $h, substr($s, $j, $i - $j), $b, 2, $align, $fill, $link); + } else { + if ($align == 'J') { + $tmp = rtrim(substr($s, $j, $sep - $j)); + ////////////////////////////////////////// + // JUSTIFY J using Unicode fonts (Word spacing doesn't work) + // WORD SPACING NON_UNICODE/CJK + // Change NON_BREAKING SPACE to spaces so they are 'spaced' properly + $tmp = str_replace(chr(160), chr(32), $tmp); + $len_ligne = $this->GetStringWidth($tmp); + $nb_carac = strlen($tmp); + $nb_spaces = substr_count($tmp, ' '); + $tmpOTLdata = []; + list($charspacing, $ws, $kashida) = $this->GetJspacing($nb_carac, $nb_spaces, ((($wmax) - $len_ligne) * Mpdf::SCALE), false, $tmpOTLdata); + $this->SetSpacing($charspacing, $ws); + ////////////////////////////////////////// + } + $this->Cell($w, $h, substr($s, $j, $sep - $j), $b, 2, $align, $fill, $link); + $i = $sep + 1; + } + if ($maxrows != false && isset($this->form) && ($this->y - $start_y) / $h > $maxrows) { + return false; + } + $sep = -1; + $j = $i; + $l = 0; + $ns = 0; + $nl++; + if ($border and $nl == 2) { + $b = $b2; + } + } else { + $i++; + } + } + // Last chunk + // WORD SPACING + + $this->ResetSpacing(); + } + // Last chunk + if ($border and is_int(strpos($border, 'B'))) { + $b .= 'B'; + } + if (!$this->usingCoreFont) { + $tmp = rtrim(mb_substr($s, $j, $i - $j, $this->mb_enc)); + $tmpOTLdata = false; + /* -- OTL -- */ + if (isset($OTLdata)) { + $tmpOTLdata = $this->otl->sliceOTLdata($OTLdata, $j, $i - $j); + $this->otl->trimOTLdata($tmpOTLdata, false, true); + $this->magic_reverse_dir($tmp, $directionality, $tmpOTLdata); + } + /* -- END OTL -- */ + $this->Cell($w, $h, $tmp, $b, 2, $align, $fill, $link, 0, 0, 0, 'M', 0, false, $tmpOTLdata); + } else { + $this->Cell($w, $h, substr($s, $j, $i - $j), $b, 2, $align, $fill, $link); + } + $this->x = $this->lMargin; + } + + /* -- DIRECTW -- */ + + function Write($h, $txt, $currentx = 0, $link = '', $directionality = 'ltr', $align = '', $fill = 0) + { + if (empty($this->directWrite)) { + $this->directWrite = new DirectWrite($this, $this->otl, $this->sizeConverter, $this->colorConverter); + } + + $this->directWrite->Write($h, $txt, $currentx, $link, $directionality, $align, $fill); + } + + /* -- END DIRECTW -- */ + + + /* -- HTML-CSS -- */ + + function saveInlineProperties() + { + $saved = []; + $saved['family'] = $this->FontFamily; + $saved['style'] = $this->FontStyle; + $saved['sizePt'] = $this->FontSizePt; + $saved['size'] = $this->FontSize; + $saved['HREF'] = $this->HREF; + $saved['textvar'] = $this->textvar; // mPDF 5.7.1 + $saved['OTLtags'] = $this->OTLtags; // mPDF 5.7.1 + $saved['textshadow'] = $this->textshadow; + $saved['linewidth'] = $this->LineWidth; + $saved['drawcolor'] = $this->DrawColor; + $saved['textparam'] = $this->textparam; + $saved['lSpacingCSS'] = $this->lSpacingCSS; + $saved['wSpacingCSS'] = $this->wSpacingCSS; + $saved['I'] = $this->I; + $saved['B'] = $this->B; + $saved['colorarray'] = $this->colorarray; + $saved['bgcolorarray'] = $this->spanbgcolorarray; + $saved['border'] = $this->spanborddet; + $saved['color'] = $this->TextColor; + $saved['bgcolor'] = $this->FillColor; + $saved['lang'] = $this->currentLang; + $saved['fontLanguageOverride'] = $this->fontLanguageOverride; // mPDF 5.7.1 + $saved['display_off'] = $this->inlineDisplayOff; + + return $saved; + } + + function restoreInlineProperties(&$saved) + { + $FontFamily = $saved['family']; + $this->FontStyle = $saved['style']; + $this->FontSizePt = $saved['sizePt']; + $this->FontSize = $saved['size']; + + $this->currentLang = $saved['lang']; + $this->fontLanguageOverride = $saved['fontLanguageOverride']; // mPDF 5.7.1 + + $this->ColorFlag = ($this->FillColor != $this->TextColor); // Restore ColorFlag as well + + $this->HREF = $saved['HREF']; + $this->textvar = $saved['textvar']; // mPDF 5.7.1 + $this->OTLtags = $saved['OTLtags']; // mPDF 5.7.1 + $this->textshadow = $saved['textshadow']; + $this->LineWidth = $saved['linewidth']; + $this->DrawColor = $saved['drawcolor']; + $this->textparam = $saved['textparam']; + $this->inlineDisplayOff = $saved['display_off']; + + $this->lSpacingCSS = $saved['lSpacingCSS']; + if (($this->lSpacingCSS || $this->lSpacingCSS === '0') && strtoupper($this->lSpacingCSS) != 'NORMAL') { + $this->fixedlSpacing = $this->sizeConverter->convert($this->lSpacingCSS, $this->FontSize); + } else { + $this->fixedlSpacing = false; + } + $this->wSpacingCSS = $saved['wSpacingCSS']; + if ($this->wSpacingCSS && strtoupper($this->wSpacingCSS) != 'NORMAL') { + $this->minwSpacing = $this->sizeConverter->convert($this->wSpacingCSS, $this->FontSize); + } else { + $this->minwSpacing = 0; + } + + $this->SetFont($FontFamily, $saved['style'], $saved['sizePt'], false); + + $this->currentfontstyle = $saved['style']; + $this->currentfontsize = $saved['sizePt']; + $this->SetStylesArray(['B' => $saved['B'], 'I' => $saved['I']]); // mPDF 5.7.1 + + $this->TextColor = $saved['color']; + $this->FillColor = $saved['bgcolor']; + $this->colorarray = $saved['colorarray']; + $cor = $saved['colorarray']; + if ($cor) { + $this->SetTColor($cor); + } + $this->spanbgcolorarray = $saved['bgcolorarray']; + $cor = $saved['bgcolorarray']; + if ($cor) { + $this->SetFColor($cor); + } + $this->spanborddet = $saved['border']; + } + + // Used when ColActive for tables - updated to return first block with background fill OR borders + function GetFirstBlockFill() + { + // Returns the first blocklevel that uses a bgcolor fill + $startfill = 0; + for ($i = 1; $i <= $this->blklvl; $i++) { + if ($this->blk[$i]['bgcolor'] || $this->blk[$i]['border_left']['w'] || $this->blk[$i]['border_right']['w'] || $this->blk[$i]['border_top']['w'] || $this->blk[$i]['border_bottom']['w']) { + $startfill = $i; + break; + } + } + return $startfill; + } + + // -------------------------FLOWING BLOCK------------------------------------// + // The following functions were originally written by Damon Kohler // + // --------------------------------------------------------------------------// + + function saveFont() + { + $saved = []; + $saved['family'] = $this->FontFamily; + $saved['style'] = $this->FontStyle; + $saved['sizePt'] = $this->FontSizePt; + $saved['size'] = $this->FontSize; + $saved['curr'] = &$this->CurrentFont; + $saved['lang'] = $this->currentLang; // mPDF 6 + $saved['color'] = $this->TextColor; + $saved['spanbgcolor'] = $this->spanbgcolor; + $saved['spanbgcolorarray'] = $this->spanbgcolorarray; + $saved['bord'] = $this->spanborder; + $saved['border'] = $this->spanborddet; + $saved['HREF'] = $this->HREF; + $saved['textvar'] = $this->textvar; // mPDF 5.7.1 + $saved['textshadow'] = $this->textshadow; + $saved['linewidth'] = $this->LineWidth; + $saved['drawcolor'] = $this->DrawColor; + $saved['textparam'] = $this->textparam; + $saved['ReqFontStyle'] = $this->ReqFontStyle; + $saved['fixedlSpacing'] = $this->fixedlSpacing; + $saved['minwSpacing'] = $this->minwSpacing; + return $saved; + } + + function restoreFont(&$saved, $write = true) + { + if (!isset($saved) || empty($saved)) { + return; + } + + $this->FontFamily = $saved['family']; + $this->FontStyle = $saved['style']; + $this->FontSizePt = $saved['sizePt']; + $this->FontSize = $saved['size']; + $this->CurrentFont = &$saved['curr']; + $this->currentLang = $saved['lang']; // mPDF 6 + $this->TextColor = $saved['color']; + $this->spanbgcolor = $saved['spanbgcolor']; + $this->spanbgcolorarray = $saved['spanbgcolorarray']; + $this->spanborder = $saved['bord']; + $this->spanborddet = $saved['border']; + $this->ColorFlag = ($this->FillColor != $this->TextColor); // Restore ColorFlag as well + $this->HREF = $saved['HREF']; + $this->fixedlSpacing = $saved['fixedlSpacing']; + $this->minwSpacing = $saved['minwSpacing']; + $this->textvar = $saved['textvar']; // mPDF 5.7.1 + $this->textshadow = $saved['textshadow']; + $this->LineWidth = $saved['linewidth']; + $this->DrawColor = $saved['drawcolor']; + $this->textparam = $saved['textparam']; + if ($write) { + $this->SetFont($saved['family'], $saved['style'], $saved['sizePt'], true, true); // force output + $fontout = (sprintf('BT /F%d %.3F Tf ET', $this->CurrentFont['i'], $this->FontSizePt)); + if ($this->page > 0 && ((isset($this->pageoutput[$this->page]['Font']) && $this->pageoutput[$this->page]['Font'] != $fontout) || !isset($this->pageoutput[$this->page]['Font']))) { + $this->writer->write($fontout); + } + $this->pageoutput[$this->page]['Font'] = $fontout; + } else { + $this->SetFont($saved['family'], $saved['style'], $saved['sizePt'], false); + } + $this->ReqFontStyle = $saved['ReqFontStyle']; + } + + function newFlowingBlock($w, $h, $a = '', $is_table = false, $blockstate = 0, $newblock = true, $blockdir = 'ltr', $table_draft = false) + { + if (!$a) { + if ($blockdir == 'rtl') { + $a = 'R'; + } else { + $a = 'L'; + } + } + $this->flowingBlockAttr['width'] = ($w * Mpdf::SCALE); + // line height in user units + $this->flowingBlockAttr['is_table'] = $is_table; + $this->flowingBlockAttr['table_draft'] = $table_draft; + $this->flowingBlockAttr['height'] = $h; + $this->flowingBlockAttr['lineCount'] = 0; + $this->flowingBlockAttr['align'] = $a; + $this->flowingBlockAttr['font'] = []; + $this->flowingBlockAttr['content'] = []; + $this->flowingBlockAttr['contentB'] = []; + $this->flowingBlockAttr['contentWidth'] = 0; + $this->flowingBlockAttr['blockstate'] = $blockstate; + + $this->flowingBlockAttr['newblock'] = $newblock; + $this->flowingBlockAttr['valign'] = 'M'; + $this->flowingBlockAttr['blockdir'] = $blockdir; + $this->flowingBlockAttr['cOTLdata'] = []; // mPDF 5.7.1 + $this->flowingBlockAttr['lastBidiText'] = ''; // mPDF 5.7.1 + if (!empty($this->otl)) { + $this->otl->lastBidiStrongType = ''; + } // *OTL* + } + + function finishFlowingBlock($endofblock = false, $next = '') + { + $currentx = $this->x; + // prints out the last chunk + $is_table = $this->flowingBlockAttr['is_table']; + $table_draft = $this->flowingBlockAttr['table_draft']; + $maxWidth = & $this->flowingBlockAttr['width']; + $stackHeight = & $this->flowingBlockAttr['height']; + $align = & $this->flowingBlockAttr['align']; + $content = & $this->flowingBlockAttr['content']; + $contentB = & $this->flowingBlockAttr['contentB']; + $font = & $this->flowingBlockAttr['font']; + $contentWidth = & $this->flowingBlockAttr['contentWidth']; + $lineCount = & $this->flowingBlockAttr['lineCount']; + $valign = & $this->flowingBlockAttr['valign']; + $blockstate = $this->flowingBlockAttr['blockstate']; + + $cOTLdata = & $this->flowingBlockAttr['cOTLdata']; // mPDF 5.7.1 + $newblock = $this->flowingBlockAttr['newblock']; + $blockdir = $this->flowingBlockAttr['blockdir']; + + // *********** BLOCK BACKGROUND COLOR *****************// + if ($this->blk[$this->blklvl]['bgcolor'] && !$is_table) { + $fill = 0; + } else { + $this->SetFColor($this->colorConverter->convert(255, $this->PDFAXwarnings)); + $fill = 0; + } + + $hanger = ''; + // Always right trim! + // Right trim last content and adjust width if needed to justify (later) + if (isset($content[count($content) - 1]) && preg_match('/[ ]+$/', $content[count($content) - 1], $m)) { + $strip = strlen($m[0]); + $content[count($content) - 1] = substr($content[count($content) - 1], 0, (strlen($content[count($content) - 1]) - $strip)); + /* -- OTL -- */ + if (isset($this->CurrentFont['useOTL']) && $this->CurrentFont['useOTL']) { + $this->otl->trimOTLdata($cOTLdata[count($cOTLdata) - 1], false, true); + } + /* -- END OTL -- */ + } + + // the amount of space taken up so far in user units + $usedWidth = 0; + + // COLS + $oldcolumn = $this->CurrCol; + + if ($this->ColActive && !$is_table) { + $this->breakpoints[$this->CurrCol][] = $this->y; + } // *COLUMNS* + // Print out each chunk + + /* -- TABLES -- */ + if ($is_table) { + $ipaddingL = 0; + $ipaddingR = 0; + $paddingL = 0; + $paddingR = 0; + } else { + /* -- END TABLES -- */ + $ipaddingL = $this->blk[$this->blklvl]['padding_left']; + $ipaddingR = $this->blk[$this->blklvl]['padding_right']; + $paddingL = ($ipaddingL * Mpdf::SCALE); + $paddingR = ($ipaddingR * Mpdf::SCALE); + $this->cMarginL = $this->blk[$this->blklvl]['border_left']['w']; + $this->cMarginR = $this->blk[$this->blklvl]['border_right']['w']; + + // Added mPDF 3.0 Float DIV + $fpaddingR = 0; + $fpaddingL = 0; + /* -- CSS-FLOAT -- */ + if (count($this->floatDivs)) { + list($l_exists, $r_exists, $l_max, $r_max, $l_width, $r_width) = $this->GetFloatDivInfo($this->blklvl); + if ($r_exists) { + $fpaddingR = $r_width; + } + if ($l_exists) { + $fpaddingL = $l_width; + } + } + /* -- END CSS-FLOAT -- */ + + $usey = $this->y + 0.002; + if (($newblock) && ($blockstate == 1 || $blockstate == 3) && ($lineCount == 0)) { + $usey += $this->blk[$this->blklvl]['margin_top'] + $this->blk[$this->blklvl]['padding_top'] + $this->blk[$this->blklvl]['border_top']['w']; + } + /* -- CSS-IMAGE-FLOAT -- */ + // If float exists at this level + if (isset($this->floatmargins['R']) && $usey <= $this->floatmargins['R']['y1'] && $usey >= $this->floatmargins['R']['y0'] && !$this->floatmargins['R']['skipline']) { + $fpaddingR += $this->floatmargins['R']['w']; + } + if (isset($this->floatmargins['L']) && $usey <= $this->floatmargins['L']['y1'] && $usey >= $this->floatmargins['L']['y0'] && !$this->floatmargins['L']['skipline']) { + $fpaddingL += $this->floatmargins['L']['w']; + } + /* -- END CSS-IMAGE-FLOAT -- */ + } // *TABLES* + + + $lineBox = []; + + $this->_setInlineBlockHeights($lineBox, $stackHeight, $content, $font, $is_table); + + if ($is_table && count($content) == 0) { + $stackHeight = 0; + } + + if ($table_draft) { + $this->y += $stackHeight; + $this->objectbuffer = []; + return 0; + } + + // While we're at it, check if contains cursive text + // Change NBSP to SPACE. + // Re-calculate contentWidth + $contentWidth = 0; + + foreach ($content as $k => $chunk) { + $this->restoreFont($font[$k], false); + if (!isset($this->objectbuffer[$k]) || (isset($this->objectbuffer[$k]) && !$this->objectbuffer[$k])) { + // Soft Hyphens chr(173) + if (!$this->usingCoreFont) { + /* -- OTL -- */ + // mPDF 5.7.1 + if (isset($this->CurrentFont['useOTL']) && $this->CurrentFont['useOTL']) { + $this->otl->removeChar($chunk, $cOTLdata[$k], "\xc2\xad"); + $this->otl->replaceSpace($chunk, $cOTLdata[$k]); + $content[$k] = $chunk; + } /* -- END OTL -- */ else { // *OTL* + $content[$k] = $chunk = str_replace("\xc2\xad", '', $chunk); + $content[$k] = $chunk = str_replace(chr(194) . chr(160), chr(32), $chunk); + } // *OTL* + } elseif ($this->FontFamily != 'csymbol' && $this->FontFamily != 'czapfdingbats') { + $content[$k] = $chunk = str_replace(chr(173), '', $chunk); + $content[$k] = $chunk = str_replace(chr(160), chr(32), $chunk); + } + $contentWidth += $this->GetStringWidth($chunk, true, (isset($cOTLdata[$k]) ? $cOTLdata[$k] : false), $this->textvar) * Mpdf::SCALE; + } elseif (isset($this->objectbuffer[$k]) && $this->objectbuffer[$k]) { + // LIST MARKERS // mPDF 6 Lists + if ($this->objectbuffer[$k]['type'] == 'image' && isset($this->objectbuffer[$k]['listmarker']) && $this->objectbuffer[$k]['listmarker'] && $this->objectbuffer[$k]['listmarkerposition'] == 'outside') { + // do nothing + } else { + $contentWidth += $this->objectbuffer[$k]['OUTER-WIDTH'] * Mpdf::SCALE; + } + } + } + + if (isset($font[count($font) - 1])) { + $lastfontreqstyle = (isset($font[count($font) - 1]['ReqFontStyle']) ? $font[count($font) - 1]['ReqFontStyle'] : ''); + $lastfontstyle = (isset($font[count($font) - 1]['style']) ? $font[count($font) - 1]['style'] : ''); + } else { + $lastfontreqstyle = null; + $lastfontstyle = null; + } + if ($blockdir == 'ltr' && strpos($lastfontreqstyle, "I") !== false && strpos($lastfontstyle, "I") === false) { // Artificial italic + $lastitalic = $this->FontSize * 0.15 * Mpdf::SCALE; + } else { + $lastitalic = 0; + } + + // Get PAGEBREAK TO TEST for height including the bottom border/padding + $check_h = max($this->divheight, $stackHeight); + + // This fixes a proven bug... + if ($endofblock && $newblock && $blockstate == 0 && !$content) { + $check_h = 0; + } + // but ? needs to fix potentially more widespread... + // if (!$content) { $check_h = 0; } + + if ($this->blklvl > 0 && !$is_table) { + if ($endofblock && $blockstate > 1) { + if ($this->blk[$this->blklvl]['page_break_after_avoid']) { + $check_h += $stackHeight; + } + $check_h += ($this->blk[$this->blklvl]['padding_bottom'] + $this->blk[$this->blklvl]['border_bottom']['w']); + } + if (($newblock && ($blockstate == 1 || $blockstate == 3) && $lineCount == 0) || ($endofblock && $blockstate == 3 && $lineCount == 0)) { + $check_h += ($this->blk[$this->blklvl]['padding_top'] + $this->blk[$this->blklvl]['margin_top'] + $this->blk[$this->blklvl]['border_top']['w']); + } + } + + // Force PAGE break if column height cannot take check-height + if ($this->ColActive && $check_h > ($this->PageBreakTrigger - $this->y0)) { + $this->SetCol($this->NbCol - 1); + } + + // Avoid just border/background-color moved on to next page + if ($endofblock && $blockstate > 1 && !$content) { + $buff = $this->margBuffer; + } else { + $buff = 0; + } + + + // PAGEBREAK + if (!$is_table && ($this->y + $check_h) > ($this->PageBreakTrigger + $buff) and ! $this->InFooter and $this->AcceptPageBreak()) { + $bak_x = $this->x; // Current X position + // WORD SPACING + $ws = $this->ws; // Word Spacing + $charspacing = $this->charspacing; // Character Spacing + $this->ResetSpacing(); + + $this->AddPage($this->CurOrientation); + + $this->x = $bak_x; + // Added to correct for OddEven Margins + $currentx += $this->MarginCorrection; + $this->x += $this->MarginCorrection; + + // WORD SPACING + $this->SetSpacing($charspacing, $ws); + } + + + /* -- COLUMNS -- */ + // COLS + // COLUMN CHANGE + if ($this->CurrCol != $oldcolumn) { + $currentx += $this->ChangeColumn * ($this->ColWidth + $this->ColGap); + $this->x += $this->ChangeColumn * ($this->ColWidth + $this->ColGap); + $oldcolumn = $this->CurrCol; + } + + + if ($this->ColActive && !$is_table) { + $this->breakpoints[$this->CurrCol][] = $this->y; + } + /* -- END COLUMNS -- */ + + // TOP MARGIN + if ($newblock && ($blockstate == 1 || $blockstate == 3) && ($this->blk[$this->blklvl]['margin_top']) && $lineCount == 0 && !$is_table) { + $this->DivLn($this->blk[$this->blklvl]['margin_top'], $this->blklvl - 1, true, $this->blk[$this->blklvl]['margin_collapse']); + if ($this->ColActive) { + $this->breakpoints[$this->CurrCol][] = $this->y; + } // *COLUMNS* + } + + if ($newblock && ($blockstate == 1 || $blockstate == 3) && $lineCount == 0 && !$is_table) { + $this->blk[$this->blklvl]['y0'] = $this->y; + $this->blk[$this->blklvl]['startpage'] = $this->page; + if ($this->blk[$this->blklvl]['float']) { + $this->blk[$this->blklvl]['float_start_y'] = $this->y; + } + if ($this->ColActive) { + $this->breakpoints[$this->CurrCol][] = $this->y; + } // *COLUMNS* + } + + // Paragraph INDENT + $WidthCorrection = 0; + if (($newblock) && ($blockstate == 1 || $blockstate == 3) && isset($this->blk[$this->blklvl]['text_indent']) && ($lineCount == 0) && (!$is_table) && ($align != 'C')) { + $ti = $this->sizeConverter->convert($this->blk[$this->blklvl]['text_indent'], $this->blk[$this->blklvl]['inner_width'], $this->blk[$this->blklvl]['InlineProperties']['size'], false); // mPDF 5.7.4 + $WidthCorrection = ($ti * Mpdf::SCALE); + } + + + // PADDING and BORDER spacing/fill + if (($newblock) && ($blockstate == 1 || $blockstate == 3) && (($this->blk[$this->blklvl]['padding_top']) || ($this->blk[$this->blklvl]['border_top'])) && ($lineCount == 0) && (!$is_table)) { + // $state = 0 normal; 1 top; 2 bottom; 3 top and bottom + $this->DivLn($this->blk[$this->blklvl]['padding_top'] + $this->blk[$this->blklvl]['border_top']['w'], -3, true, false, 1); + if ($this->ColActive) { + $this->breakpoints[$this->CurrCol][] = $this->y; + } // *COLUMNS* + $this->x = $currentx; + } + + + // Added mPDF 3.0 Float DIV + $fpaddingR = 0; + $fpaddingL = 0; + /* -- CSS-FLOAT -- */ + if (count($this->floatDivs)) { + list($l_exists, $r_exists, $l_max, $r_max, $l_width, $r_width) = $this->GetFloatDivInfo($this->blklvl); + if ($r_exists) { + $fpaddingR = $r_width; + } + if ($l_exists) { + $fpaddingL = $l_width; + } + } + /* -- END CSS-FLOAT -- */ + + $usey = $this->y + 0.002; + if (($newblock) && ($blockstate == 1 || $blockstate == 3) && ($lineCount == 0)) { + $usey += $this->blk[$this->blklvl]['margin_top'] + $this->blk[$this->blklvl]['padding_top'] + $this->blk[$this->blklvl]['border_top']['w']; + } + /* -- CSS-IMAGE-FLOAT -- */ + // If float exists at this level + if (isset($this->floatmargins['R']) && $usey <= $this->floatmargins['R']['y1'] && $usey >= $this->floatmargins['R']['y0'] && !$this->floatmargins['R']['skipline']) { + $fpaddingR += $this->floatmargins['R']['w']; + } + if (isset($this->floatmargins['L']) && $usey <= $this->floatmargins['L']['y1'] && $usey >= $this->floatmargins['L']['y0'] && !$this->floatmargins['L']['skipline']) { + $fpaddingL += $this->floatmargins['L']['w']; + } + /* -- END CSS-IMAGE-FLOAT -- */ + + + if ($content) { + // In FinishFlowing Block no lines are justified as it is always last line + // but if CJKorphan has allowed content width to go over max width, use J charspacing to compress line + // JUSTIFICATION J - NOT! + $nb_carac = 0; + $nb_spaces = 0; + $jcharspacing = 0; + $jkashida = 0; + $jws = 0; + $inclCursive = false; + $dottab = false; + foreach ($content as $k => $chunk) { + if (!isset($this->objectbuffer[$k]) || (isset($this->objectbuffer[$k]) && !$this->objectbuffer[$k])) { + $nb_carac += mb_strlen($chunk, $this->mb_enc); + $nb_spaces += mb_substr_count($chunk, ' ', $this->mb_enc); + // mPDF 6 + // Use GPOS OTL + $this->restoreFont($font[$k], false); + if (isset($this->CurrentFont['useOTL']) && $this->CurrentFont['useOTL']) { + if (isset($cOTLdata[$k]['group']) && $cOTLdata[$k]['group']) { + $nb_marks = substr_count($cOTLdata[$k]['group'], 'M'); + $nb_carac -= $nb_marks; + } + if (preg_match("/([" . $this->pregCURSchars . "])/u", $chunk)) { + $inclCursive = true; + } + } + } else { + $nb_carac ++; // mPDF 6 allow spacing for inline object + if ($this->objectbuffer[$k]['type'] == 'dottab') { + $dottab = $this->objectbuffer[$k]['outdent']; + } + } + } + + // DIRECTIONALITY RTL + $chunkorder = range(0, count($content) - 1); // mPDF 6 + /* -- OTL -- */ + // mPDF 6 + if ($blockdir == 'rtl' || $this->biDirectional) { + $this->otl->bidiReorder($chunkorder, $content, $cOTLdata, $blockdir); + // From this point on, $content and $cOTLdata may contain more elements (and re-ordered) compared to + // $this->objectbuffer and $font ($chunkorder contains the mapping) + } + /* -- END OTL -- */ + + // Remove any XAdvance from OTL data at end of line + // And correct for XPlacement on last character + // BIDI is applied + foreach ($chunkorder as $aord => $k) { + if (count($cOTLdata)) { + $this->restoreFont($font[$k], false); + // ...FinishFlowingBlock... + if ($aord == count($chunkorder) - 1 && isset($cOTLdata[$aord]['group'])) { // Last chunk on line + $nGPOS = strlen($cOTLdata[$aord]['group']) - 1; // Last character + if (isset($cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XAdvanceL']) || isset($cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XAdvanceR'])) { + if (isset($cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XAdvanceL'])) { + $w = $cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XAdvanceL'] * 1000 / $this->CurrentFont['unitsPerEm']; + } else { + $w = $cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XAdvanceR'] * 1000 / $this->CurrentFont['unitsPerEm']; + } + $w *= ($this->FontSize / 1000); + $contentWidth -= $w * Mpdf::SCALE; + $cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XAdvanceL'] = 0; + $cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XAdvanceR'] = 0; + } + + // If last character has an XPlacement set, adjust width calculation, and add to XAdvance to account for it + if (isset($cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XPlacement'])) { + $w = -$cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XPlacement'] * 1000 / $this->CurrentFont['unitsPerEm']; + $w *= ($this->FontSize / 1000); + $contentWidth -= $w * Mpdf::SCALE; + $cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XAdvanceL'] = $cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XPlacement']; + $cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XAdvanceR'] = $cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XPlacement']; + } + } + } + } + + // if it's justified, we need to find the char/word spacing (or if orphans have allowed length of line to go over the maxwidth) + // If "orphans" in fact is just a final space - ignore this + $lastchar = mb_substr($content[(count($chunkorder) - 1)], mb_strlen($content[(count($chunkorder) - 1)], $this->mb_enc) - 1, 1, $this->mb_enc); + if (preg_match("/[" . $this->CJKoverflow . "]/u", $lastchar)) { + $CJKoverflow = true; + } else { + $CJKoverflow = false; + } + if ((((($contentWidth + $lastitalic) > $maxWidth) && ($content[(count($chunkorder) - 1)] != ' ') ) || + (!$endofblock && $align == 'J' && ($next == 'image' || $next == 'select' || $next == 'input' || $next == 'textarea' || ($next == 'br' && $this->justifyB4br)))) && !($CJKoverflow && $this->allowCJKoverflow)) { + // WORD SPACING + list($jcharspacing, $jws, $jkashida) = $this->GetJspacing($nb_carac, $nb_spaces, ($maxWidth - $lastitalic - $contentWidth - $WidthCorrection - (($this->cMarginL + $this->cMarginR) * Mpdf::SCALE) - ($paddingL + $paddingR + (($fpaddingL + $fpaddingR) * Mpdf::SCALE) )), $inclCursive, $cOTLdata); + } /* -- CJK-FONTS -- */ elseif ($this->checkCJK && $align == 'J' && $CJKoverflow && $this->allowCJKoverflow && $this->CJKforceend) { + // force-end overhang + $hanger = mb_substr($content[(count($chunkorder) - 1)], mb_strlen($content[(count($chunkorder) - 1)], $this->mb_enc) - 1, 1, $this->mb_enc); + if (preg_match("/[" . $this->CJKoverflow . "]/u", $hanger)) { + $content[(count($chunkorder) - 1)] = mb_substr($content[(count($chunkorder) - 1)], 0, mb_strlen($content[(count($chunkorder) - 1)], $this->mb_enc) - 1, $this->mb_enc); + $this->restoreFont($font[$chunkorder[count($chunkorder) - 1]], false); + $contentWidth -= $this->GetStringWidth($hanger) * Mpdf::SCALE; + $nb_carac -= 1; + list($jcharspacing, $jws, $jkashida) = $this->GetJspacing($nb_carac, $nb_spaces, ($maxWidth - $lastitalic - $contentWidth - $WidthCorrection - (($this->cMarginL + $this->cMarginR) * Mpdf::SCALE) - ($paddingL + $paddingR + (($fpaddingL + $fpaddingR) * Mpdf::SCALE) )), $inclCursive, $cOTLdata); + } + } /* -- END CJK-FONTS -- */ + + // Check if will fit at word/char spacing of previous line - if so continue it + // but only allow a maximum of $this->jSmaxWordLast and $this->jSmaxCharLast + elseif ($contentWidth < ($maxWidth - $lastitalic - $WidthCorrection - (($this->cMarginL + $this->cMarginR) * Mpdf::SCALE) - ($paddingL + $paddingR + (($fpaddingL + $fpaddingR) * Mpdf::SCALE))) && !$this->fixedlSpacing) { + if ($this->ws > $this->jSmaxWordLast) { + $jws = $this->jSmaxWordLast; + } + if ($this->charspacing > $this->jSmaxCharLast) { + $jcharspacing = $this->jSmaxCharLast; + } + $check = $maxWidth - $lastitalic - $WidthCorrection - $contentWidth - (($this->cMarginL + $this->cMarginR) * Mpdf::SCALE) - ($paddingL + $paddingR + (($fpaddingL + $fpaddingR) * Mpdf::SCALE) ) - ( $jcharspacing * $nb_carac) - ( $jws * $nb_spaces); + if ($check <= 0) { + $jcharspacing = 0; + $jws = 0; + } + } + + $empty = $maxWidth - $lastitalic - $WidthCorrection - $contentWidth - (($this->cMarginL + $this->cMarginR) * Mpdf::SCALE) - ($paddingL + $paddingR + (($fpaddingL + $fpaddingR) * Mpdf::SCALE) ); + + + $empty -= ($jcharspacing * ($nb_carac - 1)); // mPDF 6 nb_carac MINUS 1 + $empty -= ($jws * $nb_spaces); + $empty -= ($jkashida); + + $empty /= Mpdf::SCALE; + + if (!$is_table) { + $this->maxPosR = max($this->maxPosR, ($this->w - $this->rMargin - $this->blk[$this->blklvl]['outer_right_margin'] - $empty)); + $this->maxPosL = min($this->maxPosL, ($this->lMargin + $this->blk[$this->blklvl]['outer_left_margin'] + $empty)); + } + + $arraysize = count($chunkorder); + + $margins = ($this->cMarginL + $this->cMarginR) + ($ipaddingL + $ipaddingR + $fpaddingR + $fpaddingR ); + + if (!$is_table) { + $this->DivLn($stackHeight, $this->blklvl, false); + } // false -> don't advance y + + $this->x = $currentx + $this->cMarginL + $ipaddingL + $fpaddingL; + if ($dottab !== false && $blockdir == 'rtl') { + $this->x -= $dottab; + } elseif ($align == 'R') { + $this->x += $empty; + } elseif ($align == 'J' && $blockdir == 'rtl') { + $this->x += $empty; + } elseif ($align == 'C') { + $this->x += ($empty / 2); + } + + // Paragraph INDENT + $WidthCorrection = 0; + if (($newblock) && ($blockstate == 1 || $blockstate == 3) && isset($this->blk[$this->blklvl]['text_indent']) && ($lineCount == 0) && (!$is_table) && ($align != 'C')) { + $ti = $this->sizeConverter->convert($this->blk[$this->blklvl]['text_indent'], $this->blk[$this->blklvl]['inner_width'], $this->blk[$this->blklvl]['InlineProperties']['size'], false); // mPDF 5.7.4 + if ($blockdir != 'rtl') { + $this->x += $ti; + } // mPDF 6 + } + + foreach ($chunkorder as $aord => $k) { // mPDF 5.7 + $chunk = $content[$aord]; + if (isset($this->objectbuffer[$k]) && $this->objectbuffer[$k]) { + $xadj = $this->x - $this->objectbuffer[$k]['OUTER-X']; + $this->objectbuffer[$k]['OUTER-X'] += $xadj; + $this->objectbuffer[$k]['BORDER-X'] += $xadj; + $this->objectbuffer[$k]['INNER-X'] += $xadj; + + if ($this->objectbuffer[$k]['type'] == 'listmarker') { + $this->objectbuffer[$k]['lineBox'] = $lineBox[-1]; // Block element details for glyph-origin + } + $yadj = $this->y - $this->objectbuffer[$k]['OUTER-Y']; + if ($this->objectbuffer[$k]['type'] == 'dottab') { // mPDF 6 DOTTAB + $this->objectbuffer[$k]['lineBox'] = $lineBox[$k]; // element details for glyph-origin + } + if ($this->objectbuffer[$k]['type'] != 'dottab') { // mPDF 6 DOTTAB + $yadj += $lineBox[$k]['top']; + } + $this->objectbuffer[$k]['OUTER-Y'] += $yadj; + $this->objectbuffer[$k]['BORDER-Y'] += $yadj; + $this->objectbuffer[$k]['INNER-Y'] += $yadj; + } + + $this->restoreFont($font[$k]); // mPDF 5.7 + + if ($is_table && substr($align, 0, 1) == 'D' && $aord == 0) { + $dp = $this->decimal_align[substr($align, 0, 2)]; + $s = preg_split('/' . preg_quote($dp, '/') . '/', $content[0], 2); // ? needs to be /u if not core + $s0 = $this->GetStringWidth($s[0], false); + $this->x += ($this->decimal_offset - $s0); + } + + $this->SetSpacing(($this->fixedlSpacing * Mpdf::SCALE) + $jcharspacing, ($this->fixedlSpacing + $this->minwSpacing) * Mpdf::SCALE + $jws); + $this->fixedlSpacing = false; + $this->minwSpacing = 0; + + $save_vis = $this->visibility; + if (isset($this->textparam['visibility']) && $this->textparam['visibility'] && $this->textparam['visibility'] != $this->visibility) { + $this->SetVisibility($this->textparam['visibility']); + } + + // *********** SPAN BACKGROUND COLOR ***************** // + if (isset($this->spanbgcolor) && $this->spanbgcolor) { + $cor = $this->spanbgcolorarray; + $this->SetFColor($cor); + $save_fill = $fill; + $spanfill = 1; + $fill = 1; + } + if (!empty($this->spanborddet)) { + if (strpos($contentB[$k], 'L') !== false && isset($this->spanborddet['L'])) { + $this->x += $this->spanborddet['L']['w']; + } + if (strpos($contentB[$k], 'L') === false) { + $this->spanborddet['L']['s'] = $this->spanborddet['L']['w'] = 0; + } + if (strpos($contentB[$k], 'R') === false) { + $this->spanborddet['R']['s'] = $this->spanborddet['R']['w'] = 0; + } + } + // WORD SPACING + // mPDF 5.7.1 + $stringWidth = $this->GetStringWidth($chunk, true, (isset($cOTLdata[$aord]) ? $cOTLdata[$aord] : false), $this->textvar); + $nch = mb_strlen($chunk, $this->mb_enc); + // Use GPOS OTL + if (isset($this->CurrentFont['useOTL']) && $this->CurrentFont['useOTL']) { + if (isset($cOTLdata[$aord]['group']) && $cOTLdata[$aord]['group']) { + $nch -= substr_count($cOTLdata[$aord]['group'], 'M'); + } + } + $stringWidth += ( $this->charspacing * $nch / Mpdf::SCALE ); + + $stringWidth += ( $this->ws * mb_substr_count($chunk, ' ', $this->mb_enc) / Mpdf::SCALE ); + + if (isset($this->objectbuffer[$k])) { + if ($this->objectbuffer[$k]['type'] == 'dottab') { + $this->objectbuffer[$k]['OUTER-WIDTH'] +=$empty; + $this->objectbuffer[$k]['OUTER-WIDTH'] +=$this->objectbuffer[$k]['outdent']; + } + // LIST MARKERS // mPDF 6 Lists + if ($this->objectbuffer[$k]['type'] == 'image' && isset($this->objectbuffer[$k]['listmarker']) && $this->objectbuffer[$k]['listmarker'] && $this->objectbuffer[$k]['listmarkerposition'] == 'outside') { + // do nothing + } else { + $stringWidth = $this->objectbuffer[$k]['OUTER-WIDTH']; + } + } + + if ($stringWidth == 0) { + $stringWidth = 0.000001; + } + if ($aord == $arraysize - 1) { // mPDF 5.7 + // mPDF 5.7.1 + if ($this->checkCJK && $CJKoverflow && $align == 'J' && $this->allowCJKoverflow && $hanger && $this->CJKforceend) { + // force-end overhang + $this->Cell($stringWidth, $stackHeight, $chunk, '', 0, '', $fill, $this->HREF, $currentx, 0, 0, 'M', $fill, true, (isset($cOTLdata[$aord]) ? $cOTLdata[$aord] : false), $this->textvar, (isset($lineBox[$k]) ? $lineBox[$k] : false)); // mPDF 5.7.1 + $this->Cell($this->GetStringWidth($hanger), $stackHeight, $hanger, '', 1, '', $fill, $this->HREF, $currentx, 0, 0, 'M', $fill, true, (isset($cOTLdata[$aord]) ? $cOTLdata[$aord] : false), $this->textvar, (isset($lineBox[$k]) ? $lineBox[$k] : false)); // mPDF 5.7.1 + } else { + $this->Cell($stringWidth, $stackHeight, $chunk, '', 1, '', $fill, $this->HREF, $currentx, 0, 0, 'M', $fill, true, (isset($cOTLdata[$aord]) ? $cOTLdata[$aord] : false), $this->textvar, (isset($lineBox[$k]) ? $lineBox[$k] : false)); // mPDF 5.7.1 + } + } else { + $this->Cell($stringWidth, $stackHeight, $chunk, '', 0, '', $fill, $this->HREF, 0, 0, 0, 'M', $fill, true, (isset($cOTLdata[$aord]) ? $cOTLdata[$aord] : false), $this->textvar, (isset($lineBox[$k]) ? $lineBox[$k] : false)); // first or middle part // mPDF 5.7.1 + } + + + if (!empty($this->spanborddet)) { + if (strpos($contentB[$k], 'R') !== false && $aord != $arraysize - 1) { + $this->x += $this->spanborddet['R']['w']; + } + } + // *********** SPAN BACKGROUND COLOR OFF - RESET BLOCK BGCOLOR ***************** // + if (isset($spanfill) && $spanfill) { + $fill = $save_fill; + $spanfill = 0; + if ($fill) { + $this->SetFColor($bcor); + } + } + if (isset($this->textparam['visibility']) && $this->textparam['visibility'] && $this->visibility != $save_vis) { + $this->SetVisibility($save_vis); + } + } + + $this->printobjectbuffer($is_table, $blockdir); + $this->objectbuffer = []; + $this->ResetSpacing(); + } // END IF CONTENT + + /* -- CSS-IMAGE-FLOAT -- */ + // Update values if set to skipline + if ($this->floatmargins) { + $this->_advanceFloatMargins(); + } + + + if ($endofblock && $blockstate > 1) { + // If float exists at this level + if (isset($this->floatmargins['R']['y1'])) { + $fry1 = $this->floatmargins['R']['y1']; + } else { + $fry1 = 0; + } + if (isset($this->floatmargins['L']['y1'])) { + $fly1 = $this->floatmargins['L']['y1']; + } else { + $fly1 = 0; + } + if ($this->y < $fry1 || $this->y < $fly1) { + $drop = max($fry1, $fly1) - $this->y; + $this->DivLn($drop); + $this->x = $currentx; + } + } + /* -- END CSS-IMAGE-FLOAT -- */ + + + // PADDING and BORDER spacing/fill + if ($endofblock && ($blockstate > 1) && ($this->blk[$this->blklvl]['padding_bottom'] || $this->blk[$this->blklvl]['border_bottom'] || $this->blk[$this->blklvl]['css_set_height']) && (!$is_table)) { + // If CSS height set, extend bottom - if on same page as block started, and CSS HEIGHT > actual height, + // and does not force pagebreak + $extra = 0; + if (isset($this->blk[$this->blklvl]['css_set_height']) && $this->blk[$this->blklvl]['css_set_height'] && $this->blk[$this->blklvl]['startpage'] == $this->page) { + // predicted height + $h1 = ($this->y - $this->blk[$this->blklvl]['y0']) + $this->blk[$this->blklvl]['padding_bottom'] + $this->blk[$this->blklvl]['border_bottom']['w']; + if ($h1 < ($this->blk[$this->blklvl]['css_set_height'] + $this->blk[$this->blklvl]['padding_bottom'] + $this->blk[$this->blklvl]['padding_top'])) { + $extra = ($this->blk[$this->blklvl]['css_set_height'] + $this->blk[$this->blklvl]['padding_bottom'] + $this->blk[$this->blklvl]['padding_top']) - $h1; + } + if ($this->y + $this->blk[$this->blklvl]['padding_bottom'] + $this->blk[$this->blklvl]['border_bottom']['w'] + $extra > $this->PageBreakTrigger) { + $extra = $this->PageBreakTrigger - ($this->y + $this->blk[$this->blklvl]['padding_bottom'] + $this->blk[$this->blklvl]['border_bottom']['w']); + } + } + + // $state = 0 normal; 1 top; 2 bottom; 3 top and bottom + $this->DivLn($this->blk[$this->blklvl]['padding_bottom'] + $this->blk[$this->blklvl]['border_bottom']['w'] + $extra, -3, true, false, 2); + $this->x = $currentx; + + if ($this->ColActive) { + $this->breakpoints[$this->CurrCol][] = $this->y; + } // *COLUMNS* + } + + // SET Bottom y1 of block (used for painting borders) + if (($endofblock) && ($blockstate > 1) && (!$is_table)) { + $this->blk[$this->blklvl]['y1'] = $this->y; + } + + // BOTTOM MARGIN + if (($endofblock) && ($blockstate > 1) && ($this->blk[$this->blklvl]['margin_bottom']) && (!$is_table)) { + if ($this->y + $this->blk[$this->blklvl]['margin_bottom'] < $this->PageBreakTrigger and ! $this->InFooter) { + $this->DivLn($this->blk[$this->blklvl]['margin_bottom'], $this->blklvl - 1, true, $this->blk[$this->blklvl]['margin_collapse']); + if ($this->ColActive) { + $this->breakpoints[$this->CurrCol][] = $this->y; + } // *COLUMNS* + } + } + + // Reset lineheight + $stackHeight = $this->divheight; + } + + function printobjectbuffer($is_table = false, $blockdir = false) + { + if (!$blockdir) { + $blockdir = $this->directionality; + } + + if ($is_table && $this->shrin_k > 1) { + $k = $this->shrin_k; + } else { + $k = 1; + } + + $save_y = $this->y; + $save_x = $this->x; + + $save_currentfontfamily = $this->FontFamily; + $save_currentfontsize = $this->FontSizePt; + $save_currentfontstyle = $this->FontStyle; + + if ($blockdir == 'rtl') { + $rtlalign = 'R'; + } else { + $rtlalign = 'L'; + } + + foreach ($this->objectbuffer as $ib => $objattr) { + + if ($objattr['type'] == 'bookmark' || $objattr['type'] == 'indexentry' || $objattr['type'] == 'toc') { + $x = $objattr['OUTER-X']; + $y = $objattr['OUTER-Y']; + $this->y = $y - $this->FontSize / 2; + $this->x = $x; + if ($objattr['type'] == 'bookmark') { + $this->Bookmark($objattr['CONTENT'], $objattr['bklevel'], $y - $this->FontSize); + } // *BOOKMARKS* + if ($objattr['type'] == 'indexentry') { + $this->IndexEntry($objattr['CONTENT']); + } // *INDEX* + if ($objattr['type'] == 'toc') { + $this->TOC_Entry($objattr['CONTENT'], $objattr['toclevel'], (isset($objattr['toc_id']) ? $objattr['toc_id'] : '')); + } // *TOC* + } /* -- ANNOTATIONS -- */ elseif ($objattr['type'] == 'annot') { + if ($objattr['POS-X']) { + $x = $objattr['POS-X']; + } elseif ($this->annotMargin <> 0) { + $x = -$objattr['OUTER-X']; + } else { + $x = $objattr['OUTER-X']; + } + if ($objattr['POS-Y']) { + $y = $objattr['POS-Y']; + } else { + $y = $objattr['OUTER-Y'] - $this->FontSize / 2; + } + // Create a dummy entry in the _out/columnBuffer with position sensitive data, + // linking $y-1 in the Columnbuffer with entry in $this->columnAnnots + // and when columns are split in length will not break annotation from current line + $this->y = $y - 1; + $this->x = $x - 1; + $this->Line($x - 1, $y - 1, $x - 1, $y - 1); + $this->Annotation($objattr['CONTENT'], $x, $y, $objattr['ICON'], $objattr['AUTHOR'], $objattr['SUBJECT'], $objattr['OPACITY'], $objattr['COLOR'], (isset($objattr['POPUP']) ? $objattr['POPUP'] : ''), (isset($objattr['FILE']) ? $objattr['FILE'] : '')); + } /* -- END ANNOTATIONS -- */ else { + $y = $objattr['OUTER-Y']; + $x = $objattr['OUTER-X']; + $w = $objattr['OUTER-WIDTH']; + $h = $objattr['OUTER-HEIGHT']; + if (isset($objattr['text'])) { + $texto = $objattr['text']; + } + $this->y = $y; + $this->x = $x; + if (isset($objattr['fontfamily'])) { + $this->SetFont($objattr['fontfamily'], '', $objattr['fontsize']); + } + } + + // HR + if ($objattr['type'] == 'hr') { + $this->SetDColor($objattr['color']); + switch ($objattr['align']) { + case 'C': + $empty = $objattr['OUTER-WIDTH'] - $objattr['INNER-WIDTH']; + $empty /= 2; + $x += $empty; + break; + case 'R': + $empty = $objattr['OUTER-WIDTH'] - $objattr['INNER-WIDTH']; + $x += $empty; + break; + } + $oldlinewidth = $this->LineWidth; + $this->SetLineWidth($objattr['linewidth'] / $k); + $this->y += ($objattr['linewidth'] / 2) + $objattr['margin_top'] / $k; + $this->Line($x, $this->y, $x + $objattr['INNER-WIDTH'], $this->y); + $this->SetLineWidth($oldlinewidth); + $this->SetDColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + } + // IMAGE + if ($objattr['type'] == 'image') { + // mPDF 5.7.3 TRANSFORMS + if (isset($objattr['transform'])) { + $this->writer->write("\n" . '% BTR'); // Begin Transform + } + if (isset($objattr['z-index']) && $objattr['z-index'] > 0 && $this->current_layer == 0) { + $this->BeginLayer($objattr['z-index']); + } + if (isset($objattr['visibility']) && $objattr['visibility'] != 'visible' && $objattr['visibility']) { + $this->SetVisibility($objattr['visibility']); + } + if (isset($objattr['opacity'])) { + $this->SetAlpha($objattr['opacity']); + } + + $obiw = $objattr['INNER-WIDTH']; + $obih = $objattr['INNER-HEIGHT']; + + $sx = $objattr['orig_w'] ? ($objattr['INNER-WIDTH'] * Mpdf::SCALE / $objattr['orig_w']) : INF; + $sy = $objattr['orig_h'] ? ($objattr['INNER-HEIGHT'] * Mpdf::SCALE / $objattr['orig_h']) : INF; + + $rotate = 0; + if (isset($objattr['ROTATE'])) { + $rotate = $objattr['ROTATE']; + } + + if ($rotate == 90) { + // Clockwise + $obiw = $objattr['INNER-HEIGHT']; + $obih = $objattr['INNER-WIDTH']; + $tr = $this->transformTranslate(0, -$objattr['INNER-WIDTH'], true); + $tr .= ' ' . $this->transformRotate(90, $objattr['INNER-X'], ($objattr['INNER-Y'] + $objattr['INNER-WIDTH']), true); + $sx = $obiw * Mpdf::SCALE / $objattr['orig_h']; + $sy = $obih * Mpdf::SCALE / $objattr['orig_w']; + } elseif ($rotate == -90 || $rotate == 270) { + // AntiClockwise + $obiw = $objattr['INNER-HEIGHT']; + $obih = $objattr['INNER-WIDTH']; + $tr = $this->transformTranslate($objattr['INNER-WIDTH'], ($objattr['INNER-HEIGHT'] - $objattr['INNER-WIDTH']), true); + $tr .= ' ' . $this->transformRotate(-90, $objattr['INNER-X'], ($objattr['INNER-Y'] + $objattr['INNER-WIDTH']), true); + $sx = $obiw * Mpdf::SCALE / $objattr['orig_h']; + $sy = $obih * Mpdf::SCALE / $objattr['orig_w']; + } elseif ($rotate == 180) { + // Mirror + $tr = $this->transformTranslate($objattr['INNER-WIDTH'], -$objattr['INNER-HEIGHT'], true); + $tr .= ' ' . $this->transformRotate(180, $objattr['INNER-X'], ($objattr['INNER-Y'] + $objattr['INNER-HEIGHT']), true); + } else { + $tr = ''; + } + $tr = trim($tr); + if ($tr) { + $tr .= ' '; + } + $gradmask = ''; + + // mPDF 5.7.3 TRANSFORMS + $tr2 = ''; + if (isset($objattr['transform'])) { + $maxsize_x = $w; + $maxsize_y = $h; + $cx = $x + $w / 2; + $cy = $y + $h / 2; + preg_match_all('/(translatex|translatey|translate|scalex|scaley|scale|rotate|skewX|skewY|skew)\((.*?)\)/is', $objattr['transform'], $m); + if (count($m[0])) { + for ($i = 0; $i < count($m[0]); $i++) { + $c = strtolower($m[1][$i]); + $v = trim($m[2][$i]); + $vv = preg_split('/[ ,]+/', $v); + if ($c == 'translate' && count($vv)) { + $translate_x = $this->sizeConverter->convert($vv[0], $maxsize_x, false, false); + if (count($vv) == 2) { + $translate_y = $this->sizeConverter->convert($vv[1], $maxsize_y, false, false); + } else { + $translate_y = 0; + } + $tr2 .= $this->transformTranslate($translate_x, $translate_y, true) . ' '; + } elseif ($c == 'translatex' && count($vv)) { + $translate_x = $this->sizeConverter->convert($vv[0], $maxsize_x, false, false); + $tr2 .= $this->transformTranslate($translate_x, 0, true) . ' '; + } elseif ($c == 'translatey' && count($vv)) { + $translate_y = $this->sizeConverter->convert($vv[1], $maxsize_y, false, false); + $tr2 .= $this->transformTranslate(0, $translate_y, true) . ' '; + } elseif ($c == 'scale' && count($vv)) { + $scale_x = $vv[0] * 100; + if (count($vv) == 2) { + $scale_y = $vv[1] * 100; + } else { + $scale_y = $scale_x; + } + $tr2 .= $this->transformScale($scale_x, $scale_y, $cx, $cy, true) . ' '; + } elseif ($c == 'scalex' && count($vv)) { + $scale_x = $vv[0] * 100; + $tr2 .= $this->transformScale($scale_x, 0, $cx, $cy, true) . ' '; + } elseif ($c == 'scaley' && count($vv)) { + $scale_y = $vv[1] * 100; + $tr2 .= $this->transformScale(0, $scale_y, $cx, $cy, true) . ' '; + } elseif ($c == 'skew' && count($vv)) { + $angle_x = $this->ConvertAngle($vv[0], false); + if (count($vv) == 2) { + $angle_y = $this->ConvertAngle($vv[1], false); + } else { + $angle_y = 0; + } + $tr2 .= $this->transformSkew($angle_x, $angle_y, $cx, $cy, true) . ' '; + } elseif ($c == 'skewx' && count($vv)) { + $angle = $this->ConvertAngle($vv[0], false); + $tr2 .= $this->transformSkew($angle, 0, $cx, $cy, true) . ' '; + } elseif ($c == 'skewy' && count($vv)) { + $angle = $this->ConvertAngle($vv[0], false); + $tr2 .= $this->transformSkew(0, $angle, $cx, $cy, true) . ' '; + } elseif ($c == 'rotate' && count($vv)) { + $angle = $this->ConvertAngle($vv[0]); + $tr2 .= $this->transformRotate($angle, $cx, $cy, true) . ' '; + } + } + } + } + + // LIST MARKERS (Images) // mPDF 6 Lists + if (isset($objattr['listmarker']) && $objattr['listmarker'] && $objattr['listmarkerposition'] == 'outside') { + $mw = $objattr['OUTER-WIDTH']; + // NB If change marker-offset, also need to alter in function _getListMarkerWidth + $adjx = $this->sizeConverter->convert($this->list_marker_offset, $this->FontSize); + if ($objattr['dir'] == 'rtl') { + $objattr['INNER-X'] += $adjx; + } else { + $objattr['INNER-X'] -= $adjx; + $objattr['INNER-X'] -= $mw; + } + } + // mPDF 5.7.3 TRANSFORMS / BACKGROUND COLOR + // Transform also affects image background + if ($tr2) { + $this->writer->write('q ' . $tr2 . ' '); + } + if (isset($objattr['bgcolor']) && $objattr['bgcolor']) { + $bgcol = $objattr['bgcolor']; + $this->SetFColor($bgcol); + $this->Rect($x, $y, $w, $h, 'F'); + $this->SetFColor($this->colorConverter->convert(255, $this->PDFAXwarnings)); + } + if ($tr2) { + $this->writer->write('Q'); + } + + /* -- BACKGROUNDS -- */ + if (isset($objattr['GRADIENT-MASK'])) { + $g = $this->gradient->parseMozGradient($objattr['GRADIENT-MASK']); + if ($g) { + $dummy = $this->gradient->Gradient($objattr['INNER-X'], $objattr['INNER-Y'], $obiw, $obih, $g['type'], $g['stops'], $g['colorspace'], $g['coords'], $g['extend'], true, true); + $gradmask = '/TGS' . count($this->gradients) . ' gs '; + } + } + /* -- END BACKGROUNDS -- */ + /* -- IMAGES-WMF -- */ + if (isset($objattr['itype']) && $objattr['itype'] == 'wmf') { + $outstring = sprintf('q ' . $tr . $tr2 . '%.3F 0 0 %.3F %.3F %.3F cm /FO%d Do Q', $sx, -$sy, $objattr['INNER-X'] * Mpdf::SCALE - $sx * $objattr['wmf_x'], (($this->h - $objattr['INNER-Y']) * Mpdf::SCALE) + $sy * $objattr['wmf_y'], $objattr['ID']); // mPDF 5.7.3 TRANSFORMS + } else { /* -- END IMAGES-WMF -- */ + if (isset($objattr['itype']) && $objattr['itype'] == 'svg') { + $outstring = sprintf('q ' . $tr . $tr2 . '%.3F 0 0 %.3F %.3F %.3F cm /FO%d Do Q', $sx, -$sy, $objattr['INNER-X'] * Mpdf::SCALE - $sx * $objattr['wmf_x'], (($this->h - $objattr['INNER-Y']) * Mpdf::SCALE) + $sy * $objattr['wmf_y'], $objattr['ID']); // mPDF 5.7.3 TRANSFORMS + } else { + $outstring = sprintf("q " . $tr . $tr2 . "%.3F 0 0 %.3F %.3F %.3F cm " . $gradmask . "/I%d Do Q", $obiw * Mpdf::SCALE, $obih * Mpdf::SCALE, $objattr['INNER-X'] * Mpdf::SCALE, ($this->h - ($objattr['INNER-Y'] + $obih )) * Mpdf::SCALE, $objattr['ID']); // mPDF 5.7.3 TRANSFORMS + } + } + $this->writer->write($outstring); + // LINK + if (isset($objattr['link'])) { + $this->Link($objattr['INNER-X'], $objattr['INNER-Y'], $objattr['INNER-WIDTH'], $objattr['INNER-HEIGHT'], $objattr['link']); + } + if (isset($objattr['opacity'])) { + $this->SetAlpha(1); + } + + // mPDF 5.7.3 TRANSFORMS + // Transform also affects image borders + if ($tr2) { + $this->writer->write('q ' . $tr2 . ' '); + } + if ((isset($objattr['border_top']) && $objattr['border_top'] > 0) || (isset($objattr['border_left']) && $objattr['border_left'] > 0) || (isset($objattr['border_right']) && $objattr['border_right'] > 0) || (isset($objattr['border_bottom']) && $objattr['border_bottom'] > 0)) { + $this->PaintImgBorder($objattr, $is_table); + } + if ($tr2) { + $this->writer->write('Q'); + } + + if (isset($objattr['visibility']) && $objattr['visibility'] != 'visible' && $objattr['visibility']) { + $this->SetVisibility('visible'); + } + if (isset($objattr['z-index']) && $objattr['z-index'] > 0 && $this->current_layer == 0) { + $this->EndLayer(); + } + // mPDF 5.7.3 TRANSFORMS + if (isset($objattr['transform'])) { + $this->writer->write("\n" . '% ETR'); // End Transform + } + } + + if ($objattr['type'] === 'barcode') { + + $bgcol = $this->colorConverter->convert(255, $this->PDFAXwarnings); + + if (isset($objattr['bgcolor']) && $objattr['bgcolor']) { + $bgcol = $objattr['bgcolor']; + } + + $col = $this->colorConverter->convert(0, $this->PDFAXwarnings); + + if (isset($objattr['color']) && $objattr['color']) { + $col = $objattr['color']; + } + + $this->SetFColor($bgcol); + $this->Rect($objattr['BORDER-X'], $objattr['BORDER-Y'], $objattr['BORDER-WIDTH'], $objattr['BORDER-HEIGHT'], 'F'); + $this->SetFColor($this->colorConverter->convert(255, $this->PDFAXwarnings)); + + if (isset($objattr['BORDER-WIDTH'])) { + $this->PaintImgBorder($objattr, $is_table); + } + + $barcodeTypes = ['EAN13', 'ISBN', 'ISSN', 'UPCA', 'UPCE', 'EAN8']; + if (in_array($objattr['btype'], $barcodeTypes, true)) { + + $this->WriteBarcode( + $objattr['code'], + $objattr['showtext'], + $objattr['INNER-X'], + $objattr['INNER-Y'], + $objattr['bsize'], + 0, + 0, + 0, + 0, + 0, + $objattr['bheight'], + $bgcol, + $col, + $objattr['btype'], + $objattr['bsupp'], + (isset($objattr['bsupp_code']) ? $objattr['bsupp_code'] : ''), + $k + ); + + } elseif ($objattr['btype'] === 'QR') { + + if (!class_exists('Mpdf\QrCode\QrCode')) { + throw new \Mpdf\MpdfException('Class Mpdf\QrCode\QrCode does not exists. Install the package from Packagist with "composer require mpdf/qrcode"'); + } + + $barcodeContent = str_replace('\r\n', "\r\n", $objattr['code']); + $barcodeContent = str_replace('\n', "\n", $barcodeContent); + + $qrcode = new QrCode\QrCode($barcodeContent, $objattr['errorlevel']); + if ($objattr['disableborder']) { + $qrcode->disableBorder(); + } + + $bgColor = [255, 255, 255]; + if ($objattr['bgcolor']) { + $bgColor = array_map( + function ($col) { + return intval(255 * floatval($col)); + }, + explode(" ", $this->SetColor($objattr['bgcolor'], 'CodeOnly')) + ); + } + $color = [0, 0, 0]; + if ($objattr['color']) { + $color = array_map( + function ($col) { + return intval(255 * floatval($col)); + }, + explode(" ", $this->SetColor($objattr['color'], 'CodeOnly')) + ); + } + + $out = new QrCode\Output\Mpdf(); + $out->output( + $qrcode, + $this, + $objattr['INNER-X'], + $objattr['INNER-Y'], + $objattr['bsize'] * 25, + $bgColor, + $color + ); + + unset($qrcode); + + } else { + + $this->WriteBarcode2( + $objattr['code'], + $objattr['INNER-X'], + $objattr['INNER-Y'], + $objattr['bsize'], + $objattr['bheight'], + $bgcol, + $col, + $objattr['btype'], + $objattr['pr_ratio'], + $k + ); + + } + } + + // TEXT CIRCLE + if ($objattr['type'] == 'textcircle') { + $bgcol = ''; + if (isset($objattr['bgcolor']) && $objattr['bgcolor']) { + $bgcol = $objattr['bgcolor']; + } + $col = $this->colorConverter->convert(0, $this->PDFAXwarnings); + if (isset($objattr['color']) && $objattr['color']) { + $col = $objattr['color']; + } + $this->SetTColor($col); + $this->SetFColor($bgcol); + if ($bgcol) { + $this->Rect($objattr['BORDER-X'], $objattr['BORDER-Y'], $objattr['BORDER-WIDTH'], $objattr['BORDER-HEIGHT'], 'F'); + } + $this->SetFColor($this->colorConverter->convert(255, $this->PDFAXwarnings)); + if (isset($objattr['BORDER-WIDTH'])) { + $this->PaintImgBorder($objattr, $is_table); + } + if (empty($this->directWrite)) { + $this->directWrite = new DirectWrite($this, $this->otl, $this->sizeConverter, $this->colorConverter); + } + if (isset($objattr['top-text'])) { + $this->directWrite->CircularText($objattr['INNER-X'] + $objattr['INNER-WIDTH'] / 2, $objattr['INNER-Y'] + $objattr['INNER-HEIGHT'] / 2, $objattr['r'] / $k, $objattr['top-text'], 'top', $objattr['fontfamily'], $objattr['fontsize'] / $k, $objattr['fontstyle'], $objattr['space-width'], $objattr['char-width'], (isset($objattr['divider']) ? $objattr['divider'] : '')); + } + if (isset($objattr['bottom-text'])) { + $this->directWrite->CircularText($objattr['INNER-X'] + $objattr['INNER-WIDTH'] / 2, $objattr['INNER-Y'] + $objattr['INNER-HEIGHT'] / 2, $objattr['r'] / $k, $objattr['bottom-text'], 'bottom', $objattr['fontfamily'], $objattr['fontsize'] / $k, $objattr['fontstyle'], $objattr['space-width'], $objattr['char-width'], (isset($objattr['divider']) ? $objattr['divider'] : '')); + } + } + + $this->ResetSpacing(); + + // LIST MARKERS (Text or bullets) // mPDF 6 Lists + if ($objattr['type'] == 'listmarker') { + if (isset($objattr['fontfamily'])) { + $this->SetFont($objattr['fontfamily'], $objattr['fontstyle'], $objattr['fontsizept']); + } + $col = $this->colorConverter->convert(0, $this->PDFAXwarnings); + if (isset($objattr['colorarray']) && ($objattr['colorarray'])) { + $col = $objattr['colorarray']; + } + + if (isset($objattr['bullet']) && $objattr['bullet']) { // Used for position "outside" only + $type = $objattr['bullet']; + $size = $objattr['size']; + + if ($objattr['listmarkerposition'] == 'inside') { + $adjx = $size / 2; + if ($objattr['dir'] == 'rtl') { + $adjx += $objattr['offset']; + } + $this->x += $adjx; + } else { + $adjx = $objattr['offset']; + $adjx += $size / 2; + if ($objattr['dir'] == 'rtl') { + $this->x += $adjx; + } else { + $this->x -= $adjx; + } + } + + $yadj = $objattr['lineBox']['glyphYorigin']; + if (isset($this->CurrentFont['desc']['XHeight']) && $this->CurrentFont['desc']['XHeight']) { + $xh = $this->CurrentFont['desc']['XHeight']; + } else { + $xh = 500; + } + $yadj -= ($this->FontSize * $xh / 1000) * 0.625; // Vertical height of bullet (centre) from baseline= XHeight * 0.625 + $this->y += $yadj; + + $this->_printListBullet($this->x, $this->y, $size, $type, $col); + } else { + $this->SetTColor($col); + $w = $this->GetStringWidth($texto); + // NB If change marker-offset, also need to alter in function _getListMarkerWidth + $adjx = $this->sizeConverter->convert($this->list_marker_offset, $this->FontSize); + if ($objattr['dir'] == 'rtl') { + $align = 'L'; + $this->x += $adjx; + } else { + // Use these lines to set as marker-offset, right-aligned - default + $align = 'R'; + $this->x -= $adjx; + $this->x -= $w; + } + $this->Cell($w, $this->FontSize, $texto, 0, 0, $align, 0, '', 0, 0, 0, 'T', 0, false, false, 0, $objattr['lineBox']); + $this->SetTColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + } + } + + // DOT-TAB + if ($objattr['type'] == 'dottab') { + if (isset($objattr['fontfamily'])) { + $this->SetFont($objattr['fontfamily'], '', $objattr['fontsize']); + } + $sp = $this->GetStringWidth(' '); + $nb = floor(($w - 2 * $sp) / $this->GetStringWidth('.')); + if ($nb > 0) { + $dots = ' ' . str_repeat('.', $nb) . ' '; + } else { + $dots = ' '; + } + $col = $this->colorConverter->convert(0, $this->PDFAXwarnings); + if (isset($objattr['colorarray']) && ($objattr['colorarray'])) { + $col = $objattr['colorarray']; + } + $this->SetTColor($col); + $save_dh = $this->divheight; + $save_sbd = $this->spanborddet; + $save_textvar = $this->textvar; // mPDF 5.7.1 + $this->spanborddet = ''; + $this->divheight = 0; + $this->textvar = 0x00; // mPDF 5.7.1 + + $this->Cell($w, $h, $dots, 0, 0, 'C', 0, '', 0, 0, 0, 'T', 0, false, false, 0, $objattr['lineBox']); // mPDF 6 DOTTAB + $this->spanborddet = $save_sbd; + $this->textvar = $save_textvar; // mPDF 5.7.1 + $this->divheight = $save_dh; + $this->SetTColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + } + + /* -- FORMS -- */ + // TEXT/PASSWORD INPUT + if ($objattr['type'] == 'input' && ($objattr['subtype'] == 'TEXT' || $objattr['subtype'] == 'PASSWORD')) { + $this->form->print_ob_text($objattr, $w, $h, $texto, $rtlalign, $k, $blockdir); + } + + // TEXTAREA + if ($objattr['type'] == 'textarea') { + $this->form->print_ob_textarea($objattr, $w, $h, $texto, $rtlalign, $k, $blockdir); + } + + // SELECT + if ($objattr['type'] == 'select') { + $this->form->print_ob_select($objattr, $w, $h, $texto, $rtlalign, $k, $blockdir); + } + + + // INPUT/BUTTON as IMAGE + if ($objattr['type'] == 'input' && $objattr['subtype'] == 'IMAGE') { + $this->form->print_ob_imageinput($objattr, $w, $h, $texto, $rtlalign, $k, $blockdir, $is_table); + } + + // BUTTON + if ($objattr['type'] == 'input' && ($objattr['subtype'] == 'SUBMIT' || $objattr['subtype'] == 'RESET' || $objattr['subtype'] == 'BUTTON')) { + $this->form->print_ob_button($objattr, $w, $h, $texto, $rtlalign, $k, $blockdir); + } + + // CHECKBOX + if ($objattr['type'] == 'input' && ($objattr['subtype'] == 'CHECKBOX')) { + $this->form->print_ob_checkbox($objattr, $w, $h, $texto, $rtlalign, $k, $blockdir, $x, $y); + } + // RADIO + if ($objattr['type'] == 'input' && ($objattr['subtype'] == 'RADIO')) { + $this->form->print_ob_radio($objattr, $w, $h, $texto, $rtlalign, $k, $blockdir, $x, $y); + } + /* -- END FORMS -- */ + } + + $this->SetFont($save_currentfontfamily, $save_currentfontstyle, $save_currentfontsize); + + $this->y = $save_y; + $this->x = $save_x; + + unset($content); + } + + function _printListBullet($x, $y, $size, $type, $color) + { + // x and y are the centre of the bullet; size is the width and/or height in mm + $fcol = $this->SetTColor($color, true); + $lcol = strtoupper($fcol); // change 0 0 0 rg to 0 0 0 RG + $this->writer->write(sprintf('q %s %s', $lcol, $fcol)); + $this->writer->write('0 j 0 J [] 0 d'); + if ($type == 'square') { + $size *= 0.85; // Smaller to appear the same size as circle/disc + $this->writer->write(sprintf('%.3F %.3F %.3F %.3F re f', ($x - $size / 2) * Mpdf::SCALE, ($this->h - $y + $size / 2) * Mpdf::SCALE, ($size) * Mpdf::SCALE, (-$size) * Mpdf::SCALE)); + } elseif ($type == 'disc') { + $this->Circle($x, $y, $size / 2, 'F'); // Fill + } elseif ($type == 'circle') { + $lw = $size / 12; // Line width + $this->writer->write(sprintf('%.3F w ', $lw * Mpdf::SCALE)); + $this->Circle($x, $y, $size / 2 - $lw / 2, 'S'); // Stroke + } + $this->writer->write('Q'); + } + + // mPDF 6 + // Get previous character and move pointers + function _moveToPrevChar(&$contentctr, &$charctr, $content) + { + $lastchar = false; + $charctr--; + while ($charctr < 0) { // go back to previous $content[] + $contentctr--; + if ($contentctr < 0) { + return false; + } + if ($this->usingCoreFont) { + $charctr = strlen($content[$contentctr]) - 1; + } else { + $charctr = mb_strlen($content[$contentctr], $this->mb_enc) - 1; + } + } + if ($this->usingCoreFont) { + $lastchar = $content[$contentctr][$charctr]; + } else { + $lastchar = mb_substr($content[$contentctr], $charctr, 1, $this->mb_enc); + } + return $lastchar; + } + + // Get previous character + function _getPrevChar($contentctr, $charctr, $content) + { + $lastchar = false; + $charctr--; + while ($charctr < 0) { // go back to previous $content[] + $contentctr--; + if ($contentctr < 0) { + return false; + } + if ($this->usingCoreFont) { + $charctr = strlen($content[$contentctr]) - 1; + } else { + $charctr = mb_strlen($content[$contentctr], $this->mb_enc) - 1; + } + } + if ($this->usingCoreFont) { + $lastchar = $content[$contentctr][$charctr]; + } else { + $lastchar = mb_substr($content[$contentctr], $charctr, 1, $this->mb_enc); + } + return $lastchar; + } + + function WriteFlowingBlock($s, $sOTLdata) + { + // mPDF 5.7.1 + $currentx = $this->x; + $is_table = $this->flowingBlockAttr['is_table']; + $table_draft = $this->flowingBlockAttr['table_draft']; + // width of all the content so far in points + $contentWidth = & $this->flowingBlockAttr['contentWidth']; + // cell width in points + $maxWidth = & $this->flowingBlockAttr['width']; + $lineCount = & $this->flowingBlockAttr['lineCount']; + // line height in user units + $stackHeight = & $this->flowingBlockAttr['height']; + $align = & $this->flowingBlockAttr['align']; + $content = & $this->flowingBlockAttr['content']; + $contentB = & $this->flowingBlockAttr['contentB']; + $font = & $this->flowingBlockAttr['font']; + $valign = & $this->flowingBlockAttr['valign']; + $blockstate = $this->flowingBlockAttr['blockstate']; + $cOTLdata = & $this->flowingBlockAttr['cOTLdata']; // mPDF 5.7.1 + + $newblock = $this->flowingBlockAttr['newblock']; + $blockdir = $this->flowingBlockAttr['blockdir']; + + // *********** BLOCK BACKGROUND COLOR ***************** // + if ($this->blk[$this->blklvl]['bgcolor'] && !$is_table) { + $fill = 0; + } else { + $this->SetFColor($this->colorConverter->convert(255, $this->PDFAXwarnings)); + $fill = 0; + } + $font[] = $this->saveFont(); + $content[] = ''; + $contentB[] = ''; + $cOTLdata[] = $sOTLdata; // mPDF 5.7.1 + $currContent = & $content[count($content) - 1]; + + $CJKoverflow = false; + $Oikomi = false; // mPDF 6 + $hanger = ''; + + // COLS + $oldcolumn = $this->CurrCol; + if ($this->ColActive && !$is_table) { + $this->breakpoints[$this->CurrCol][] = $this->y; + } // *COLUMNS* + + /* -- TABLES -- */ + if ($is_table) { + $ipaddingL = 0; + $ipaddingR = 0; + $paddingL = 0; + $paddingR = 0; + $cpaddingadjustL = 0; + $cpaddingadjustR = 0; + // Added mPDF 3.0 + $fpaddingR = 0; + $fpaddingL = 0; + } else { + /* -- END TABLES -- */ + $ipaddingL = $this->blk[$this->blklvl]['padding_left']; + $ipaddingR = $this->blk[$this->blklvl]['padding_right']; + $paddingL = ($ipaddingL * Mpdf::SCALE); + $paddingR = ($ipaddingR * Mpdf::SCALE); + $this->cMarginL = $this->blk[$this->blklvl]['border_left']['w']; + $cpaddingadjustL = -$this->cMarginL; + $this->cMarginR = $this->blk[$this->blklvl]['border_right']['w']; + $cpaddingadjustR = -$this->cMarginR; + // Added mPDF 3.0 Float DIV + $fpaddingR = 0; + $fpaddingL = 0; + /* -- CSS-FLOAT -- */ + if (count($this->floatDivs)) { + list($l_exists, $r_exists, $l_max, $r_max, $l_width, $r_width) = $this->GetFloatDivInfo($this->blklvl); + if ($r_exists) { + $fpaddingR = $r_width; + } + if ($l_exists) { + $fpaddingL = $l_width; + } + } + /* -- END CSS-FLOAT -- */ + + $usey = $this->y + 0.002; + if (($newblock) && ($blockstate == 1 || $blockstate == 3) && ($lineCount == 0)) { + $usey += $this->blk[$this->blklvl]['margin_top'] + $this->blk[$this->blklvl]['padding_top'] + $this->blk[$this->blklvl]['border_top']['w']; + } + /* -- CSS-IMAGE-FLOAT -- */ + // If float exists at this level + if (isset($this->floatmargins['R']) && $usey <= $this->floatmargins['R']['y1'] && $usey >= $this->floatmargins['R']['y0'] && !$this->floatmargins['R']['skipline']) { + $fpaddingR += $this->floatmargins['R']['w']; + } + if (isset($this->floatmargins['L']) && $usey <= $this->floatmargins['L']['y1'] && $usey >= $this->floatmargins['L']['y0'] && !$this->floatmargins['L']['skipline']) { + $fpaddingL += $this->floatmargins['L']['w']; + } + /* -- END CSS-IMAGE-FLOAT -- */ + } // *TABLES* + // OBJECTS - IMAGES & FORM Elements (NB has already skipped line/page if required - in printbuffer) + if (substr($s, 0, 3) == "\xbb\xa4\xac") { // identifier has been identified! + $objattr = $this->_getObjAttr($s); + $h_corr = 0; + if ($is_table) { // *TABLES* + $maximumW = ($maxWidth / Mpdf::SCALE) - ($this->cellPaddingL + $this->cMarginL + $this->cellPaddingR + $this->cMarginR); // *TABLES* + } // *TABLES* + else { // *TABLES* + if (($newblock) && ($blockstate == 1 || $blockstate == 3) && ($lineCount == 0) && (!$is_table)) { + $h_corr = $this->blk[$this->blklvl]['padding_top'] + $this->blk[$this->blklvl]['border_top']['w']; + } + $maximumW = ($maxWidth / Mpdf::SCALE) - ($this->blk[$this->blklvl]['padding_left'] + $this->blk[$this->blklvl]['border_left']['w'] + $this->blk[$this->blklvl]['padding_right'] + $this->blk[$this->blklvl]['border_right']['w'] + $fpaddingL + $fpaddingR ); + } // *TABLES* + $objattr = $this->inlineObject($objattr['type'], $this->lMargin + $fpaddingL + ($contentWidth / Mpdf::SCALE), ($this->y + $h_corr), $objattr, $this->lMargin, ($contentWidth / Mpdf::SCALE), $maximumW, $stackHeight, true, $is_table); + + // SET LINEHEIGHT for this line ================ RESET AT END + $stackHeight = max($stackHeight, $objattr['OUTER-HEIGHT']); + $this->objectbuffer[count($content) - 1] = $objattr; + // if (isset($objattr['vertical-align'])) { $valign = $objattr['vertical-align']; } + // else { $valign = ''; } + // LIST MARKERS // mPDF 6 Lists + if ($objattr['type'] == 'image' && isset($objattr['listmarker']) && $objattr['listmarker'] && $objattr['listmarkerposition'] == 'outside') { + // do nothing + } else { + $contentWidth += ($objattr['OUTER-WIDTH'] * Mpdf::SCALE); + } + return; + } + + $lbw = $rbw = 0; // Border widths + if (!empty($this->spanborddet)) { + if (isset($this->spanborddet['L'])) { + $lbw = $this->spanborddet['L']['w']; + } + if (isset($this->spanborddet['R'])) { + $rbw = $this->spanborddet['R']['w']; + } + } + + if ($this->usingCoreFont) { + $clen = strlen($s); + } else { + $clen = mb_strlen($s, $this->mb_enc); + } + + // for every character in the string + for ($i = 0; $i < $clen; $i++) { + // extract the current character + // get the width of the character in points + if ($this->usingCoreFont) { + $c = $s[$i]; + // Soft Hyphens chr(173) + $cw = ($this->GetCharWidthCore($c) * Mpdf::SCALE); + if (($this->textvar & TextVars::FC_KERNING) && $i > 0) { // mPDF 5.7.1 + if (isset($this->CurrentFont['kerninfo'][$s[($i - 1)]][$c])) { + $cw += ($this->CurrentFont['kerninfo'][$s[($i - 1)]][$c] * $this->FontSizePt / 1000 ); + } + } + } else { + $c = mb_substr($s, $i, 1, $this->mb_enc); + $cw = ($this->GetCharWidthNonCore($c, false) * Mpdf::SCALE); + // mPDF 5.7.1 + // Use OTL GPOS + if (isset($this->CurrentFont['useOTL']) && ($this->CurrentFont['useOTL'] & 0xFF)) { + // ...WriteFlowingBlock... + // Only add XAdvanceL (not sure at present whether RTL or LTR writing direction) + // At this point, XAdvanceL and XAdvanceR will balance + if (isset($sOTLdata['GPOSinfo'][$i]['XAdvanceL'])) { + $cw += $sOTLdata['GPOSinfo'][$i]['XAdvanceL'] * (1000 / $this->CurrentFont['unitsPerEm']) * ($this->FontSize / 1000) * Mpdf::SCALE; + } + } + if (($this->textvar & TextVars::FC_KERNING) && $i > 0) { // mPDF 5.7.1 + $lastc = mb_substr($s, ($i - 1), 1, $this->mb_enc); + $ulastc = $this->UTF8StringToArray($lastc, false); + $uc = $this->UTF8StringToArray($c, false); + if (isset($this->CurrentFont['kerninfo'][$ulastc[0]][$uc[0]])) { + $cw += ($this->CurrentFont['kerninfo'][$ulastc[0]][$uc[0]] * $this->FontSizePt / 1000 ); + } + } + } + + if ($i == 0) { + $cw += $lbw * Mpdf::SCALE; + $contentB[(count($contentB) - 1)] .= 'L'; + } + if ($i == ($clen - 1)) { + $cw += $rbw * Mpdf::SCALE; + $contentB[(count($contentB) - 1)] .= 'R'; + } + if ($c == ' ') { + $currContent .= $c; + $contentWidth += $cw; + continue; + } + + // Paragraph INDENT + $WidthCorrection = 0; + if (($newblock) && ($blockstate == 1 || $blockstate == 3) && isset($this->blk[$this->blklvl]['text_indent']) && ($lineCount == 0) && (!$is_table) && ($align != 'C')) { + $ti = $this->sizeConverter->convert($this->blk[$this->blklvl]['text_indent'], $this->blk[$this->blklvl]['inner_width'], $this->blk[$this->blklvl]['InlineProperties']['size'], false); // mPDF 5.7.4 + $WidthCorrection = ($ti * Mpdf::SCALE); + } + // OUTDENT + foreach ($this->objectbuffer as $k => $objattr) { // mPDF 6 DOTTAB + if ($objattr['type'] == 'dottab') { + $WidthCorrection -= ($objattr['outdent'] * Mpdf::SCALE); + break; + } + } + + + // Added mPDF 3.0 Float DIV + $fpaddingR = 0; + $fpaddingL = 0; + /* -- CSS-FLOAT -- */ + if (count($this->floatDivs)) { + list($l_exists, $r_exists, $l_max, $r_max, $l_width, $r_width) = $this->GetFloatDivInfo($this->blklvl); + if ($r_exists) { + $fpaddingR = $r_width; + } + if ($l_exists) { + $fpaddingL = $l_width; + } + } + /* -- END CSS-FLOAT -- */ + + $usey = $this->y + 0.002; + if (($newblock) && ($blockstate == 1 || $blockstate == 3) && ($lineCount == 0)) { + $usey += $this->blk[$this->blklvl]['margin_top'] + $this->blk[$this->blklvl]['padding_top'] + $this->blk[$this->blklvl]['border_top']['w']; + } + + /* -- CSS-IMAGE-FLOAT -- */ + // If float exists at this level + if (isset($this->floatmargins['R']) && $usey <= $this->floatmargins['R']['y1'] && $usey >= $this->floatmargins['R']['y0'] && !$this->floatmargins['R']['skipline']) { + $fpaddingR += $this->floatmargins['R']['w']; + } + if (isset($this->floatmargins['L']) && $usey <= $this->floatmargins['L']['y1'] && $usey >= $this->floatmargins['L']['y0'] && !$this->floatmargins['L']['skipline']) { + $fpaddingL += $this->floatmargins['L']['w']; + } + /* -- END CSS-IMAGE-FLOAT -- */ + + + // try adding another char + if (( $contentWidth + $cw > $maxWidth - $WidthCorrection - (($this->cMarginL + $this->cMarginR) * Mpdf::SCALE) - ($paddingL + $paddingR + (($fpaddingL + $fpaddingR) * Mpdf::SCALE) ) + 0.001)) {// 0.001 is to correct for deviations converting mm=>pts + // it won't fit, output what we already have + $lineCount++; + + // contains any content that didn't make it into this print + $savedContent = ''; + $savedContentB = ''; + $savedOTLdata = []; // mPDF 5.7.1 + $savedFont = []; + $savedObj = []; + $savedPreOTLdata = []; // mPDF 5.7.1 + $savedPreContent = []; + $savedPreContentB = []; + $savedPreFont = []; + + // mPDF 6 + // New line-breaking algorithm + ///////////////////// + // LINE BREAKING + ///////////////////// + $breakfound = false; + $contentctr = count($content) - 1; + if ($this->usingCoreFont) { + $charctr = strlen($currContent); + } else { + $charctr = mb_strlen($currContent, $this->mb_enc); + } + $checkchar = $c; + $prevchar = $this->_getPrevChar($contentctr, $charctr, $content); + + /* -- CJK-FONTS -- */ + // 1) CJK Overflowing a) punctuation or b) Oikomi + // Next character ($c) is suitable to add as overhanging or squeezed punctuation, or Oikomi + if ($CJKoverflow || $Oikomi) { // If flag already set + $CJKoverflow = false; + $Oikomi = false; + $breakfound = true; + } + if (!$this->usingCoreFont && !$breakfound && $this->checkCJK) { + + // Get next/following character (in this chunk) + $followingchar = ''; + if ($i < ($clen - 1)) { + if ($this->usingCoreFont) { + $followingchar = $s[$i + 1]; + } else { + $followingchar = mb_substr($s, $i + 1, 1, $this->mb_enc); + } + } + + // 1a) Overflow punctuation + if (preg_match("/[" . $this->pregCJKchars . "]/u", $prevchar) && preg_match("/[" . $this->CJKoverflow . "]/u", $checkchar) && $this->allowCJKorphans) { + // add character onto this line + $currContent .= $c; + $contentWidth += $cw; + $CJKoverflow = true; // Set flag + continue; + } elseif (preg_match("/[" . $this->pregCJKchars . "]/u", $checkchar) && $this->allowCJKorphans && + (preg_match("/[" . $this->CJKleading . "]/u", $followingchar) || preg_match("/[" . $this->CJKfollowing . "]/u", $checkchar)) && + !preg_match("/[" . $this->CJKleading . "]/u", $checkchar) && !preg_match("/[" . $this->CJKfollowing . "]/u", $followingchar) && + !(preg_match("/[0-9\x{ff10}-\x{ff19}]/u", $followingchar) && preg_match("/[0-9\x{ff10}-\x{ff19}]/u", $checkchar))) { + // 1b) Try squeezing another character(s) onto this line = Oikomi, if character cannot end line + // or next character cannot start line (and not splitting CJK numerals) + // NB otherwise it move lastchar(s) to next line to keep $c company = Oidashi, which is done below in standard way + // add character onto this line + $currContent .= $c; + $contentWidth += $cw; + $Oikomi = true; // Set flag + continue; + } + } + /* -- END CJK-FONTS -- */ + /* -- HYPHENATION -- */ + + // AUTOMATIC HYPHENATION + // 2) Automatic hyphen in current word (does not cross tags) + if (isset($this->textparam['hyphens']) && $this->textparam['hyphens'] == 1) { + $currWord = ''; + // Look back and ahead to get current word + for ($ac = $charctr - 1; $ac >= 0; $ac--) { + if ($this->usingCoreFont) { + $addc = substr($currContent, $ac, 1); + } else { + $addc = mb_substr($currContent, $ac, 1, $this->mb_enc); + } + if ($addc == ' ') { + break; + } + $currWord = $addc . $currWord; + } + $start = $ac + 1; + for ($ac = $i; $ac < ($clen - 1); $ac++) { + if ($this->usingCoreFont) { + $addc = substr($s, $ac, 1); + } else { + $addc = mb_substr($s, $ac, 1, $this->mb_enc); + } + if ($addc == ' ') { + break; + } + $currWord .= $addc; + } + $ptr = $this->hyphenator->hyphenateWord($currWord, $charctr - $start); + if ($ptr > -1) { + $breakfound = [$contentctr, $start + $ptr, $contentctr, $start + $ptr, 'hyphen']; + } + } + /* -- END HYPHENATION -- */ + + // Search backwards to find first line-break opportunity + while ($breakfound == false && $prevchar !== false) { + $cutcontentctr = $contentctr; + $cutcharctr = $charctr; + $prevchar = $this->_moveToPrevChar($contentctr, $charctr, $content); + ///////////////////// + // 3) Break at SPACE + ///////////////////// + if ($prevchar == ' ') { + $breakfound = [$contentctr, $charctr, $cutcontentctr, $cutcharctr, 'discard']; + } ///////////////////// + // 4) Break at U+200B in current word (Khmer, Lao & Thai Invisible word boundary, and Tibetan) + ///////////////////// + elseif ($prevchar == "\xe2\x80\x8b") { // U+200B Zero-width Word Break + $breakfound = [$contentctr, $charctr, $cutcontentctr, $cutcharctr, 'discard']; + } ///////////////////// + // 5) Break at Hard HYPHEN '-' or U+2010 + ///////////////////// + elseif (isset($this->textparam['hyphens']) && $this->textparam['hyphens'] != 2 && ($prevchar == '-' || $prevchar == "\xe2\x80\x90")) { + // Don't break a URL + // Look back to get first part of current word + $checkw = ''; + for ($ac = $charctr - 1; $ac >= 0; $ac--) { + if ($this->usingCoreFont) { + $addc = substr($currContent, $ac, 1); + } else { + $addc = mb_substr($currContent, $ac, 1, $this->mb_enc); + } + if ($addc == ' ') { + break; + } + $checkw = $addc . $checkw; + } + // Don't break if HyphenMinus AND (a URL or before a numeral or before a >) + if ((!preg_match('/(http:|ftp:|https:|www\.)/', $checkw) && $checkchar != '>' && !preg_match('/[0-9]/', $checkchar)) || $prevchar == "\xe2\x80\x90") { + $breakfound = [$cutcontentctr, $cutcharctr, $cutcontentctr, $cutcharctr, 'cut']; + } + } ///////////////////// + // 6) Break at Soft HYPHEN (replace with hard hyphen) + ///////////////////// + elseif (isset($this->textparam['hyphens']) && $this->textparam['hyphens'] != 2 && !$this->usingCoreFont && $prevchar == "\xc2\xad") { + $breakfound = [$cutcontentctr, $cutcharctr, $cutcontentctr, $cutcharctr, 'cut']; + $content[$contentctr] = mb_substr($content[$contentctr], 0, $charctr, $this->mb_enc) . '-' . mb_substr($content[$contentctr], $charctr + 1, mb_strlen($content[$contentctr]), $this->mb_enc); + if (!empty($cOTLdata[$contentctr])) { + $cOTLdata[$contentctr]['char_data'][$charctr] = ['bidi_class' => 9, 'uni' => 45]; + $cOTLdata[$contentctr]['group'][$charctr] = 'C'; + } + } elseif (isset($this->textparam['hyphens']) && $this->textparam['hyphens'] != 2 && $this->FontFamily != 'csymbol' && $this->FontFamily != 'czapfdingbats' && $prevchar == chr(173)) { + $breakfound = [$cutcontentctr, $cutcharctr, $cutcontentctr, $cutcharctr, 'cut']; + $content[$contentctr] = substr($content[$contentctr], 0, $charctr) . '-' . substr($content[$contentctr], $charctr + 1); + } /* -- CJK-FONTS -- */ + ///////////////////// + // 7) Break at CJK characters (unless forbidden characters to end or start line) + // CJK Avoiding line break in the middle of numerals + ///////////////////// + elseif (!$this->usingCoreFont && $this->checkCJK && preg_match("/[" . $this->pregCJKchars . "]/u", $checkchar) && + !preg_match("/[" . $this->CJKfollowing . "]/u", $checkchar) && !preg_match("/[" . $this->CJKleading . "]/u", $prevchar) && + !(preg_match("/[0-9\x{ff10}-\x{ff19}]/u", $prevchar) && preg_match("/[0-9\x{ff10}-\x{ff19}]/u", $checkchar))) { + $breakfound = [$cutcontentctr, $cutcharctr, $cutcontentctr, $cutcharctr, 'cut']; + } + /* -- END CJK-FONTS -- */ + ///////////////////// + // 8) Break at OBJECT (Break before all objects here - selected objects are moved forward to next line below e.g. dottab) + ///////////////////// + if (isset($this->objectbuffer[$contentctr])) { + $breakfound = [$cutcontentctr, $cutcharctr, $cutcontentctr, $cutcharctr, 'cut']; + } + + + $checkchar = $prevchar; + } + + // If a line-break opportunity found: + if (is_array($breakfound)) { + $contentctr = $breakfound[0]; + $charctr = $breakfound[1]; + $cutcontentctr = $breakfound[2]; + $cutcharctr = $breakfound[3]; + $type = $breakfound[4]; + // Cache chunks which are already processed, but now need to be passed on to the new line + for ($ix = count($content) - 1; $ix > $cutcontentctr; $ix--) { + // save and crop off any subsequent chunks + /* -- OTL -- */ + if (!empty($sOTLdata)) { + $tmpOTL = array_pop($cOTLdata); + $savedPreOTLdata[] = $tmpOTL; + } + /* -- END OTL -- */ + $savedPreContent[] = array_pop($content); + $savedPreContentB[] = array_pop($contentB); + $savedPreFont[] = array_pop($font); + } + + // Next cache the part which will start the next line + if ($this->usingCoreFont) { + $savedPreContent[] = substr($content[$cutcontentctr], $cutcharctr); + } else { + $savedPreContent[] = mb_substr($content[$cutcontentctr], $cutcharctr, mb_strlen($content[$cutcontentctr]), $this->mb_enc); + } + $savedPreContentB[] = preg_replace('/L/', '', $contentB[$cutcontentctr]); + $savedPreFont[] = $font[$cutcontentctr]; + /* -- OTL -- */ + if (!empty($sOTLdata)) { + $savedPreOTLdata[] = $this->otl->splitOTLdata($cOTLdata[$cutcontentctr], $cutcharctr, $cutcharctr); + } + /* -- END OTL -- */ + + + // Finally adjust the Current content which ends this line + if ($cutcharctr == 0 && $type == 'discard') { + array_pop($content); + array_pop($contentB); + array_pop($font); + array_pop($cOTLdata); + } + + $currContent = & $content[count($content) - 1]; + if ($this->usingCoreFont) { + $currContent = substr($currContent, 0, $charctr); + } else { + $currContent = mb_substr($currContent, 0, $charctr, $this->mb_enc); + } + + if (!empty($sOTLdata)) { + $savedPreOTLdata[] = $this->otl->splitOTLdata($cOTLdata[(count($cOTLdata) - 1)], mb_strlen($currContent, $this->mb_enc)); + } + + if (strpos($contentB[(count($contentB) - 1)], 'R') !== false) { // ??? + $contentB[count($content) - 1] = preg_replace('/R/', '', $contentB[count($content) - 1]); // ??? + } + + if ($type == 'hyphen') { + $currContent .= '-'; + if (!empty($cOTLdata[(count($cOTLdata) - 1)])) { + $cOTLdata[(count($cOTLdata) - 1)]['char_data'][] = ['bidi_class' => 9, 'uni' => 45]; + $cOTLdata[(count($cOTLdata) - 1)]['group'] .= 'C'; + } + } + + $savedContent = ''; + $savedContentB = ''; + $savedFont = []; + $savedOTLdata = []; + } + // If no line-break opportunity found - split at current position + // or - Next character ($c) is suitable to add as overhanging or squeezed punctuation, or Oikomi, as set above by: + // 1) CJK Overflowing a) punctuation or b) Oikomi + // in which case $breakfound==1 and NOT array + + if (!is_array($breakfound)) { + $savedFont = $this->saveFont(); + if (!empty($sOTLdata)) { + $savedOTLdata = $this->otl->splitOTLdata($cOTLdata[(count($cOTLdata) - 1)], mb_strlen($currContent, $this->mb_enc)); + } + } + + if ($content[count($content) - 1] == '' && !isset($this->objectbuffer[count($content) - 1])) { + array_pop($content); + array_pop($contentB); + array_pop($font); + array_pop($cOTLdata); + $currContent = & $content[count($content) - 1]; + } + + // Right Trim current content - including CJK space, and for OTLdata + // incl. CJK - strip CJK space at end of line   = \xe3\x80\x80 = CJK space + $currContent = rtrim($currContent); + if ($this->checkCJK) { + $currContent = preg_replace("/\xe3\x80\x80$/", '', $currContent); + } // *CJK-FONTS* + /* -- OTL -- */ + if (isset($this->CurrentFont['useOTL']) && $this->CurrentFont['useOTL']) { + $this->otl->trimOTLdata($cOTLdata[count($cOTLdata) - 1], false, true); // NB also does U+3000 + } + /* -- END OTL -- */ + + + // Selected OBJECTS are moved forward to next line, unless they come before a space or U+200B (type='discard') + if (isset($this->objectbuffer[(count($content) - 1)]) && (!isset($type) || $type != 'discard')) { + $objtype = $this->objectbuffer[(count($content) - 1)]['type']; + if ($objtype == 'dottab' || $objtype == 'bookmark' || $objtype == 'indexentry' || $objtype == 'toc' || $objtype == 'annot') { + $savedObj = array_pop($this->objectbuffer); + } + } + + + // Decimal alignment (cancel if wraps to > 1 line) + if ($is_table && substr($align, 0, 1) == 'D') { + $align = substr($align, 2, 1); + } + + $lineBox = []; + + $this->_setInlineBlockHeights($lineBox, $stackHeight, $content, $font, $is_table); + + // update $contentWidth since it has changed with cropping + $contentWidth = 0; + + $inclCursive = false; + foreach ($content as $k => $chunk) { + if (isset($this->objectbuffer[$k]) && $this->objectbuffer[$k]) { + // LIST MARKERS + if ($this->objectbuffer[$k]['type'] == 'image' && isset($this->objectbuffer[$k]['listmarker']) && $this->objectbuffer[$k]['listmarker']) { + if ($this->objectbuffer[$k]['listmarkerposition'] != 'outside') { + $contentWidth += $this->objectbuffer[$k]['OUTER-WIDTH'] * Mpdf::SCALE; + } + } else { + $contentWidth += $this->objectbuffer[$k]['OUTER-WIDTH'] * Mpdf::SCALE; + } + } elseif (!isset($this->objectbuffer[$k]) || (isset($this->objectbuffer[$k]) && !$this->objectbuffer[$k])) { + $this->restoreFont($font[$k], false); + if ($this->checkCJK && $k == count($content) - 1 && $CJKoverflow && $align == 'J' && $this->allowCJKoverflow && $this->CJKforceend) { + // force-end overhang + $hanger = mb_substr($chunk, mb_strlen($chunk, $this->mb_enc) - 1, 1, $this->mb_enc); + // Probably ought to do something with char_data and GPOS in cOTLdata... + $content[$k] = $chunk = mb_substr($chunk, 0, mb_strlen($chunk, $this->mb_enc) - 1, $this->mb_enc); + } + + // Soft Hyphens chr(173) + Replace NBSP with SPACE + Set inclcursive if includes CURSIVE TEXT + if (!$this->usingCoreFont) { + /* -- OTL -- */ + if ((isset($this->CurrentFont['useOTL']) && $this->CurrentFont['useOTL']) || !empty($sOTLdata)) { + $this->otl->removeChar($chunk, $cOTLdata[$k], "\xc2\xad"); + $this->otl->replaceSpace($chunk, $cOTLdata[$k]); // NBSP -> space + if (preg_match("/([" . $this->pregCURSchars . "])/u", $chunk)) { + $inclCursive = true; + } + $content[$k] = $chunk; + } /* -- END OTL -- */ else { // *OTL* + $content[$k] = $chunk = str_replace("\xc2\xad", '', $chunk); + $content[$k] = $chunk = str_replace(chr(194) . chr(160), chr(32), $chunk); + } // *OTL* + } elseif ($this->FontFamily != 'csymbol' && $this->FontFamily != 'czapfdingbats') { + $content[$k] = $chunk = str_replace(chr(173), '', $chunk); + $content[$k] = $chunk = str_replace(chr(160), chr(32), $chunk); + } + + $contentWidth += $this->GetStringWidth($chunk, true, (isset($cOTLdata[$k]) ? $cOTLdata[$k] : false), $this->textvar) * Mpdf::SCALE; // mPDF 5.7.1 + if (!empty($this->spanborddet)) { + if (isset($this->spanborddet['L']['w']) && strpos($contentB[$k], 'L') !== false) { + $contentWidth += $this->spanborddet['L']['w'] * Mpdf::SCALE; + } + if (isset($this->spanborddet['R']['w']) && strpos($contentB[$k], 'R') !== false) { + $contentWidth += $this->spanborddet['R']['w'] * Mpdf::SCALE; + } + } + } + } + + $lastfontreqstyle = (isset($font[count($font) - 1]['ReqFontStyle']) ? $font[count($font) - 1]['ReqFontStyle'] : ''); + $lastfontstyle = (isset($font[count($font) - 1]['style']) ? $font[count($font) - 1]['style'] : ''); + if ($blockdir == 'ltr' && strpos($lastfontreqstyle, "I") !== false && strpos($lastfontstyle, "I") === false) { // Artificial italic + $lastitalic = $this->FontSize * 0.15 * Mpdf::SCALE; + } else { + $lastitalic = 0; + } + + + + + // NOW FORMAT THE LINE TO OUTPUT + if (!$table_draft) { + // DIRECTIONALITY RTL + $chunkorder = range(0, count($content) - 1); // mPDF 5.7 + /* -- OTL -- */ + // mPDF 6 + if ($blockdir == 'rtl' || $this->biDirectional) { + $this->otl->bidiReorder($chunkorder, $content, $cOTLdata, $blockdir); + // From this point on, $content and $cOTLdata may contain more elements (and re-ordered) compared to + // $this->objectbuffer and $font ($chunkorder contains the mapping) + } + + /* -- END OTL -- */ + // Remove any XAdvance from OTL data at end of line + foreach ($chunkorder as $aord => $k) { + if (count($cOTLdata)) { + $this->restoreFont($font[$k], false); + // ...WriteFlowingBlock... + if ($aord == count($chunkorder) - 1 && isset($cOTLdata[$aord]['group'])) { // Last chunk on line + $nGPOS = strlen($cOTLdata[$aord]['group']) - 1; // Last character + if (isset($cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XAdvanceL']) || isset($cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XAdvanceR'])) { + if (isset($cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XAdvanceL'])) { + $w = $cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XAdvanceL'] * 1000 / $this->CurrentFont['unitsPerEm']; + } else { + $w = $cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XAdvanceR'] * 1000 / $this->CurrentFont['unitsPerEm']; + } + $w *= ($this->FontSize / 1000); + $contentWidth -= $w * Mpdf::SCALE; + $cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XAdvanceL'] = 0; + $cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XAdvanceR'] = 0; + } + + // If last character has an XPlacement set, adjust width calculation, and add to XAdvance to account for it + if (isset($cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XPlacement'])) { + $w = -$cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XPlacement'] * 1000 / $this->CurrentFont['unitsPerEm']; + $w *= ($this->FontSize / 1000); + $contentWidth -= $w * Mpdf::SCALE; + $cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XAdvanceL'] = $cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XPlacement']; + $cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XAdvanceR'] = $cOTLdata[$aord]['GPOSinfo'][$nGPOS]['XPlacement']; + } + } + } + } + + // JUSTIFICATION J + $jcharspacing = 0; + $jws = 0; + $nb_carac = 0; + $nb_spaces = 0; + $jkashida = 0; + // if it's justified, we need to find the char/word spacing (or if hanger $this->CJKforceend) + if (($align == 'J' && !$CJKoverflow) || (($contentWidth + $lastitalic > $maxWidth - $WidthCorrection - (($this->cMarginL + $this->cMarginR) * Mpdf::SCALE) - ($paddingL + $paddingR + (($fpaddingL + $fpaddingR) * Mpdf::SCALE) ) + 0.001) && (!$CJKoverflow || ($CJKoverflow && !$this->allowCJKoverflow))) || $CJKoverflow && $align == 'J' && $this->allowCJKoverflow && $hanger && $this->CJKforceend) { // 0.001 is to correct for deviations converting mm=>pts + // JUSTIFY J (Use character spacing) + // WORD SPACING + // mPDF 5.7 + foreach ($chunkorder as $aord => $k) { + $chunk = isset($content[$aord]) ? $content[$aord] : ''; + if (!isset($this->objectbuffer[$k]) || (isset($this->objectbuffer[$k]) && !$this->objectbuffer[$k])) { + $nb_carac += mb_strlen($chunk, $this->mb_enc); + $nb_spaces += mb_substr_count($chunk, ' ', $this->mb_enc); + // Use GPOS OTL + if (isset($this->CurrentFont['useOTL']) && ($this->CurrentFont['useOTL'] & 0xFF)) { + if (isset($cOTLdata[$aord]['group']) && $cOTLdata[$aord]['group']) { + $nb_carac -= substr_count($cOTLdata[$aord]['group'], 'M'); + } + } + } else { + $nb_carac ++; + } // mPDF 6 allow spacing for inline object + } + // GetJSpacing adds kashida spacing to GPOSinfo if appropriate for Font + list($jcharspacing, $jws, $jkashida) = $this->GetJspacing($nb_carac, $nb_spaces, ($maxWidth - $lastitalic - $contentWidth - $WidthCorrection - (($this->cMarginL + $this->cMarginR) * Mpdf::SCALE) - ($paddingL + $paddingR + (($fpaddingL + $fpaddingR) * Mpdf::SCALE) )), $inclCursive, $cOTLdata); + } + + // WORD SPACING + $empty = $maxWidth - $lastitalic - $WidthCorrection - $contentWidth - (($this->cMarginL + $this->cMarginR) * Mpdf::SCALE) - ($paddingL + $paddingR + (($fpaddingL + $fpaddingR) * Mpdf::SCALE) ); + + $empty -= ($jcharspacing * ($nb_carac - 1)); // mPDF 6 nb_carac MINUS 1 + $empty -= ($jws * $nb_spaces); + $empty -= ($jkashida); + $empty /= Mpdf::SCALE; + + $b = ''; // do not use borders + // Get PAGEBREAK TO TEST for height including the top border/padding + $check_h = max($this->divheight, $stackHeight); + if (($newblock) && ($blockstate == 1 || $blockstate == 3) && ($this->blklvl > 0) && ($lineCount == 1) && (!$is_table)) { + $check_h += ($this->blk[$this->blklvl]['padding_top'] + $this->blk[$this->blklvl]['margin_top'] + $this->blk[$this->blklvl]['border_top']['w']); + } + + if ($this->ColActive && $check_h > ($this->PageBreakTrigger - $this->y0)) { + $this->SetCol($this->NbCol - 1); + } + + // PAGEBREAK + // 'If' below used in order to fix "first-line of other page with justify on" bug + if (!$is_table && ($this->y + $check_h) > $this->PageBreakTrigger and ! $this->InFooter and $this->AcceptPageBreak()) { + $bak_x = $this->x; // Current X position + // WORD SPACING + $ws = $this->ws; // Word Spacing + $charspacing = $this->charspacing; // Character Spacing + $this->ResetSpacing(); + + $this->AddPage($this->CurOrientation); + + $this->x = $bak_x; + // Added to correct for OddEven Margins + $currentx += $this->MarginCorrection; + $this->x += $this->MarginCorrection; + + // WORD SPACING + $this->SetSpacing($charspacing, $ws); + } + + if ($this->kwt && !$is_table) { // mPDF 5.7+ + $this->printkwtbuffer(); + $this->kwt = false; + } + + + /* -- COLUMNS -- */ + // COLS + // COLUMN CHANGE + if ($this->CurrCol != $oldcolumn) { + $currentx += $this->ChangeColumn * ($this->ColWidth + $this->ColGap); + $this->x += $this->ChangeColumn * ($this->ColWidth + $this->ColGap); + $oldcolumn = $this->CurrCol; + } + + if ($this->ColActive && !$is_table) { + $this->breakpoints[$this->CurrCol][] = $this->y; + } // *COLUMNS* + /* -- END COLUMNS -- */ + + // TOP MARGIN + if (($newblock) && ($blockstate == 1 || $blockstate == 3) && ($this->blk[$this->blklvl]['margin_top']) && ($lineCount == 1) && (!$is_table)) { + $this->DivLn($this->blk[$this->blklvl]['margin_top'], $this->blklvl - 1, true, $this->blk[$this->blklvl]['margin_collapse']); + if ($this->ColActive) { + $this->breakpoints[$this->CurrCol][] = $this->y; + } // *COLUMNS* + } + + + // Update y0 for top of block (used to paint border) + if (($newblock) && ($blockstate == 1 || $blockstate == 3) && ($lineCount == 1) && (!$is_table)) { + $this->blk[$this->blklvl]['y0'] = $this->y; + $this->blk[$this->blklvl]['startpage'] = $this->page; + if ($this->blk[$this->blklvl]['float']) { + $this->blk[$this->blklvl]['float_start_y'] = $this->y; + } + } + + // TOP PADDING and BORDER spacing/fill + if (($newblock) && ($blockstate == 1 || $blockstate == 3) && (($this->blk[$this->blklvl]['padding_top']) || ($this->blk[$this->blklvl]['border_top'])) && ($lineCount == 1) && (!$is_table)) { + // $state = 0 normal; 1 top; 2 bottom; 3 top and bottom + $this->DivLn($this->blk[$this->blklvl]['padding_top'] + $this->blk[$this->blklvl]['border_top']['w'], -3, true, false, 1); + if ($this->ColActive) { + $this->breakpoints[$this->CurrCol][] = $this->y; + } // *COLUMNS* + } + + $arraysize = count($chunkorder); + + $margins = ($this->cMarginL + $this->cMarginR) + ($ipaddingL + $ipaddingR + $fpaddingR + $fpaddingR ); + + // PAINT BACKGROUND FOR THIS LINE + if (!$is_table) { + $this->DivLn($stackHeight, $this->blklvl, false); + } // false -> don't advance y + + $this->x = $currentx + $this->cMarginL + $ipaddingL + $fpaddingL; + if ($align == 'R') { + $this->x += $empty; + } elseif ($align == 'C') { + $this->x += ($empty / 2); + } + + // Paragraph INDENT + if (isset($this->blk[$this->blklvl]['text_indent']) && ($newblock) && ($blockstate == 1 || $blockstate == 3) && ($lineCount == 1) && (!$is_table) && ($blockdir != 'rtl') && ($align != 'C')) { + $ti = $this->sizeConverter->convert($this->blk[$this->blklvl]['text_indent'], $this->blk[$this->blklvl]['inner_width'], $this->blk[$this->blklvl]['InlineProperties']['size'], false); // mPDF 5.7.4 + $this->x += $ti; + } + + // BIDI magic_reverse moved upwards from here + foreach ($chunkorder as $aord => $k) { // mPDF 5.7 + + $chunk = isset($content[$aord]) ? $content[$aord] : ''; + + if (isset($this->objectbuffer[$k]) && $this->objectbuffer[$k]) { + $xadj = $this->x - $this->objectbuffer[$k]['OUTER-X']; + $this->objectbuffer[$k]['OUTER-X'] += $xadj; + $this->objectbuffer[$k]['BORDER-X'] += $xadj; + $this->objectbuffer[$k]['INNER-X'] += $xadj; + + if ($this->objectbuffer[$k]['type'] == 'listmarker') { + $this->objectbuffer[$k]['lineBox'] = $lineBox[-1]; // Block element details for glyph-origin + } + $yadj = $this->y - $this->objectbuffer[$k]['OUTER-Y']; + if ($this->objectbuffer[$k]['type'] == 'dottab') { // mPDF 6 DOTTAB + $this->objectbuffer[$k]['lineBox'] = $lineBox[$k]; // element details for glyph-origin + } + if ($this->objectbuffer[$k]['type'] != 'dottab') { // mPDF 6 DOTTAB + $yadj += $lineBox[$k]['top']; + } + $this->objectbuffer[$k]['OUTER-Y'] += $yadj; + $this->objectbuffer[$k]['BORDER-Y'] += $yadj; + $this->objectbuffer[$k]['INNER-Y'] += $yadj; + } + + $this->restoreFont($font[$k]); // mPDF 5.7 + + $this->SetSpacing(($this->fixedlSpacing * Mpdf::SCALE) + $jcharspacing, ($this->fixedlSpacing + $this->minwSpacing) * Mpdf::SCALE + $jws); + // Now unset these values so they don't influence GetStringwidth below or in fn. Cell + $this->fixedlSpacing = false; + $this->minwSpacing = 0; + + $save_vis = $this->visibility; + if (isset($this->textparam['visibility']) && $this->textparam['visibility'] && $this->textparam['visibility'] != $this->visibility) { + $this->SetVisibility($this->textparam['visibility']); + } + // *********** SPAN BACKGROUND COLOR ***************** // + if ($this->spanbgcolor) { + $cor = $this->spanbgcolorarray; + $this->SetFColor($cor); + $save_fill = $fill; + $spanfill = 1; + $fill = 1; + } + if (!empty($this->spanborddet)) { + if (strpos($contentB[$k], 'L') !== false) { + $this->x += (isset($this->spanborddet['L']['w']) ? $this->spanborddet['L']['w'] : 0); + } + if (strpos($contentB[$k], 'L') === false) { + $this->spanborddet['L']['s'] = $this->spanborddet['L']['w'] = 0; + } + if (strpos($contentB[$k], 'R') === false) { + $this->spanborddet['R']['s'] = $this->spanborddet['R']['w'] = 0; + } + } + + // WORD SPACING + // StringWidth this time includes any kashida spacing + $stringWidth = $this->GetStringWidth($chunk, true, (isset($cOTLdata[$aord]) ? $cOTLdata[$aord] : false), $this->textvar, true); + + $nch = mb_strlen($chunk, $this->mb_enc); + // Use GPOS OTL + if (isset($this->CurrentFont['useOTL']) && ($this->CurrentFont['useOTL'] & 0xFF)) { + if (isset($cOTLdata[$aord]['group']) && $cOTLdata[$aord]['group']) { + $nch -= substr_count($cOTLdata[$aord]['group'], 'M'); + } + } + $stringWidth += ( $this->charspacing * $nch / Mpdf::SCALE ); + + $stringWidth += ( $this->ws * mb_substr_count($chunk, ' ', $this->mb_enc) / Mpdf::SCALE ); + + if (isset($this->objectbuffer[$k])) { + // LIST MARKERS // mPDF 6 Lists + if ($this->objectbuffer[$k]['type'] == 'image' && isset($this->objectbuffer[$k]['listmarker']) && $this->objectbuffer[$k]['listmarker'] && $this->objectbuffer[$k]['listmarkerposition'] == 'outside') { + $stringWidth = 0; + } else { + $stringWidth = $this->objectbuffer[$k]['OUTER-WIDTH']; + } + } + + if ($stringWidth == 0) { + $stringWidth = 0.000001; + } + + if ($aord == $arraysize - 1) { + $stringWidth -= ( $this->charspacing / Mpdf::SCALE ); + if ($this->checkCJK && $CJKoverflow && $align == 'J' && $this->allowCJKoverflow && $hanger && $this->CJKforceend) { + // force-end overhang + $this->Cell($stringWidth, $stackHeight, $chunk, '', 0, '', $fill, $this->HREF, $currentx, 0, 0, 'M', $fill, true, (isset($cOTLdata[$aord]) ? $cOTLdata[$aord] : false), $this->textvar, (isset($lineBox[$k]) ? $lineBox[$k] : false)); + $this->Cell($this->GetStringWidth($hanger), $stackHeight, $hanger, '', 1, '', $fill, $this->HREF, $currentx, 0, 0, 'M', $fill, true, (isset($cOTLdata[$aord]) ? $cOTLdata[$aord] : false), $this->textvar, (isset($lineBox[$k]) ? $lineBox[$k] : false)); + } else { + $this->Cell($stringWidth, $stackHeight, $chunk, '', 1, '', $fill, $this->HREF, $currentx, 0, 0, 'M', $fill, true, (isset($cOTLdata[$aord]) ? $cOTLdata[$aord] : false), $this->textvar, (isset($lineBox[$k]) ? $lineBox[$k] : false)); // mono-style line or last part (skips line) + } + } else { + $this->Cell($stringWidth, $stackHeight, $chunk, '', 0, '', $fill, $this->HREF, 0, 0, 0, 'M', $fill, true, (isset($cOTLdata[$aord]) ? $cOTLdata[$aord] : false), $this->textvar, (isset($lineBox[$k]) ? $lineBox[$k] : false)); // first or middle part + } + + if (!empty($this->spanborddet)) { + if (strpos($contentB[$k], 'R') !== false && $aord != $arraysize - 1) { + $this->x += $this->spanborddet['R']['w']; + } + } + // *********** SPAN BACKGROUND COLOR OFF - RESET BLOCK BGCOLOR ***************** // + if (isset($spanfill) && $spanfill) { + $fill = $save_fill; + $spanfill = 0; + if ($fill) { + $this->SetFColor($bcor); + } + } + if (isset($this->textparam['visibility']) && $this->textparam['visibility'] && $this->visibility != $save_vis) { + $this->SetVisibility($save_vis); + } + } + } elseif ($table_draft) { + $this->y += $stackHeight; + } + + if (!$is_table) { + $this->maxPosR = max($this->maxPosR, ($this->w - $this->rMargin - $this->blk[$this->blklvl]['outer_right_margin'])); + $this->maxPosL = min($this->maxPosL, ($this->lMargin + $this->blk[$this->blklvl]['outer_left_margin'])); + } + + // move on to the next line, reset variables, tack on saved content and current char + + if (!$table_draft) { + $this->printobjectbuffer($is_table, $blockdir); + } + $this->objectbuffer = []; + + + /* -- CSS-IMAGE-FLOAT -- */ + // Update values if set to skipline + if ($this->floatmargins) { + $this->_advanceFloatMargins(); + } + /* -- END CSS-IMAGE-FLOAT -- */ + + // Reset lineheight + $stackHeight = $this->divheight; + $valign = 'M'; + + $font = []; + $content = []; + $contentB = []; + $cOTLdata = []; // mPDF 5.7.1 + $contentWidth = 0; + if (!empty($savedObj)) { + $this->objectbuffer[] = $savedObj; + $font[] = $savedFont; + $content[] = ''; + $contentB[] = ''; + $cOTLdata[] = []; // mPDF 5.7.1 + $contentWidth += $savedObj['OUTER-WIDTH'] * Mpdf::SCALE; + } + if (count($savedPreContent) > 0) { + for ($ix = count($savedPreContent) - 1; $ix >= 0; $ix--) { + $font[] = $savedPreFont[$ix]; + $content[] = $savedPreContent[$ix]; + $contentB[] = $savedPreContentB[$ix]; + if (!empty($sOTLdata)) { + $cOTLdata[] = $savedPreOTLdata[$ix]; + } + $this->restoreFont($savedPreFont[$ix]); + $lbw = $rbw = 0; // Border widths + if (!empty($this->spanborddet)) { + $lbw = (isset($this->spanborddet['L']['w']) ? $this->spanborddet['L']['w'] : 0); + $rbw = (isset($this->spanborddet['R']['w']) ? $this->spanborddet['R']['w'] : 0); + } + if ($ix > 0) { + $contentWidth += $this->GetStringWidth($savedPreContent[$ix], true, (isset($savedPreOTLdata[$ix]) ? $savedPreOTLdata[$ix] : false), $this->textvar) * Mpdf::SCALE; // mPDF 5.7.1 + if (strpos($savedPreContentB[$ix], 'L') !== false) { + $contentWidth += $lbw; + } + if (strpos($savedPreContentB[$ix], 'R') !== false) { + $contentWidth += $rbw; + } + } + } + $savedPreContent = []; + $savedPreContentB = []; + $savedPreOTLdata = []; // mPDF 5.7.1 + $savedPreFont = []; + $content[(count($content) - 1)] .= $c; + } else { + $font[] = $savedFont; + $content[] = $savedContent . $c; + $contentB[] = $savedContentB; + $cOTLdata[] = $savedOTLdata; // mPDF 5.7.1 + } + + $currContent = & $content[(count($content) - 1)]; + $this->restoreFont($font[(count($font) - 1)]); // mPDF 6.0 + + /* -- CJK-FONTS -- */ + // CJK - strip CJK space at start of line + //   = \xe3\x80\x80 = CJK space + if ($this->checkCJK && $currContent == "\xe3\x80\x80") { + $currContent = ''; + if (isset($this->CurrentFont['useOTL']) && $this->CurrentFont['useOTL']) { + $this->otl->trimOTLdata($cOTLdata[count($cOTLdata) - 1], true, false); // left trim U+3000 + } + } + /* -- END CJK-FONTS -- */ + + $lbw = $rbw = 0; // Border widths + if (!empty($this->spanborddet)) { + $lbw = (isset($this->spanborddet['L']['w']) ? $this->spanborddet['L']['w'] : 0); + $rbw = (isset($this->spanborddet['R']['w']) ? $this->spanborddet['R']['w'] : 0); + } + + $contentWidth += $this->GetStringWidth($currContent, false, (isset($cOTLdata[(count($cOTLdata) - 1)]) ? $cOTLdata[(count($cOTLdata) - 1)] : false), $this->textvar) * Mpdf::SCALE; // mPDF 5.7.1 + if (strpos($savedContentB, 'L') !== false) { + $contentWidth += $lbw; + } + $CJKoverflow = false; + $hanger = ''; + } // another character will fit, so add it on + else { + $contentWidth += $cw; + $currContent .= $c; + } + } + + unset($content); + unset($contentB); + } + + // ----------------------END OF FLOWING BLOCK------------------------------------// + + + /* -- CSS-IMAGE-FLOAT -- */ + // Update values if set to skipline + function _advanceFloatMargins() + { + // Update floatmargins - L + if (isset($this->floatmargins['L']) && $this->floatmargins['L']['skipline'] && $this->floatmargins['L']['y0'] != $this->y) { + $yadj = $this->y - $this->floatmargins['L']['y0']; + $this->floatmargins['L']['y0'] = $this->y; + $this->floatmargins['L']['y1'] += $yadj; + + // Update objattr in floatbuffer + if ($this->floatbuffer[$this->floatmargins['L']['id']]['border_left']['w']) { + $this->floatbuffer[$this->floatmargins['L']['id']]['BORDER-Y'] += $yadj; + } + $this->floatbuffer[$this->floatmargins['L']['id']]['INNER-Y'] += $yadj; + $this->floatbuffer[$this->floatmargins['L']['id']]['OUTER-Y'] += $yadj; + + // Unset values + $this->floatbuffer[$this->floatmargins['L']['id']]['skipline'] = false; + $this->floatmargins['L']['skipline'] = false; + $this->floatmargins['L']['id'] = ''; + } + // Update floatmargins - R + if (isset($this->floatmargins['R']) && $this->floatmargins['R']['skipline'] && $this->floatmargins['R']['y0'] != $this->y) { + $yadj = $this->y - $this->floatmargins['R']['y0']; + $this->floatmargins['R']['y0'] = $this->y; + $this->floatmargins['R']['y1'] += $yadj; + + // Update objattr in floatbuffer + if ($this->floatbuffer[$this->floatmargins['R']['id']]['border_left']['w']) { + $this->floatbuffer[$this->floatmargins['R']['id']]['BORDER-Y'] += $yadj; + } + $this->floatbuffer[$this->floatmargins['R']['id']]['INNER-Y'] += $yadj; + $this->floatbuffer[$this->floatmargins['R']['id']]['OUTER-Y'] += $yadj; + + // Unset values + $this->floatbuffer[$this->floatmargins['R']['id']]['skipline'] = false; + $this->floatmargins['R']['skipline'] = false; + $this->floatmargins['R']['id'] = ''; + } + } + + /* -- END CSS-IMAGE-FLOAT -- */ + + + + /* -- END HTML-CSS -- */ + + function _SetTextRendering($mode) + { + if (!(($mode == 0) || ($mode == 1) || ($mode == 2))) { + throw new \Mpdf\MpdfException("Text rendering mode should be 0, 1 or 2 (value : $mode)"); + } + $tr = ($mode . ' Tr'); + if ($this->page > 0 && ((isset($this->pageoutput[$this->page]['TextRendering']) && $this->pageoutput[$this->page]['TextRendering'] != $tr) || !isset($this->pageoutput[$this->page]['TextRendering']))) { + $this->writer->write($tr); + } + $this->pageoutput[$this->page]['TextRendering'] = $tr; + } + + function SetTextOutline($params = []) + { + if (isset($params['outline-s']) && $params['outline-s']) { + $this->SetLineWidth($params['outline-WIDTH']); + $this->SetDColor($params['outline-COLOR']); + $tr = ('2 Tr'); + if ($this->page > 0 && ((isset($this->pageoutput[$this->page]['TextRendering']) && $this->pageoutput[$this->page]['TextRendering'] != $tr) || !isset($this->pageoutput[$this->page]['TextRendering']))) { + $this->writer->write($tr); + } + $this->pageoutput[$this->page]['TextRendering'] = $tr; + } else { // Now resets all values + $this->SetLineWidth(0.2); + $this->SetDColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + $this->_SetTextRendering(0); + $tr = ('0 Tr'); + if ($this->page > 0 && ((isset($this->pageoutput[$this->page]['TextRendering']) && $this->pageoutput[$this->page]['TextRendering'] != $tr) || !isset($this->pageoutput[$this->page]['TextRendering']))) { + $this->writer->write($tr); + } + $this->pageoutput[$this->page]['TextRendering'] = $tr; + } + } + + function Image($file, $x, $y, $w = 0, $h = 0, $type = '', $link = '', $paint = true, $constrain = true, $watermark = false, $shownoimg = true, $allowvector = true) + { + $orig_srcpath = $file; + $this->GetFullPath($file); + + $info = $this->imageProcessor->getImage($file, true, $allowvector, $orig_srcpath); + if (!$info && $paint) { + $info = $this->imageProcessor->getImage($this->noImageFile); + if ($info) { + $file = $this->noImageFile; + $w = ($info['w'] * (25.4 / $this->img_dpi)); // 14 x 16px + $h = ($info['h'] * (25.4 / $this->img_dpi)); // 14 x 16px + } + } + if (!$info) { + return false; + } + // Automatic width and height calculation if needed + if ($w == 0 and $h == 0) { + /* -- IMAGES-WMF -- */ + if ($info['type'] == 'wmf') { + // WMF units are twips (1/20pt) + // divide by 20 to get points + // divide by k to get user units + $w = abs($info['w']) / (20 * Mpdf::SCALE); + $h = abs($info['h']) / (20 * Mpdf::SCALE); + } else { /* -- END IMAGES-WMF -- */ + if ($info['type'] == 'svg') { + // returned SVG units are pts + // divide by k to get user units (mm) + $w = abs($info['w']) / Mpdf::SCALE; + $h = abs($info['h']) / Mpdf::SCALE; + } else { + // Put image at default image dpi + $w = ($info['w'] / Mpdf::SCALE) * (72 / $this->img_dpi); + $h = ($info['h'] / Mpdf::SCALE) * (72 / $this->img_dpi); + } + } + } + if ($w == 0) { + $w = abs($h * $info['w'] / $info['h']); + } + if ($h == 0) { + $h = abs($w * $info['h'] / $info['w']); + } + + /* -- WATERMARK -- */ + if ($watermark) { + $maxw = $this->w; + $maxh = $this->h; + // Size = D PF or array + if (is_array($this->watermark_size)) { + $w = $this->watermark_size[0]; + $h = $this->watermark_size[1]; + } elseif (!is_string($this->watermark_size)) { + $maxw -= $this->watermark_size * 2; + $maxh -= $this->watermark_size * 2; + $w = $maxw; + $h = abs($w * $info['h'] / $info['w']); + if ($h > $maxh) { + $h = $maxh; + $w = abs($h * $info['w'] / $info['h']); + } + } elseif ($this->watermark_size == 'F') { + if ($this->ColActive) { + $maxw = $this->w - ($this->DeflMargin + $this->DefrMargin); + } else { + $maxw = $this->pgwidth; + } + $maxh = $this->h - ($this->tMargin + $this->bMargin); + $w = $maxw; + $h = abs($w * $info['h'] / $info['w']); + if ($h > $maxh) { + $h = $maxh; + $w = abs($h * $info['w'] / $info['h']); + } + } elseif ($this->watermark_size == 'P') { // Default P + $w = $maxw; + $h = abs($w * $info['h'] / $info['w']); + if ($h > $maxh) { + $h = $maxh; + $w = abs($h * $info['w'] / $info['h']); + } + } + // Automatically resize to maximum dimensions of page if too large + if ($w > $maxw) { + $w = $maxw; + $h = abs($w * $info['h'] / $info['w']); + } + if ($h > $maxh) { + $h = $maxh; + $w = abs($h * $info['w'] / $info['h']); + } + // Position + if (is_array($this->watermark_pos)) { + $x = $this->watermark_pos[0]; + $y = $this->watermark_pos[1]; + } elseif ($this->watermark_pos == 'F') { // centred on printable area + if ($this->ColActive) { // *COLUMNS* + if (($this->mirrorMargins) && (($this->page) % 2 == 0)) { + $xadj = $this->DeflMargin - $this->DefrMargin; + } // *COLUMNS* + else { + $xadj = 0; + } // *COLUMNS* + $x = ($this->DeflMargin - $xadj + ($this->w - ($this->DeflMargin + $this->DefrMargin)) / 2) - ($w / 2); // *COLUMNS* + } // *COLUMNS* + else { // *COLUMNS* + $x = ($this->lMargin + ($this->pgwidth) / 2) - ($w / 2); + } // *COLUMNS* + $y = ($this->tMargin + ($this->h - ($this->tMargin + $this->bMargin)) / 2) - ($h / 2); + } else { // default P - centred on whole page + $x = ($this->w / 2) - ($w / 2); + $y = ($this->h / 2) - ($h / 2); + } + /* -- IMAGES-WMF -- */ + if ($info['type'] == 'wmf') { + $sx = $w * Mpdf::SCALE / $info['w']; + $sy = -$h * Mpdf::SCALE / $info['h']; + $outstring = sprintf('q %.3F 0 0 %.3F %.3F %.3F cm /FO%d Do Q', $sx, $sy, $x * Mpdf::SCALE - $sx * $info['x'], (($this->h - $y) * Mpdf::SCALE) - $sy * $info['y'], $info['i']); + } else { /* -- END IMAGES-WMF -- */ + if ($info['type'] == 'svg') { + $sx = $w * Mpdf::SCALE / $info['w']; + $sy = -$h * Mpdf::SCALE / $info['h']; + $outstring = sprintf('q %.3F 0 0 %.3F %.3F %.3F cm /FO%d Do Q', $sx, $sy, $x * Mpdf::SCALE - $sx * $info['x'], (($this->h - $y) * Mpdf::SCALE) - $sy * $info['y'], $info['i']); + } else { + $outstring = sprintf("q %.3F 0 0 %.3F %.3F %.3F cm /I%d Do Q", $w * Mpdf::SCALE, $h * Mpdf::SCALE, $x * Mpdf::SCALE, ($this->h - ($y + $h)) * Mpdf::SCALE, $info['i']); + } + } + + if ($this->watermarkImgBehind) { + $outstring = $this->watermarkImgAlpha . "\n" . $outstring . "\n" . $this->SetAlpha(1, 'Normal', true) . "\n"; + $this->pages[$this->page] = preg_replace('/(___BACKGROUND___PATTERNS' . $this->uniqstr . ')/', "\n" . $outstring . "\n" . '\\1', $this->pages[$this->page]); + } else { + $this->writer->write($outstring); + } + + return 0; + } // end of IF watermark + /* -- END WATERMARK -- */ + + if ($constrain) { + // Automatically resize to maximum dimensions of page if too large + if (isset($this->blk[$this->blklvl]['inner_width']) && $this->blk[$this->blklvl]['inner_width']) { + $maxw = $this->blk[$this->blklvl]['inner_width']; + } else { + $maxw = $this->pgwidth; + } + if ($w > $maxw) { + $w = $maxw; + $h = abs($w * $info['h'] / $info['w']); + } + if ($h > $this->h - ($this->tMargin + $this->bMargin + 1)) { // see below - +10 to avoid drawing too close to border of page + $h = $this->h - ($this->tMargin + $this->bMargin + 1); + if ($this->fullImageHeight) { + $h = $this->fullImageHeight; + } + $w = abs($h * $info['w'] / $info['h']); + } + + + // Avoid drawing out of the paper(exceeding width limits). + // if ( ($x + $w) > $this->fw ) { + if (($x + $w) > $this->w) { + $x = $this->lMargin; + $y += 5; + } + + $changedpage = false; + $oldcolumn = $this->CurrCol; + // Avoid drawing out of the page. + if ($y + $h > $this->PageBreakTrigger and ! $this->InFooter and $this->AcceptPageBreak()) { + $this->AddPage($this->CurOrientation); + // Added to correct for OddEven Margins + $x = $x + $this->MarginCorrection; + $y = $this->tMargin; // mPDF 5.7.3 + $changedpage = true; + } + /* -- COLUMNS -- */ + // COLS + // COLUMN CHANGE + if ($this->CurrCol != $oldcolumn) { + $y = $this->y0; + $x += $this->ChangeColumn * ($this->ColWidth + $this->ColGap); + $this->x += $this->ChangeColumn * ($this->ColWidth + $this->ColGap); + } + /* -- END COLUMNS -- */ + } // end of IF constrain + + /* -- IMAGES-WMF -- */ + if ($info['type'] == 'wmf') { + $sx = $w * Mpdf::SCALE / $info['w']; + $sy = -$h * Mpdf::SCALE / $info['h']; + $outstring = sprintf('q %.3F 0 0 %.3F %.3F %.3F cm /FO%d Do Q', $sx, $sy, $x * Mpdf::SCALE - $sx * $info['x'], (($this->h - $y) * Mpdf::SCALE) - $sy * $info['y'], $info['i']); + } else { /* -- END IMAGES-WMF -- */ + if ($info['type'] == 'svg') { + $sx = $w * Mpdf::SCALE / $info['w']; + $sy = -$h * Mpdf::SCALE / $info['h']; + $outstring = sprintf('q %.3F 0 0 %.3F %.3F %.3F cm /FO%d Do Q', $sx, $sy, $x * Mpdf::SCALE - $sx * $info['x'], (($this->h - $y) * Mpdf::SCALE) - $sy * $info['y'], $info['i']); + } else { + $outstring = sprintf("q %.3F 0 0 %.3F %.3F %.3F cm /I%d Do Q", $w * Mpdf::SCALE, $h * Mpdf::SCALE, $x * Mpdf::SCALE, ($this->h - ($y + $h)) * Mpdf::SCALE, $info['i']); + } + } + + if ($paint) { + $this->writer->write($outstring); + if ($link) { + $this->Link($x, $y, $w, $h, $link); + } + + // Avoid writing text on top of the image. // THIS WAS OUTSIDE THE if ($paint) bit!!!!!!!!!!!!!!!! + $this->y = $y + $h; + } + + // Return width-height array + $sizesarray['WIDTH'] = $w; + $sizesarray['HEIGHT'] = $h; + $sizesarray['X'] = $x; // Position before painting image + $sizesarray['Y'] = $y; // Position before painting image + $sizesarray['OUTPUT'] = $outstring; + + $sizesarray['IMAGE_ID'] = $info['i']; + $sizesarray['itype'] = $info['type']; + $sizesarray['set-dpi'] = (isset($info['set-dpi']) ? $info['set-dpi'] : 0); + return $sizesarray; + } + + // ============================================================= + // ============================================================= + // ============================================================= + // ============================================================= + // ============================================================= + /* -- HTML-CSS -- */ + + function _getObjAttr($t) + { + $c = explode("\xbb\xa4\xac", $t, 2); + $c = explode(",", $c[1], 2); + foreach ($c as $v) { + $v = explode("=", $v, 2); + $sp[$v[0]] = $v[1]; + } + return (unserialize($sp['objattr'])); + } + + function inlineObject($type, $x, $y, $objattr, $Lmargin, $widthUsed, $maxWidth, $lineHeight, $paint = false, $is_table = false) + { + if ($is_table) { + $k = $this->shrin_k; + } else { + $k = 1; + } + + // NB $x is only used when paint=true + // Lmargin not used + $w = 0; + if (isset($objattr['width'])) { + $w = $objattr['width'] / $k; + } + $h = 0; + if (isset($objattr['height'])) { + $h = abs($objattr['height'] / $k); + } + $widthLeft = $maxWidth - $widthUsed; + $maxHeight = $this->h - ($this->tMargin + $this->bMargin + 10); + if ($this->fullImageHeight) { + $maxHeight = $this->fullImageHeight; + } + // For Images + if (isset($objattr['border_left'])) { + $extraWidth = ($objattr['border_left']['w'] + $objattr['border_right']['w'] + $objattr['margin_left'] + $objattr['margin_right']) / $k; + $extraHeight = ($objattr['border_top']['w'] + $objattr['border_bottom']['w'] + $objattr['margin_top'] + $objattr['margin_bottom']) / $k; + + if ($type == 'image' || $type == 'barcode' || $type == 'textcircle') { + $extraWidth += ($objattr['padding_left'] + $objattr['padding_right']) / $k; + $extraHeight += ($objattr['padding_top'] + $objattr['padding_bottom']) / $k; + } + } + + if (!isset($objattr['vertical-align'])) { + if ($objattr['type'] == 'select') { + $objattr['vertical-align'] = 'M'; + } else { + $objattr['vertical-align'] = 'BS'; + } + } // mPDF 6 + + if ($type == 'image' || (isset($objattr['subtype']) && $objattr['subtype'] == 'IMAGE')) { + if (isset($objattr['itype']) && ($objattr['itype'] == 'wmf' || $objattr['itype'] == 'svg')) { + $file = $objattr['file']; + $info = $this->formobjects[$file]; + } elseif (isset($objattr['file'])) { + $file = $objattr['file']; + $info = $this->images[$file]; + } + } + if ($type == 'annot' || $type == 'bookmark' || $type == 'indexentry' || $type == 'toc') { + $w = 0.00001; + $h = 0.00001; + } + + // TEST whether need to skipline + if (!$paint) { + if ($type == 'hr') { // always force new line + if (($y + $h + $lineHeight > $this->PageBreakTrigger) && !$this->InFooter && !$is_table) { + return [-2, $w, $h]; + } // New page + new line + else { + return [1, $w, $h]; + } // new line + } else { + // LIST MARKERS // mPDF 6 Lists + $displayheight = $h; + $displaywidth = $w; + if ($objattr['type'] == 'image' && isset($objattr['listmarker']) && $objattr['listmarker']) { + $displayheight = 0; + if ($objattr['listmarkerposition'] == 'outside') { + $displaywidth = 0; + } + } + + if ($widthUsed > 0 && $displaywidth > $widthLeft && (!$is_table || $type != 'image')) { // New line needed + // mPDF 6 Lists + if (($y + $displayheight + $lineHeight > $this->PageBreakTrigger) && !$this->InFooter) { + return [-2, $w, $h]; + } // New page + new line + return [1, $w, $h]; // new line + } elseif ($widthUsed > 0 && $displaywidth > $widthLeft && $is_table) { // New line needed in TABLE + return [1, $w, $h]; // new line + } // Will fit on line but NEW PAGE REQUIRED + elseif (($y + $displayheight > $this->PageBreakTrigger) && !$this->InFooter && !$is_table) { + return [-1, $w, $h]; + } // mPDF 6 Lists + else { + return [0, $w, $h]; + } + } + } + + if ($type == 'annot' || $type == 'bookmark' || $type == 'indexentry' || $type == 'toc') { + $w = 0.00001; + $h = 0.00001; + $objattr['BORDER-WIDTH'] = 0; + $objattr['BORDER-HEIGHT'] = 0; + $objattr['BORDER-X'] = $x; + $objattr['BORDER-Y'] = $y; + $objattr['INNER-WIDTH'] = 0; + $objattr['INNER-HEIGHT'] = 0; + $objattr['INNER-X'] = $x; + $objattr['INNER-Y'] = $y; + } + + if ($type == 'image') { + // Automatically resize to width remaining + if ($w > ($widthLeft + 0.0001) && !$is_table) { // mPDF 5.7.4 0.0001 to allow for rounding errors when w==maxWidth + $w = $widthLeft; + $h = abs($w * $info['h'] / $info['w']); + } + $img_w = $w - $extraWidth; + $img_h = $h - $extraHeight; + + $objattr['BORDER-WIDTH'] = $img_w + $objattr['padding_left'] / $k + $objattr['padding_right'] / $k + (($objattr['border_left']['w'] / $k + $objattr['border_right']['w'] / $k) / 2); + $objattr['BORDER-HEIGHT'] = $img_h + $objattr['padding_top'] / $k + $objattr['padding_bottom'] / $k + (($objattr['border_top']['w'] / $k + $objattr['border_bottom']['w'] / $k) / 2); + $objattr['BORDER-X'] = $x + $objattr['margin_left'] / $k + (($objattr['border_left']['w'] / $k) / 2); + $objattr['BORDER-Y'] = $y + $objattr['margin_top'] / $k + (($objattr['border_top']['w'] / $k) / 2); + $objattr['INNER-WIDTH'] = $img_w; + $objattr['INNER-HEIGHT'] = $img_h; + $objattr['INNER-X'] = $x + $objattr['padding_left'] / $k + $objattr['margin_left'] / $k + ($objattr['border_left']['w'] / $k); + $objattr['INNER-Y'] = $y + $objattr['padding_top'] / $k + $objattr['margin_top'] / $k + ($objattr['border_top']['w'] / $k); + $objattr['ID'] = $info['i']; + } + + if ($type == 'input' && $objattr['subtype'] == 'IMAGE') { + $img_w = $w - $extraWidth; + $img_h = $h - $extraHeight; + $objattr['BORDER-WIDTH'] = $img_w + (($objattr['border_left']['w'] / $k + $objattr['border_right']['w'] / $k) / 2); + $objattr['BORDER-HEIGHT'] = $img_h + (($objattr['border_top']['w'] / $k + $objattr['border_bottom']['w'] / $k) / 2); + $objattr['BORDER-X'] = $x + $objattr['margin_left'] / $k + (($objattr['border_left']['w'] / $k) / 2); + $objattr['BORDER-Y'] = $y + $objattr['margin_top'] / $k + (($objattr['border_top']['w'] / $k) / 2); + $objattr['INNER-WIDTH'] = $img_w; + $objattr['INNER-HEIGHT'] = $img_h; + $objattr['INNER-X'] = $x + $objattr['margin_left'] / $k + ($objattr['border_left']['w'] / $k); + $objattr['INNER-Y'] = $y + $objattr['margin_top'] / $k + ($objattr['border_top']['w'] / $k); + $objattr['ID'] = $info['i']; + } + + if ($type == 'barcode' || $type == 'textcircle') { + $b_w = $w - $extraWidth; + $b_h = $h - $extraHeight; + $objattr['BORDER-WIDTH'] = $b_w + $objattr['padding_left'] / $k + $objattr['padding_right'] / $k + (($objattr['border_left']['w'] / $k + $objattr['border_right']['w'] / $k) / 2); + $objattr['BORDER-HEIGHT'] = $b_h + $objattr['padding_top'] / $k + $objattr['padding_bottom'] / $k + (($objattr['border_top']['w'] / $k + $objattr['border_bottom']['w'] / $k) / 2); + $objattr['BORDER-X'] = $x + $objattr['margin_left'] / $k + (($objattr['border_left']['w'] / $k) / 2); + $objattr['BORDER-Y'] = $y + $objattr['margin_top'] / $k + (($objattr['border_top']['w'] / $k) / 2); + $objattr['INNER-X'] = $x + $objattr['padding_left'] / $k + $objattr['margin_left'] / $k + ($objattr['border_left']['w'] / $k); + $objattr['INNER-Y'] = $y + $objattr['padding_top'] / $k + $objattr['margin_top'] / $k + ($objattr['border_top']['w'] / $k); + $objattr['INNER-WIDTH'] = $b_w; + $objattr['INNER-HEIGHT'] = $b_h; + } + + + if ($type == 'textarea') { + // Automatically resize to width remaining + if ($w > $widthLeft && !$is_table) { + $w = $widthLeft; + } + // This used to resize height to maximum remaining on page ? why. Causes problems when in table and causing a new column + // if (($y + $h > $this->PageBreakTrigger) && !$this->InFooter) { + // $h=$this->h - $y - $this->bMargin; + // } + } + + if ($type == 'hr') { + if ($is_table) { + $objattr['INNER-WIDTH'] = $maxWidth * $objattr['W-PERCENT'] / 100; + $objattr['width'] = $objattr['INNER-WIDTH']; + $w = $maxWidth; + } else { + if ($w > $maxWidth) { + $w = $maxWidth; + } + $objattr['INNER-WIDTH'] = $w; + $w = $maxWidth; + } + } + + + + if (($type == 'select') || ($type == 'input' && ($objattr['subtype'] == 'TEXT' || $objattr['subtype'] == 'PASSWORD'))) { + // Automatically resize to width remaining + if ($w > $widthLeft && !$is_table) { + $w = $widthLeft; + } + } + + if ($type == 'textarea' || $type == 'select' || $type == 'input') { + if (isset($objattr['fontsize'])) { + $objattr['fontsize'] /= $k; + } + if (isset($objattr['linewidth'])) { + $objattr['linewidth'] /= $k; + } + } + + if (!isset($objattr['BORDER-Y'])) { + $objattr['BORDER-Y'] = 0; + } + if (!isset($objattr['BORDER-X'])) { + $objattr['BORDER-X'] = 0; + } + if (!isset($objattr['INNER-Y'])) { + $objattr['INNER-Y'] = 0; + } + if (!isset($objattr['INNER-X'])) { + $objattr['INNER-X'] = 0; + } + + // Return width-height array + $objattr['OUTER-WIDTH'] = $w; + $objattr['OUTER-HEIGHT'] = $h; + $objattr['OUTER-X'] = $x; + $objattr['OUTER-Y'] = $y; + return $objattr; + } + + /* -- END HTML-CSS -- */ + + // ============================================================= + // ============================================================= + // ============================================================= + // ============================================================= + // ============================================================= + + function SetLineJoin($mode = 0) + { + $s = sprintf('%d j', $mode); + if ($this->page > 0 && ((isset($this->pageoutput[$this->page]['LineJoin']) && $this->pageoutput[$this->page]['LineJoin'] != $s) || !isset($this->pageoutput[$this->page]['LineJoin']))) { + $this->writer->write($s); + } + $this->pageoutput[$this->page]['LineJoin'] = $s; + } + + function SetLineCap($mode = 2) + { + $s = sprintf('%d J', $mode); + if ($this->page > 0 && ((isset($this->pageoutput[$this->page]['LineCap']) && $this->pageoutput[$this->page]['LineCap'] != $s) || !isset($this->pageoutput[$this->page]['LineCap']))) { + $this->writer->write($s); + } + $this->pageoutput[$this->page]['LineCap'] = $s; + } + + function SetDash($black = false, $white = false) + { + if ($black and $white) { + $s = sprintf('[%.3F %.3F] 0 d', $black * Mpdf::SCALE, $white * Mpdf::SCALE); + } else { + $s = '[] 0 d'; + } + if ($this->page > 0 && ((isset($this->pageoutput[$this->page]['Dash']) && $this->pageoutput[$this->page]['Dash'] != $s) || !isset($this->pageoutput[$this->page]['Dash']))) { + $this->writer->write($s); + } + $this->pageoutput[$this->page]['Dash'] = $s; + } + + function SetDisplayPreferences($preferences) + { + // String containing any or none of /HideMenubar/HideToolbar/HideWindowUI/DisplayDocTitle/CenterWindow/FitWindow + $this->DisplayPreferences .= $preferences; + } + + function Ln($h = '', $collapsible = 0) + { + // Added collapsible to allow collapsible top-margin on new page + // Line feed; default value is last cell height + $this->x = $this->lMargin + $this->blk[$this->blklvl]['outer_left_margin']; + if ($collapsible && ($this->y == $this->tMargin) && (!$this->ColActive)) { + $h = 0; + } + if (is_string($h)) { + $this->y+=$this->lasth; + } else { + $this->y+=$h; + } + } + + /* -- HTML-CSS -- */ + + function DivLn($h, $level = -3, $move_y = true, $collapsible = false, $state = 0) + { + // $state = 0 normal; 1 top; 2 bottom; 3 top and bottom + // Used in Columns and keep-with-table i.e. "kwt" + // writes background block by block so it can be repositioned + // and also used in writingFlowingBlock at top and bottom of blocks to move y (not to draw/paint anything) + // adds lines (y) where DIV bgcolors are filled in + // this->x is returned as it was + // allows .00001 as nominal height used for bookmarks/annotations etc. + if ($collapsible && (sprintf("%0.4f", $this->y) == sprintf("%0.4f", $this->tMargin)) && (!$this->ColActive)) { + return; + } + + // mPDF 6 Columns + // if ($collapsible && (sprintf("%0.4f", $this->y)==sprintf("%0.4f", $this->y0)) && ($this->ColActive) && $this->CurrCol == 0) { return; } // *COLUMNS* + if ($collapsible && (sprintf("%0.4f", $this->y) == sprintf("%0.4f", $this->y0)) && ($this->ColActive)) { + return; + } // *COLUMNS* + // Still use this method if columns or keep-with-table, as it allows repositioning later + // otherwise, now uses PaintDivBB() + if (!$this->ColActive && !$this->kwt) { + if ($move_y && !$this->ColActive) { + $this->y += $h; + } + return; + } + + if ($level == -3) { + $level = $this->blklvl; + } + $firstblockfill = $this->GetFirstBlockFill(); + if ($firstblockfill && $this->blklvl > 0 && $this->blklvl >= $firstblockfill) { + $last_x = 0; + $last_w = 0; + $last_fc = $this->FillColor; + $bak_x = $this->x; + $bak_h = $this->divheight; + $this->divheight = 0; // Temporarily turn off divheight - as Cell() uses it to check for PageBreak + for ($blvl = $firstblockfill; $blvl <= $level; $blvl++) { + $this->x = $this->lMargin + $this->blk[$blvl]['outer_left_margin']; + // mPDF 6 + if ($this->blk[$blvl]['bgcolor']) { + $this->SetFColor($this->blk[$blvl]['bgcolorarray']); + } + if ($last_x != ($this->lMargin + $this->blk[$blvl]['outer_left_margin']) || ($last_w != $this->blk[$blvl]['width']) || $last_fc != $this->FillColor || (isset($this->blk[$blvl]['border_top']['s']) && $this->blk[$blvl]['border_top']['s']) || (isset($this->blk[$blvl]['border_bottom']['s']) && $this->blk[$blvl]['border_bottom']['s']) || (isset($this->blk[$blvl]['border_left']['s']) && $this->blk[$blvl]['border_left']['s']) || (isset($this->blk[$blvl]['border_right']['s']) && $this->blk[$blvl]['border_right']['s'])) { + $x = $this->x; + $this->Cell(($this->blk[$blvl]['width']), $h, '', '', 0, '', 1); + $this->x = $x; + if (!$this->keep_block_together && !$this->writingHTMLheader && !$this->writingHTMLfooter) { + // $state = 0 normal; 1 top; 2 bottom; 3 top and bottom + if ($blvl == $this->blklvl) { + $this->PaintDivLnBorder($state, $blvl, $h); + } else { + $this->PaintDivLnBorder(0, $blvl, $h); + } + } + } + $last_x = $this->lMargin + $this->blk[$blvl]['outer_left_margin']; + $last_w = $this->blk[$blvl]['width']; + $last_fc = $this->FillColor; + } + // Reset current block fill + if (isset($this->blk[$this->blklvl]['bgcolorarray'])) { + $bcor = $this->blk[$this->blklvl]['bgcolorarray']; + $this->SetFColor($bcor); + } + $this->x = $bak_x; + $this->divheight = $bak_h; + } + if ($move_y) { + $this->y += $h; + } + } + + /* -- END HTML-CSS -- */ + + function SetX($x) + { + // Set x position + if ($x >= 0) { + $this->x = $x; + } else { + $this->x = $this->w + $x; + } + } + + function SetY($y) + { + // Set y position and reset x + $this->x = $this->lMargin; + if ($y >= 0) { + $this->y = $y; + } else { + $this->y = $this->h + $y; + } + } + + function SetXY($x, $y) + { + // Set x and y positions + $this->SetY($y); + $this->SetX($x); + } + + function Output($name = '', $dest = '') + { + $this->logger->debug(sprintf('PDF generated in %.6F seconds', microtime(true) - $this->time0), ['context' => LogContext::STATISTICS]); + + // Finish document if necessary + if ($this->state < 3) { + $this->Close(); + } + + if ($this->debug && error_get_last()) { + $e = error_get_last(); + if (($e['type'] < 2048 && $e['type'] != 8) || (intval($e['type']) & intval(ini_get("error_reporting")))) { + throw new \Mpdf\MpdfException( + sprintf('Error detected. PDF file generation aborted: %s', $e['message']), + $e['type'], + 1, + $e['file'], + $e['line'] + ); + } + } + + if (($this->PDFA || $this->PDFX) && $this->encrypted) { + throw new \Mpdf\MpdfException('PDF/A1-b or PDF/X1-a does not permit encryption of documents.'); + } + + if (count($this->PDFAXwarnings) && (($this->PDFA && !$this->PDFAauto) || ($this->PDFX && !$this->PDFXauto))) { + if ($this->PDFA) { + $standard = 'PDFA/1-b'; + $option = '$mpdf->PDFAauto'; + } else { + $standard = 'PDFX/1-a '; + $option = '$mpdf->PDFXauto'; + } + + $this->logger->warning(sprintf('PDF could not be generated as it stands as a %s compliant file.', $standard), ['context' => LogContext::PDFA_PDFX]); + $this->logger->warning(sprintf('These issues can be automatically fixed by mPDF using %s = true;', $option), ['context' => LogContext::PDFA_PDFX]); + $this->logger->warning(sprintf('Action that mPDF will take to automatically force %s compliance are shown further in the log.', $standard), ['context' => LogContext::PDFA_PDFX]); + + $this->PDFAXwarnings = array_unique($this->PDFAXwarnings); + foreach ($this->PDFAXwarnings as $w) { + $this->logger->warning($w, ['context' => LogContext::PDFA_PDFX]); + } + + throw new \Mpdf\MpdfException('PDFA/PDFX warnings generated. See log for further details'); + } + + $this->logger->debug(sprintf('Compiled in %.6F seconds', microtime(true) - $this->time0), ['context' => LogContext::STATISTICS]); + $this->logger->debug(sprintf('Peak Memory usage %s MB', number_format(memory_get_peak_usage(true) / (1024 * 1024), 2)), ['context' => LogContext::STATISTICS]); + $this->logger->debug(sprintf('PDF file size %s kB', number_format(strlen($this->buffer) / 1024)), ['context' => LogContext::STATISTICS]); + $this->logger->debug(sprintf('%d fonts used', count($this->fonts)), ['context' => LogContext::STATISTICS]); + + if (is_bool($dest)) { + $dest = $dest ? Destination::DOWNLOAD : Destination::FILE; + } + + $dest = strtoupper($dest); + if (empty($dest)) { + if (empty($name)) { + $name = 'mpdf.pdf'; + $dest = Destination::INLINE; + } else { + $dest = Destination::FILE; + } + } + + switch ($dest) { + + case Destination::INLINE: + + if (headers_sent($filename, $line)) { + throw new \Mpdf\MpdfException( + sprintf('Data has already been sent to output (%s at line %s), unable to output PDF file', $filename, $line) + ); + } + + if ($this->debug && !$this->allow_output_buffering && ob_get_contents()) { + throw new \Mpdf\MpdfException('Output has already been sent from the script - PDF file generation aborted.'); + } + + // We send to a browser + if (PHP_SAPI !== 'cli') { + header('Content-Type: application/pdf'); + + if (!isset($_SERVER['HTTP_ACCEPT_ENCODING']) || empty($_SERVER['HTTP_ACCEPT_ENCODING'])) { + // don't use length if server using compression + header('Content-Length: ' . strlen($this->buffer)); + } + + header('Content-disposition: inline; filename="' . $name . '"'); + header('Cache-Control: public, must-revalidate, max-age=0'); + header('Pragma: public'); + header('X-Generator: mPDF' . ($this->exposeVersion ? (' ' . static::VERSION) : '')); + header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); + header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); + } + + echo $this->buffer; + + break; + + case Destination::DOWNLOAD: + + if (headers_sent()) { + throw new \Mpdf\MpdfException('Data has already been sent to output, unable to output PDF file'); + } + + header('Content-Description: File Transfer'); + header('Content-Transfer-Encoding: binary'); + header('Cache-Control: public, must-revalidate, max-age=0'); + header('Pragma: public'); + header('X-Generator: mPDF' . ($this->exposeVersion ? (' ' . static::VERSION) : '')); + header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); + header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); + header('Content-Type: application/pdf'); + + if (!isset($_SERVER['HTTP_ACCEPT_ENCODING']) || empty($_SERVER['HTTP_ACCEPT_ENCODING'])) { + // don't use length if server using compression + header('Content-Length: ' . strlen($this->buffer)); + } + + header('Content-Disposition: attachment; filename="' . $name . '"'); + + echo $this->buffer; + + break; + + case Destination::FILE: + $f = fopen($name, 'wb'); + + if (!$f) { + throw new \Mpdf\MpdfException(sprintf('Unable to create output file %s', $name)); + } + + fwrite($f, $this->buffer, strlen($this->buffer)); + fclose($f); + + break; + + case Destination::STRING_RETURN: + $this->cache->clearOld(); + return $this->buffer; + + default: + throw new \Mpdf\MpdfException(sprintf('Incorrect output destination %s', $dest)); + } + + $this->cache->clearOld(); + } + + // ***************************************************************************** + // * + // Protected methods * + // * + // ***************************************************************************** + function _dochecks() + { + // Check for locale-related bug + if (1.1 == 1) { + throw new \Mpdf\MpdfException('Do not alter the locale before including mPDF'); + } + + // Check for decimal separator + if (sprintf('%.1f', 1.0) != '1.0') { + setlocale(LC_NUMERIC, 'C'); + } + + if (ini_get('mbstring.func_overload')) { + throw new \Mpdf\MpdfException('Mpdf cannot function properly with mbstring.func_overload enabled'); + } + + if (!function_exists('mb_substr')) { + throw new \Mpdf\MpdfException('mbstring extension must be loaded in order to run mPDF'); + } + } + + function _puthtmlheaders() + { + $this->state = 2; + $nb = $this->page; + for ($n = 1; $n <= $nb; $n++) { + if ($this->mirrorMargins && $n % 2 == 0) { + $OE = 'E'; + } // EVEN + else { + $OE = 'O'; + } + $this->page = $n; + $pn = $this->docPageNum($n); + if ($pn) { + $pnstr = $this->pagenumPrefix . $pn . $this->pagenumSuffix; + } else { + $pnstr = ''; + } + + $pnt = $this->docPageNumTotal($n); + + if ($pnt) { + $pntstr = $this->nbpgPrefix . $pnt . $this->nbpgSuffix; + } else { + $pntstr = ''; + } + + if (isset($this->saveHTMLHeader[$n][$OE])) { + $html = isset($this->saveHTMLHeader[$n][$OE]['html']) ? $this->saveHTMLHeader[$n][$OE]['html'] : ''; + $this->lMargin = $this->saveHTMLHeader[$n][$OE]['ml']; + $this->rMargin = $this->saveHTMLHeader[$n][$OE]['mr']; + $this->tMargin = $this->saveHTMLHeader[$n][$OE]['mh']; + $this->bMargin = $this->saveHTMLHeader[$n][$OE]['mf']; + $this->margin_header = $this->saveHTMLHeader[$n][$OE]['mh']; + $this->margin_footer = $this->saveHTMLHeader[$n][$OE]['mf']; + $this->w = $this->saveHTMLHeader[$n][$OE]['pw']; + $this->h = $this->saveHTMLHeader[$n][$OE]['ph']; + $rotate = (isset($this->saveHTMLHeader[$n][$OE]['rotate']) ? $this->saveHTMLHeader[$n][$OE]['rotate'] : null); + $this->Reset(); + $this->pageoutput[$n] = []; + $this->pgwidth = $this->w - $this->lMargin - $this->rMargin; + $this->x = $this->lMargin; + $this->y = $this->margin_header; + $html = str_replace('{PAGENO}', $pnstr, $html); + $html = str_replace($this->aliasNbPgGp, $pntstr, $html); // {nbpg} + $html = str_replace($this->aliasNbPg, $nb, $html); // {nb} + $html = preg_replace_callback('/\{DATE\s+(.*?)\}/', [$this, 'date_callback'], $html); // mPDF 5.7 + + $this->HTMLheaderPageLinks = []; + $this->HTMLheaderPageAnnots = []; + $this->HTMLheaderPageForms = []; + $this->pageBackgrounds = []; + + $this->writingHTMLheader = true; + $this->WriteHTML($html, HTMLParserMode::HTML_HEADER_BUFFER); + $this->writingHTMLheader = false; + $this->Reset(); + $this->pageoutput[$n] = []; + + $s = $this->PrintPageBackgrounds(); + $this->headerbuffer = $s . $this->headerbuffer; + $os = ''; + if ($rotate) { + $os .= sprintf('q 0 -1 1 0 0 %.3F cm ', ($this->w * Mpdf::SCALE)); + // To rotate the other way i.e. Header to left of page: + // $os .= sprintf('q 0 1 -1 0 %.3F %.3F cm ',($this->h*Mpdf::SCALE), (($this->rMargin - $this->lMargin )*Mpdf::SCALE)); + } + $os .= $this->headerbuffer; + if ($rotate) { + $os .= ' Q' . "\n"; + } + + // Writes over the page background but behind any other output on page + $os = preg_replace(['/\\\\/', '/\$/'], ['\\\\\\\\', '\\\\$'], $os); + + $this->pages[$n] = preg_replace('/(___HEADER___MARKER' . $this->uniqstr . ')/', "\n" . $os . "\n" . '\\1', $this->pages[$n]); + + $lks = $this->HTMLheaderPageLinks; + foreach ($lks as $lk) { + if ($rotate) { + $lw = $lk[2]; + $lh = $lk[3]; + $lk[2] = $lh; + $lk[3] = $lw; // swap width and height + $ax = $lk[0] / Mpdf::SCALE; + $ay = $lk[1] / Mpdf::SCALE; + $bx = $ay - ($lh / Mpdf::SCALE); + $by = $this->w - $ax; + $lk[0] = $bx * Mpdf::SCALE; + $lk[1] = ($this->h - $by) * Mpdf::SCALE - $lw; + } + $this->PageLinks[$n][] = $lk; + } + /* -- FORMS -- */ + foreach ($this->HTMLheaderPageForms as $f) { + $this->form->forms[$f['n']] = $f; + } + /* -- END FORMS -- */ + } + + if (isset($this->saveHTMLFooter[$n][$OE])) { + + $html = $this->saveHTMLFooter[$this->page][$OE]['html']; + + $this->lMargin = $this->saveHTMLFooter[$n][$OE]['ml']; + $this->rMargin = $this->saveHTMLFooter[$n][$OE]['mr']; + $this->tMargin = $this->saveHTMLFooter[$n][$OE]['mh']; + $this->bMargin = $this->saveHTMLFooter[$n][$OE]['mf']; + $this->margin_header = $this->saveHTMLFooter[$n][$OE]['mh']; + $this->margin_footer = $this->saveHTMLFooter[$n][$OE]['mf']; + $this->w = $this->saveHTMLFooter[$n][$OE]['pw']; + $this->h = $this->saveHTMLFooter[$n][$OE]['ph']; + $rotate = (isset($this->saveHTMLFooter[$n][$OE]['rotate']) ? $this->saveHTMLFooter[$n][$OE]['rotate'] : null); + $this->Reset(); + $this->pageoutput[$n] = []; + $this->pgwidth = $this->w - $this->lMargin - $this->rMargin; + $this->x = $this->lMargin; + $top_y = $this->y = $this->h - $this->margin_footer; + + // if bottom-margin==0, corrects to avoid division by zero + if ($this->y == $this->h) { + $top_y = $this->y = ($this->h + 0.01); + } + + $html = str_replace('{PAGENO}', $pnstr, $html); + $html = str_replace($this->aliasNbPgGp, $pntstr, $html); // {nbpg} + $html = str_replace($this->aliasNbPg, $nb, $html); // {nb} + $html = preg_replace_callback('/\{DATE\s+(.*?)\}/', [$this, 'date_callback'], $html); // mPDF 5.7 + + + $this->HTMLheaderPageLinks = []; + $this->HTMLheaderPageAnnots = []; + $this->HTMLheaderPageForms = []; + $this->pageBackgrounds = []; + + $this->writingHTMLfooter = true; + $this->InFooter = true; + $this->WriteHTML($html, HTMLParserMode::HTML_HEADER_BUFFER); + $this->InFooter = false; + $this->Reset(); + $this->pageoutput[$n] = []; + + $fheight = $this->y - $top_y; + $adj = -$fheight; + + $s = $this->PrintPageBackgrounds(-$adj); + $this->headerbuffer = $s . $this->headerbuffer; + $this->writingHTMLfooter = false; // mPDF 5.7.3 (moved after PrintPageBackgrounds so can adjust position of images in footer) + + $os = ''; + $os .= $this->StartTransform(true) . "\n"; + + if ($rotate) { + $os .= sprintf('q 0 -1 1 0 0 %.3F cm ', ($this->w * Mpdf::SCALE)); + // To rotate the other way i.e. Header to left of page: + // $os .= sprintf('q 0 1 -1 0 %.3F %.3F cm ',($this->h*Mpdf::SCALE), (($this->rMargin - $this->lMargin )*Mpdf::SCALE)); + } + + $os .= $this->transformTranslate(0, $adj, true) . "\n"; + $os .= $this->headerbuffer; + + if ($rotate) { + $os .= ' Q' . "\n"; + } + + $os .= $this->StopTransform(true) . "\n"; + + // Writes over the page background but behind any other output on page + $os = preg_replace(['/\\\\/', '/\$/'], ['\\\\\\\\', '\\\\$'], $os); + + $this->pages[$n] = preg_replace('/(___HEADER___MARKER' . $this->uniqstr . ')/', "\n" . $os . "\n" . '\\1', $this->pages[$n]); + + $lks = $this->HTMLheaderPageLinks; + + foreach ($lks as $lk) { + + $lk[1] -= $adj * Mpdf::SCALE; + + if ($rotate) { + $lw = $lk[2]; + $lh = $lk[3]; + $lk[2] = $lh; + $lk[3] = $lw; // swap width and height + + $ax = $lk[0] / Mpdf::SCALE; + $ay = $lk[1] / Mpdf::SCALE; + $bx = $ay - ($lh / Mpdf::SCALE); + $by = $this->w - $ax; + $lk[0] = $bx * Mpdf::SCALE; + $lk[1] = ($this->h - $by) * Mpdf::SCALE - $lw; + } + + $this->PageLinks[$n][] = $lk; + } + + /* -- FORMS -- */ + foreach ($this->HTMLheaderPageForms as $f) { + $f['y'] += $adj; + $this->form->forms[$f['n']] = $f; + } + /* -- END FORMS -- */ + } + } + + $this->page = $nb; + $this->state = 1; + } + + /* -- ANNOTATIONS -- */ + function Annotation($text, $x = 0, $y = 0, $icon = 'Note', $author = '', $subject = '', $opacity = 0, $colarray = false, $popup = '', $file = '') + { + if (is_array($colarray) && count($colarray) == 3) { + $colarray = $this->colorConverter->convert('rgb(' . $colarray[0] . ',' . $colarray[1] . ',' . $colarray[2] . ')', $this->PDFAXwarnings); + } + if ($colarray === false) { + $colarray = $this->colorConverter->convert('yellow', $this->PDFAXwarnings); + } + if ($x == 0) { + $x = $this->x; + } + if ($y == 0) { + $y = $this->y; + } + $page = $this->page; + if ($page < 1) { // Document has not been started - assume it's for first page + $page = 1; + if ($x == 0) { + $x = $this->lMargin; + } + if ($y == 0) { + $y = $this->tMargin; + } + } + + if ($this->PDFA || $this->PDFX) { + if (($this->PDFA && !$this->PDFAauto) || ($this->PDFX && !$this->PDFXauto)) { + $this->PDFAXwarnings[] = "Annotation markers cannot be semi-transparent in PDFA1-b or PDFX/1-a, so they may make underlying text unreadable. (Annotation markers moved to right margin)"; + } + $x = ($this->w) - $this->rMargin * 0.66; + } + if (!$this->annotMargin) { + $y -= $this->FontSize / 2; + } + + if (!$opacity && $this->annotMargin) { + $opacity = 1; + } elseif (!$opacity) { + $opacity = $this->annotOpacity; + } + + $an = ['txt' => $text, 'x' => $x, 'y' => $y, 'opt' => ['Icon' => $icon, 'T' => $author, 'Subj' => $subject, 'C' => $colarray, 'CA' => $opacity, 'popup' => $popup, 'file' => $file]]; + + if ($this->keep_block_together) { // don't write yet + return; + } elseif ($this->table_rotate) { + $this->tbrot_Annots[$this->page][] = $an; + return; + } elseif ($this->kwt) { + $this->kwt_Annots[$this->page][] = $an; + return; + } + + if ($this->writingHTMLheader || $this->writingHTMLfooter) { + $this->HTMLheaderPageAnnots[] = $an; + return; + } + + // Put an Annotation on the page + $this->PageAnnots[$page][] = $an; + + /* -- COLUMNS -- */ + // Save cross-reference to Column buffer + $ref = isset($this->PageAnnots[$this->page]) ? (count($this->PageAnnots[$this->page]) - 1) : -1; + $this->columnAnnots[$this->CurrCol][intval($this->x)][intval($this->y)] = $ref; + /* -- END COLUMNS -- */ + } + + /* -- END ANNOTATIONS -- */ + + function _enddoc() + { + // @log Writing Headers & Footers + + $this->_puthtmlheaders(); + + // @log Writing Pages + + // Remove references to unused fonts (usually default font) + foreach ($this->fonts as $fk => $font) { + if (isset($font['type']) && $font['type'] == 'TTF' && !$font['used']) { + if ($font['sip'] || $font['smp']) { + foreach ($font['subsetfontids'] as $k => $fid) { + foreach ($this->pages as $pn => $page) { + $this->pages[$pn] = preg_replace('/\s\/F' . $fid . ' \d[\d.]* Tf\s/is', ' ', $this->pages[$pn]); + } + } + } else { + foreach ($this->pages as $pn => $page) { + $this->pages[$pn] = preg_replace('/\s\/F' . $font['i'] . ' \d[\d.]* Tf\s/is', ' ', $this->pages[$pn]); + } + } + } + } + + if (count($this->layers)) { + foreach ($this->pages as $pn => $page) { + preg_match_all('/\/OCZ-index \/ZI(\d+) BDC(.*?)(EMCZ)-index/is', $this->pages[$pn], $m1); + preg_match_all('/\/OCBZ-index \/ZI(\d+) BDC(.*?)(EMCBZ)-index/is', $this->pages[$pn], $m2); + preg_match_all('/\/OCGZ-index \/ZI(\d+) BDC(.*?)(EMCGZ)-index/is', $this->pages[$pn], $m3); + $m = []; + for ($i = 0; $i < 4; $i++) { + $m[$i] = array_merge($m1[$i], $m2[$i], $m3[$i]); + } + if (count($m[0])) { + $sortarr = []; + for ($i = 0; $i < count($m[0]); $i++) { + $key = $m[1][$i] * 2; + if ($m[3][$i] == 'EMCZ') { + $key +=2; // background first then gradient then normal + } elseif ($m[3][$i] == 'EMCGZ') { + $key +=1; + } + $sortarr[$i] = $key; + } + asort($sortarr); + foreach ($sortarr as $i => $k) { + $this->pages[$pn] = str_replace($m[0][$i], '', $this->pages[$pn]); + $this->pages[$pn] .= "\n" . $m[0][$i] . "\n"; + } + $this->pages[$pn] = preg_replace('/\/OC[BG]{0,1}Z-index \/ZI(\d+) BDC/is', '/OC /ZI\\1 BDC ', $this->pages[$pn]); + $this->pages[$pn] = preg_replace('/EMC[BG]{0,1}Z-index/is', 'EMC', $this->pages[$pn]); + } + } + } + + $this->pageWriter->writePages(); + + // @log Writing document resources + + $this->resourceWriter->writeResources(); + + // Info + $this->writer->object(); + $this->InfoRoot = $this->n; + $this->writer->write('<<'); + + // @log Writing document info + $this->metadataWriter->writeInfo(); + + $this->writer->write('>>'); + $this->writer->write('endobj'); + + // METADATA + if ($this->PDFA || $this->PDFX) { + $this->metadataWriter->writeMetadata(); + } + + // OUTPUTINTENT + if ($this->PDFA || $this->PDFX || $this->ICCProfile) { + $this->metadataWriter->writeOutputIntent(); + } + + // Associated files + if ($this->associatedFiles) { + $this->metadataWriter->writeAssociatedFiles(); + } + + // Catalog + $this->writer->object(); + $this->writer->write('<<'); + + // @log Writing document catalog + + $this->metadataWriter->writeCatalog(); + + $this->writer->write('>>'); + $this->writer->write('endobj'); + + // Cross-ref + $o = strlen($this->buffer); + $this->writer->write('xref'); + $this->writer->write('0 ' . ($this->n + 1)); + $this->writer->write('0000000000 65535 f '); + + for ($i = 1; $i <= $this->n; $i++) { + $this->writer->write(sprintf('%010d 00000 n ', $this->offsets[$i])); + } + + // Trailer + $this->writer->write('trailer'); + $this->writer->write('<<'); + + $this->metadataWriter->writeTrailer(); + + $this->writer->write('>>'); + $this->writer->write('startxref'); + $this->writer->write($o); + + $this->buffer .= '%%EOF'; + $this->state = 3; + } + + function _beginpage( + $orientation, + $mgl = '', + $mgr = '', + $mgt = '', + $mgb = '', + $mgh = '', + $mgf = '', + $ohname = '', + $ehname = '', + $ofname = '', + $efname = '', + $ohvalue = 0, + $ehvalue = 0, + $ofvalue = 0, + $efvalue = 0, + $pagesel = '', + $newformat = '' + ) { + if (!($pagesel && $this->page == 1 && (sprintf("%0.4f", $this->y) == sprintf("%0.4f", $this->tMargin)))) { + $this->page++; + $this->pages[$this->page] = ''; + } + $this->state = 2; + $resetHTMLHeadersrequired = false; + + if ($newformat) { + $this->_setPageSize($newformat, $orientation); + } + + /* -- CSS-PAGE -- */ + // Paged media (page-box) + if ($pagesel || (isset($this->page_box['using']) && $this->page_box['using'])) { + + if ($pagesel || $this->page == 1) { + $first = true; + } else { + $first = false; + } + + if ($this->mirrorMargins && ($this->page % 2 == 0)) { + $oddEven = 'E'; + } else { + $oddEven = 'O'; + } + + if ($pagesel) { + $psel = $pagesel; + } elseif ($this->page_box['current']) { + $psel = $this->page_box['current']; + } else { + $psel = ''; + } + + list($orientation, $mgl, $mgr, $mgt, $mgb, $mgh, $mgf, $hname, $fname, $bg, $resetpagenum, $pagenumstyle, $suppress, $marks, $newformat) = $this->SetPagedMediaCSS($psel, $first, $oddEven); + + if ($this->mirrorMargins && ($this->page % 2 == 0)) { + + if ($hname) { + $ehvalue = 1; + $ehname = $hname; + } else { + $ehvalue = -1; + } + + if ($fname) { + $efvalue = 1; + $efname = $fname; + } else { + $efvalue = -1; + } + + } else { + + if ($hname) { + $ohvalue = 1; + $ohname = $hname; + } else { + $ohvalue = -1; + } + + if ($fname) { + $ofvalue = 1; + $ofname = $fname; + } else { + $ofvalue = -1; + } + } + + if ($resetpagenum || $pagenumstyle || $suppress) { + $this->PageNumSubstitutions[] = ['from' => ($this->page), 'reset' => $resetpagenum, 'type' => $pagenumstyle, 'suppress' => $suppress]; + } + + // PAGED MEDIA - CROP / CROSS MARKS from @PAGE + $this->show_marks = $marks; + + // Background color + if (isset($bg['BACKGROUND-COLOR'])) { + $cor = $this->colorConverter->convert($bg['BACKGROUND-COLOR'], $this->PDFAXwarnings); + if ($cor) { + $this->bodyBackgroundColor = $cor; + } + } else { + $this->bodyBackgroundColor = false; + } + + /* -- BACKGROUNDS -- */ + if (isset($bg['BACKGROUND-GRADIENT'])) { + $this->bodyBackgroundGradient = $bg['BACKGROUND-GRADIENT']; + } else { + $this->bodyBackgroundGradient = false; + } + + // Tiling Patterns + if (isset($bg['BACKGROUND-IMAGE']) && $bg['BACKGROUND-IMAGE']) { + $ret = $this->SetBackground($bg, $this->pgwidth); + if ($ret) { + $this->bodyBackgroundImage = $ret; + } + } else { + $this->bodyBackgroundImage = false; + } + /* -- END BACKGROUNDS -- */ + + $this->page_box['current'] = $psel; + $this->page_box['using'] = true; + } + /* -- END CSS-PAGE -- */ + + // Page orientation + if (!$orientation) { + $orientation = $this->DefOrientation; + } else { + $orientation = strtoupper(substr($orientation, 0, 1)); + if ($orientation != $this->DefOrientation) { + $this->OrientationChanges[$this->page] = true; + } + } + + if ($orientation != $this->CurOrientation || $newformat) { + + // Change orientation + if ($orientation == 'P') { + $this->wPt = $this->fwPt; + $this->hPt = $this->fhPt; + $this->w = $this->fw; + $this->h = $this->fh; + if (($this->forcePortraitHeaders || $this->forcePortraitMargins) && $this->DefOrientation == 'P') { + $this->tMargin = $this->orig_tMargin; + $this->bMargin = $this->orig_bMargin; + $this->DeflMargin = $this->orig_lMargin; + $this->DefrMargin = $this->orig_rMargin; + $this->margin_header = $this->orig_hMargin; + $this->margin_footer = $this->orig_fMargin; + } else { + $resetHTMLHeadersrequired = true; + } + } else { + $this->wPt = $this->fhPt; + $this->hPt = $this->fwPt; + $this->w = $this->fh; + $this->h = $this->fw; + + if (($this->forcePortraitHeaders || $this->forcePortraitMargins) && $this->DefOrientation == 'P') { + $this->tMargin = $this->orig_lMargin; + $this->bMargin = $this->orig_rMargin; + $this->DeflMargin = $this->orig_bMargin; + $this->DefrMargin = $this->orig_tMargin; + $this->margin_header = $this->orig_hMargin; + $this->margin_footer = $this->orig_fMargin; + } else { + $resetHTMLHeadersrequired = true; + } + } + + $this->CurOrientation = $orientation; + $this->ResetMargins(); + $this->pgwidth = $this->w - $this->lMargin - $this->rMargin; + $this->PageBreakTrigger = $this->h - $this->bMargin; + } + + $this->pageDim[$this->page]['w'] = $this->w; + $this->pageDim[$this->page]['h'] = $this->h; + + $this->pageDim[$this->page]['outer_width_LR'] = isset($this->page_box['outer_width_LR']) ? $this->page_box['outer_width_LR'] : 0; + $this->pageDim[$this->page]['outer_width_TB'] = isset($this->page_box['outer_width_TB']) ? $this->page_box['outer_width_TB'] : 0; + + if (!isset($this->page_box['outer_width_LR']) && !isset($this->page_box['outer_width_TB'])) { + $this->pageDim[$this->page]['bleedMargin'] = 0; + } elseif ($this->bleedMargin <= $this->page_box['outer_width_LR'] && $this->bleedMargin <= $this->page_box['outer_width_TB']) { + $this->pageDim[$this->page]['bleedMargin'] = $this->bleedMargin; + } else { + $this->pageDim[$this->page]['bleedMargin'] = min($this->page_box['outer_width_LR'], $this->page_box['outer_width_TB']) - 0.01; + } + + // If Page Margins are re-defined + // strlen()>0 is used to pick up (integer) 0, (string) '0', or set value + if ((strlen($mgl) > 0 && $this->DeflMargin != $mgl) || (strlen($mgr) > 0 && $this->DefrMargin != $mgr) || (strlen($mgt) > 0 && $this->tMargin != $mgt) || (strlen($mgb) > 0 && $this->bMargin != $mgb) || (strlen($mgh) > 0 && $this->margin_header != $mgh) || (strlen($mgf) > 0 && $this->margin_footer != $mgf)) { + + if (strlen($mgl) > 0) { + $this->DeflMargin = $mgl; + } + + if (strlen($mgr) > 0) { + $this->DefrMargin = $mgr; + } + + if (strlen($mgt) > 0) { + $this->tMargin = $mgt; + } + + if (strlen($mgb) > 0) { + $this->bMargin = $mgb; + } + + if (strlen($mgh) > 0) { + $this->margin_header = $mgh; + } + + if (strlen($mgf) > 0) { + $this->margin_footer = $mgf; + } + + $this->ResetMargins(); + $this->SetAutoPageBreak($this->autoPageBreak, $this->bMargin); + + $this->pgwidth = $this->w - $this->lMargin - $this->rMargin; + $resetHTMLHeadersrequired = true; + } + + $this->ResetMargins(); + $this->pgwidth = $this->w - $this->lMargin - $this->rMargin; + $this->SetAutoPageBreak($this->autoPageBreak, $this->bMargin); + + // Reset column top margin + $this->y0 = $this->tMargin; + + $this->x = $this->lMargin; + $this->y = $this->tMargin; + $this->FontFamily = ''; + + // HEADERS AND FOOTERS // mPDF 6 + if ($ohvalue < 0 || strtoupper($ohvalue) == 'OFF') { + $this->HTMLHeader = ''; + $resetHTMLHeadersrequired = true; + } elseif ($ohname && $ohvalue > 0) { + if (preg_match('/^html_(.*)$/i', $ohname, $n)) { + $name = $n[1]; + } else { + $name = $ohname; + } + if (isset($this->pageHTMLheaders[$name])) { + $this->HTMLHeader = $this->pageHTMLheaders[$name]; + } else { + $this->HTMLHeader = ''; + } + $resetHTMLHeadersrequired = true; + } + + if ($ehvalue < 0 || strtoupper($ehvalue) == 'OFF') { + $this->HTMLHeaderE = ''; + $resetHTMLHeadersrequired = true; + } elseif ($ehname && $ehvalue > 0) { + if (preg_match('/^html_(.*)$/i', $ehname, $n)) { + $name = $n[1]; + } else { + $name = $ehname; + } + if (isset($this->pageHTMLheaders[$name])) { + $this->HTMLHeaderE = $this->pageHTMLheaders[$name]; + } else { + $this->HTMLHeaderE = ''; + } + $resetHTMLHeadersrequired = true; + } + + if ($ofvalue < 0 || strtoupper($ofvalue) == 'OFF') { + $this->HTMLFooter = ''; + $resetHTMLHeadersrequired = true; + } elseif ($ofname && $ofvalue > 0) { + if (preg_match('/^html_(.*)$/i', $ofname, $n)) { + $name = $n[1]; + } else { + $name = $ofname; + } + if (isset($this->pageHTMLfooters[$name])) { + $this->HTMLFooter = $this->pageHTMLfooters[$name]; + } else { + $this->HTMLFooter = ''; + } + $resetHTMLHeadersrequired = true; + } + + if ($efvalue < 0 || strtoupper($efvalue) == 'OFF') { + $this->HTMLFooterE = ''; + $resetHTMLHeadersrequired = true; + } elseif ($efname && $efvalue > 0) { + if (preg_match('/^html_(.*)$/i', $efname, $n)) { + $name = $n[1]; + } else { + $name = $efname; + } + if (isset($this->pageHTMLfooters[$name])) { + $this->HTMLFooterE = $this->pageHTMLfooters[$name]; + } else { + $this->HTMLFooterE = ''; + } + $resetHTMLHeadersrequired = true; + } + + if ($resetHTMLHeadersrequired) { + $this->SetHTMLHeader($this->HTMLHeader); + $this->SetHTMLHeader($this->HTMLHeaderE, 'E'); + $this->SetHTMLFooter($this->HTMLFooter); + $this->SetHTMLFooter($this->HTMLFooterE, 'E'); + } + + + if (($this->mirrorMargins) && (($this->page) % 2 == 0)) { // EVEN + $this->_setAutoHeaderHeight($this->HTMLHeaderE); + $this->_setAutoFooterHeight($this->HTMLFooterE); + } else { // ODD or DEFAULT + $this->_setAutoHeaderHeight($this->HTMLHeader); + $this->_setAutoFooterHeight($this->HTMLFooter); + } + + // Reset column top margin + $this->y0 = $this->tMargin; + + $this->x = $this->lMargin; + $this->y = $this->tMargin; + } + + // mPDF 6 + function _setAutoHeaderHeight(&$htmlh) + { + /* When the setAutoTopMargin option is set to pad/stretch, only apply auto header height when a header exists */ + if ($this->HTMLHeader === '' && $this->HTMLHeaderE === '') { + return; + } + + if ($this->setAutoTopMargin == 'pad') { + if (isset($htmlh['h']) && $htmlh['h']) { + $h = $htmlh['h']; + } // 5.7.3 + else { + $h = 0; + } + $this->tMargin = $this->margin_header + $h + $this->orig_tMargin; + } elseif ($this->setAutoTopMargin == 'stretch') { + if (isset($htmlh['h']) && $htmlh['h']) { + $h = $htmlh['h']; + } // 5.7.3 + else { + $h = 0; + } + $this->tMargin = max($this->orig_tMargin, $this->margin_header + $h + $this->autoMarginPadding); + } + } + + // mPDF 6 + function _setAutoFooterHeight(&$htmlf) + { + /* When the setAutoTopMargin option is set to pad/stretch, only apply auto footer height when a footer exists */ + if ($this->HTMLFooter === '' && $this->HTMLFooterE === '') { + return; + } + + if ($this->setAutoBottomMargin == 'pad') { + if (isset($htmlf['h']) && $htmlf['h']) { + $h = $htmlf['h']; + } // 5.7.3 + else { + $h = 0; + } + $this->bMargin = $this->margin_footer + $h + $this->orig_bMargin; + $this->PageBreakTrigger = $this->h - $this->bMargin; + } elseif ($this->setAutoBottomMargin == 'stretch') { + if (isset($htmlf['h']) && $htmlf['h']) { + $h = $htmlf['h']; + } // 5.7.3 + else { + $h = 0; + } + $this->bMargin = max($this->orig_bMargin, $this->margin_footer + $h + $this->autoMarginPadding); + $this->PageBreakTrigger = $this->h - $this->bMargin; + } + } + + function _endpage() + { + /* -- CSS-IMAGE-FLOAT -- */ + $this->printfloatbuffer(); + /* -- END CSS-IMAGE-FLOAT -- */ + + if ($this->visibility != 'visible') { + $this->SetVisibility('visible'); + } + $this->EndLayer(); + // End of page contents + $this->state = 1; + } + + function _dounderline($x, $y, $txt, $OTLdata = false, $textvar = 0) + { + // Now print line exactly where $y secifies - called from Text() and Cell() - adjust position there + // WORD SPACING + $w = ($this->GetStringWidth($txt, false, $OTLdata, $textvar) * Mpdf::SCALE) + ($this->charspacing * mb_strlen($txt, $this->mb_enc)) + ( $this->ws * mb_substr_count($txt, ' ', $this->mb_enc)); + // Draw a line + return sprintf('%.3F %.3F m %.3F %.3F l S', $x * Mpdf::SCALE, ($this->h - $y) * Mpdf::SCALE, ($x * Mpdf::SCALE) + $w, ($this->h - $y) * Mpdf::SCALE); + } + + + + /* -- WATERMARK -- */ + + // add a watermark + function watermark($texte, $angle = 45, $fontsize = 96, $alpha = 0.2) + { + if ($this->PDFA || $this->PDFX) { + throw new \Mpdf\MpdfException('PDFA and PDFX do not permit transparency, so mPDF does not allow Watermarks!'); + } + + if (!$this->watermark_font) { + $this->watermark_font = $this->default_font; + } + + $this->SetFont($this->watermark_font, "B", $fontsize, false); // Don't output + $texte = $this->purify_utf8_text($texte); + + if ($this->text_input_as_HTML) { + $texte = $this->all_entities_to_utf8($texte); + } + + if ($this->usingCoreFont) { + $texte = mb_convert_encoding($texte, $this->mb_enc, 'UTF-8'); + } + + // DIRECTIONALITY + if (preg_match("/([" . $this->pregRTLchars . "])/u", $texte)) { + $this->biDirectional = true; + } // *OTL* + + $textvar = 0; + $save_OTLtags = $this->OTLtags; + $this->OTLtags = []; + if ($this->useKerning) { + if ($this->CurrentFont['haskernGPOS']) { + $this->OTLtags['Plus'] .= ' kern'; + } else { + $textvar = ($textvar | TextVars::FC_KERNING); + } + } + + /* -- OTL -- */ + // Use OTL OpenType Table Layout - GSUB & GPOS + if (isset($this->CurrentFont['useOTL']) && $this->CurrentFont['useOTL']) { + $texte = $this->otl->applyOTL($texte, $this->CurrentFont['useOTL']); + $OTLdata = $this->otl->OTLdata; + } + /* -- END OTL -- */ + $this->OTLtags = $save_OTLtags; + + $this->magic_reverse_dir($texte, $this->directionality, $OTLdata); + + $this->SetAlpha($alpha); + + $this->SetTColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + + $szfont = $fontsize; + $loop = 0; + $maxlen = (min($this->w, $this->h) ); // sets max length of text as 7/8 width/height of page + + while ($loop == 0) { + $this->SetFont($this->watermark_font, "B", $szfont, false); // Don't output + $offset = ((sin(deg2rad($angle))) * ($szfont / Mpdf::SCALE)); + + $strlen = $this->GetStringWidth($texte, true, $OTLdata, $textvar); + if ($strlen > $maxlen - $offset) { + $szfont --; + } else { + $loop ++; + } + } + + $this->SetFont($this->watermark_font, "B", $szfont - 0.1, true, true); // Output The -0.1 is because SetFont above is not written to PDF + + // Repeating it will not output anything as mPDF thinks it is set + $adj = ((cos(deg2rad($angle))) * ($strlen / 2)); + $opp = ((sin(deg2rad($angle))) * ($strlen / 2)); + + $wx = ($this->w / 2) - $adj + $offset / 3; + $wy = ($this->h / 2) + $opp; + + $this->Rotate($angle, $wx, $wy); + $this->Text($wx, $wy, $texte, $OTLdata, $textvar); + $this->Rotate(0); + $this->SetTColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + + $this->SetAlpha(1); + } + + function watermarkImg($src, $alpha = 0.2) + { + if ($this->PDFA || $this->PDFX) { + throw new \Mpdf\MpdfException('PDFA and PDFX do not permit transparency, so mPDF does not allow Watermarks!'); + } + + if ($this->watermarkImgBehind) { + $this->watermarkImgAlpha = $this->SetAlpha($alpha, 'Normal', true); + } else { + $this->SetAlpha($alpha, $this->watermarkImgAlphaBlend); + } + + $this->Image($src, 0, 0, 0, 0, '', '', true, true, true); + + if (!$this->watermarkImgBehind) { + $this->SetAlpha(1); + } + } + + /* -- END WATERMARK -- */ + + function Rotate($angle, $x = -1, $y = -1) + { + if ($x == -1) { + $x = $this->x; + } + if ($y == -1) { + $y = $this->y; + } + if ($this->angle != 0) { + $this->writer->write('Q'); + } + $this->angle = $angle; + if ($angle != 0) { + $angle*=M_PI / 180; + $c = cos($angle); + $s = sin($angle); + $cx = $x * Mpdf::SCALE; + $cy = ($this->h - $y) * Mpdf::SCALE; + $this->writer->write(sprintf('q %.5F %.5F %.5F %.5F %.3F %.3F cm 1 0 0 1 %.3F %.3F cm', $c, $s, -$s, $c, $cx, $cy, -$cx, -$cy)); + } + } + + function CircularText($x, $y, $r, $text, $align = 'top', $fontfamily = '', $fontsize = 0, $fontstyle = '', $kerning = 120, $fontwidth = 100, $divider = '') + { + if (empty($this->directWrite)) { + $this->directWrite = new DirectWrite($this, $this->otl, $this->sizeConverter, $this->colorConverter); + } + + $this->directWrite->CircularText($x, $y, $r, $text, $align, $fontfamily, $fontsize, $fontstyle, $kerning, $fontwidth, $divider); + } + + // From Invoice + function RoundedRect($x, $y, $w, $h, $r, $style = '') + { + $hp = $this->h; + + if ($style == 'F') { + $op = 'f'; + } elseif ($style == 'FD' or $style == 'DF') { + $op = 'B'; + } else { + $op = 'S'; + } + + $MyArc = 4 / 3 * (sqrt(2) - 1); + $this->writer->write(sprintf('%.3F %.3F m', ($x + $r) * Mpdf::SCALE, ($hp - $y) * Mpdf::SCALE)); + $xc = $x + $w - $r; + $yc = $y + $r; + $this->writer->write(sprintf('%.3F %.3F l', $xc * Mpdf::SCALE, ($hp - $y) * Mpdf::SCALE)); + + $this->_Arc($xc + $r * $MyArc, $yc - $r, $xc + $r, $yc - $r * $MyArc, $xc + $r, $yc); + $xc = $x + $w - $r; + $yc = $y + $h - $r; + $this->writer->write(sprintf('%.3F %.3F l', ($x + $w) * Mpdf::SCALE, ($hp - $yc) * Mpdf::SCALE)); + + $this->_Arc($xc + $r, $yc + $r * $MyArc, $xc + $r * $MyArc, $yc + $r, $xc, $yc + $r); + $xc = $x + $r; + $yc = $y + $h - $r; + $this->writer->write(sprintf('%.3F %.3F l', $xc * Mpdf::SCALE, ($hp - ($y + $h)) * Mpdf::SCALE)); + + $this->_Arc($xc - $r * $MyArc, $yc + $r, $xc - $r, $yc + $r * $MyArc, $xc - $r, $yc); + $xc = $x + $r; + $yc = $y + $r; + $this->writer->write(sprintf('%.3F %.3F l', ($x) * Mpdf::SCALE, ($hp - $yc) * Mpdf::SCALE)); + + $this->_Arc($xc - $r, $yc - $r * $MyArc, $xc - $r * $MyArc, $yc - $r, $xc, $yc - $r); + $this->writer->write($op); + } + + function _Arc($x1, $y1, $x2, $y2, $x3, $y3) + { + $h = $this->h; + $this->writer->write(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F c ', $x1 * Mpdf::SCALE, ($h - $y1) * Mpdf::SCALE, $x2 * Mpdf::SCALE, ($h - $y2) * Mpdf::SCALE, $x3 * Mpdf::SCALE, ($h - $y3) * Mpdf::SCALE)); + } + + // ==================================================== + + + + /* -- DIRECTW -- */ + function Shaded_box($text, $font = '', $fontstyle = 'B', $szfont = '', $width = '70%', $style = 'DF', $radius = 2.5, $fill = '#FFFFFF', $color = '#000000', $pad = 2) + { + // F (shading - no line),S (line, no shading),DF (both) + if (empty($this->directWrite)) { + $this->directWrite = new DirectWrite($this, $this->otl, $this->sizeConverter, $this->colorConverter); + } + $this->directWrite->Shaded_box($text, $font, $fontstyle, $szfont, $width, $style, $radius, $fill, $color, $pad); + } + + /* -- END DIRECTW -- */ + + function UTF8StringToArray($str, $addSubset = true) + { + $out = []; + $len = strlen($str); + for ($i = 0; $i < $len; $i++) { + $uni = -1; + $h = ord($str[$i]); + if ($h <= 0x7F) { + $uni = $h; + } elseif ($h >= 0xC2) { + if (($h <= 0xDF) && ($i < $len - 1)) { + $uni = ($h & 0x1F) << 6 | (ord($str[++$i]) & 0x3F); + } elseif (($h <= 0xEF) && ($i < $len - 2)) { + $uni = ($h & 0x0F) << 12 | (ord($str[++$i]) & 0x3F) << 6 | (ord($str[++$i]) & 0x3F); + } elseif (($h <= 0xF4) && ($i < $len - 3)) { + $uni = ($h & 0x0F) << 18 | (ord($str[++$i]) & 0x3F) << 12 | (ord($str[++$i]) & 0x3F) << 6 | (ord($str[++$i]) & 0x3F); + } + } + if ($uni >= 0) { + $out[] = $uni; + if ($addSubset && isset($this->CurrentFont['subset'])) { + $this->CurrentFont['subset'][$uni] = $uni; + } + } + } + return $out; + } + + // Convert utf-8 string to for Font Subsets + function UTF8toSubset($str) + { + $ret = '<'; + // $str = preg_replace('/'.preg_quote($this->aliasNbPg,'/').'/', chr(7), $str ); // mPDF 6 deleted + // $str = preg_replace('/'.preg_quote($this->aliasNbPgGp,'/').'/', chr(8), $str ); // mPDF 6 deleted + $unicode = $this->UTF8StringToArray($str); + $orig_fid = $this->CurrentFont['subsetfontids'][0]; + $last_fid = $this->CurrentFont['subsetfontids'][0]; + foreach ($unicode as $c) { + /* // mPDF 6 deleted + if ($c == 7 || $c == 8) { + if ($orig_fid != $last_fid) { + $ret .= '> Tj /F'.$orig_fid.' '.$this->FontSizePt.' Tf <'; + $last_fid = $orig_fid; + } + if ($c == 7) { $ret .= $this->aliasNbPgHex; } + else { $ret .= $this->aliasNbPgGpHex; } + continue; + } + */ + if (!$this->_charDefined($this->CurrentFont['cw'], $c)) { + $c = 0; + } // mPDF 6 + for ($i = 0; $i < 99; $i++) { + // return c as decimal char + $init = array_search($c, $this->CurrentFont['subsets'][$i]); + if ($init !== false) { + if ($this->CurrentFont['subsetfontids'][$i] != $last_fid) { + $ret .= '> Tj /F' . $this->CurrentFont['subsetfontids'][$i] . ' ' . $this->FontSizePt . ' Tf <'; + $last_fid = $this->CurrentFont['subsetfontids'][$i]; + } + $ret .= sprintf("%02s", strtoupper(dechex($init))); + break; + } // TrueType embedded SUBSETS + elseif (count($this->CurrentFont['subsets'][$i]) < 255) { + $n = count($this->CurrentFont['subsets'][$i]); + $this->CurrentFont['subsets'][$i][$n] = $c; + if ($this->CurrentFont['subsetfontids'][$i] != $last_fid) { + $ret .= '> Tj /F' . $this->CurrentFont['subsetfontids'][$i] . ' ' . $this->FontSizePt . ' Tf <'; + $last_fid = $this->CurrentFont['subsetfontids'][$i]; + } + $ret .= sprintf("%02s", strtoupper(dechex($n))); + break; + } elseif (!isset($this->CurrentFont['subsets'][($i + 1)])) { + // TrueType embedded SUBSETS + $this->CurrentFont['subsets'][($i + 1)] = [0 => 0]; + $new_fid = count($this->fonts) + $this->extraFontSubsets + 1; + $this->CurrentFont['subsetfontids'][($i + 1)] = $new_fid; + $this->extraFontSubsets++; + } + } + } + $ret .= '>'; + if ($last_fid != $orig_fid) { + $ret .= ' Tj /F' . $orig_fid . ' ' . $this->FontSizePt . ' Tf <> '; + } + return $ret; + } + + /* -- CJK-FONTS -- */ + + // from class PDF_Chinese CJK EXTENSIONS + function AddCIDFont($family, $style, $name, &$cw, $CMap, $registry, $desc) + { + $fontkey = strtolower($family) . strtoupper($style); + if (isset($this->fonts[$fontkey])) { + throw new \Mpdf\MpdfException("Font already added: $family $style"); + } + $i = count($this->fonts) + $this->extraFontSubsets + 1; + $name = str_replace(' ', '', $name); + if ($family == 'sjis') { + $up = -120; + } else { + $up = -130; + } + // ? 'up' and 'ut' do not seem to be referenced anywhere + $this->fonts[$fontkey] = ['i' => $i, 'type' => 'Type0', 'name' => $name, 'up' => $up, 'ut' => 40, 'cw' => $cw, 'CMap' => $CMap, 'registry' => $registry, 'MissingWidth' => 1000, 'desc' => $desc]; + } + + function AddCJKFont($family) + { + + if ($this->PDFA || $this->PDFX) { + throw new \Mpdf\MpdfException("Adobe CJK fonts cannot be embedded in mPDF (required for PDFA1-b and PDFX/1-a)."); + } + if ($family == 'big5') { + $this->AddBig5Font(); + } elseif ($family == 'gb') { + $this->AddGBFont(); + } elseif ($family == 'sjis') { + $this->AddSJISFont(); + } elseif ($family == 'uhc') { + $this->AddUHCFont(); + } + } + + function AddBig5Font() + { + // Add Big5 font with proportional Latin + $family = 'big5'; + $name = 'MSungStd-Light-Acro'; + $cw = $this->Big5_widths; + $CMap = 'UniCNS-UTF16-H'; + $registry = ['ordering' => 'CNS1', 'supplement' => 4]; + $desc = [ + 'Ascent' => 880, + 'Descent' => -120, + 'CapHeight' => 880, + 'Flags' => 6, + 'FontBBox' => '[-160 -249 1015 1071]', + 'ItalicAngle' => 0, + 'StemV' => 93, + ]; + $this->AddCIDFont($family, '', $name, $cw, $CMap, $registry, $desc); + $this->AddCIDFont($family, 'B', $name . ',Bold', $cw, $CMap, $registry, $desc); + $this->AddCIDFont($family, 'I', $name . ',Italic', $cw, $CMap, $registry, $desc); + $this->AddCIDFont($family, 'BI', $name . ',BoldItalic', $cw, $CMap, $registry, $desc); + } + + function AddGBFont() + { + // Add GB font with proportional Latin + $family = 'gb'; + $name = 'STSongStd-Light-Acro'; + $cw = $this->GB_widths; + $CMap = 'UniGB-UTF16-H'; + $registry = ['ordering' => 'GB1', 'supplement' => 4]; + $desc = [ + 'Ascent' => 880, + 'Descent' => -120, + 'CapHeight' => 737, + 'Flags' => 6, + 'FontBBox' => '[-25 -254 1000 880]', + 'ItalicAngle' => 0, + 'StemV' => 58, + 'Style' => '<< /Panose <000000000400000000000000> >>', + ]; + $this->AddCIDFont($family, '', $name, $cw, $CMap, $registry, $desc); + $this->AddCIDFont($family, 'B', $name . ',Bold', $cw, $CMap, $registry, $desc); + $this->AddCIDFont($family, 'I', $name . ',Italic', $cw, $CMap, $registry, $desc); + $this->AddCIDFont($family, 'BI', $name . ',BoldItalic', $cw, $CMap, $registry, $desc); + } + + function AddSJISFont() + { + // Add SJIS font with proportional Latin + $family = 'sjis'; + $name = 'KozMinPro-Regular-Acro'; + $cw = $this->SJIS_widths; + $CMap = 'UniJIS-UTF16-H'; + $registry = ['ordering' => 'Japan1', 'supplement' => 5]; + $desc = [ + 'Ascent' => 880, + 'Descent' => -120, + 'CapHeight' => 740, + 'Flags' => 6, + 'FontBBox' => '[-195 -272 1110 1075]', + 'ItalicAngle' => 0, + 'StemV' => 86, + 'XHeight' => 502, + ]; + $this->AddCIDFont($family, '', $name, $cw, $CMap, $registry, $desc); + $this->AddCIDFont($family, 'B', $name . ',Bold', $cw, $CMap, $registry, $desc); + $this->AddCIDFont($family, 'I', $name . ',Italic', $cw, $CMap, $registry, $desc); + $this->AddCIDFont($family, 'BI', $name . ',BoldItalic', $cw, $CMap, $registry, $desc); + } + + function AddUHCFont() + { + // Add UHC font with proportional Latin + $family = 'uhc'; + $name = 'HYSMyeongJoStd-Medium-Acro'; + $cw = $this->UHC_widths; + $CMap = 'UniKS-UTF16-H'; + $registry = ['ordering' => 'Korea1', 'supplement' => 2]; + $desc = [ + 'Ascent' => 880, + 'Descent' => -120, + 'CapHeight' => 720, + 'Flags' => 6, + 'FontBBox' => '[-28 -148 1001 880]', + 'ItalicAngle' => 0, + 'StemV' => 60, + 'Style' => '<< /Panose <000000000600000000000000> >>', + ]; + $this->AddCIDFont($family, '', $name, $cw, $CMap, $registry, $desc); + $this->AddCIDFont($family, 'B', $name . ',Bold', $cw, $CMap, $registry, $desc); + $this->AddCIDFont($family, 'I', $name . ',Italic', $cw, $CMap, $registry, $desc); + $this->AddCIDFont($family, 'BI', $name . ',BoldItalic', $cw, $CMap, $registry, $desc); + } + + /* -- END CJK-FONTS -- */ + + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + function SetDefaultFont($font) + { + // Disallow embedded fonts to be used as defaults in PDFA + if ($this->PDFA || $this->PDFX) { + if (strtolower($font) == 'ctimes') { + $font = 'serif'; + } + if (strtolower($font) == 'ccourier') { + $font = 'monospace'; + } + if (strtolower($font) == 'chelvetica') { + $font = 'sans-serif'; + } + } + $font = $this->SetFont($font); // returns substituted font if necessary + $this->default_font = $font; + $this->original_default_font = $font; + if (!$this->watermark_font) { + $this->watermark_font = $font; + } // *WATERMARK* + $this->defaultCSS['BODY']['FONT-FAMILY'] = $font; + $this->cssManager->CSS['BODY']['FONT-FAMILY'] = $font; + } + + function SetDefaultFontSize($fontsize) + { + $this->default_font_size = $fontsize; + $this->original_default_font_size = $fontsize; + $this->SetFontSize($fontsize); + $this->defaultCSS['BODY']['FONT-SIZE'] = $fontsize . 'pt'; + $this->cssManager->CSS['BODY']['FONT-SIZE'] = $fontsize . 'pt'; + } + + function SetDefaultBodyCSS($prop, $val) + { + if ($prop) { + $this->defaultCSS['BODY'][strtoupper($prop)] = $val; + $this->cssManager->CSS['BODY'][strtoupper($prop)] = $val; + } + } + + function SetDirectionality($dir = 'ltr') + { + /* -- OTL -- */ + if (strtolower($dir) == 'rtl') { + if ($this->directionality != 'rtl') { + // Swop L/R Margins so page 1 RTL is an 'even' page + $tmp = $this->DeflMargin; + $this->DeflMargin = $this->DefrMargin; + $this->DefrMargin = $tmp; + $this->orig_lMargin = $this->DeflMargin; + $this->orig_rMargin = $this->DefrMargin; + + $this->SetMargins($this->DeflMargin, $this->DefrMargin, $this->tMargin); + } + $this->directionality = 'rtl'; + $this->defaultAlign = 'R'; + $this->defaultTableAlign = 'R'; + } else { + /* -- END OTL -- */ + $this->directionality = 'ltr'; + $this->defaultAlign = 'L'; + $this->defaultTableAlign = 'L'; + } // *OTL* + $this->cssManager->CSS['BODY']['DIRECTION'] = $this->directionality; + } + + // Return either a number (factor) - based on current set fontsize (if % or em) - or exact lineheight (with 'mm' after it) + function fixLineheight($v) + { + $lh = false; + if (preg_match('/^[0-9\.,]*$/', $v) && $v >= 0) { + return ($v + 0); + } elseif (strtoupper($v) == 'NORMAL' || $v == 'N') { + return 'N'; // mPDF 6 + } else { + $tlh = $this->sizeConverter->convert($v, $this->FontSize, $this->FontSize, true); + if ($tlh) { + return ($tlh . 'mm'); + } + } + return $this->normalLineheight; + } + + function _getNormalLineheight($desc = false) + { + if (!$desc) { + $desc = $this->CurrentFont['desc']; + } + if (!isset($desc['Leading'])) { + $desc['Leading'] = 0; + } + if ($this->useFixedNormalLineHeight) { + $lh = $this->normalLineheight; + } elseif (isset($desc['Ascent']) && $desc['Ascent']) { + $lh = ($this->adjustFontDescLineheight * ($desc['Ascent'] - $desc['Descent'] + $desc['Leading']) / 1000); + } else { + $lh = $this->normalLineheight; + } + return $lh; + } + + // Set a (fixed) lineheight to an actual value - either to named fontsize(pts) or default + function SetLineHeight($FontPt = '', $lh = '') + { + if (!$FontPt) { + $FontPt = $this->FontSizePt; + } + $fs = $FontPt / Mpdf::SCALE; + $this->lineheight = $this->_computeLineheight($lh, $fs); + } + + function _computeLineheight($lh, $fs = '') + { + if ($this->shrin_k > 1) { + $k = $this->shrin_k; + } else { + $k = 1; + } + if (!$fs) { + $fs = $this->FontSize; + } + if ($lh == 'N') { + $lh = $this->_getNormalLineheight(); + } + if (preg_match('/mm/', $lh)) { + return (((float) $lh) / $k); // convert to number + } elseif ($lh > 0) { + return ($fs * $lh); + } + return ($fs * $this->normalLineheight); + } + + function _setLineYpos(&$fontsize, &$fontdesc, &$CSSlineheight, $blockYpos = false) + { + $ypos['glyphYorigin'] = 0; + $ypos['baseline-shift'] = 0; + $linegap = 0; + $leading = 0; + + if (isset($fontdesc['Ascent']) && $fontdesc['Ascent'] && !$this->useFixedTextBaseline) { + // Fontsize uses font metrics - this method seems to produce results compatible with browsers (except IE9) + $ypos['boxtop'] = $fontdesc['Ascent'] / 1000 * $fontsize; + $ypos['boxbottom'] = $fontdesc['Descent'] / 1000 * $fontsize; + if (isset($fontdesc['Leading'])) { + $linegap = $fontdesc['Leading'] / 1000 * $fontsize; + } + } // Default if not set - uses baselineC + else { + $ypos['boxtop'] = (0.5 + $this->baselineC) * $fontsize; + $ypos['boxbottom'] = -(0.5 - $this->baselineC) * $fontsize; + } + $fontheight = $ypos['boxtop'] - $ypos['boxbottom']; + + if ($this->shrin_k > 1) { + $shrin_k = $this->shrin_k; + } else { + $shrin_k = 1; + } + + $leading = 0; + if ($CSSlineheight == 'N') { + $lh = $this->_getNormalLineheight($fontdesc); + $lineheight = ($fontsize * $lh); + $leading += $linegap; // specified in hhea or sTypo in OpenType tables + } elseif (preg_match('/mm/', $CSSlineheight)) { + $lineheight = (((float) $CSSlineheight) / $shrin_k); // convert to number + } // ??? If lineheight is a factor e.g. 1.3 ?? use factor x 1em or ? use 'normal' lineheight * factor + // Could depend on value for $text_height - a draft CSS value as set above for now + elseif ($CSSlineheight > 0) { + $lineheight = ($fontsize * $CSSlineheight); + } else { + $lineheight = ($fontsize * $this->normalLineheight); + } + + // In general, calculate the "leading" - the difference between the fontheight and the lineheight + // and add half to the top and half to the bottom. BUT + // If an inline element has a font-size less than the block element, and the line-height is set as an em or % value + // it will add too much leading below the font and expand the height of the line - so just use the block element exttop/extbottom: + if (preg_match('/mm/', $CSSlineheight) + && ($blockYpos && $ypos['boxtop'] < $blockYpos['boxtop']) + && ($blockYpos && $ypos['boxbottom'] > $blockYpos['boxbottom'])) { + + $ypos['exttop'] = $blockYpos['exttop']; + $ypos['extbottom'] = $blockYpos['extbottom']; + + } else { + + $leading += ($lineheight - $fontheight); + + $ypos['exttop'] = $ypos['boxtop'] + $leading / 2; + $ypos['extbottom'] = $ypos['boxbottom'] - $leading / 2; + } + + + // TEMP ONLY FOR DEBUGGING ********************************* + // $ypos['lineheight'] = $lineheight; + // $ypos['fontheight'] = $fontheight; + // $ypos['leading'] = $leading; + + return $ypos; + } + + /* Called from WriteFlowingBlock() and finishFlowingBlock() + Determines the line hieght and glyph/writing position + for each element in the line to be written */ + + function _setInlineBlockHeights(&$lineBox, &$stackHeight, &$content, &$font, $is_table) + { + if ($this->shrin_k > 1) { + $shrin_k = $this->shrin_k; + } else { + $shrin_k = 1; + } + + $ypos = []; + $bordypos = []; + $bgypos = []; + + if ($is_table) { + // FOR TABLE + $fontsize = $this->FontSize; + $fontkey = $this->FontFamily . $this->FontStyle; + $fontdesc = $this->fonts[$fontkey]['desc']; + $CSSlineheight = $this->cellLineHeight; + $line_stacking_strategy = $this->cellLineStackingStrategy; // inline-line-height [default] | block-line-height | max-height | grid-height + $line_stacking_shift = $this->cellLineStackingShift; // consider-shifts [default] | disregard-shifts + } else { + // FOR BLOCK FONT + $fontsize = $this->blk[$this->blklvl]['InlineProperties']['size']; + $fontkey = $this->blk[$this->blklvl]['InlineProperties']['family'] . $this->blk[$this->blklvl]['InlineProperties']['style']; + $fontdesc = $this->fonts[$fontkey]['desc']; + $CSSlineheight = $this->blk[$this->blklvl]['line_height']; + // inline-line-height | block-line-height | max-height | grid-height + $line_stacking_strategy = (isset($this->blk[$this->blklvl]['line_stacking_strategy']) ? $this->blk[$this->blklvl]['line_stacking_strategy'] : 'inline-line-height'); + // consider-shifts | disregard-shifts + $line_stacking_shift = (isset($this->blk[$this->blklvl]['line_stacking_shift']) ? $this->blk[$this->blklvl]['line_stacking_shift'] : 'consider-shifts'); + } + $boxLineHeight = $this->_computeLineheight($CSSlineheight, $fontsize); + + + // First, set a "strut" using block font at index $lineBox[-1] + $ypos[-1] = $this->_setLineYpos($fontsize, $fontdesc, $CSSlineheight); + + // for the block element - always taking the block EXTENDED progression including leading - which may be negative + if ($line_stacking_strategy == 'block-line-height') { + $topy = $ypos[-1]['exttop']; + $bottomy = $ypos[-1]['extbottom']; + } else { + $topy = 0; + $bottomy = 0; + } + + // Get text-middle for aligning images/objects + $midpoint = $ypos[-1]['boxtop'] - (($ypos[-1]['boxtop'] - $ypos[-1]['boxbottom']) / 2); + + // for images / inline objects / replaced elements + $mta = 0; // Maximum top-aligned + $mba = 0; // Maximum bottom-aligned + foreach ($content as $k => $chunk) { + if (isset($this->objectbuffer[$k]) && $this->objectbuffer[$k]['type'] == 'listmarker') { + $ypos[$k] = $ypos[-1]; + // UPDATE Maximums + if ($line_stacking_strategy == 'block-line-height' || $line_stacking_strategy == 'grid-height' || $line_stacking_strategy == 'max-height') { // don't include extended block progression of all inline elements + if ($ypos[$k]['boxtop'] > $topy) { + $topy = $ypos[$k]['boxtop']; + } + if ($ypos[$k]['boxbottom'] < $bottomy) { + $bottomy = $ypos[$k]['boxbottom']; + } + } else { + if ($ypos[$k]['exttop'] > $topy) { + $topy = $ypos[$k]['exttop']; + } + if ($ypos[$k]['extbottom'] < $bottomy) { + $bottomy = $ypos[$k]['extbottom']; + } + } + } elseif (isset($this->objectbuffer[$k]) && $this->objectbuffer[$k]['type'] == 'dottab') { // mPDF 6 DOTTAB + $fontsize = $font[$k]['size']; + $fontdesc = $font[$k]['curr']['desc']; + $lh = 1; + $ypos[$k] = $this->_setLineYpos($fontsize, $fontdesc, $lh, $ypos[-1]); // Lineheight=1 fixed + } elseif (isset($this->objectbuffer[$k])) { + $oh = $this->objectbuffer[$k]['OUTER-HEIGHT']; + $va = $this->objectbuffer[$k]['vertical-align']; + + if ($va == 'BS') { // (BASELINE default) + if ($oh > $topy) { + $topy = $oh; + } + } elseif ($va == 'M') { + if (($midpoint + $oh / 2) > $topy) { + $topy = $midpoint + $oh / 2; + } + if (($midpoint - $oh / 2) < $bottomy) { + $bottomy = $midpoint - $oh / 2; + } + } elseif ($va == 'TT') { + if (($ypos[-1]['boxtop'] - $oh) < $bottomy) { + $bottomy = $ypos[-1]['boxtop'] - $oh; + $topy = max($topy, $ypos[-1]['boxtop']); + } + } elseif ($va == 'TB') { + if (($ypos[-1]['boxbottom'] + $oh) > $topy) { + $topy = $ypos[-1]['boxbottom'] + $oh; + $bottomy = min($bottomy, $ypos[-1]['boxbottom']); + } + } elseif ($va == 'T') { + if ($oh > $mta) { + $mta = $oh; + } + } elseif ($va == 'B') { + if ($oh > $mba) { + $mba = $oh; + } + } + } elseif ($content[$k] || $content[$k] === '0') { + // FOR FLOWING BLOCK + $fontsize = $font[$k]['size']; + $fontdesc = $font[$k]['curr']['desc']; + // In future could set CSS line-height from inline elements; for now, use block level: + $ypos[$k] = $this->_setLineYpos($fontsize, $fontdesc, $CSSlineheight, $ypos[-1]); + + if (isset($font[$k]['textparam']['text-baseline']) && $font[$k]['textparam']['text-baseline'] != 0) { + $ypos[$k]['baseline-shift'] = $font[$k]['textparam']['text-baseline']; + } + + // DO ALIGNMENT FOR BASELINES ******************* + // Until most fonts have OpenType BASE tables, this won't work + // $ypos[$k] compared to $ypos[-1] or $ypos[$k-1] using $dominant_baseline and $baseline_table + // UPDATE Maximums + if ($line_stacking_strategy == 'block-line-height' || $line_stacking_strategy == 'grid-height' || $line_stacking_strategy == 'max-height') { // don't include extended block progression of all inline elements + if ($line_stacking_shift == 'disregard-shifts') { + if ($ypos[$k]['boxtop'] > $topy) { + $topy = $ypos[$k]['boxtop']; + } + if ($ypos[$k]['boxbottom'] < $bottomy) { + $bottomy = $ypos[$k]['boxbottom']; + } + } else { + if (($ypos[$k]['boxtop'] + $ypos[$k]['baseline-shift']) > $topy) { + $topy = $ypos[$k]['boxtop'] + $ypos[$k]['baseline-shift']; + } + if (($ypos[$k]['boxbottom'] + $ypos[$k]['baseline-shift']) < $bottomy) { + $bottomy = $ypos[$k]['boxbottom'] + $ypos[$k]['baseline-shift']; + } + } + } else { + if ($line_stacking_shift == 'disregard-shifts') { + if ($ypos[$k]['exttop'] > $topy) { + $topy = $ypos[$k]['exttop']; + } + if ($ypos[$k]['extbottom'] < $bottomy) { + $bottomy = $ypos[$k]['extbottom']; + } + } else { + if (($ypos[$k]['exttop'] + $ypos[$k]['baseline-shift']) > $topy) { + $topy = $ypos[$k]['exttop'] + $ypos[$k]['baseline-shift']; + } + if (($ypos[$k]['extbottom'] + $ypos[$k]['baseline-shift']) < $bottomy) { + $bottomy = $ypos[$k]['extbottom'] + $ypos[$k]['baseline-shift']; + } + } + } + + // If BORDER set on inline element + if (isset($font[$k]['bord']) && $font[$k]['bord']) { + $bordfontsize = $font[$k]['textparam']['bord-decoration']['fontsize'] / $shrin_k; + $bordfontkey = $font[$k]['textparam']['bord-decoration']['fontkey']; + if ($bordfontkey != $fontkey || $bordfontsize != $fontsize || isset($font[$k]['textparam']['bord-decoration']['baseline'])) { + $bordfontdesc = $this->fonts[$bordfontkey]['desc']; + $bordypos[$k] = $this->_setLineYpos($bordfontsize, $bordfontdesc, $CSSlineheight, $ypos[-1]); + if (isset($font[$k]['textparam']['bord-decoration']['baseline']) && $font[$k]['textparam']['bord-decoration']['baseline'] != 0) { + $bordypos[$k]['baseline-shift'] = $font[$k]['textparam']['bord-decoration']['baseline'] / $shrin_k; + } + } + } + // If BACKGROUND set on inline element + if (isset($font[$k]['spanbgcolor']) && $font[$k]['spanbgcolor']) { + $bgfontsize = $font[$k]['textparam']['bg-decoration']['fontsize'] / $shrin_k; + $bgfontkey = $font[$k]['textparam']['bg-decoration']['fontkey']; + if ($bgfontkey != $fontkey || $bgfontsize != $fontsize || isset($font[$k]['textparam']['bg-decoration']['baseline'])) { + $bgfontdesc = $this->fonts[$bgfontkey]['desc']; + $bgypos[$k] = $this->_setLineYpos($bgfontsize, $bgfontdesc, $CSSlineheight, $ypos[-1]); + if (isset($font[$k]['textparam']['bg-decoration']['baseline']) && $font[$k]['textparam']['bg-decoration']['baseline'] != 0) { + $bgypos[$k]['baseline-shift'] = $font[$k]['textparam']['bg-decoration']['baseline'] / $shrin_k; + } + } + } + } + } + + + // TOP or BOTTOM aligned images + if ($mta > ($topy - $bottomy)) { + if (($topy - $mta) < $bottomy) { + $bottomy = $topy - $mta; + } + } + if ($mba > ($topy - $bottomy)) { + if (($bottomy + $mba) > $topy) { + $topy = $bottomy + $mba; + } + } + + if ($line_stacking_strategy == 'block-line-height') { // fixed height set by block element (whether present or not) + $topy = $ypos[-1]['exttop']; + $bottomy = $ypos[-1]['extbottom']; + } + + $inclusiveHeight = $topy - $bottomy; + + // SET $stackHeight taking note of line_stacking_strategy + // NB inclusive height already takes account of need to consider block progression height (excludes leading set by lineheight) + // or extended block progression height (includes leading set by lineheight) + if ($line_stacking_strategy == 'block-line-height') { // fixed = extended block progression height of block element + $stackHeight = $boxLineHeight; + } elseif ($line_stacking_strategy == 'max-height') { // smallest height which includes extended block progression height of block element + // and block progression heights of inline elements (NOT extended) + $stackHeight = $inclusiveHeight; + } elseif ($line_stacking_strategy == 'grid-height') { // smallest multiple of block element lineheight to include + // block progression heights of inline elements (NOT extended) + $stackHeight = $boxLineHeight; + while ($stackHeight < $inclusiveHeight) { + $stackHeight += $boxLineHeight; + } + } else { // 'inline-line-height' = default // smallest height which includes extended block progression height of block element + // AND extended block progression heights of inline elements + $stackHeight = $inclusiveHeight; + } + + $diff = $stackHeight - $inclusiveHeight; + $topy += $diff / 2; + $bottomy -= $diff / 2; + + // ADJUST $ypos => lineBox using $stackHeight; lineBox are all offsets from the top of stackHeight in mm + // and SET IMAGE OFFSETS + $lineBox[-1]['boxtop'] = $topy - $ypos[-1]['boxtop']; + $lineBox[-1]['boxbottom'] = $topy - $ypos[-1]['boxbottom']; + // $lineBox[-1]['exttop'] = $topy - $ypos[-1]['exttop']; + // $lineBox[-1]['extbottom'] = $topy - $ypos[-1]['extbottom']; + $lineBox[-1]['glyphYorigin'] = $topy - $ypos[-1]['glyphYorigin']; + $lineBox[-1]['baseline-shift'] = $ypos[-1]['baseline-shift']; + + $midpoint = $lineBox[-1]['boxbottom'] - (($lineBox[-1]['boxbottom'] - $lineBox[-1]['boxtop']) / 2); + + foreach ($content as $k => $chunk) { + if (isset($this->objectbuffer[$k])) { + $oh = $this->objectbuffer[$k]['OUTER-HEIGHT']; + // LIST MARKERS + if ($this->objectbuffer[$k]['type'] == 'listmarker') { + $oh = $fontsize; + } elseif ($this->objectbuffer[$k]['type'] == 'dottab') { // mPDF 6 DOTTAB + $oh = $font[$k]['size']; // == $this->objectbuffer[$k]['fontsize']/Mpdf::SCALE; + $lineBox[$k]['boxtop'] = $topy - $ypos[$k]['boxtop']; + $lineBox[$k]['boxbottom'] = $topy - $ypos[$k]['boxbottom']; + $lineBox[$k]['glyphYorigin'] = $topy - $ypos[$k]['glyphYorigin']; + $lineBox[$k]['baseline-shift'] = 0; + // continue; + } + $va = $this->objectbuffer[$k]['vertical-align']; // = $objattr['vertical-align'] = set as M,T,B,S + + if ($va == 'BS') { // (BASELINE default) + $lineBox[$k]['top'] = $lineBox[-1]['glyphYorigin'] - $oh; + } elseif ($va == 'M') { + $lineBox[$k]['top'] = $midpoint - $oh / 2; + } elseif ($va == 'TT') { + $lineBox[$k]['top'] = $lineBox[-1]['boxtop']; + } elseif ($va == 'TB') { + $lineBox[$k]['top'] = $lineBox[-1]['boxbottom'] - $oh; + } elseif ($va == 'T') { + $lineBox[$k]['top'] = 0; + } elseif ($va == 'B') { + $lineBox[$k]['top'] = $stackHeight - $oh; + } + } elseif ($content[$k] || $content[$k] === '0') { + $lineBox[$k]['boxtop'] = $topy - $ypos[$k]['boxtop']; + $lineBox[$k]['boxbottom'] = $topy - $ypos[$k]['boxbottom']; + // $lineBox[$k]['exttop'] = $topy - $ypos[$k]['exttop']; + // $lineBox[$k]['extbottom'] = $topy - $ypos[$k]['extbottom']; + $lineBox[$k]['glyphYorigin'] = $topy - $ypos[$k]['glyphYorigin']; + $lineBox[$k]['baseline-shift'] = $ypos[$k]['baseline-shift']; + if (isset($bordypos[$k]['boxtop'])) { + $lineBox[$k]['border-boxtop'] = $topy - $bordypos[$k]['boxtop']; + $lineBox[$k]['border-boxbottom'] = $topy - $bordypos[$k]['boxbottom']; + $lineBox[$k]['border-baseline-shift'] = $bordypos[$k]['baseline-shift']; + } + if (isset($bgypos[$k]['boxtop'])) { + $lineBox[$k]['background-boxtop'] = $topy - $bgypos[$k]['boxtop']; + $lineBox[$k]['background-boxbottom'] = $topy - $bgypos[$k]['boxbottom']; + $lineBox[$k]['background-baseline-shift'] = $bgypos[$k]['baseline-shift']; + } + } + } + } + + function SetBasePath($str = '') + { + if (isset($_SERVER['HTTP_HOST'])) { + $host = $_SERVER['HTTP_HOST']; + } elseif (isset($_SERVER['SERVER_NAME'])) { + $host = $_SERVER['SERVER_NAME']; + } else { + $host = ''; + } + if (!$str) { + if (isset($_SERVER['SCRIPT_NAME'])) { + $currentPath = dirname($_SERVER['SCRIPT_NAME']); + } else { + $currentPath = dirname($_SERVER['PHP_SELF']); + } + $currentPath = str_replace("\\", "/", $currentPath); + if ($currentPath == '/') { + $currentPath = ''; + } + if ($host) { // mPDF 6 + if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] && $_SERVER['HTTPS'] !== 'off') { + $currpath = 'https://' . $host . $currentPath . '/'; + } else { + $currpath = 'http://' . $host . $currentPath . '/'; + } + } else { + $currpath = ''; + } + $this->basepath = $currpath; + $this->basepathIsLocal = true; + return; + } + $str = preg_replace('/\?.*/', '', $str); + if (!preg_match('/(http|https|ftp):\/\/.*\//i', $str)) { + $str .= '/'; + } + $str .= 'xxx'; // in case $str ends in / e.g. http://www.bbc.co.uk/ + $this->basepath = dirname($str) . "/"; // returns e.g. e.g. http://www.google.com/dir1/dir2/dir3/ + $this->basepath = str_replace("\\", "/", $this->basepath); // If on Windows + $tr = parse_url($this->basepath); + if (isset($tr['host']) && ($tr['host'] == $host)) { + $this->basepathIsLocal = true; + } else { + $this->basepathIsLocal = false; + } + } + + public function GetFullPath(&$path, $basepath = '') + { + // When parsing CSS need to pass temporary basepath - so links are relative to current stylesheet + if (!$basepath) { + $basepath = $this->basepath; + } + + // Fix path value + $path = str_replace("\\", '/', $path); // If on Windows + + // mPDF 5.7.2 + if (substr($path, 0, 2) === '//') { + $scheme = parse_url($basepath, PHP_URL_SCHEME); + $scheme = $scheme ?: 'http'; + $path = $scheme . ':' . $path; + } + + $path = preg_replace('|^./|', '', $path); // Inadvertently corrects "./path/etc" and "//www.domain.com/etc" + + if (substr($path, 0, 1) == '#') { + return; + } + + if (preg_match('@^(mailto|tel|fax):.*@i', $path)) { + return; + } + + if (substr($path, 0, 3) == "../") { // It is a relative link + + $backtrackamount = substr_count($path, "../"); + $maxbacktrack = substr_count($basepath, "/") - 3; + $filepath = str_replace("../", '', $path); + $path = $basepath; + + // If it is an invalid relative link, then make it go to directory root + if ($backtrackamount > $maxbacktrack) { + $backtrackamount = $maxbacktrack; + } + + // Backtrack some directories + for ($i = 0; $i < $backtrackamount + 1; $i++) { + $path = substr($path, 0, strrpos($path, "/")); + } + + $path = $path . "/" . $filepath; // Make it an absolute path + + } elseif ((strpos($path, ":/") === false || strpos($path, ":/") > 10) && !is_file($path)) { // It is a local link + + if (substr($path, 0, 1) == "/") { + + $tr = parse_url($basepath); + + // mPDF 5.7.2 + $root = ''; + if (!empty($tr['scheme'])) { + $root .= $tr['scheme'] . '://'; + } + + $root .= isset($tr['host']) ? $tr['host'] : ''; + $root .= ((isset($tr['port']) && $tr['port']) ? (':' . $tr['port']) : ''); // mPDF 5.7.3 + + $path = $root . $path; + + } else { + $path = $basepath . $path; + } + } + // Do nothing if it is an Absolute Link + } + + function docPageNum($num = 0, $extras = false) + { + if ($num < 1) { + $num = $this->page; + } + + $type = $this->defaultPageNumStyle; // set default Page Number Style + $ppgno = $num; + $suppress = 0; + $offset = 0; + $lastreset = 0; + + foreach ($this->PageNumSubstitutions as $psarr) { + + if ($num >= $psarr['from']) { + + if ($psarr['reset']) { + if ($psarr['reset'] > 1) { + $offset = $psarr['reset'] - 1; + } + $ppgno = $num - $psarr['from'] + 1 + $offset; + $lastreset = $psarr['from']; + } + + if ($psarr['type']) { + $type = $psarr['type']; + } + + if (strtoupper($psarr['suppress']) == 'ON' || $psarr['suppress'] == 1) { + $suppress = 1; + } elseif (strtoupper($psarr['suppress']) == 'OFF') { + $suppress = 0; + } + } + } + + if ($suppress) { + return ''; + } + + $ppgno = $this->_getStyledNumber($ppgno, $type); + + if ($extras) { + $ppgno = $this->pagenumPrefix . $ppgno . $this->pagenumSuffix; + } + + return $ppgno; + } + + function docPageNumTotal($num = 0, $extras = false) + { + if ($num < 1) { + $num = $this->page; + } + + $type = $this->defaultPageNumStyle; // set default Page Number Style + $ppgstart = 1; + $ppgend = count($this->pages) + 1; + $suppress = 0; + $offset = 0; + + foreach ($this->PageNumSubstitutions as $psarr) { + if ($num >= $psarr['from']) { + if ($psarr['reset']) { + if ($psarr['reset'] > 1) { + $offset = $psarr['reset'] - 1; + } + $ppgstart = $psarr['from'] + $offset; + $ppgend = count($this->pages) + 1 + $offset; + } + if ($psarr['type']) { + $type = $psarr['type']; + } + if (strtoupper($psarr['suppress']) == 'ON' || $psarr['suppress'] == 1) { + $suppress = 1; + } elseif (strtoupper($psarr['suppress']) == 'OFF') { + $suppress = 0; + } + } + if ($num < $psarr['from']) { + if ($psarr['reset']) { + $ppgend = $psarr['from'] + $offset; + break; + } + } + } + + if ($suppress) { + return ''; + } + + $ppgno = $ppgend - $ppgstart + $offset; + $ppgno = $this->_getStyledNumber($ppgno, $type); + + if ($extras) { + $ppgno = $this->pagenumPrefix . $ppgno . $this->pagenumSuffix; + } + + return $ppgno; + } + + // mPDF 6 + function _getStyledNumber($ppgno, $type, $listmarker = false) + { + if ($listmarker) { + $reverse = true; // Reverse RTL numerals (Hebrew) when using for list + $checkfont = true; // Using list - font is set, so check if character is available + } else { + $reverse = false; // For pagenumbers, RTL numerals (Hebrew) will get reversed later by bidi + $checkfont = false; // For pagenumbers - font is not set, so no check + } + + $decToAlpha = new Conversion\DecToAlpha(); + $decToCjk = new Conversion\DecToCjk(); + $decToHebrew = new Conversion\DecToHebrew(); + $decToRoman = new Conversion\DecToRoman(); + $decToOther = new Conversion\DecToOther($this); + + $lowertype = strtolower($type); + + if ($lowertype == 'upper-latin' || $lowertype == 'upper-alpha' || $type == 'A') { + + $ppgno = $decToAlpha->convert($ppgno, true); + + } elseif ($lowertype == 'lower-latin' || $lowertype == 'lower-alpha' || $type == 'a') { + + $ppgno = $decToAlpha->convert($ppgno, false); + + } elseif ($lowertype == 'upper-roman' || $type == 'I') { + + $ppgno = $decToRoman->convert($ppgno, true); + + } elseif ($lowertype == 'lower-roman' || $type == 'i') { + + $ppgno = $decToRoman->convert($ppgno, false); + + } elseif ($lowertype == 'hebrew') { + + $ppgno = $decToHebrew->convert($ppgno, $reverse); + + } elseif (preg_match('/(arabic-indic|bengali|devanagari|gujarati|gurmukhi|kannada|malayalam|oriya|persian|tamil|telugu|thai|urdu|cambodian|khmer|lao)/i', $lowertype, $m)) { + + $cp = $decToOther->getCodePage($m[1]); + $ppgno = $decToOther->convert($ppgno, $cp, $checkfont); + + } elseif ($lowertype == 'cjk-decimal') { + + $ppgno = $decToCjk->convert($ppgno); + + } + + return $ppgno; + } + + function docPageSettings($num = 0) + { + // Returns current type (numberstyle), suppression state for this page number; + // reset is only returned if set for this page number + if ($num < 1) { + $num = $this->page; + } + + $type = $this->defaultPageNumStyle; // set default Page Number Style + $ppgno = $num; + $suppress = 0; + $offset = 0; + $reset = ''; + + foreach ($this->PageNumSubstitutions as $psarr) { + if ($num >= $psarr['from']) { + if ($psarr['reset']) { + if ($psarr['reset'] > 1) { + $offset = $psarr['reset'] - 1; + } + $ppgno = $num - $psarr['from'] + 1 + $offset; + } + if ($psarr['type']) { + $type = $psarr['type']; + } + if (strtoupper($psarr['suppress']) == 'ON' || $psarr['suppress'] == 1) { + $suppress = 1; + } elseif (strtoupper($psarr['suppress']) == 'OFF') { + $suppress = 0; + } + } + if ($num == $psarr['from']) { + $reset = $psarr['reset']; + } + } + + if ($suppress) { + $suppress = 'on'; + } else { + $suppress = 'off'; + } + + return [$type, $suppress, $reset]; + } + + function RestartDocTemplate() + { + $this->docTemplateStart = $this->page; + } + + // Page header + function Header($content = '') + { + + $this->cMarginL = 0; + $this->cMarginR = 0; + + + if (($this->mirrorMargins && ($this->page % 2 == 0) && $this->HTMLHeaderE) || ($this->mirrorMargins && ($this->page % 2 == 1) && $this->HTMLHeader) || (!$this->mirrorMargins && $this->HTMLHeader)) { + $this->writeHTMLHeaders(); + return; + } + } + + /* -- TABLES -- */ + function TableHeaderFooter($content = '', $tablestartpage = '', $tablestartcolumn = '', $horf = 'H', $level = 0, $firstSpread = true, $finalSpread = true) + { + if (($horf == 'H' || $horf == 'F') && !empty($content)) { // mPDF 5.7.2 + $table = &$this->table[1][1]; + + // mPDF 5.7.2 + if ($horf == 'F') { // Table Footer + $firstrow = count($table['cells']) - $table['footernrows']; + $lastrow = count($table['cells']) - 1; + } else { // Table Header + $firstrow = 0; + $lastrow = $table['headernrows'] - 1; + } + if (empty($content[$firstrow])) { + if ($this->debug) { + throw new \Mpdf\MpdfException(" must precede in a table"); + } else { + return; + } + } + + + // Advance down page by half width of top border + if ($horf == 'H') { // Only if header + if ($table['borders_separate']) { + $adv = $table['border_spacing_V'] / 2 + $table['border_details']['T']['w'] + $table['padding']['T']; + } else { + $adv = $table['max_cell_border_width']['T'] / 2; + } + if ($adv) { + if ($this->table_rotate) { + $this->y += ($adv); + } else { + $this->DivLn($adv, $this->blklvl, true); + } + } + } + + $topy = $content[$firstrow][0]['y'] - $this->y; + + for ($i = $firstrow; $i <= $lastrow; $i++) { + $y = $this->y; + + /* -- COLUMNS -- */ + // If outside columns, this is done in PaintDivBB + if ($this->ColActive) { + // OUTER FILL BGCOLOR of DIVS + if ($this->blklvl > 0) { + $firstblockfill = $this->GetFirstBlockFill(); + if ($firstblockfill && $this->blklvl >= $firstblockfill) { + $divh = $content[$i][0]['h']; + $bak_x = $this->x; + $this->DivLn($divh, -3, false); + // Reset current block fill + $bcor = $this->blk[$this->blklvl]['bgcolorarray']; + $this->SetFColor($bcor); + $this->x = $bak_x; + } + } + } + /* -- END COLUMNS -- */ + + $colctr = 0; + foreach ($content[$i] as $tablehf) { + $colctr++; + $y = Arrays::get($tablehf, 'y', null) - $topy; + $this->y = $y; + // Set some cell values + $x = Arrays::get($tablehf, 'x', null); + if (($this->mirrorMargins) && ($tablestartpage == 'ODD') && (($this->page) % 2 == 0)) { // EVEN + $x = $x + $this->MarginCorrection; + } elseif (($this->mirrorMargins) && ($tablestartpage == 'EVEN') && (($this->page) % 2 == 1)) { // ODD + $x = $x + $this->MarginCorrection; + } + /* -- COLUMNS -- */ + // Added to correct for Columns + if ($this->ColActive) { + if ($this->directionality == 'rtl') { // *OTL* + $x -= ($this->CurrCol - $tablestartcolumn) * ($this->ColWidth + $this->ColGap); // *OTL* + } // *OTL* + else { // *OTL* + $x += ($this->CurrCol - $tablestartcolumn) * ($this->ColWidth + $this->ColGap); + } // *OTL* + } + /* -- END COLUMNS -- */ + + if ($colctr == 1) { + $x0 = $x; + } + + // mPDF ITERATION + if ($this->iterationCounter) { + foreach ($tablehf['textbuffer'] as $k => $t) { + if (!is_array($t[0]) && preg_match('/{iteration ([a-zA-Z0-9_]+)}/', $t[0], $m)) { + $vname = '__' . $m[1] . '_'; + if (!isset($this->$vname)) { + $this->$vname = 1; + } else { + $this->$vname++; + } + $tablehf['textbuffer'][$k][0] = preg_replace('/{iteration ' . $m[1] . '}/', $this->$vname, $tablehf['textbuffer'][$k][0]); + } + } + } + + $w = Arrays::get($tablehf, 'w', null); + $h = Arrays::get($tablehf, 'h', null); + $va = Arrays::get($tablehf, 'va', null); + $R = Arrays::get($tablehf, 'R', null); + $direction = Arrays::get($tablehf, 'direction', null); + $mih = Arrays::get($tablehf, 'mih', null); + $border = Arrays::get($tablehf, 'border', null); + $border_details = Arrays::get($tablehf, 'border_details', null); + $padding = Arrays::get($tablehf, 'padding', null); + $this->tabletheadjustfinished = true; + + $textbuffer = Arrays::get($tablehf, 'textbuffer', null); + + // Align + $align = Arrays::get($tablehf, 'a', null); + $this->cellTextAlign = $align; + + $this->cellLineHeight = Arrays::get($tablehf, 'cellLineHeight', null); + $this->cellLineStackingStrategy = Arrays::get($tablehf, 'cellLineStackingStrategy', null); + $this->cellLineStackingShift = Arrays::get($tablehf, 'cellLineStackingShift', null); + + $this->x = $x; + + if ($this->ColActive) { + if ($table['borders_separate']) { + $tablefill = isset($table['bgcolor'][-1]) ? $table['bgcolor'][-1] : 0; + if ($tablefill) { + $color = $this->colorConverter->convert($tablefill, $this->PDFAXwarnings); + if ($color) { + $xadj = ($table['border_spacing_H'] / 2); + $yadj = ($table['border_spacing_V'] / 2); + $wadj = $table['border_spacing_H']; + $hadj = $table['border_spacing_V']; + if ($i == $firstrow && $horf == 'H') { // Top + $yadj += $table['padding']['T'] + $table['border_details']['T']['w']; + $hadj += $table['padding']['T'] + $table['border_details']['T']['w']; + } + if (($i == ($lastrow) || (isset($tablehf['rowspan']) && ($i + $tablehf['rowspan']) == ($lastrow + 1)) || (!isset($tablehf['rowspan']) && ($i + 1) == ($lastrow + 1))) && $horf == 'F') { // Bottom + $hadj += $table['padding']['B'] + $table['border_details']['B']['w']; + } + if ($colctr == 1) { // Left + $xadj += $table['padding']['L'] + $table['border_details']['L']['w']; + $wadj += $table['padding']['L'] + $table['border_details']['L']['w']; + } + if ($colctr == count($content[$i])) { // Right + $wadj += $table['padding']['R'] + $table['border_details']['R']['w']; + } + $this->SetFColor($color); + $this->Rect($x - $xadj, $y - $yadj, $w + $wadj, $h + $hadj, 'F'); + } + } + } + } + + if ($table['empty_cells'] != 'hide' || !empty($textbuffer) || !$table['borders_separate']) { + $paintcell = true; + } else { + $paintcell = false; + } + + // Vertical align + if ($R && intval($R) > 0 && isset($va) && $va != 'B') { + $va = 'B'; + } + + if (!isset($va) || empty($va) || $va == 'M') { + $this->y += ($h - $mih) / 2; + } elseif (isset($va) && $va == 'B') { + $this->y += $h - $mih; + } + + + // TABLE ROW OR CELL FILL BGCOLOR + $fill = 0; + if (isset($tablehf['bgcolor']) && $tablehf['bgcolor'] && $tablehf['bgcolor'] != 'transparent') { + $fill = $tablehf['bgcolor']; + $leveladj = 6; + } elseif (isset($content[$i][0]['trbgcolor']) && $content[$i][0]['trbgcolor'] && $content[$i][0]['trbgcolor'] != 'transparent') { // Row color + $fill = $content[$i][0]['trbgcolor']; + $leveladj = 3; + } + if ($fill && $paintcell) { + $color = $this->colorConverter->convert($fill, $this->PDFAXwarnings); + if ($color) { + if ($table['borders_separate']) { + if ($this->ColActive) { + $this->SetFColor($color); + $this->Rect($x + ($table['border_spacing_H'] / 2), $y + ($table['border_spacing_V'] / 2), $w - $table['border_spacing_H'], $h - $table['border_spacing_V'], 'F'); + } else { + $this->tableBackgrounds[$level * 9 + $leveladj][] = ['gradient' => false, 'x' => ($x + ($table['border_spacing_H'] / 2)), 'y' => ($y + ($table['border_spacing_V'] / 2)), 'w' => ($w - $table['border_spacing_H']), 'h' => ($h - $table['border_spacing_V']), 'col' => $color]; + } + } else { + if ($this->ColActive) { + $this->SetFColor($color); + $this->Rect($x, $y, $w, $h, 'F'); + } else { + $this->tableBackgrounds[$level * 9 + $leveladj][] = ['gradient' => false, 'x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'col' => $color]; + } + } + } + } + + + /* -- BACKGROUNDS -- */ + if (isset($tablehf['gradient']) && $tablehf['gradient'] && $paintcell) { + $g = $this->gradient->parseBackgroundGradient($tablehf['gradient']); + if ($g) { + if ($table['borders_separate']) { + $px = $x + ($table['border_spacing_H'] / 2); + $py = $y + ($table['border_spacing_V'] / 2); + $pw = $w - $table['border_spacing_H']; + $ph = $h - $table['border_spacing_V']; + } else { + $px = $x; + $py = $y; + $pw = $w; + $ph = $h; + } + if ($this->ColActive) { + $this->gradient->Gradient($px, $py, $pw, $ph, $g['type'], $g['stops'], $g['colorspace'], $g['coords'], $g['extend']); + } else { + $this->tableBackgrounds[$level * 9 + 7][] = ['gradient' => true, 'x' => $px, 'y' => $py, 'w' => $pw, 'h' => $ph, 'gradtype' => $g['type'], 'stops' => $g['stops'], 'colorspace' => $g['colorspace'], 'coords' => $g['coords'], 'extend' => $g['extend'], 'clippath' => '']; + } + } + } + + if (isset($tablehf['background-image']) && $paintcell) { + if ($tablehf['background-image']['gradient'] && preg_match('/(-moz-)*(repeating-)*(linear|radial)-gradient/', $tablehf['background-image']['gradient'])) { + $g = $this->gradient->parseMozGradient($tablehf['background-image']['gradient']); + if ($g) { + if ($table['borders_separate']) { + $px = $x + ($table['border_spacing_H'] / 2); + $py = $y + ($table['border_spacing_V'] / 2); + $pw = $w - $table['border_spacing_H']; + $ph = $h - $table['border_spacing_V']; + } else { + $px = $x; + $py = $y; + $pw = $w; + $ph = $h; + } + if ($this->ColActive) { + $this->gradient->Gradient($px, $py, $pw, $ph, $g['type'], $g['stops'], $g['colorspace'], $g['coords'], $g['extend']); + } else { + $this->tableBackgrounds[$level * 9 + 7][] = ['gradient' => true, 'x' => $px, 'y' => $py, 'w' => $pw, 'h' => $ph, 'gradtype' => $g['type'], 'stops' => $g['stops'], 'colorspace' => $g['colorspace'], 'coords' => $g['coords'], 'extend' => $g['extend'], 'clippath' => '']; + } + } + } elseif ($tablehf['background-image']['image_id']) { // Background pattern + $n = count($this->patterns) + 1; + if ($table['borders_separate']) { + $px = $x + ($table['border_spacing_H'] / 2); + $py = $y + ($table['border_spacing_V'] / 2); + $pw = $w - $table['border_spacing_H']; + $ph = $h - $table['border_spacing_V']; + } else { + $px = $x; + $py = $y; + $pw = $w; + $ph = $h; + } + if ($this->ColActive) { + list($orig_w, $orig_h, $x_repeat, $y_repeat) = $this->_resizeBackgroundImage($tablehf['background-image']['orig_w'], $tablehf['background-image']['orig_h'], $pw, $ph, $tablehf['background-image']['resize'], $tablehf['background-image']['x_repeat'], $tablehf['background-image']['y_repeat']); + $this->patterns[$n] = ['x' => $px, 'y' => $py, 'w' => $pw, 'h' => $ph, 'pgh' => $this->h, 'image_id' => $tablehf['background-image']['image_id'], 'orig_w' => $orig_w, 'orig_h' => $orig_h, 'x_pos' => $tablehf['background-image']['x_pos'], 'y_pos' => $tablehf['background-image']['y_pos'], 'x_repeat' => $x_repeat, 'y_repeat' => $y_repeat, 'itype' => $tablehf['background-image']['itype']]; + if ($tablehf['background-image']['opacity'] > 0 && $tablehf['background-image']['opacity'] < 1) { + $opac = $this->SetAlpha($tablehf['background-image']['opacity'], 'Normal', true); + } else { + $opac = ''; + } + $this->writer->write(sprintf('q /Pattern cs /P%d scn %s %.3F %.3F %.3F %.3F re f Q', $n, $opac, $px * Mpdf::SCALE, ($this->h - $py) * Mpdf::SCALE, $pw * Mpdf::SCALE, -$ph * Mpdf::SCALE)); + } else { + $this->tableBackgrounds[$level * 9 + 8][] = ['x' => $px, 'y' => $py, 'w' => $pw, 'h' => $ph, 'image_id' => $tablehf['background-image']['image_id'], 'orig_w' => $tablehf['background-image']['orig_w'], 'orig_h' => $tablehf['background-image']['orig_h'], 'x_pos' => $tablehf['background-image']['x_pos'], 'y_pos' => $tablehf['background-image']['y_pos'], 'x_repeat' => $tablehf['background-image']['x_repeat'], 'y_repeat' => $tablehf['background-image']['y_repeat'], 'clippath' => '', 'resize' => $tablehf['background-image']['resize'], 'opacity' => $tablehf['background-image']['opacity'], 'itype' => $tablehf['background-image']['itype']]; + } + } + } + /* -- END BACKGROUNDS -- */ + + // Cell Border + if ($table['borders_separate'] && $paintcell && $border) { + $this->_tableRect($x + ($table['border_spacing_H'] / 2) + ($border_details['L']['w'] / 2), $y + ($table['border_spacing_V'] / 2) + ($border_details['T']['w'] / 2), $w - $table['border_spacing_H'] - ($border_details['L']['w'] / 2) - ($border_details['R']['w'] / 2), $h - $table['border_spacing_V'] - ($border_details['T']['w'] / 2) - ($border_details['B']['w'] / 2), $border, $border_details, false, $table['borders_separate']); + } elseif ($paintcell && $border) { + $this->_tableRect($x, $y, $w, $h, $border, $border_details, true, $table['borders_separate']); // true causes buffer + } + + // Print cell content + if (!empty($textbuffer)) { + if ($horf == 'F' && preg_match('/{colsum([0-9]*)[_]*}/', $textbuffer[0][0], $m)) { + $rep = sprintf("%01." . intval($m[1]) . "f", $this->colsums[$colctr - 1]); + $textbuffer[0][0] = preg_replace('/{colsum[0-9_]*}/', $rep, $textbuffer[0][0]); + } + + if ($R) { + $cellPtSize = $textbuffer[0][11] / $this->shrin_k; + if (!$cellPtSize) { + $cellPtSize = $this->default_font_size; + } + $cellFontHeight = ($cellPtSize / Mpdf::SCALE); + $opx = $this->x; + $opy = $this->y; + $angle = intval($R); + + // Only allow 45 - 90 degrees (when bottom-aligned) or -90 + if ($angle > 90) { + $angle = 90; + } elseif ($angle > 0 && (isset($va) && $va != 'B')) { + $angle = 90; + } elseif ($angle > 0 && $angle < 45) { + $angle = 45; + } elseif ($angle < 0) { + $angle = -90; + } + + $offset = ((sin(deg2rad($angle))) * 0.37 * $cellFontHeight); + if (isset($align) && $align == 'R') { + $this->x += ($w) + ($offset) - ($cellFontHeight / 3) - ($padding['R'] + $border_details['R']['w']); + } elseif (!isset($align) || $align == 'C') { + $this->x += ($w / 2) + ($offset); + } else { + $this->x += ($offset) + ($cellFontHeight / 3) + ($padding['L'] + $border_details['L']['w']); + } + $str = ''; + foreach ($tablehf['textbuffer'] as $t) { + $str .= $t[0] . ' '; + } + $str = rtrim($str); + + if (!isset($va) || $va == 'M') { + $this->y -= ($h - $mih) / 2; // Undo what was added earlier VERTICAL ALIGN + if ($angle > 0) { + $this->y += (($h - $mih) / 2) + ($padding['T'] + $border_details['T']['w']) + ($mih - ($padding['T'] + $border_details['T']['w'] + $border_details['B']['w'] + $padding['B'])); + } elseif ($angle < 0) { + $this->y += (($h - $mih) / 2) + ($padding['T'] + $border_details['T']['w']); + } + } elseif (isset($va) && $va == 'B') { + $this->y -= $h - $mih; // Undo what was added earlier VERTICAL ALIGN + if ($angle > 0) { + $this->y += $h - ($border_details['B']['w'] + $padding['B']); + } elseif ($angle < 0) { + $this->y += $h - $mih + ($padding['T'] + $border_details['T']['w']); + } + } elseif (isset($va) && $va == 'T') { + if ($angle > 0) { + $this->y += $mih - ($border_details['B']['w'] + $padding['B']); + } elseif ($angle < 0) { + $this->y += ($padding['T'] + $border_details['T']['w']); + } + } + + $this->Rotate($angle, $this->x, $this->y); + $s_fs = $this->FontSizePt; + $s_f = $this->FontFamily; + $s_st = $this->FontStyle; + if (!empty($textbuffer[0][3])) { // Font Color + $cor = $textbuffer[0][3]; + $this->SetTColor($cor); + } + $this->SetFont($textbuffer[0][4], $textbuffer[0][2], $cellPtSize, true, true); + + $this->magic_reverse_dir($str, $this->directionality, $textbuffer[0][18]); + $this->Text($this->x, $this->y, $str, $textbuffer[0][18], $textbuffer[0][8]); // textvar + $this->Rotate(0); + $this->SetFont($s_f, $s_st, $s_fs, true, true); + $this->SetTColor(0); + $this->x = $opx; + $this->y = $opy; + } else { + if ($table['borders_separate']) { // NB twice border width + $xadj = $border_details['L']['w'] + $padding['L'] + ($table['border_spacing_H'] / 2); + $wadj = $border_details['L']['w'] + $border_details['R']['w'] + $padding['L'] + $padding['R'] + $table['border_spacing_H']; + $yadj = $border_details['T']['w'] + $padding['T'] + ($table['border_spacing_H'] / 2); + } else { + $xadj = $border_details['L']['w'] / 2 + $padding['L']; + $wadj = ($border_details['L']['w'] + $border_details['R']['w']) / 2 + $padding['L'] + $padding['R']; + $yadj = $border_details['T']['w'] / 2 + $padding['T']; + } + + $this->divwidth = $w - ($wadj); + $this->x += $xadj; + $this->y += $yadj; + $this->printbuffer($textbuffer, '', true, false, $direction); + } + } + $textbuffer = []; + + /* -- BACKGROUNDS -- */ + if (!$this->ColActive) { + if (isset($content[$i][0]['trgradients']) && ($colctr == 1 || $table['borders_separate'])) { + $g = $this->gradient->parseBackgroundGradient($content[$i][0]['trgradients']); + if ($g) { + $gx = $x0; + $gy = $y; + $gh = $h; + $gw = $table['w'] - ($table['max_cell_border_width']['L'] / 2) - ($table['max_cell_border_width']['R'] / 2) - $table['margin']['L'] - $table['margin']['R']; + if ($table['borders_separate']) { + $gw -= ($table['padding']['L'] + $table['border_details']['L']['w'] + $table['padding']['R'] + $table['border_details']['R']['w'] + $table['border_spacing_H']); + $clx = $x + ($table['border_spacing_H'] / 2); + $cly = $y + ($table['border_spacing_V'] / 2); + $clw = $w - $table['border_spacing_H']; + $clh = $h - $table['border_spacing_V']; + // Set clipping path + $s = $this->_setClippingPath($clx, $cly, $clw, $clh); // mPDF 6 + $this->tableBackgrounds[$level * 9 + 4][] = ['gradient' => true, 'x' => $gx + ($table['border_spacing_H'] / 2), 'y' => $gy + ($table['border_spacing_V'] / 2), 'w' => $gw - $table['border_spacing_V'], 'h' => $gh - $table['border_spacing_H'], 'gradtype' => $g['type'], 'stops' => $g['stops'], 'colorspace' => $g['colorspace'], 'coords' => $g['coords'], 'extend' => $g['extend'], 'clippath' => $s]; + } else { + $this->tableBackgrounds[$level * 9 + 4][] = ['gradient' => true, 'x' => $gx, 'y' => $gy, 'w' => $gw, 'h' => $gh, 'gradtype' => $g['type'], 'stops' => $g['stops'], 'colorspace' => $g['colorspace'], 'coords' => $g['coords'], 'extend' => $g['extend'], 'clippath' => '']; + } + } + } + + if (isset($content[$i][0]['trbackground-images']) && ($colctr == 1 || $table['borders_separate'])) { + if ($content[$i][0]['trbackground-images']['gradient'] && preg_match('/(-moz-)*(repeating-)*(linear|radial)-gradient/', $content[$i][0]['trbackground-images']['gradient'])) { + $g = $this->gradient->parseMozGradient($content[$i][0]['trbackground-images']['gradient']); + if ($g) { + $gx = $x0; + $gy = $y; + $gh = $h; + $gw = $table['w'] - ($table['max_cell_border_width']['L'] / 2) - ($table['max_cell_border_width']['R'] / 2) - $table['margin']['L'] - $table['margin']['R']; + if ($table['borders_separate']) { + $gw -= ($table['padding']['L'] + $table['border_details']['L']['w'] + $table['padding']['R'] + $table['border_details']['R']['w'] + $table['border_spacing_H']); + $clx = $x + ($table['border_spacing_H'] / 2); + $cly = $y + ($table['border_spacing_V'] / 2); + $clw = $w - $table['border_spacing_H']; + $clh = $h - $table['border_spacing_V']; + // Set clipping path + $s = $this->_setClippingPath($clx, $cly, $clw, $clh); // mPDF 6 + $this->tableBackgrounds[$level * 9 + 4][] = ['gradient' => true, 'x' => $gx + ($table['border_spacing_H'] / 2), 'y' => $gy + ($table['border_spacing_V'] / 2), 'w' => $gw - $table['border_spacing_V'], 'h' => $gh - $table['border_spacing_H'], 'gradtype' => $g['type'], 'stops' => $g['stops'], 'colorspace' => $g['colorspace'], 'coords' => $g['coords'], 'extend' => $g['extend'], 'clippath' => $s]; + } else { + $this->tableBackgrounds[$level * 9 + 4][] = ['gradient' => true, 'x' => $gx, 'y' => $gy, 'w' => $gw, 'h' => $gh, 'gradtype' => $g['type'], 'stops' => $g['stops'], 'colorspace' => $g['colorspace'], 'coords' => $g['coords'], 'extend' => $g['extend'], 'clippath' => '']; + } + } + } else { + $image_id = $content[$i][0]['trbackground-images']['image_id']; + $orig_w = $content[$i][0]['trbackground-images']['orig_w']; + $orig_h = $content[$i][0]['trbackground-images']['orig_h']; + $x_pos = $content[$i][0]['trbackground-images']['x_pos']; + $y_pos = $content[$i][0]['trbackground-images']['y_pos']; + $x_repeat = $content[$i][0]['trbackground-images']['x_repeat']; + $y_repeat = $content[$i][0]['trbackground-images']['y_repeat']; + $resize = $content[$i][0]['trbackground-images']['resize']; + $opacity = $content[$i][0]['trbackground-images']['opacity']; + $itype = $content[$i][0]['trbackground-images']['itype']; + + $clippath = ''; + $gx = $x0; + $gy = $y; + $gh = $h; + $gw = $table['w'] - ($table['max_cell_border_width']['L'] / 2) - ($table['max_cell_border_width']['R'] / 2) - $table['margin']['L'] - $table['margin']['R']; + if ($table['borders_separate']) { + $gw -= ($table['padding']['L'] + $table['border_details']['L']['w'] + $table['padding']['R'] + $table['border_details']['R']['w'] + $table['border_spacing_H']); + $clx = $x + ($table['border_spacing_H'] / 2); + $cly = $y + ($table['border_spacing_V'] / 2); + $clw = $w - $table['border_spacing_H']; + $clh = $h - $table['border_spacing_V']; + // Set clipping path + $s = $this->_setClippingPath($clx, $cly, $clw, $clh); // mPDF 6 + $this->tableBackgrounds[$level * 9 + 5][] = ['x' => $gx + ($table['border_spacing_H'] / 2), 'y' => $gy + ($table['border_spacing_V'] / 2), 'w' => $gw - $table['border_spacing_V'], 'h' => $gh - $table['border_spacing_H'], 'image_id' => $image_id, 'orig_w' => $orig_w, 'orig_h' => $orig_h, 'x_pos' => $x_pos, 'y_pos' => $y_pos, 'x_repeat' => $x_repeat, 'y_repeat' => $y_repeat, 'clippath' => $s, 'resize' => $resize, 'opacity' => $opacity, 'itype' => $itype]; + } else { + $this->tableBackgrounds[$level * 9 + 5][] = ['x' => $gx, 'y' => $gy, 'w' => $gw, 'h' => $gh, 'image_id' => $image_id, 'orig_w' => $orig_w, 'orig_h' => $orig_h, 'x_pos' => $x_pos, 'y_pos' => $y_pos, 'x_repeat' => $x_repeat, 'y_repeat' => $y_repeat, 'clippath' => '', 'resize' => $resize, 'opacity' => $opacity, 'itype' => $itype]; + } + } + } + } + /* -- END BACKGROUNDS -- */ + + // TABLE BORDER - if separate OR collapsed and only table border + if (($table['borders_separate'] || ($this->simpleTables && !$table['simple']['border'])) && $table['border']) { + $halfspaceL = $table['padding']['L'] + ($table['border_spacing_H'] / 2); + $halfspaceR = $table['padding']['R'] + ($table['border_spacing_H'] / 2); + $halfspaceT = $table['padding']['T'] + ($table['border_spacing_V'] / 2); + $halfspaceB = $table['padding']['B'] + ($table['border_spacing_V'] / 2); + $tbx = $x; + $tby = $y; + $tbw = $w; + $tbh = $h; + $tab_bord = 0; + $corner = ''; + if ($i == $firstrow && $horf == 'H') { // Top + $tby -= $halfspaceT + ($table['border_details']['T']['w'] / 2); + $tbh += $halfspaceT + ($table['border_details']['T']['w'] / 2); + $this->setBorder($tab_bord, Border::TOP); + $corner .= 'T'; + } + if (($i == ($lastrow) || (isset($tablehf['rowspan']) && ($i + $tablehf['rowspan']) == ($lastrow + 1))) && $horf == 'F') { // Bottom + $tbh += $halfspaceB + ($table['border_details']['B']['w'] / 2); + $this->setBorder($tab_bord, Border::BOTTOM); + $corner .= 'B'; + } + if ($colctr == 1 && $firstSpread) { // Left + $tbx -= $halfspaceL + ($table['border_details']['L']['w'] / 2); + $tbw += $halfspaceL + ($table['border_details']['L']['w'] / 2); + $this->setBorder($tab_bord, Border::LEFT); + $corner .= 'L'; + } + if ($colctr == count($content[$i]) && $finalSpread) { // Right + $tbw += $halfspaceR + ($table['border_details']['R']['w'] / 2); + $this->setBorder($tab_bord, Border::RIGHT); + $corner .= 'R'; + } + $this->_tableRect($tbx, $tby, $tbw, $tbh, $tab_bord, $table['border_details'], false, $table['borders_separate'], 'table', $corner, $table['border_spacing_V'], $table['border_spacing_H']); + } + }// end column $content + $this->y = $y + $h; // Update y coordinate + }// end row $i + unset($table); + $this->colsums = []; + } + } + + /* -- END TABLES -- */ + + function SetHTMLHeader($header = '', $OE = '', $write = false) + { + + $height = 0; + if (is_array($header) && isset($header['html']) && $header['html']) { + $Hhtml = $header['html']; + if ($this->setAutoTopMargin) { + if (isset($header['h'])) { + $height = $header['h']; + } else { + $height = $this->_getHtmlHeight($Hhtml); + } + } + } elseif (!is_array($header) && $header) { + $Hhtml = $header; + if ($this->setAutoTopMargin) { + $height = $this->_getHtmlHeight($Hhtml); + } + } else { + $Hhtml = ''; + } + + if ($OE !== 'E') { + $OE = 'O'; + } + + if ($OE === 'E') { + if ($Hhtml) { + $this->HTMLHeaderE = []; + $this->HTMLHeaderE['html'] = $Hhtml; + $this->HTMLHeaderE['h'] = $height; + } else { + $this->HTMLHeaderE = ''; + } + } else { + if ($Hhtml) { + $this->HTMLHeader = []; + $this->HTMLHeader['html'] = $Hhtml; + $this->HTMLHeader['h'] = $height; + } else { + $this->HTMLHeader = ''; + } + } + + if (!$this->mirrorMargins && $OE == 'E') { + return; + } + if ($Hhtml == '') { + return; + } + + if ($this->setAutoTopMargin == 'pad') { + $this->tMargin = $this->margin_header + $height + $this->orig_tMargin; + if (isset($this->saveHTMLHeader[$this->page][$OE]['mt'])) { + $this->saveHTMLHeader[$this->page][$OE]['mt'] = $this->tMargin; + } + } elseif ($this->setAutoTopMargin == 'stretch') { + $this->tMargin = max($this->orig_tMargin, $this->margin_header + $height + $this->autoMarginPadding); + if (isset($this->saveHTMLHeader[$this->page][$OE]['mt'])) { + $this->saveHTMLHeader[$this->page][$OE]['mt'] = $this->tMargin; + } + } + if ($write && $this->state != 0 && (($this->mirrorMargins && $OE == 'E' && ($this->page) % 2 == 0) || ($this->mirrorMargins && $OE != 'E' && ($this->page) % 2 == 1) || !$this->mirrorMargins)) { + $this->writeHTMLHeaders(); + } + } + + function SetHTMLFooter($footer = '', $OE = '') + { + $height = 0; + if (is_array($footer) && isset($footer['html']) && $footer['html']) { + $Fhtml = $footer['html']; + if ($this->setAutoBottomMargin) { + if (isset($footer['h'])) { + $height = $footer['h']; + } else { + $height = $this->_getHtmlHeight($Fhtml); + } + } + } elseif (!is_array($footer) && $footer) { + $Fhtml = $footer; + if ($this->setAutoBottomMargin) { + $height = $this->_getHtmlHeight($Fhtml); + } + } else { + $Fhtml = ''; + } + + if ($OE !== 'E') { + $OE = 'O'; + } + + if ($OE === 'E') { + if ($Fhtml) { + $this->HTMLFooterE = []; + $this->HTMLFooterE['html'] = $Fhtml; + $this->HTMLFooterE['h'] = $height; + } else { + $this->HTMLFooterE = ''; + } + } else { + if ($Fhtml) { + $this->HTMLFooter = []; + $this->HTMLFooter['html'] = $Fhtml; + $this->HTMLFooter['h'] = $height; + } else { + $this->HTMLFooter = ''; + } + } + + if (!$this->mirrorMargins && $OE == 'E') { + return; + } + + if ($Fhtml == '') { + return false; + } + + if ($this->setAutoBottomMargin == 'pad') { + $this->bMargin = $this->margin_footer + $height + $this->orig_bMargin; + $this->PageBreakTrigger = $this->h - $this->bMargin; + if (isset($this->saveHTMLHeader[$this->page][$OE]['mb'])) { + $this->saveHTMLHeader[$this->page][$OE]['mb'] = $this->bMargin; + } + } elseif ($this->setAutoBottomMargin == 'stretch') { + $this->bMargin = max($this->orig_bMargin, $this->margin_footer + $height + $this->autoMarginPadding); + $this->PageBreakTrigger = $this->h - $this->bMargin; + if (isset($this->saveHTMLHeader[$this->page][$OE]['mb'])) { + $this->saveHTMLHeader[$this->page][$OE]['mb'] = $this->bMargin; + } + } + } + + function _getHtmlHeight($html) + { + $save_state = $this->state; + if ($this->state == 0) { + $this->AddPage($this->CurOrientation); + } + $this->state = 2; + $this->Reset(); + $this->pageoutput[$this->page] = []; + $save_x = $this->x; + $save_y = $this->y; + $this->x = $this->lMargin; + $this->y = $this->margin_header; + $html = str_replace('{PAGENO}', $this->pagenumPrefix . $this->docPageNum($this->page) . $this->pagenumSuffix, $html); + $html = str_replace($this->aliasNbPgGp, $this->nbpgPrefix . $this->docPageNumTotal($this->page) . $this->nbpgSuffix, $html); + $html = str_replace($this->aliasNbPg, $this->page, $html); + $html = preg_replace_callback('/\{DATE\s+(.*?)\}/', [$this, 'date_callback'], $html); // mPDF 5.7 + $this->HTMLheaderPageLinks = []; + $this->HTMLheaderPageAnnots = []; + $this->HTMLheaderPageForms = []; + $savepb = $this->pageBackgrounds; + $this->writingHTMLheader = true; + $this->WriteHTML($html, HTMLParserMode::HTML_HEADER_BUFFER); + $this->writingHTMLheader = false; + $h = ($this->y - $this->margin_header); + $this->Reset(); + // mPDF 5.7.2 - Clear in case Float used in Header/Footer + $this->blk[0]['blockContext'] = 0; + $this->blk[0]['float_endpos'] = 0; + + $this->pageoutput[$this->page] = []; + $this->headerbuffer = ''; + $this->pageBackgrounds = $savepb; + $this->x = $save_x; + $this->y = $save_y; + $this->state = $save_state; + if ($save_state == 0) { + unset($this->pages[1]); + $this->page = 0; + } + return $h; + } + + // Called internally from Header + function writeHTMLHeaders() + { + + if ($this->mirrorMargins && ($this->page) % 2 == 0) { + $OE = 'E'; + } else { + $OE = 'O'; + } + + if ($OE === 'E') { + $this->saveHTMLHeader[$this->page][$OE]['html'] = $this->HTMLHeaderE['html']; + } else { + $this->saveHTMLHeader[$this->page][$OE]['html'] = $this->HTMLHeader['html']; + } + + if ($this->forcePortraitHeaders && $this->CurOrientation == 'L' && $this->CurOrientation != $this->DefOrientation) { + $this->saveHTMLHeader[$this->page][$OE]['rotate'] = true; + $this->saveHTMLHeader[$this->page][$OE]['ml'] = $this->tMargin; + $this->saveHTMLHeader[$this->page][$OE]['mr'] = $this->bMargin; + $this->saveHTMLHeader[$this->page][$OE]['mh'] = $this->margin_header; + $this->saveHTMLHeader[$this->page][$OE]['mf'] = $this->margin_footer; + $this->saveHTMLHeader[$this->page][$OE]['pw'] = $this->h; + $this->saveHTMLHeader[$this->page][$OE]['ph'] = $this->w; + } else { + $this->saveHTMLHeader[$this->page][$OE]['ml'] = $this->lMargin; + $this->saveHTMLHeader[$this->page][$OE]['mr'] = $this->rMargin; + $this->saveHTMLHeader[$this->page][$OE]['mh'] = $this->margin_header; + $this->saveHTMLHeader[$this->page][$OE]['mf'] = $this->margin_footer; + $this->saveHTMLHeader[$this->page][$OE]['pw'] = $this->w; + $this->saveHTMLHeader[$this->page][$OE]['ph'] = $this->h; + } + } + + function writeHTMLFooters() + { + + if ($this->mirrorMargins && ($this->page) % 2 == 0) { + $OE = 'E'; + } else { + $OE = 'O'; + } + + if ($OE === 'E') { + $this->saveHTMLFooter[$this->page][$OE]['html'] = $this->HTMLFooterE['html']; + } else { + $this->saveHTMLFooter[$this->page][$OE]['html'] = $this->HTMLFooter['html']; + } + + if ($this->forcePortraitHeaders && $this->CurOrientation == 'L' && $this->CurOrientation != $this->DefOrientation) { + $this->saveHTMLFooter[$this->page][$OE]['rotate'] = true; + $this->saveHTMLFooter[$this->page][$OE]['ml'] = $this->tMargin; + $this->saveHTMLFooter[$this->page][$OE]['mr'] = $this->bMargin; + $this->saveHTMLFooter[$this->page][$OE]['mt'] = $this->rMargin; + $this->saveHTMLFooter[$this->page][$OE]['mb'] = $this->lMargin; + $this->saveHTMLFooter[$this->page][$OE]['mh'] = $this->margin_header; + $this->saveHTMLFooter[$this->page][$OE]['mf'] = $this->margin_footer; + $this->saveHTMLFooter[$this->page][$OE]['pw'] = $this->h; + $this->saveHTMLFooter[$this->page][$OE]['ph'] = $this->w; + } else { + $this->saveHTMLFooter[$this->page][$OE]['ml'] = $this->lMargin; + $this->saveHTMLFooter[$this->page][$OE]['mr'] = $this->rMargin; + $this->saveHTMLFooter[$this->page][$OE]['mt'] = $this->tMargin; + $this->saveHTMLFooter[$this->page][$OE]['mb'] = $this->bMargin; + $this->saveHTMLFooter[$this->page][$OE]['mh'] = $this->margin_header; + $this->saveHTMLFooter[$this->page][$OE]['mf'] = $this->margin_footer; + $this->saveHTMLFooter[$this->page][$OE]['pw'] = $this->w; + $this->saveHTMLFooter[$this->page][$OE]['ph'] = $this->h; + } + } + + // mPDF 6 + function _shareHeaderFooterWidth($cl, $cc, $cr) + { + // mPDF 6 + $l = mb_strlen($cl, 'UTF-8'); + $c = mb_strlen($cc, 'UTF-8'); + $r = mb_strlen($cr, 'UTF-8'); + $s = max($l, $r); + $tw = $c + 2 * $s; + if ($tw > 0) { + return [intval($s * 100 / $tw), intval($c * 100 / $tw), intval($s * 100 / $tw)]; + } else { + return [33, 33, 33]; + } + } + + // mPDF 6 + // Create an HTML header/footer from array (non-HTML header/footer) + function _createHTMLheaderFooter($arr, $hf) + { + $lContent = (isset($arr['L']['content']) ? $arr['L']['content'] : ''); + $cContent = (isset($arr['C']['content']) ? $arr['C']['content'] : ''); + $rContent = (isset($arr['R']['content']) ? $arr['R']['content'] : ''); + list($lw, $cw, $rw) = $this->_shareHeaderFooterWidth($lContent, $cContent, $rContent); + if ($hf == 'H') { + $valign = 'bottom'; + $vpadding = '0 0 ' . $this->header_line_spacing . 'em 0'; + } else { + $valign = 'top'; + $vpadding = '' . $this->footer_line_spacing . 'em 0 0 0'; + } + if ($this->directionality == 'rtl') { // table columns get reversed so need different text-alignment + $talignL = 'right'; + $talignR = 'left'; + } else { + $talignL = 'left'; + $talignR = 'right'; + } + $html = ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= '
    ' . $lContent . '' . $cContent . '' . $rContent . '
    '; + return $html; + } + + function DefHeaderByName($name, $arr) + { + if (!$name) { + $name = '_nonhtmldefault'; + } + $html = $this->_createHTMLheaderFooter($arr, 'H'); + + $this->pageHTMLheaders[$name]['html'] = $html; + $this->pageHTMLheaders[$name]['h'] = $this->_getHtmlHeight($html); + } + + function DefFooterByName($name, $arr) + { + if (!$name) { + $name = '_nonhtmldefault'; + } + $html = $this->_createHTMLheaderFooter($arr, 'F'); + + $this->pageHTMLfooters[$name]['html'] = $html; + $this->pageHTMLfooters[$name]['h'] = $this->_getHtmlHeight($html); + } + + function SetHeaderByName($name, $side = 'O', $write = false) + { + if (!$name) { + $name = '_nonhtmldefault'; + } + $this->SetHTMLHeader($this->pageHTMLheaders[$name], $side, $write); + } + + function SetFooterByName($name, $side = 'O') + { + if (!$name) { + $name = '_nonhtmldefault'; + } + $this->SetHTMLFooter($this->pageHTMLfooters[$name], $side); + } + + function DefHTMLHeaderByName($name, $html) + { + if (!$name) { + $name = '_default'; + } + + $this->pageHTMLheaders[$name]['html'] = $html; + $this->pageHTMLheaders[$name]['h'] = $this->_getHtmlHeight($html); + } + + function DefHTMLFooterByName($name, $html) + { + if (!$name) { + $name = '_default'; + } + + $this->pageHTMLfooters[$name]['html'] = $html; + $this->pageHTMLfooters[$name]['h'] = $this->_getHtmlHeight($html); + } + + function SetHTMLHeaderByName($name, $side = 'O', $write = false) + { + if (!$name) { + $name = '_default'; + } + $this->SetHTMLHeader($this->pageHTMLheaders[$name], $side, $write); + } + + function SetHTMLFooterByName($name, $side = 'O') + { + if (!$name) { + $name = '_default'; + } + $this->SetHTMLFooter($this->pageHTMLfooters[$name], $side); + } + + function SetHeader($Harray = [], $side = '', $write = false) + { + $oddhtml = ''; + $evenhtml = ''; + + if (is_string($Harray)) { + + if (strlen($Harray) === 0) { + + $oddhtml = ''; + $evenhtml = ''; + + } elseif (strpos($Harray, '|') !== false) { + + $hdet = explode('|', $Harray); + + list($lw, $cw, $rw) = $this->_shareHeaderFooterWidth($hdet[0], $hdet[1], $hdet[2]); + $oddhtml = ''; + $oddhtml .= ''; + $oddhtml .= ''; + $oddhtml .= ''; + $oddhtml .= ''; + $oddhtml .= '
    ' . $hdet[0] . '' . $hdet[1] . '' . $hdet[2] . '
    '; + + $evenhtml = ''; + $evenhtml .= ''; + $evenhtml .= ''; + $evenhtml .= ''; + $evenhtml .= ''; + $evenhtml .= '
    ' . $hdet[2] . '' . $hdet[1] . '' . $hdet[0] . '
    '; + + } else { + + $oddhtml = '

    ' . $Harray . '
    '; + $evenhtml = '
    ' . $Harray . '
    '; + } + + } elseif (is_array($Harray) && !empty($Harray)) { + + $odd = null; + $even = null; + + if ($side === 'O') { + $odd = $Harray; + } elseif ($side === 'E') { + $even = $Harray; + } else { + $odd = Arrays::get($Harray, 'odd', null); + $even = Arrays::get($Harray, 'even', null); + } + + $oddhtml = $this->_createHTMLheaderFooter($odd, 'H'); + $evenhtml = $this->_createHTMLheaderFooter($even, 'H'); + } + + if ($side === 'E') { + $this->SetHTMLHeader($evenhtml, 'E', $write); + } elseif ($side === 'O') { + $this->SetHTMLHeader($oddhtml, 'O', $write); + } else { + $this->SetHTMLHeader($oddhtml, 'O', $write); + $this->SetHTMLHeader($evenhtml, 'E', $write); + } + } + + function SetFooter($Farray = [], $side = '') + { + $oddhtml = ''; + $evenhtml = ''; + + if (is_string($Farray)) { + + if (strlen($Farray) == 0) { + + $oddhtml = ''; + $evenhtml = ''; + + } elseif (strpos($Farray, '|') !== false) { + + $hdet = explode('|', $Farray); + $oddhtml = ''; + $oddhtml .= ''; + $oddhtml .= ''; + $oddhtml .= ''; + $oddhtml .= ''; + $oddhtml .= '
    ' . $hdet[0] . '' . $hdet[1] . '' . $hdet[2] . '
    '; + + $evenhtml = ''; + $evenhtml .= ''; + $evenhtml .= ''; + $evenhtml .= ''; + $evenhtml .= ''; + $evenhtml .= '
    ' . $hdet[2] . '' . $hdet[1] . '' . $hdet[0] . '
    '; + + } else { + + $oddhtml = '
    ' . $Farray . '
    '; + + $evenhtml = '
    ' . $Farray . '
    '; + } + + } elseif (is_array($Farray)) { + + $odd = null; + $even = null; + + if ($side === 'O') { + $odd = $Farray; + } elseif ($side == 'E') { + $even = $Farray; + } else { + $odd = Arrays::get($Farray, 'odd', null); + $even = Arrays::get($Farray, 'even', null); + } + + $oddhtml = $this->_createHTMLheaderFooter($odd, 'F'); + $evenhtml = $this->_createHTMLheaderFooter($even, 'F'); + } + + if ($side === 'E') { + $this->SetHTMLFooter($evenhtml, 'E'); + } elseif ($side === 'O') { + $this->SetHTMLFooter($oddhtml, 'O'); + } else { + $this->SetHTMLFooter($oddhtml, 'O'); + $this->SetHTMLFooter($evenhtml, 'E'); + } + } + + /* -- WATERMARK -- */ + + function SetWatermarkText($txt = '', $alpha = -1) + { + if ($alpha >= 0) { + $this->watermarkTextAlpha = $alpha; + } + $this->watermarkText = $txt; + } + + function SetWatermarkImage($src, $alpha = -1, $size = 'D', $pos = 'F') + { + if ($alpha >= 0) { + $this->watermarkImageAlpha = $alpha; + } + $this->watermarkImage = $src; + $this->watermark_size = $size; + $this->watermark_pos = $pos; + } + + /* -- END WATERMARK -- */ + + // Page footer + function Footer() + { + /* -- CSS-PAGE -- */ + // PAGED MEDIA - CROP / CROSS MARKS from @PAGE + if ($this->show_marks == 'CROP' || $this->show_marks == 'CROPCROSS') { + // Show TICK MARKS + $this->SetLineWidth(0.1); // = 0.1 mm + $this->SetDColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + $l = $this->cropMarkLength; + $m = $this->cropMarkMargin; // Distance of crop mark from margin + $b = $this->nonPrintMargin; // Non-printable border at edge of paper sheet + $ax1 = $b; + $bx = $this->page_box['outer_width_LR'] - $m; + $ax = max($ax1, $bx - $l); + $cx1 = $this->w - $b; + $dx = $this->w - $this->page_box['outer_width_LR'] + $m; + $cx = min($cx1, $dx + $l); + $ay1 = $b; + $by = $this->page_box['outer_width_TB'] - $m; + $ay = max($ay1, $by - $l); + $cy1 = $this->h - $b; + $dy = $this->h - $this->page_box['outer_width_TB'] + $m; + $cy = min($cy1, $dy + $l); + + $this->Line($ax, $this->page_box['outer_width_TB'], $bx, $this->page_box['outer_width_TB']); + $this->Line($cx, $this->page_box['outer_width_TB'], $dx, $this->page_box['outer_width_TB']); + $this->Line($ax, $this->h - $this->page_box['outer_width_TB'], $bx, $this->h - $this->page_box['outer_width_TB']); + $this->Line($cx, $this->h - $this->page_box['outer_width_TB'], $dx, $this->h - $this->page_box['outer_width_TB']); + $this->Line($this->page_box['outer_width_LR'], $ay, $this->page_box['outer_width_LR'], $by); + $this->Line($this->page_box['outer_width_LR'], $cy, $this->page_box['outer_width_LR'], $dy); + $this->Line($this->w - $this->page_box['outer_width_LR'], $ay, $this->w - $this->page_box['outer_width_LR'], $by); + $this->Line($this->w - $this->page_box['outer_width_LR'], $cy, $this->w - $this->page_box['outer_width_LR'], $dy); + + if ($this->printers_info) { + $hd = date('Y-m-d H:i') . ' Page ' . $this->page . ' of {nb}'; + $this->SetTColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + $this->SetFont('arial', '', 7.5, true, true); + $this->x = $this->page_box['outer_width_LR'] + 1.5; + $this->y = 1; + $this->Cell($headerpgwidth, $this->FontSize, $hd, 0, 0, 'L', 0, '', 0, 0, 0, 'M'); + $this->SetFont($this->default_font, '', $this->original_default_font_size); + } + } + if ($this->show_marks == 'CROSS' || $this->show_marks == 'CROPCROSS') { + $this->SetLineWidth(0.1); // = 0.1 mm + $this->SetDColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + $l = 14 / 2; // longer length of the cross line (half) + $w = 6 / 2; // shorter width of the cross line (half) + $r = 1.2; // radius of circle + $m = $this->crossMarkMargin; // Distance of cross mark from margin + $x1 = $this->page_box['outer_width_LR'] - $m; + $x2 = $this->w - $this->page_box['outer_width_LR'] + $m; + $y1 = $this->page_box['outer_width_TB'] - $m; + $y2 = $this->h - $this->page_box['outer_width_TB'] + $m; + // Left + $this->Circle($x1, $this->h / 2, $r, 'S'); + $this->Line($x1 - $w, $this->h / 2, $x1 + $w, $this->h / 2); + $this->Line($x1, $this->h / 2 - $l, $x1, $this->h / 2 + $l); + // Right + $this->Circle($x2, $this->h / 2, $r, 'S'); + $this->Line($x2 - $w, $this->h / 2, $x2 + $w, $this->h / 2); + $this->Line($x2, $this->h / 2 - $l, $x2, $this->h / 2 + $l); + // Top + $this->Circle($this->w / 2, $y1, $r, 'S'); + $this->Line($this->w / 2, $y1 - $w, $this->w / 2, $y1 + $w); + $this->Line($this->w / 2 - $l, $y1, $this->w / 2 + $l, $y1); + // Bottom + $this->Circle($this->w / 2, $y2, $r, 'S'); + $this->Line($this->w / 2, $y2 - $w, $this->w / 2, $y2 + $w); + $this->Line($this->w / 2 - $l, $y2, $this->w / 2 + $l, $y2); + } + + /* -- END CSS-PAGE -- */ + + // mPDF 6 + // If @page set non-HTML headers/footers named, they were not read until later in the HTML code - so now set them + if ($this->page == 1) { + if ($this->firstPageBoxHeader) { + if (isset($this->pageHTMLheaders[$this->firstPageBoxHeader])) { + $this->HTMLHeader = $this->pageHTMLheaders[$this->firstPageBoxHeader]; + } + $this->Header(); + } + if ($this->firstPageBoxFooter) { + if (isset($this->pageHTMLfooters[$this->firstPageBoxFooter])) { + $this->HTMLFooter = $this->pageHTMLfooters[$this->firstPageBoxFooter]; + } + } + $this->firstPageBoxHeader = ''; + $this->firstPageBoxFooter = ''; + } + + + if (($this->mirrorMargins && ($this->page % 2 == 0) && $this->HTMLFooterE) || ($this->mirrorMargins && ($this->page % 2 == 1) && $this->HTMLFooter) || (!$this->mirrorMargins && $this->HTMLFooter)) { + $this->writeHTMLFooters(); + } + + /* -- WATERMARK -- */ + if (($this->watermarkText) && ($this->showWatermarkText)) { + $this->watermark($this->watermarkText, $this->watermarkAngle, 120, $this->watermarkTextAlpha); // Watermark text + } + if (($this->watermarkImage) && ($this->showWatermarkImage)) { + $this->watermarkImg($this->watermarkImage, $this->watermarkImageAlpha); // Watermark image + } + /* -- END WATERMARK -- */ + } + + /* -- HTML-CSS -- */ + + /** + * Write HTML code to the document + * + * Also used internally to parse HTML into buffers + * + * @param string $html + * @param int $mode Use HTMLParserMode constants. Controls what parts of the $html code is parsed. + * @param bool $init Clears and sets buffers to Top level block etc. + * @param bool $close If false leaves buffers etc. in current state, so that it can continue a block etc. + */ + function WriteHTML($html, $mode = HTMLParserMode::DEFAULT_MODE, $init = true, $close = true) + { + /* Check $html is an integer, float, string, boolean or class with __toString(), otherwise throw exception */ + if (is_scalar($html) === false) { + if (!is_object($html) || ! method_exists($html, '__toString')) { + throw new \Mpdf\MpdfException('WriteHTML() requires $html be an integer, float, string, boolean or an object with the __toString() magic method.'); + } + } + + // Check the mode is valid + if (in_array($mode, HTMLParserMode::getAllModes(), true) === false) { + throw new \Mpdf\MpdfException('WriteHTML() requires $mode to be one of the modes defined in HTMLParserMode'); + } + + /* Cast $html as a string */ + $html = (string) $html; + + // @log Parsing CSS & Headers + + if ($init) { + $this->headerbuffer = ''; + $this->textbuffer = []; + $this->fixedPosBlockSave = []; + } + if ($mode === HTMLParserMode::HEADER_CSS) { + $html = ''; + } // stylesheet only + + if ($this->allow_charset_conversion) { + if ($mode === HTMLParserMode::DEFAULT_MODE) { + $this->ReadCharset($html); + } + if ($this->charset_in && $mode !== HTMLParserMode::HTML_HEADER_BUFFER) { + $success = iconv($this->charset_in, 'UTF-8//TRANSLIT', $html); + if ($success) { + $html = $success; + } + } + } + + $html = $this->purify_utf8($html, false); + if ($init) { + $this->blklvl = 0; + $this->lastblocklevelchange = 0; + $this->blk = []; + $this->initialiseBlock($this->blk[0]); + $this->blk[0]['width'] = & $this->pgwidth; + $this->blk[0]['inner_width'] = & $this->pgwidth; + $this->blk[0]['blockContext'] = $this->blockContext; + } + + $zproperties = []; + if ($mode === HTMLParserMode::DEFAULT_MODE || $mode === HTMLParserMode::HEADER_CSS) { + $this->ReadMetaTags($html); + + if (preg_match('/]*href=["\']([^"\'>]*)["\']/i', $html, $m)) { + $this->SetBasePath($m[1]); + } + $html = $this->cssManager->ReadCSS($html); + + if ($this->autoLangToFont && !$this->usingCoreFont && preg_match('/]*lang=[\'\"](.*?)[\'\"]/ism', $html, $m)) { + $html_lang = $m[1]; + } + + if (preg_match('/]*dir=[\'\"]\s*rtl\s*[\'\"]/ism', $html)) { + $zproperties['DIRECTION'] = 'rtl'; + } + + // allow in-line CSS for body tag to be parsed // Get tag inline CSS + if (preg_match('/]*)>(.*?)<\/body>/ism', $html, $m) || preg_match('/]*)>(.*)$/ism', $html, $m)) { + $html = $m[2]; + // Changed to allow style="background: url('bg.jpg')" + if (preg_match('/style=[\"](.*?)[\"]/ism', $m[1], $mm) || preg_match('/style=[\'](.*?)[\']/ism', $m[1], $mm)) { + $zproperties = $this->cssManager->readInlineCSS($mm[1]); + } + if (preg_match('/dir=[\'\"]\s*rtl\s*[\'\"]/ism', $m[1])) { + $zproperties['DIRECTION'] = 'rtl'; + } + if (isset($html_lang) && $html_lang) { + $zproperties['LANG'] = $html_lang; + } + if ($this->autoLangToFont && !$this->onlyCoreFonts && preg_match('/lang=[\'\"](.*?)[\'\"]/ism', $m[1], $mm)) { + $zproperties['LANG'] = $mm[1]; + } + } + } + $properties = $this->cssManager->MergeCSS('BLOCK', 'BODY', ''); + if ($zproperties) { + $properties = $this->cssManager->array_merge_recursive_unique($properties, $zproperties); + } + + if (isset($properties['DIRECTION']) && $properties['DIRECTION']) { + $this->cssManager->CSS['BODY']['DIRECTION'] = $properties['DIRECTION']; + } + if (!isset($this->cssManager->CSS['BODY']['DIRECTION'])) { + $this->cssManager->CSS['BODY']['DIRECTION'] = $this->directionality; + } else { + $this->SetDirectionality($this->cssManager->CSS['BODY']['DIRECTION']); + } + + $this->setCSS($properties, '', 'BODY'); + + $this->blk[0]['InlineProperties'] = $this->saveInlineProperties(); + + if ($mode === HTMLParserMode::HEADER_CSS) { + return ''; + } + if (!isset($this->cssManager->CSS['BODY'])) { + $this->cssManager->CSS['BODY'] = []; + } + + /* -- BACKGROUNDS -- */ + if (isset($properties['BACKGROUND-GRADIENT'])) { + $this->bodyBackgroundGradient = $properties['BACKGROUND-GRADIENT']; + } + + if (isset($properties['BACKGROUND-IMAGE']) && $properties['BACKGROUND-IMAGE']) { + $ret = $this->SetBackground($properties, $this->pgwidth); + if ($ret) { + $this->bodyBackgroundImage = $ret; + } + } + /* -- END BACKGROUNDS -- */ + + /* -- CSS-PAGE -- */ + // If page-box is set + if ($this->state == 0 && ((isset($this->cssManager->CSS['@PAGE']) && $this->cssManager->CSS['@PAGE']) || (isset($this->cssManager->CSS['@PAGE>>PSEUDO>>FIRST']) && $this->cssManager->CSS['@PAGE>>PSEUDO>>FIRST']))) { // mPDF 5.7.3 + $this->page_box['current'] = ''; + $this->page_box['using'] = true; + list($pborientation, $pbmgl, $pbmgr, $pbmgt, $pbmgb, $pbmgh, $pbmgf, $hname, $fname, $bg, $resetpagenum, $pagenumstyle, $suppress, $marks, $newformat) = $this->SetPagedMediaCSS('', false, 'O'); + $this->DefOrientation = $this->CurOrientation = $pborientation; + $this->orig_lMargin = $this->DeflMargin = $pbmgl; + $this->orig_rMargin = $this->DefrMargin = $pbmgr; + $this->orig_tMargin = $this->tMargin = $pbmgt; + $this->orig_bMargin = $this->bMargin = $pbmgb; + $this->orig_hMargin = $this->margin_header = $pbmgh; + $this->orig_fMargin = $this->margin_footer = $pbmgf; + list($pborientation, $pbmgl, $pbmgr, $pbmgt, $pbmgb, $pbmgh, $pbmgf, $hname, $fname, $bg, $resetpagenum, $pagenumstyle, $suppress, $marks, $newformat) = $this->SetPagedMediaCSS('', true, 'O'); // first page + $this->show_marks = $marks; + if ($hname) { + $this->firstPageBoxHeader = $hname; + } + if ($fname) { + $this->firstPageBoxFooter = $fname; + } + } + /* -- END CSS-PAGE -- */ + + $parseonly = false; + $this->bufferoutput = false; + if ($mode == HTMLParserMode::HTML_PARSE_NO_WRITE) { + $parseonly = true; + // Close any open block tags + $arr = []; + $ai = 0; + for ($b = $this->blklvl; $b > 0; $b--) { + $this->tag->CloseTag($this->blk[$b]['tag'], $arr, $ai); + } + // Output any text left in buffer + if (count($this->textbuffer)) { + $this->printbuffer($this->textbuffer); + } + $this->textbuffer = []; + } elseif ($mode === HTMLParserMode::HTML_HEADER_BUFFER) { + // Close any open block tags + $arr = []; + $ai = 0; + for ($b = $this->blklvl; $b > 0; $b--) { + $this->tag->CloseTag($this->blk[$b]['tag'], $arr, $ai); + } + // Output any text left in buffer + if (count($this->textbuffer)) { + $this->printbuffer($this->textbuffer); + } + $this->bufferoutput = true; + $this->textbuffer = []; + $this->headerbuffer = ''; + $properties = $this->cssManager->MergeCSS('BLOCK', 'BODY', ''); + $this->setCSS($properties, '', 'BODY'); + } + + mb_internal_encoding('UTF-8'); + + $html = $this->AdjustHTML($html, $this->tabSpaces); // Try to make HTML look more like XHTML + + if ($this->autoScriptToLang) { + $html = $this->markScriptToLang($html); + } + + preg_match_all('/]*)>(.*?)<\/htmlpageheader>/si', $html, $h); + for ($i = 0; $i < count($h[1]); $i++) { + if (preg_match('/name=[\'|\"](.*?)[\'|\"]/', $h[1][$i], $n)) { + $this->pageHTMLheaders[$n[1]]['html'] = $h[2][$i]; + $this->pageHTMLheaders[$n[1]]['h'] = $this->_getHtmlHeight($h[2][$i]); + } + } + preg_match_all('/]*)>(.*?)<\/htmlpagefooter>/si', $html, $f); + for ($i = 0; $i < count($f[1]); $i++) { + if (preg_match('/name=[\'|\"](.*?)[\'|\"]/', $f[1][$i], $n)) { + $this->pageHTMLfooters[$n[1]]['html'] = $f[2][$i]; + $this->pageHTMLfooters[$n[1]]['h'] = $this->_getHtmlHeight($f[2][$i]); + } + } + + $html = preg_replace('//si', '', $html); + $html = preg_replace('//si', '', $html); + + if ($this->state == 0 && ($mode === HTMLParserMode::DEFAULT_MODE || $mode === HTMLParserMode::HTML_BODY)) { + $this->AddPage($this->CurOrientation); + } + + + if (isset($hname) && preg_match('/^html_(.*)$/i', $hname, $n)) { + $this->SetHTMLHeader($this->pageHTMLheaders[$n[1]], 'O', true); + } + if (isset($fname) && preg_match('/^html_(.*)$/i', $fname, $n)) { + $this->SetHTMLFooter($this->pageHTMLfooters[$n[1]], 'O'); + } + + + + $html = str_replace('checkSIP = false; + $this->checkSMP = false; + $this->checkCJK = false; + if ($this->onlyCoreFonts) { + $html = $this->SubstituteChars($html); + } else { + if (preg_match("/([" . $this->pregRTLchars . "])/u", $html)) { + $this->biDirectional = true; + } // *OTL* + if (preg_match("/([\x{20000}-\x{2FFFF}])/u", $html)) { + $this->checkSIP = true; + } + if (preg_match("/([\x{10000}-\x{1FFFF}])/u", $html)) { + $this->checkSMP = true; + } + /* -- CJK-FONTS -- */ + if (preg_match("/([" . $this->pregCJKchars . "])/u", $html)) { + $this->checkCJK = true; + } + /* -- END CJK-FONTS -- */ + } + + // Don't allow non-breaking spaces that are converted to substituted chars or will break anyway and mess up table width calc. + $html = str_replace('160', chr(32), $html); + $html = str_replace('', '|', $html); + $html = str_replace('', '|', $html); + $html = str_replace('', '|', $html); + + // Add new supported tags in the DisableTags function + $html = strip_tags($html, $this->enabledtags); // remove all unsupported tags, but the ones inside the 'enabledtags' string + // Explode the string in order to parse the HTML code + $a = preg_split('/<(.*?)>/ms', $html, -1, PREG_SPLIT_DELIM_CAPTURE); + // ? more accurate regexp that allows e.g. + // if changing - also change in fn.SubstituteChars() + // $a = preg_split ('/<((?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+)>/ms', $html, -1, PREG_SPLIT_DELIM_CAPTURE); + + if ($this->mb_enc) { + mb_internal_encoding($this->mb_enc); + } + $pbc = 0; + $this->subPos = -1; + $cnt = count($a); + for ($i = 0; $i < $cnt; $i++) { + $e = $a[$i]; + if ($i % 2 == 0) { + // TEXT + if ($this->blk[$this->blklvl]['hide']) { + continue; + } + if ($this->inlineDisplayOff) { + continue; + } + if ($this->inMeter) { + continue; + } + + if ($this->inFixedPosBlock) { + $this->fixedPosBlock .= $e; + continue; + } // *CSS-POSITION* + if (strlen($e) == 0) { + continue; + } + + if ($this->ignorefollowingspaces && !$this->ispre) { + if (strlen(ltrim($e)) == 0) { + continue; + } + if ($this->FontFamily != 'csymbol' && $this->FontFamily != 'czapfdingbats' && substr($e, 0, 1) == ' ') { + $this->ignorefollowingspaces = false; + $e = ltrim($e); + } + } + + $this->OTLdata = null; // mPDF 5.7.1 + + $e = UtfString::strcode2utf($e); + $e = $this->lesser_entity_decode($e); + + if ($this->usingCoreFont) { + // If core font is selected in document which is not onlyCoreFonts - substitute with non-core font + if ($this->useSubstitutions && !$this->onlyCoreFonts && $this->subPos < $i && !$this->specialcontent) { + $cnt += $this->SubstituteCharsNonCore($a, $i, $e); + } + // CONVERT ENCODING + $e = mb_convert_encoding($e, $this->mb_enc, 'UTF-8'); + if ($this->textvar & TextVars::FT_UPPERCASE) { + $e = mb_strtoupper($e, $this->mb_enc); + } // mPDF 5.7.1 + elseif ($this->textvar & TextVars::FT_LOWERCASE) { + $e = mb_strtolower($e, $this->mb_enc); + } // mPDF 5.7.1 + elseif ($this->textvar & TextVars::FT_CAPITALIZE) { + $e = mb_convert_case($e, MB_CASE_TITLE, "UTF-8"); + } // mPDF 5.7.1 + } else { + if ($this->checkSIP && $this->CurrentFont['sipext'] && $this->subPos < $i && (!$this->specialcontent || !$this->useActiveForms)) { + $cnt += $this->SubstituteCharsSIP($a, $i, $e); + } + + if ($this->useSubstitutions && !$this->onlyCoreFonts && $this->CurrentFont['type'] != 'Type0' && $this->subPos < $i && (!$this->specialcontent || !$this->useActiveForms)) { + $cnt += $this->SubstituteCharsMB($a, $i, $e); + } + + if ($this->textvar & TextVars::FT_UPPERCASE) { + $e = mb_strtoupper($e, $this->mb_enc); + } elseif ($this->textvar & TextVars::FT_LOWERCASE) { + $e = mb_strtolower($e, $this->mb_enc); + } elseif ($this->textvar & TextVars::FT_CAPITALIZE) { + $e = mb_convert_case($e, MB_CASE_TITLE, "UTF-8"); + } + + /* -- OTL -- */ + // Use OTL OpenType Table Layout - GSUB & GPOS + if (isset($this->CurrentFont['useOTL']) && $this->CurrentFont['useOTL'] && (!$this->specialcontent || !$this->useActiveForms)) { + if (!$this->otl) { + $this->otl = new Otl($this, $this->fontCache); + } + $e = $this->otl->applyOTL($e, $this->CurrentFont['useOTL']); + $this->OTLdata = $this->otl->OTLdata; + $this->otl->removeChar($e, $this->OTLdata, "\xef\xbb\xbf"); // Remove ZWNBSP (also Byte order mark FEFF) + } /* -- END OTL -- */ + else { + // removes U+200E/U+200F LTR and RTL mark and U+200C/U+200D Zero-width Joiner and Non-joiner + $e = preg_replace("/[\xe2\x80\x8c\xe2\x80\x8d\xe2\x80\x8e\xe2\x80\x8f]/u", '', $e); + $e = preg_replace("/[\xef\xbb\xbf]/u", '', $e); // Remove ZWNBSP (also Byte order mark FEFF) + } + } + + if (($this->tts) || ($this->ttz) || ($this->tta)) { + $es = explode('|', $e); + $e = ''; + foreach ($es as $val) { + $e .= chr($val); + } + } + + // FORM ELEMENTS + if ($this->specialcontent) { + /* -- FORMS -- */ + // SELECT tag (form element) + if ($this->specialcontent == "type=select") { + $e = ltrim($e); + if (!empty($this->OTLdata)) { + $this->otl->trimOTLdata($this->OTLdata, true, false); + } // *OTL* + $stringwidth = $this->GetStringWidth($e); + if (!isset($this->selectoption['MAXWIDTH']) || $stringwidth > $this->selectoption['MAXWIDTH']) { + $this->selectoption['MAXWIDTH'] = $stringwidth; + } + if (!isset($this->selectoption['SELECTED']) || $this->selectoption['SELECTED'] == '') { + $this->selectoption['SELECTED'] = $e; + if (!empty($this->OTLdata)) { + $this->selectoption['SELECTED-OTLDATA'] = $this->OTLdata; + } // *OTL* + } + // Active Forms + if (isset($this->selectoption['ACTIVE']) && $this->selectoption['ACTIVE']) { + $this->selectoption['ITEMS'][] = ['exportValue' => $this->selectoption['currentVAL'], 'content' => $e, 'selected' => $this->selectoption['currentSEL']]; + } + $this->OTLdata = []; + } // TEXTAREA + else { + $objattr = unserialize($this->specialcontent); + $objattr['text'] = $e; + $objattr['OTLdata'] = $this->OTLdata; + $this->OTLdata = []; + $te = "\xbb\xa4\xactype=textarea,objattr=" . serialize($objattr) . "\xbb\xa4\xac"; + if ($this->tdbegin) { + $this->_saveCellTextBuffer($te, $this->HREF); + } else { + $this->_saveTextBuffer($te, $this->HREF); + } + } + /* -- END FORMS -- */ + } // TABLE + elseif ($this->tableLevel) { + /* -- TABLES -- */ + if ($this->tdbegin) { + if (($this->ignorefollowingspaces) && !$this->ispre) { + $e = ltrim($e); + if (!empty($this->OTLdata)) { + $this->otl->trimOTLdata($this->OTLdata, true, false); + } // *OTL* + } + if ($e || $e === '0') { + if ($this->blockjustfinished && $this->cell[$this->row][$this->col]['s'] > 0) { + $this->_saveCellTextBuffer("\n"); + if (!isset($this->cell[$this->row][$this->col]['maxs'])) { + $this->cell[$this->row][$this->col]['maxs'] = $this->cell[$this->row][$this->col]['s']; + } elseif ($this->cell[$this->row][$this->col]['maxs'] < $this->cell[$this->row][$this->col]['s']) { + $this->cell[$this->row][$this->col]['maxs'] = $this->cell[$this->row][$this->col]['s']; + } + $this->cell[$this->row][$this->col]['s'] = 0; // reset + } + $this->blockjustfinished = false; + + if (!isset($this->cell[$this->row][$this->col]['R']) || !$this->cell[$this->row][$this->col]['R']) { + if (isset($this->cell[$this->row][$this->col]['s'])) { + $this->cell[$this->row][$this->col]['s'] += $this->GetStringWidth($e, false, $this->OTLdata, $this->textvar); + } else { + $this->cell[$this->row][$this->col]['s'] = $this->GetStringWidth($e, false, $this->OTLdata, $this->textvar); + } + if (!empty($this->spanborddet)) { + $this->cell[$this->row][$this->col]['s'] += (isset($this->spanborddet['L']['w']) ? $this->spanborddet['L']['w'] : 0) + (isset($this->spanborddet['R']['w']) ? $this->spanborddet['R']['w'] : 0); + } + } + $this->_saveCellTextBuffer($e, $this->HREF); + if (substr($this->cell[$this->row][$this->col]['a'], 0, 1) == 'D') { + $dp = $this->decimal_align[substr($this->cell[$this->row][$this->col]['a'], 0, 2)]; + $s = preg_split('/' . preg_quote($dp, '/') . '/', $e, 2); // ? needs to be /u if not core + $s0 = $this->GetStringWidth($s[0], false); + if (isset($s[1]) && $s[1]) { + $s1 = $this->GetStringWidth(($s[1] . $dp), false); + } else { + $s1 = 0; + } + if (!isset($this->table[$this->tableLevel][$this->tbctr[$this->tableLevel]]['decimal_align'][$this->col]['maxs0'])) { + $this->table[$this->tableLevel][$this->tbctr[$this->tableLevel]]['decimal_align'][$this->col]['maxs0'] = $s0; + } else { + $this->table[$this->tableLevel][$this->tbctr[$this->tableLevel]]['decimal_align'][$this->col]['maxs0'] = max($s0, $this->table[$this->tableLevel][$this->tbctr[$this->tableLevel]]['decimal_align'][$this->col]['maxs0']); + } + if (!isset($this->table[$this->tableLevel][$this->tbctr[$this->tableLevel]]['decimal_align'][$this->col]['maxs1'])) { + $this->table[$this->tableLevel][$this->tbctr[$this->tableLevel]]['decimal_align'][$this->col]['maxs1'] = $s1; + } else { + $this->table[$this->tableLevel][$this->tbctr[$this->tableLevel]]['decimal_align'][$this->col]['maxs1'] = max($s1, $this->table[$this->tableLevel][$this->tbctr[$this->tableLevel]]['decimal_align'][$this->col]['maxs1']); + } + } + + $this->nestedtablejustfinished = false; + $this->linebreakjustfinished = false; + } + } + /* -- END TABLES -- */ + } // ALL ELSE + else { + if ($this->ignorefollowingspaces && !$this->ispre) { + $e = ltrim($e); + if (!empty($this->OTLdata)) { + $this->otl->trimOTLdata($this->OTLdata, true, false); + } // *OTL* + } + if ($e || $e === '0') { + $this->_saveTextBuffer($e, $this->HREF); + } + } + if ($e || $e === '0') { + $this->ignorefollowingspaces = false; // mPDF 6 + } + if (substr($e, -1, 1) == ' ' && !$this->ispre && $this->FontFamily != 'csymbol' && $this->FontFamily != 'czapfdingbats') { + $this->ignorefollowingspaces = true; + } + } else { // TAG ** + if (isset($e[0]) && $e[0] == '/') { + $endtag = trim(strtoupper(substr($e, 1))); + + /* -- CSS-POSITION -- */ + // mPDF 6 + if ($this->inFixedPosBlock) { + if (in_array($endtag, $this->outerblocktags) || in_array($endtag, $this->innerblocktags)) { + $this->fixedPosBlockDepth--; + } + if ($this->fixedPosBlockDepth == 0) { + $this->fixedPosBlockSave[] = [$this->fixedPosBlock, $this->fixedPosBlockBBox, $this->page]; + $this->fixedPosBlock = ''; + $this->inFixedPosBlock = false; + continue; + } + $this->fixedPosBlock .= '<' . $e . '>'; + continue; + } + /* -- END CSS-POSITION -- */ + + // mPDF 6 + // Correct for tags where HTML5 specifies optional end tags (see also OpenTag() ) + if ($this->allow_html_optional_endtags && !$parseonly) { + if (isset($this->blk[$this->blklvl]['tag'])) { + $closed = false; + // li end tag may be omitted if there is no more content in the parent element + if (!$closed && $this->blk[$this->blklvl]['tag'] == 'LI' && $endtag != 'LI' && (in_array($endtag, $this->outerblocktags) || in_array($endtag, $this->innerblocktags))) { + $this->tag->CloseTag('LI', $a, $i); + $closed = true; + } + // dd end tag may be omitted if there is no more content in the parent element + if (!$closed && $this->blk[$this->blklvl]['tag'] == 'DD' && $endtag != 'DD' && (in_array($endtag, $this->outerblocktags) || in_array($endtag, $this->innerblocktags))) { + $this->tag->CloseTag('DD', $a, $i); + $closed = true; + } + // p end tag may be omitted if there is no more content in the parent element and the parent element is not an A element [??????] + if (!$closed && $this->blk[$this->blklvl]['tag'] == 'P' && $endtag != 'P' && (in_array($endtag, $this->outerblocktags) || in_array($endtag, $this->innerblocktags))) { + $this->tag->CloseTag('P', $a, $i); + $closed = true; + } + // option end tag may be omitted if there is no more content in the parent element + if (!$closed && $this->blk[$this->blklvl]['tag'] == 'OPTION' && $endtag != 'OPTION' && (in_array($endtag, $this->outerblocktags) || in_array($endtag, $this->innerblocktags))) { + $this->tag->CloseTag('OPTION', $a, $i); + $closed = true; + } + } + /* -- TABLES -- */ + // Check for Table tags where HTML specifies optional end tags, + if ($endtag == 'TABLE') { + if ($this->lastoptionaltag == 'THEAD' || $this->lastoptionaltag == 'TBODY' || $this->lastoptionaltag == 'TFOOT') { + $this->tag->CloseTag($this->lastoptionaltag, $a, $i); + } + if ($this->lastoptionaltag == 'TR') { + $this->tag->CloseTag('TR', $a, $i); + } + if ($this->lastoptionaltag == 'TD' || $this->lastoptionaltag == 'TH') { + $this->tag->CloseTag($this->lastoptionaltag, $a, $i); + $this->tag->CloseTag('TR', $a, $i); + } + } + if ($endtag == 'THEAD' || $endtag == 'TBODY' || $endtag == 'TFOOT') { + if ($this->lastoptionaltag == 'TR') { + $this->tag->CloseTag('TR', $a, $i); + } + if ($this->lastoptionaltag == 'TD' || $this->lastoptionaltag == 'TH') { + $this->tag->CloseTag($this->lastoptionaltag, $a, $i); + $this->tag->CloseTag('TR', $a, $i); + } + } + if ($endtag == 'TR') { + if ($this->lastoptionaltag == 'TD' || $this->lastoptionaltag == 'TH') { + $this->tag->CloseTag($this->lastoptionaltag, $a, $i); + } + } + /* -- END TABLES -- */ + } + + + // mPDF 6 + if ($this->blk[$this->blklvl]['hide']) { + if (in_array($endtag, $this->outerblocktags) || in_array($endtag, $this->innerblocktags)) { + unset($this->blk[$this->blklvl]); + $this->blklvl--; + } + continue; + } + + // mPDF 6 + $this->tag->CloseTag($endtag, $a, $i); // mPDF 6 + } else { // OPENING TAG + if ($this->blk[$this->blklvl]['hide']) { + if (strpos($e, ' ')) { + $te = strtoupper(substr($e, 0, strpos($e, ' '))); + } else { + $te = strtoupper($e); + } + // mPDF 6 + if ($te == 'THEAD' || $te == 'TBODY' || $te == 'TFOOT' || $te == 'TR' || $te == 'TD' || $te == 'TH') { + $this->lastoptionaltag = $te; + } + if (in_array($te, $this->outerblocktags) || in_array($te, $this->innerblocktags)) { + $this->blklvl++; + $this->blk[$this->blklvl]['hide'] = true; + $this->blk[$this->blklvl]['tag'] = $te; // mPDF 6 + } + continue; + } + + /* -- CSS-POSITION -- */ + if ($this->inFixedPosBlock) { + if (strpos($e, ' ')) { + $te = strtoupper(substr($e, 0, strpos($e, ' '))); + } else { + $te = strtoupper($e); + } + $this->fixedPosBlock .= '<' . $e . '>'; + if (in_array($te, $this->outerblocktags) || in_array($te, $this->innerblocktags)) { + $this->fixedPosBlockDepth++; + } + continue; + } + /* -- END CSS-POSITION -- */ + $regexp = '|=\'(.*?)\'|s'; // eliminate single quotes, if any + $e = preg_replace($regexp, "=\"\$1\"", $e); + // changes anykey=anyvalue to anykey="anyvalue" (only do this inside [some] tags) + if (substr($e, 0, 10) != 'pageheader' && substr($e, 0, 10) != 'pagefooter' && substr($e, 0, 12) != 'tocpagebreak' && substr($e, 0, 10) != 'indexentry' && substr($e, 0, 8) != 'tocentry') { // mPDF 6 (ZZZ99H) + $regexp = '| (\\w+?)=([^\\s>"]+)|si'; + $e = preg_replace($regexp, " \$1=\"\$2\"", $e); + } + + $e = preg_replace('/ (\\S+?)\s*=\s*"/i', " \\1=\"", $e); + + // Fix path values, if needed + $orig_srcpath = ''; + if ((stristr($e, "href=") !== false) or ( stristr($e, "src=") !== false)) { + $regexp = '/ (href|src)\s*=\s*"(.*?)"/i'; + preg_match($regexp, $e, $auxiliararray); + if (isset($auxiliararray[2])) { + $path = $auxiliararray[2]; + } else { + $path = ''; + } + if (trim($path) != '' && !(stristr($e, "src=") !== false && substr($path, 0, 4) == 'var:') && substr($path, 0, 1) != '@') { + $path = htmlspecialchars_decode($path); // mPDF 5.7.4 URLs + $orig_srcpath = $path; + $this->GetFullPath($path); + $regexp = '/ (href|src)="(.*?)"/i'; + $e = preg_replace($regexp, ' \\1="' . $path . '"', $e); + } + }//END of Fix path values + // Extract attributes + $contents = []; + $contents1 = []; + $contents2 = []; + // Changed to allow style="background: url('bg.jpg')" + // Changed to improve performance; maximum length of \S (attribute) = 16 + // Increase allowed attribute name to 32 - cutting off "toc-even-header-name" etc. + preg_match_all('/\\S{1,32}=["][^"]*["]/', $e, $contents1); + preg_match_all('/\\S{1,32}=[\'][^\']*[\']/i', $e, $contents2); + + $contents = array_merge($contents1, $contents2); + preg_match('/\\S+/', $e, $a2); + $tag = (isset($a2[0]) ? strtoupper($a2[0]) : ''); + $attr = []; + if ($orig_srcpath) { + $attr['ORIG_SRC'] = $orig_srcpath; + } + if (!empty($contents)) { + foreach ($contents[0] as $v) { + // Changed to allow style="background: url('bg.jpg')" + if (preg_match('/^([^=]*)=["]?([^"]*)["]?$/', $v, $a3) || preg_match('/^([^=]*)=[\']?([^\']*)[\']?$/', $v, $a3)) { + if (strtoupper($a3[1]) == 'ID' || strtoupper($a3[1]) == 'CLASS') { // 4.2.013 Omits STYLE + $attr[strtoupper($a3[1])] = trim(strtoupper($a3[2])); + } // includes header-style-right etc. used for + elseif (preg_match('/^(HEADER|FOOTER)-STYLE/i', $a3[1])) { + $attr[strtoupper($a3[1])] = trim(strtoupper($a3[2])); + } else { + $attr[strtoupper($a3[1])] = trim($a3[2]); + } + } + } + } + $this->tag->OpenTag($tag, $attr, $a, $i); // mPDF 6 + /* -- CSS-POSITION -- */ + if ($this->inFixedPosBlock) { + $this->fixedPosBlockBBox = [$tag, $attr, $this->x, $this->y]; + $this->fixedPosBlock = ''; + $this->fixedPosBlockDepth = 1; + } + /* -- END CSS-POSITION -- */ + if (preg_match('/\/$/', $e)) { + $this->tag->CloseTag($tag, $a, $i); + } + } + } // end TAG + } // end of foreach($a as $i=>$e) + + if ($close) { + // Close any open block tags + for ($b = $this->blklvl; $b > 0; $b--) { + $this->tag->CloseTag($this->blk[$b]['tag'], $a, $i); + } + + // Output any text left in buffer + if (count($this->textbuffer) && !$parseonly) { + $this->printbuffer($this->textbuffer); + } + if (!$parseonly) { + $this->textbuffer = []; + } + + /* -- CSS-FLOAT -- */ + // If ended with a float, need to move to end page + $currpos = $this->page * 1000 + $this->y; + if (isset($this->blk[$this->blklvl]['float_endpos']) && $this->blk[$this->blklvl]['float_endpos'] > $currpos) { + $old_page = $this->page; + $new_page = intval($this->blk[$this->blklvl]['float_endpos'] / 1000); + if ($old_page != $new_page) { + $s = $this->PrintPageBackgrounds(); + // Writes after the marker so not overwritten later by page background etc. + $this->pages[$this->page] = preg_replace('/(___BACKGROUND___PATTERNS' . $this->uniqstr . ')/', '\\1' . "\n" . $s . "\n", $this->pages[$this->page]); + $this->pageBackgrounds = []; + $this->page = $new_page; + $this->ResetMargins(); + $this->Reset(); + $this->pageoutput[$this->page] = []; + } + $this->y = (($this->blk[$this->blklvl]['float_endpos'] * 1000) % 1000000) / 1000; // mod changes operands to integers before processing + } + /* -- END CSS-FLOAT -- */ + + /* -- CSS-IMAGE-FLOAT -- */ + $this->printfloatbuffer(); + /* -- END CSS-IMAGE-FLOAT -- */ + + // Create Internal Links, if needed + if (!empty($this->internallink)) { + + foreach ($this->internallink as $k => $v) { + + if (strpos($k, "#") !== false) { + continue; + } + + if (!is_array($v)) { + continue; + } + + $ypos = $v['Y']; + $pagenum = $v['PAGE']; + $sharp = "#"; + + while (array_key_exists($sharp . $k, $this->internallink)) { + $internallink = $this->internallink[$sharp . $k]; + $this->SetLink($internallink, $ypos, $pagenum); + $sharp .= "#"; + } + } + } + + $this->bufferoutput = false; + + /* -- CSS-POSITION -- */ + if (count($this->fixedPosBlockSave)) { + foreach ($this->fixedPosBlockSave as $fpbs) { + $old_page = $this->page; + $this->page = $fpbs[2]; + $this->WriteFixedPosHTML($fpbs[0], 0, 0, 100, 100, 'auto', $fpbs[1]); // 0,0,10,10 are overwritten by bbox + $this->page = $old_page; + } + $this->fixedPosBlockSave = []; + } + /* -- END CSS-POSITION -- */ + } + } + + /* -- CSS-POSITION -- */ + + function WriteFixedPosHTML($html, $x, $y, $w, $h, $overflow = 'visible', $bounding = []) + { + // $overflow can be 'hidden', 'visible' or 'auto' - 'auto' causes autofit to size + // Annotations disabled - enabled in mPDF 5.0 + // Links do work + // Will always go on current page (or start Page 1 if required) + // Probably INCOMPATIBLE WITH keep with table, columns etc. + // Called externally or interally via
    + // When used internally, $x $y $w $h and $overflow are all overridden by $bounding + + $overflow = strtolower($overflow); + if ($this->state == 0) { + $this->AddPage($this->CurOrientation); + } + $save_y = $this->y; + $save_x = $this->x; + $this->fullImageHeight = $this->h; + $save_cols = false; + /* -- COLUMNS -- */ + if ($this->ColActive) { + $save_cols = true; + $save_nbcol = $this->NbCol; // other values of gap and vAlign will not change by setting Columns off + $this->SetColumns(0); + } + /* -- END COLUMNS -- */ + $save_annots = $this->title2annots; // *ANNOTATIONS* + $this->writingHTMLheader = true; // a FIX to stop pagebreaks etc. + $this->writingHTMLfooter = true; + $this->InFooter = true; // suppresses autopagebreaks + $save_bgs = $this->pageBackgrounds; + $checkinnerhtml = preg_replace('/\s/', '', $html); + $rotate = 0; + + if ($w > $this->w) { + $x = 0; + $w = $this->w; + } + if ($h > $this->h) { + $y = 0; + $h = $this->h; + } + if ($x > $this->w) { + $x = $this->w - $w; + } + if ($y > $this->h) { + $y = $this->h - $h; + } + + if (!empty($bounding)) { + // $cont_ containing block = full physical page (position: absolute) or page inside margins (position: fixed) + // $bbox_ Bounding box is the
    which is positioned absolutely/fixed + // top/left/right/bottom/width/height/background*/border*/padding*/margin* are taken from bounding + // font*[family/size/style/weight]/line-height/text*[align/decoration/transform/indent]/color are transferred to $inner + // as an enclosing
    (after having checked ID/CLASS) + // $x, $y, $w, $h are inside of $bbox_ = containing box for $inner_ + // $inner_ InnerHTML is the contents of that block to be output + $tag = $bounding[0]; + $attr = $bounding[1]; + $orig_x0 = $bounding[2]; + $orig_y0 = $bounding[3]; + + // As in WriteHTML() initialising + $this->blklvl = 0; + $this->lastblocklevelchange = 0; + $this->blk = []; + $this->initialiseBlock($this->blk[0]); + + $this->blk[0]['width'] = & $this->pgwidth; + $this->blk[0]['inner_width'] = & $this->pgwidth; + + $this->blk[0]['blockContext'] = $this->blockContext; + + $properties = $this->cssManager->MergeCSS('BLOCK', 'BODY', ''); + $this->setCSS($properties, '', 'BODY'); + $this->blklvl = 1; + $this->initialiseBlock($this->blk[1]); + $this->blk[1]['tag'] = $tag; + $this->blk[1]['attr'] = $attr; + $this->Reset(); + $p = $this->cssManager->MergeCSS('BLOCK', $tag, $attr); + if (isset($p['ROTATE']) && ($p['ROTATE'] == 90 || $p['ROTATE'] == -90 || $p['ROTATE'] == 180)) { + $rotate = $p['ROTATE']; + } // mPDF 6 + if (isset($p['OVERFLOW'])) { + $overflow = strtolower($p['OVERFLOW']); + } + if (strtolower($p['POSITION']) == 'fixed') { + $cont_w = $this->pgwidth; // $this->blk[0]['inner_width']; + $cont_h = $this->h - $this->tMargin - $this->bMargin; + $cont_x = $this->lMargin; + $cont_y = $this->tMargin; + } else { + $cont_w = $this->w; // ABSOLUTE; + $cont_h = $this->h; + $cont_x = 0; + $cont_y = 0; + } + + // Pass on in-line properties to the innerhtml + $css = ''; + if (isset($p['TEXT-ALIGN'])) { + $css .= 'text-align: ' . strtolower($p['TEXT-ALIGN']) . '; '; + } + if (isset($p['TEXT-TRANSFORM'])) { + $css .= 'text-transform: ' . strtolower($p['TEXT-TRANSFORM']) . '; '; + } + if (isset($p['TEXT-INDENT'])) { + $css .= 'text-indent: ' . strtolower($p['TEXT-INDENT']) . '; '; + } + if (isset($p['TEXT-DECORATION'])) { + $css .= 'text-decoration: ' . strtolower($p['TEXT-DECORATION']) . '; '; + } + if (isset($p['FONT-FAMILY'])) { + $css .= 'font-family: ' . strtolower($p['FONT-FAMILY']) . '; '; + } + if (isset($p['FONT-STYLE'])) { + $css .= 'font-style: ' . strtolower($p['FONT-STYLE']) . '; '; + } + if (isset($p['FONT-WEIGHT'])) { + $css .= 'font-weight: ' . strtolower($p['FONT-WEIGHT']) . '; '; + } + if (isset($p['FONT-SIZE'])) { + $css .= 'font-size: ' . strtolower($p['FONT-SIZE']) . '; '; + } + if (isset($p['LINE-HEIGHT'])) { + $css .= 'line-height: ' . strtolower($p['LINE-HEIGHT']) . '; '; + } + if (isset($p['TEXT-SHADOW'])) { + $css .= 'text-shadow: ' . strtolower($p['TEXT-SHADOW']) . '; '; + } + if (isset($p['LETTER-SPACING'])) { + $css .= 'letter-spacing: ' . strtolower($p['LETTER-SPACING']) . '; '; + } + // mPDF 6 + if (isset($p['FONT-VARIANT-POSITION'])) { + $css .= 'font-variant-position: ' . strtolower($p['FONT-VARIANT-POSITION']) . '; '; + } + if (isset($p['FONT-VARIANT-CAPS'])) { + $css .= 'font-variant-caps: ' . strtolower($p['FONT-VARIANT-CAPS']) . '; '; + } + if (isset($p['FONT-VARIANT-LIGATURES'])) { + $css .= 'font-variant-ligatures: ' . strtolower($p['FONT-VARIANT-LIGATURES']) . '; '; + } + if (isset($p['FONT-VARIANT-NUMERIC'])) { + $css .= 'font-variant-numeric: ' . strtolower($p['FONT-VARIANT-NUMERIC']) . '; '; + } + if (isset($p['FONT-VARIANT-ALTERNATES'])) { + $css .= 'font-variant-alternates: ' . strtolower($p['FONT-VARIANT-ALTERNATES']) . '; '; + } + if (isset($p['FONT-FEATURE-SETTINGS'])) { + $css .= 'font-feature-settings: ' . strtolower($p['FONT-FEATURE-SETTINGS']) . '; '; + } + if (isset($p['FONT-LANGUAGE-OVERRIDE'])) { + $css .= 'font-language-override: ' . strtolower($p['FONT-LANGUAGE-OVERRIDE']) . '; '; + } + if (isset($p['FONT-KERNING'])) { + $css .= 'font-kerning: ' . strtolower($p['FONT-KERNING']) . '; '; + } + + if (isset($p['COLOR'])) { + $css .= 'color: ' . strtolower($p['COLOR']) . '; '; + } + if (isset($p['Z-INDEX'])) { + $css .= 'z-index: ' . $p['Z-INDEX'] . '; '; + } + if ($css) { + $html = '
    ' . $html . '
    '; + } + // Copy over (only) the properties to set for border and background + $pb = []; + $pb['MARGIN-TOP'] = (isset($p['MARGIN-TOP']) ? $p['MARGIN-TOP'] : ''); + $pb['MARGIN-RIGHT'] = (isset($p['MARGIN-RIGHT']) ? $p['MARGIN-RIGHT'] : ''); + $pb['MARGIN-BOTTOM'] = (isset($p['MARGIN-BOTTOM']) ? $p['MARGIN-BOTTOM'] : ''); + $pb['MARGIN-LEFT'] = (isset($p['MARGIN-LEFT']) ? $p['MARGIN-LEFT'] : ''); + $pb['PADDING-TOP'] = (isset($p['PADDING-TOP']) ? $p['PADDING-TOP'] : ''); + $pb['PADDING-RIGHT'] = (isset($p['PADDING-RIGHT']) ? $p['PADDING-RIGHT'] : ''); + $pb['PADDING-BOTTOM'] = (isset($p['PADDING-BOTTOM']) ? $p['PADDING-BOTTOM'] : ''); + $pb['PADDING-LEFT'] = (isset($p['PADDING-LEFT']) ? $p['PADDING-LEFT'] : ''); + $pb['BORDER-TOP'] = (isset($p['BORDER-TOP']) ? $p['BORDER-TOP'] : ''); + $pb['BORDER-RIGHT'] = (isset($p['BORDER-RIGHT']) ? $p['BORDER-RIGHT'] : ''); + $pb['BORDER-BOTTOM'] = (isset($p['BORDER-BOTTOM']) ? $p['BORDER-BOTTOM'] : ''); + $pb['BORDER-LEFT'] = (isset($p['BORDER-LEFT']) ? $p['BORDER-LEFT'] : ''); + if (isset($p['BORDER-TOP-LEFT-RADIUS-H'])) { + $pb['BORDER-TOP-LEFT-RADIUS-H'] = $p['BORDER-TOP-LEFT-RADIUS-H']; + } + if (isset($p['BORDER-TOP-LEFT-RADIUS-V'])) { + $pb['BORDER-TOP-LEFT-RADIUS-V'] = $p['BORDER-TOP-LEFT-RADIUS-V']; + } + if (isset($p['BORDER-TOP-RIGHT-RADIUS-H'])) { + $pb['BORDER-TOP-RIGHT-RADIUS-H'] = $p['BORDER-TOP-RIGHT-RADIUS-H']; + } + if (isset($p['BORDER-TOP-RIGHT-RADIUS-V'])) { + $pb['BORDER-TOP-RIGHT-RADIUS-V'] = $p['BORDER-TOP-RIGHT-RADIUS-V']; + } + if (isset($p['BORDER-BOTTOM-LEFT-RADIUS-H'])) { + $pb['BORDER-BOTTOM-LEFT-RADIUS-H'] = $p['BORDER-BOTTOM-LEFT-RADIUS-H']; + } + if (isset($p['BORDER-BOTTOM-LEFT-RADIUS-V'])) { + $pb['BORDER-BOTTOM-LEFT-RADIUS-V'] = $p['BORDER-BOTTOM-LEFT-RADIUS-V']; + } + if (isset($p['BORDER-BOTTOM-RIGHT-RADIUS-H'])) { + $pb['BORDER-BOTTOM-RIGHT-RADIUS-H'] = $p['BORDER-BOTTOM-RIGHT-RADIUS-H']; + } + if (isset($p['BORDER-BOTTOM-RIGHT-RADIUS-V'])) { + $pb['BORDER-BOTTOM-RIGHT-RADIUS-V'] = $p['BORDER-BOTTOM-RIGHT-RADIUS-V']; + } + if (isset($p['BACKGROUND-COLOR'])) { + $pb['BACKGROUND-COLOR'] = $p['BACKGROUND-COLOR']; + } + if (isset($p['BOX-SHADOW'])) { + $pb['BOX-SHADOW'] = $p['BOX-SHADOW']; + } + /* -- BACKGROUNDS -- */ + if (isset($p['BACKGROUND-IMAGE'])) { + $pb['BACKGROUND-IMAGE'] = $p['BACKGROUND-IMAGE']; + } + if (isset($p['BACKGROUND-IMAGE-RESIZE'])) { + $pb['BACKGROUND-IMAGE-RESIZE'] = $p['BACKGROUND-IMAGE-RESIZE']; + } + if (isset($p['BACKGROUND-IMAGE-OPACITY'])) { + $pb['BACKGROUND-IMAGE-OPACITY'] = $p['BACKGROUND-IMAGE-OPACITY']; + } + if (isset($p['BACKGROUND-REPEAT'])) { + $pb['BACKGROUND-REPEAT'] = $p['BACKGROUND-REPEAT']; + } + if (isset($p['BACKGROUND-POSITION'])) { + $pb['BACKGROUND-POSITION'] = $p['BACKGROUND-POSITION']; + } + if (isset($p['BACKGROUND-GRADIENT'])) { + $pb['BACKGROUND-GRADIENT'] = $p['BACKGROUND-GRADIENT']; + } + if (isset($p['BACKGROUND-SIZE'])) { + $pb['BACKGROUND-SIZE'] = $p['BACKGROUND-SIZE']; + } + if (isset($p['BACKGROUND-ORIGIN'])) { + $pb['BACKGROUND-ORIGIN'] = $p['BACKGROUND-ORIGIN']; + } + if (isset($p['BACKGROUND-CLIP'])) { + $pb['BACKGROUND-CLIP'] = $p['BACKGROUND-CLIP']; + } + + /* -- END BACKGROUNDS -- */ + + $this->setCSS($pb, 'BLOCK', $tag); + + // ================================================================ + $bbox_br = $this->blk[1]['border_right']['w']; + $bbox_bl = $this->blk[1]['border_left']['w']; + $bbox_bt = $this->blk[1]['border_top']['w']; + $bbox_bb = $this->blk[1]['border_bottom']['w']; + $bbox_pr = $this->blk[1]['padding_right']; + $bbox_pl = $this->blk[1]['padding_left']; + $bbox_pt = $this->blk[1]['padding_top']; + $bbox_pb = $this->blk[1]['padding_bottom']; + $bbox_mr = $this->blk[1]['margin_right']; + if (isset($p['MARGIN-RIGHT']) && strtolower($p['MARGIN-RIGHT']) == 'auto') { + $bbox_mr = 'auto'; + } + $bbox_ml = $this->blk[1]['margin_left']; + if (isset($p['MARGIN-LEFT']) && strtolower($p['MARGIN-LEFT']) == 'auto') { + $bbox_ml = 'auto'; + } + $bbox_mt = $this->blk[1]['margin_top']; + if (isset($p['MARGIN-TOP']) && strtolower($p['MARGIN-TOP']) == 'auto') { + $bbox_mt = 'auto'; + } + $bbox_mb = $this->blk[1]['margin_bottom']; + if (isset($p['MARGIN-BOTTOM']) && strtolower($p['MARGIN-BOTTOM']) == 'auto') { + $bbox_mb = 'auto'; + } + if (isset($p['LEFT']) && strtolower($p['LEFT']) != 'auto') { + $bbox_left = $this->sizeConverter->convert($p['LEFT'], $cont_w, $this->FontSize, false); + } else { + $bbox_left = 'auto'; + } + if (isset($p['TOP']) && strtolower($p['TOP']) != 'auto') { + $bbox_top = $this->sizeConverter->convert($p['TOP'], $cont_h, $this->FontSize, false); + } else { + $bbox_top = 'auto'; + } + if (isset($p['RIGHT']) && strtolower($p['RIGHT']) != 'auto') { + $bbox_right = $this->sizeConverter->convert($p['RIGHT'], $cont_w, $this->FontSize, false); + } else { + $bbox_right = 'auto'; + } + if (isset($p['BOTTOM']) && strtolower($p['BOTTOM']) != 'auto') { + $bbox_bottom = $this->sizeConverter->convert($p['BOTTOM'], $cont_h, $this->FontSize, false); + } else { + $bbox_bottom = 'auto'; + } + if (isset($p['WIDTH']) && strtolower($p['WIDTH']) != 'auto') { + $inner_w = $this->sizeConverter->convert($p['WIDTH'], $cont_w, $this->FontSize, false); + } else { + $inner_w = 'auto'; + } + if (isset($p['HEIGHT']) && strtolower($p['HEIGHT']) != 'auto') { + $inner_h = $this->sizeConverter->convert($p['HEIGHT'], $cont_h, $this->FontSize, false); + } else { + $inner_h = 'auto'; + } + + // If bottom or right pos are set and not left / top - save this to adjust rotated block later + if ($rotate == 90 || $rotate == -90) { // mPDF 6 + if ($bbox_left === 'auto' && $bbox_right !== 'auto') { + $rot_rpos = $bbox_right; + } else { + $rot_rpos = false; + } + if ($bbox_top === 'auto' && $bbox_bottom !== 'auto') { + $rot_bpos = $bbox_bottom; + } else { + $rot_bpos = false; + } + } + + // ================================================================ + if ($checkinnerhtml == '' && $inner_h === 'auto') { + $inner_h = 0.0001; + } + if ($checkinnerhtml == '' && $inner_w === 'auto') { + $inner_w = 2 * $this->GetCharWidth('W', false); + } + // ================================================================ + // Algorithm from CSS2.1 See http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-height + // mPD 5.3.14 + // Special case (not CSS) if all not specified, centre vertically on page + $bbox_top_orig = ''; + if ($bbox_top === 'auto' && $inner_h === 'auto' && $bbox_bottom === 'auto' && $bbox_mt === 'auto' && $bbox_mb === 'auto') { + $bbox_top_orig = $bbox_top; + if ($bbox_mt === 'auto') { + $bbox_mt = 0; + } + if ($bbox_mb === 'auto') { + $bbox_mb = 0; + } + $bbox_top = $orig_y0 - $bbox_mt - $cont_y; + // solve for $bbox_bottom when content_h known - $inner_h=='auto' && $bbox_bottom=='auto' + } // mPD 5.3.14 + elseif ($bbox_top === 'auto' && $inner_h === 'auto' && $bbox_bottom === 'auto') { + $bbox_top_orig = $bbox_top = $orig_y0 - $cont_y; + if ($bbox_mt === 'auto') { + $bbox_mt = 0; + } + if ($bbox_mb === 'auto') { + $bbox_mb = 0; + } + // solve for $bbox_bottom when content_h known - $inner_h=='auto' && $bbox_bottom=='auto' + } elseif ($bbox_top !== 'auto' && $inner_h !== 'auto' && $bbox_bottom !== 'auto') { + if ($bbox_mt === 'auto' && $bbox_mb === 'auto') { + $x = $cont_h - $bbox_top - $bbox_bt - $bbox_pt - $inner_h - $bbox_pb - $bbox_bb - $bbox_bottom; + $bbox_mt = $bbox_mb = ($x / 2); + } elseif ($bbox_mt === 'auto') { + $bbox_mt = $cont_h - $bbox_top - $bbox_bt - $bbox_pt - $inner_h - $bbox_pb - $bbox_bb - $bbox_mb - $bbox_bottom; + } elseif ($bbox_mb === 'auto') { + $bbox_mb = $cont_h - $bbox_top - $bbox_mt - $bbox_bt - $bbox_pt - $inner_h - $bbox_pb - $bbox_bb - $bbox_bottom; + } else { + $bbox_bottom = $cont_h - $bbox_top - $bbox_mt - $bbox_bt - $bbox_pt - $inner_h - $bbox_pb - $bbox_bb - $bbox_mt; + } + } else { + if ($bbox_mt === 'auto') { + $bbox_mt = 0; + } + if ($bbox_mb === 'auto') { + $bbox_mb = 0; + } + if ($bbox_top === 'auto' && $inner_h === 'auto' && $bbox_bottom !== 'auto') { + // solve for $bbox_top when content_h known - $inner_h=='auto' && $bbox_top =='auto' + } elseif ($bbox_top === 'auto' && $bbox_bottom === 'auto' && $inner_h !== 'auto') { + $bbox_top = $orig_y0 - $bbox_mt - $cont_y; + $bbox_bottom = $cont_h - $bbox_top - $bbox_mt - $bbox_bt - $bbox_pt - $inner_h - $bbox_pb - $bbox_bb - $bbox_mt; + } elseif ($inner_h === 'auto' && $bbox_bottom === 'auto' && $bbox_top !== 'auto') { + // solve for $bbox_bottom when content_h known - $inner_h=='auto' && $bbox_bottom=='auto' + } elseif ($bbox_top === 'auto' && $inner_h !== 'auto' && $bbox_bottom !== 'auto') { + $bbox_top = $cont_h - $bbox_mt - $bbox_bt - $bbox_pt - $inner_h - $bbox_pb - $bbox_bb - $bbox_mt - $bbox_bottom; + } elseif ($inner_h === 'auto' && $bbox_top !== 'auto' && $bbox_bottom !== 'auto') { + $inner_h = $cont_h - $bbox_top - $bbox_mt - $bbox_bt - $bbox_pt - $bbox_pb - $bbox_bb - $bbox_mt - $bbox_bottom; + } elseif ($bbox_bottom === 'auto' && $bbox_top !== 'auto' && $inner_h !== 'auto') { + $bbox_bottom = $cont_h - $bbox_top - $bbox_mt - $bbox_bt - $bbox_pt - $inner_h - $bbox_pb - $bbox_bb - $bbox_mt; + } + } + + // THEN DO SAME FOR WIDTH + // http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width + if ($bbox_left === 'auto' && $inner_w === 'auto' && $bbox_right === 'auto') { + if ($bbox_ml === 'auto') { + $bbox_ml = 0; + } + if ($bbox_mr === 'auto') { + $bbox_mr = 0; + } + // IF containing element RTL, should set $bbox_right + $bbox_left = $orig_x0 - $bbox_ml - $cont_x; + // solve for $bbox_right when content_w known - $inner_w=='auto' && $bbox_right=='auto' + } elseif ($bbox_left !== 'auto' && $inner_w !== 'auto' && $bbox_right !== 'auto') { + if ($bbox_ml === 'auto' && $bbox_mr === 'auto') { + $x = $cont_w - $bbox_left - $bbox_bl - $bbox_pl - $inner_w - $bbox_pr - $bbox_br - $bbox_right; + $bbox_ml = $bbox_mr = ($x / 2); + } elseif ($bbox_ml === 'auto') { + $bbox_ml = $cont_w - $bbox_left - $bbox_bl - $bbox_pl - $inner_w - $bbox_pr - $bbox_br - $bbox_mr - $bbox_right; + } elseif ($bbox_mr === 'auto') { + $bbox_mr = $cont_w - $bbox_left - $bbox_ml - $bbox_bl - $bbox_pl - $inner_w - $bbox_pr - $bbox_br - $bbox_right; + } else { + $bbox_right = $cont_w - $bbox_left - $bbox_ml - $bbox_bl - $bbox_pl - $inner_w - $bbox_pr - $bbox_br - $bbox_ml; + } + } else { + if ($bbox_ml === 'auto') { + $bbox_ml = 0; + } + if ($bbox_mr === 'auto') { + $bbox_mr = 0; + } + if ($bbox_left === 'auto' && $inner_w === 'auto' && $bbox_right !== 'auto') { + // solve for $bbox_left when content_w known - $inner_w=='auto' && $bbox_left =='auto' + } elseif ($bbox_left === 'auto' && $bbox_right === 'auto' && $inner_w !== 'auto') { + // IF containing element RTL, should set $bbox_right + $bbox_left = $orig_x0 - $bbox_ml - $cont_x; + $bbox_right = $cont_w - $bbox_left - $bbox_ml - $bbox_bl - $bbox_pl - $inner_w - $bbox_pr - $bbox_br - $bbox_ml; + } elseif ($inner_w === 'auto' && $bbox_right === 'auto' && $bbox_left !== 'auto') { + // solve for $bbox_right when content_w known - $inner_w=='auto' && $bbox_right=='auto' + } elseif ($bbox_left === 'auto' && $inner_w !== 'auto' && $bbox_right !== 'auto') { + $bbox_left = $cont_w - $bbox_ml - $bbox_bl - $bbox_pl - $inner_w - $bbox_pr - $bbox_br - $bbox_ml - $bbox_right; + } elseif ($inner_w === 'auto' && $bbox_left !== 'auto' && $bbox_right !== 'auto') { + $inner_w = $cont_w - $bbox_left - $bbox_ml - $bbox_bl - $bbox_pl - $bbox_pr - $bbox_br - $bbox_ml - $bbox_right; + } elseif ($bbox_right === 'auto' && $bbox_left !== 'auto' && $inner_w !== 'auto') { + $bbox_right = $cont_w - $bbox_left - $bbox_ml - $bbox_bl - $bbox_pl - $inner_w - $bbox_pr - $bbox_br - $bbox_ml; + } + } + + // ================================================================ + // ================================================================ + /* -- BACKGROUNDS -- */ + if (isset($pb['BACKGROUND-IMAGE']) && $pb['BACKGROUND-IMAGE']) { + $ret = $this->SetBackground($pb, $this->blk[1]['inner_width']); + if ($ret) { + $this->blk[1]['background-image'] = $ret; + } + } + /* -- END BACKGROUNDS -- */ + + $bbox_top_auto = $bbox_top === 'auto'; + $bbox_left_auto = $bbox_left === 'auto'; + $bbox_right_auto = $bbox_right === 'auto'; + $bbox_bottom_auto = $bbox_bottom === 'auto'; + + $bbox_top = is_numeric($bbox_top) ? $bbox_top : 0; + $bbox_left = is_numeric($bbox_left) ? $bbox_left : 0; + $bbox_right = is_numeric($bbox_right) ? $bbox_right : 0; + $bbox_bottom = is_numeric($bbox_bottom) ? $bbox_bottom : 0; + + $y = $cont_y + $bbox_top + $bbox_mt + $bbox_bt + $bbox_pt; + $h = $cont_h - $bbox_top - $bbox_mt - $bbox_bt - $bbox_pt - $bbox_pb - $bbox_bb - $bbox_mb - $bbox_bottom; + + $x = $cont_x + $bbox_left + $bbox_ml + $bbox_bl + $bbox_pl; + $w = $cont_w - $bbox_left - $bbox_ml - $bbox_bl - $bbox_pl - $bbox_pr - $bbox_br - $bbox_mr - $bbox_right; + + // Set (temporary) values for x y w h to do first paint, if values are auto + if ($inner_h === 'auto' && $bbox_top_auto) { + $y = $cont_y + $bbox_mt + $bbox_bt + $bbox_pt; + $h = $cont_h - ($bbox_bottom + $bbox_mt + $bbox_mb + $bbox_bt + $bbox_bb + $bbox_pt + $bbox_pb); + } elseif ($inner_h === 'auto' && $bbox_bottom_auto) { + $y = $cont_y + $bbox_top + $bbox_mt + $bbox_bt + $bbox_pt; + $h = $cont_h - ($bbox_top + $bbox_mt + $bbox_mb + $bbox_bt + $bbox_bb + $bbox_pt + $bbox_pb); + } + if ($inner_w === 'auto' && $bbox_left_auto) { + $x = $cont_x + $bbox_ml + $bbox_bl + $bbox_pl; + $w = $cont_w - ($bbox_right + $bbox_ml + $bbox_mr + $bbox_bl + $bbox_br + $bbox_pl + $bbox_pr); + } elseif ($inner_w === 'auto' && $bbox_right_auto) { + $x = $cont_x + $bbox_left + $bbox_ml + $bbox_bl + $bbox_pl; + $w = $cont_w - ($bbox_left + $bbox_ml + $bbox_mr + $bbox_bl + $bbox_br + $bbox_pl + $bbox_pr); + } + + $bbox_y = $cont_y + $bbox_top + $bbox_mt; + $bbox_x = $cont_x + $bbox_left + $bbox_ml; + + $saved_block1 = $this->blk[1]; + + unset($p); + unset($pb); + + // ================================================================ + if ($inner_w === 'auto') { // do a first write + $this->lMargin = $x; + $this->rMargin = $this->w - $w - $x; + + // SET POSITION & FONT VALUES + $this->pgwidth = $this->w - $this->lMargin - $this->rMargin; + $this->pageoutput[$this->page] = []; + $this->x = $x; + $this->y = $y; + $this->HTMLheaderPageLinks = []; + $this->HTMLheaderPageAnnots = []; + $this->HTMLheaderPageForms = []; + $this->pageBackgrounds = []; + $this->maxPosR = 0; + $this->maxPosL = $this->w; // For RTL + $this->WriteHTML($html, HTMLParserMode::HTML_HEADER_BUFFER); + $inner_w = $this->maxPosR - $this->lMargin; + if ($bbox_right_auto) { + $bbox_right = $cont_w - $bbox_left - $bbox_ml - $bbox_bl - $bbox_pl - $inner_w - $bbox_pr - $bbox_br - $bbox_ml; + } elseif ($bbox_left_auto) { + $bbox_left = $cont_w - $bbox_ml - $bbox_bl - $bbox_pl - $inner_w - $bbox_pr - $bbox_br - $bbox_ml - $bbox_right; + $bbox_x = $cont_x + $bbox_left + $bbox_ml; + $inner_x = $bbox_x + $bbox_bl + $bbox_pl; + $x = $inner_x; + } + + $w = $inner_w; + $bbox_y = $cont_y + $bbox_top + $bbox_mt; + $bbox_x = $cont_x + $bbox_left + $bbox_ml; + } + + if ($inner_h === 'auto') { // do a first write + + $this->lMargin = $x; + $this->rMargin = $this->w - $w - $x; + + // SET POSITION & FONT VALUES + $this->pgwidth = $this->w - $this->lMargin - $this->rMargin; + $this->pageoutput[$this->page] = []; + $this->x = $x; + $this->y = $y; + $this->HTMLheaderPageLinks = []; + $this->HTMLheaderPageAnnots = []; + $this->HTMLheaderPageForms = []; + $this->pageBackgrounds = []; + $this->WriteHTML($html, HTMLParserMode::HTML_HEADER_BUFFER); + $inner_h = $this->y - $y; + + if ($overflow != 'hidden' && $overflow != 'visible') { // constrained + if (($this->y + $bbox_pb + $bbox_bb) > ($cont_y + $cont_h)) { + $adj = ($this->y + $bbox_pb + $bbox_bb) - ($cont_y + $cont_h); + $inner_h -= $adj; + } + } + if ($bbox_bottom_auto && $bbox_top_orig === 'auto') { + $bbox_bottom = $bbox_top = ($cont_h - $bbox_mt - $bbox_bt - $bbox_pt - $inner_h - $bbox_pb - $bbox_bb - $bbox_mb) / 2; + if ($overflow != 'hidden' && $overflow != 'visible') { // constrained + if ($bbox_top < 0) { + $bbox_top = 0; + $inner_h = $cont_h - $bbox_top - $bbox_mt - $bbox_bt - $bbox_pt - $bbox_pb - $bbox_bb - $bbox_mb - $bbox_bottom; + } + } + $bbox_y = $cont_y + $bbox_top + $bbox_mt; + $inner_y = $bbox_y + $bbox_bt + $bbox_pt; + $y = $inner_y; + } elseif ($bbox_bottom_auto) { + $bbox_bottom = $cont_h - $bbox_top - $bbox_mt - $bbox_bt - $bbox_pt - $inner_h - $bbox_pb - $bbox_bb - $bbox_mb; + } elseif ($bbox_top_auto) { + $bbox_top = $cont_h - $bbox_mt - $bbox_bt - $bbox_pt - $inner_h - $bbox_pb - $bbox_bb - $bbox_mb - $bbox_bottom; + if ($overflow != 'hidden' && $overflow != 'visible') { // constrained + if ($bbox_top < 0) { + $bbox_top = 0; + $inner_h = $cont_h - $bbox_top - $bbox_mt - $bbox_bt - $bbox_pt - $bbox_pb - $bbox_bb - $bbox_mb - $bbox_bottom; + } + } + $bbox_y = $cont_y + $bbox_top + $bbox_mt; + $inner_y = $bbox_y + $bbox_bt + $bbox_pt; + $y = $inner_y; + } + $h = $inner_h; + $bbox_y = $cont_y + $bbox_top + $bbox_mt; + $bbox_x = $cont_x + $bbox_left + $bbox_ml; + } + + $inner_w = $w; + $inner_h = $h; + } + + $this->lMargin = $x; + $this->rMargin = $this->w - $w - $x; + + // SET POSITION & FONT VALUES + $this->pgwidth = $this->w - $this->lMargin - $this->rMargin; + $this->pageoutput[$this->page] = []; + + $this->x = $x; + $this->y = $y; + + $this->HTMLheaderPageLinks = []; + $this->HTMLheaderPageAnnots = []; + $this->HTMLheaderPageForms = []; + + $this->pageBackgrounds = []; + + $this->WriteHTML($html, HTMLParserMode::HTML_HEADER_BUFFER); + + $actual_h = $this->y - $y; + $use_w = $w; + $use_h = $h; + $ratio = $actual_h / $use_w; + + if ($overflow != 'hidden' && $overflow != 'visible') { + $target = $h / $w; + if ($target > 0) { + if (($ratio / $target) > 1) { + $nl = ceil($actual_h / $this->lineheight); + $l = $use_w * $nl; + $est_w = sqrt(($l * $this->lineheight) / $target) * 0.8; + $use_w += ($est_w - $use_w) - ($w / 100); + } + $bpcstart = ($ratio / $target); + $bpcctr = 1; + + while (($ratio / $target) > 1) { + // @log 'Auto-sizing fixed-position block $bpcctr++ + + $this->x = $x; + $this->y = $y; + + if (($ratio / $target) > 1.5 || ($ratio / $target) < 0.6) { + $use_w += ($w / $this->incrementFPR1); + } elseif (($ratio / $target) > 1.2 || ($ratio / $target) < 0.85) { + $use_w += ($w / $this->incrementFPR2); + } elseif (($ratio / $target) > 1.1 || ($ratio / $target) < 0.91) { + $use_w += ($w / $this->incrementFPR3); + } else { + $use_w += ($w / $this->incrementFPR4); + } + + $use_h = $use_w * $target; + $this->rMargin = $this->w - $use_w - $x; + $this->pgwidth = $this->w - $this->lMargin - $this->rMargin; + $this->HTMLheaderPageLinks = []; + $this->HTMLheaderPageAnnots = []; + $this->HTMLheaderPageForms = []; + $this->pageBackgrounds = []; + $this->WriteHTML($html, HTMLParserMode::HTML_HEADER_BUFFER); + $actual_h = $this->y - $y; + $ratio = $actual_h / $use_w; + } + } + } + + $shrink_f = $w / $use_w; + + // ================================================================ + + $this->pages[$this->page] .= '___BEFORE_BORDERS___'; + $block_s = $this->PrintPageBackgrounds(); // Save to print later inside clipping path + $this->pageBackgrounds = []; + + // ================================================================ + + if ($rotate == 90 || $rotate == -90) { // mPDF 6 + $prerotw = $bbox_bl + $bbox_pl + $inner_w + $bbox_pr + $bbox_br; + $preroth = $bbox_bt + $bbox_pt + $inner_h + $bbox_pb + $bbox_bb; + $rot_start = " q\n"; + if ($rotate == 90) { + if ($rot_rpos !== false) { + $adjw = $prerotw; + } // width before rotation + else { + $adjw = $preroth; + } // height before rotation + if ($rot_bpos !== false) { + $adjh = -$prerotw + $preroth; + } else { + $adjh = 0; + } + } else { + if ($rot_rpos !== false) { + $adjw = $prerotw - $preroth; + } else { + $adjw = 0; + } + if ($rot_bpos !== false) { + $adjh = $preroth; + } // height before rotation + else { + $adjh = $prerotw; + } // width before rotation + } + $rot_start .= $this->transformTranslate($adjw, $adjh, true) . "\n"; + $rot_start .= $this->transformRotate($rotate, $bbox_x, $bbox_y, true) . "\n"; + $rot_end = " Q\n"; + } elseif ($rotate == 180) { // mPDF 6 + $rot_start = " q\n"; + $rot_start .= $this->transformTranslate($bbox_bl + $bbox_pl + $inner_w + $bbox_pr + $bbox_br, $bbox_bt + $bbox_pt + $inner_h + $bbox_pb + $bbox_bb, true) . "\n"; + $rot_start .= $this->transformRotate(180, $bbox_x, $bbox_y, true) . "\n"; + $rot_end = " Q\n"; + } else { + $rot_start = ''; + $rot_end = ''; + } + + // ================================================================ + if (!empty($bounding)) { + // WHEN HEIGHT // BOTTOM EDGE IS KNOWN and $this->y is set to the bottom + // Re-instate saved $this->blk[1] + $this->blk[1] = $saved_block1; + + // These are only needed when painting border/background + $this->blk[1]['width'] = $bbox_w = $cont_w - $bbox_left - $bbox_ml - $bbox_mr - $bbox_right; + $this->blk[1]['x0'] = $bbox_x; + $this->blk[1]['y0'] = $bbox_y; + $this->blk[1]['startpage'] = $this->page; + $this->blk[1]['y1'] = $bbox_y + $bbox_bt + $bbox_pt + $inner_h + $bbox_pb + $bbox_bb; + $this->writer->write($rot_start); + $this->PaintDivBB('', 0, 1); // Prints borders and sets backgrounds in $this->pageBackgrounds + $this->writer->write($rot_end); + } + + $s = $this->PrintPageBackgrounds(); + $s = $rot_start . $s . $rot_end; + $this->pages[$this->page] = preg_replace('/___BEFORE_BORDERS___/', "\n" . $s . "\n", $this->pages[$this->page]); + $this->pageBackgrounds = []; + + $this->writer->write($rot_start); + + // Clipping Output + if ($overflow == 'hidden') { + // Bounding rectangle to clip + $clip_y1 = $this->y; + if (!empty($bounding) && ($this->y + $bbox_pb + $bbox_bb) > ($bbox_y + $bbox_bt + $bbox_pt + $inner_h + $bbox_pb + $bbox_bb )) { + $clip_y1 = ($bbox_y + $bbox_bt + $bbox_pt + $inner_h + $bbox_pb + $bbox_bb ) - ($bbox_pb + $bbox_bb); + } + // $op = 'W* n'; // Clipping + $op = 'W n'; // Clipping alternative mode + $this->writer->write("q"); + $ch = $clip_y1 - $y; + $this->writer->write(sprintf('%.3F %.3F %.3F %.3F re %s', $x * Mpdf::SCALE, ($this->h - $y) * Mpdf::SCALE, $w * Mpdf::SCALE, -$ch * Mpdf::SCALE, $op)); + if (!empty($block_s)) { + $tmp = "q\n" . sprintf('%.3F %.3F %.3F %.3F re %s', $x * Mpdf::SCALE, ($this->h - $y) * Mpdf::SCALE, $w * Mpdf::SCALE, -$ch * Mpdf::SCALE, $op); + $tmp .= "\n" . $block_s . "\nQ"; + $block_s = $tmp; + } + } + + + if (!empty($block_s)) { + if ($shrink_f != 1) { // i.e. autofit has resized the box + $tmp = "q\n" . $this->transformScale(($shrink_f * 100), ($shrink_f * 100), $x, $y, true); + $tmp .= "\n" . $block_s . "\nQ"; + $block_s = $tmp; + } + $this->writer->write($block_s); + } + + + + if ($shrink_f != 1) { // i.e. autofit has resized the box + $this->StartTransform(); + $this->transformScale(($shrink_f * 100), ($shrink_f * 100), $x, $y); + } + + $this->writer->write($this->headerbuffer); + + if ($shrink_f != 1) { // i.e. autofit has resized the box + $this->StopTransform(); + } + + if ($overflow == 'hidden') { + // End clipping + $this->writer->write("Q"); + } + + $this->writer->write($rot_end); + + + // Page Links + foreach ($this->HTMLheaderPageLinks as $lk) { + if ($rotate) { + $tmp = $lk[2]; // Switch h - w + $lk[2] = $lk[3]; + $lk[3] = $tmp; + + $lx1 = (($lk[0] / Mpdf::SCALE)); + $ly1 = (($this->h - ($lk[1] / Mpdf::SCALE))); + if ($rotate == 90) { + $adjx = -($lx1 - $bbox_x) + ($preroth - ($ly1 - $bbox_y)); + $adjy = -($ly1 - $bbox_y) + ($lx1 - $bbox_x); + $lk[2] = -$lk[2]; + } elseif ($rotate == -90) { + $adjx = -($lx1 - $bbox_x) + ($ly1 - $bbox_y); + $adjy = -($ly1 - $bbox_y) - ($lx1 - $bbox_x) + $prerotw; + $lk[3] = -$lk[3]; + } + if ($rot_rpos !== false) { + $adjx += $prerotw - $preroth; + } + if ($rot_bpos !== false) { + $adjy += $preroth - $prerotw; + } + $lx1 += $adjx; + $ly1 += $adjy; + + $lk[0] = $lx1 * Mpdf::SCALE; + $lk[1] = ($this->h - $ly1) * Mpdf::SCALE; + } + if ($shrink_f != 1) { // i.e. autofit has resized the box + $lx1 = (($lk[0] / Mpdf::SCALE) - $x); + $lx2 = $x + ($lx1 * $shrink_f); + $lk[0] = $lx2 * Mpdf::SCALE; + $ly1 = (($this->h - ($lk[1] / Mpdf::SCALE)) - $y); + $ly2 = $y + ($ly1 * $shrink_f); + $lk[1] = ($this->h - $ly2) * Mpdf::SCALE; + $lk[2] *= $shrink_f; // width + $lk[3] *= $shrink_f; // height + } + $this->PageLinks[$this->page][] = $lk; + } + + foreach ($this->HTMLheaderPageForms as $n => $f) { + if ($shrink_f != 1) { // i.e. autofit has resized the box + $f['x'] = $x + (($f['x'] - $x) * $shrink_f); + $f['y'] = $y + (($f['y'] - $y) * $shrink_f); + $f['w'] *= $shrink_f; + $f['h'] *= $shrink_f; + $f['style']['fontsize'] *= $shrink_f; + } + $this->form->forms[$f['n']] = $f; + } + // Page Annotations + foreach ($this->HTMLheaderPageAnnots as $lk) { + if ($rotate) { + if ($rotate == 90) { + $adjx = -($lk['x'] - $bbox_x) + ($preroth - ($lk['y'] - $bbox_y)); + $adjy = -($lk['y'] - $bbox_y) + ($lk['x'] - $bbox_x); + } elseif ($rotate == -90) { + $adjx = -($lk['x'] - $bbox_x) + ($lk['y'] - $bbox_y); + $adjy = -($lk['y'] - $bbox_y) - ($lk['x'] - $bbox_x) + $prerotw; + } + if ($rot_rpos !== false) { + $adjx += $prerotw - $preroth; + } + if ($rot_bpos !== false) { + $adjy += $preroth - $prerotw; + } + $lk['x'] += $adjx; + $lk['y'] += $adjy; + } + if ($shrink_f != 1) { // i.e. autofit has resized the box + $lk['x'] = $x + (($lk['x'] - $x) * $shrink_f); + $lk['y'] = $y + (($lk['y'] - $y) * $shrink_f); + } + $this->PageAnnots[$this->page][] = $lk; + } + + // Restore + $this->headerbuffer = ''; + $this->HTMLheaderPageLinks = []; + $this->HTMLheaderPageAnnots = []; + $this->HTMLheaderPageForms = []; + $this->pageBackgrounds = $save_bgs; + $this->writingHTMLheader = false; + + $this->writingHTMLfooter = false; + $this->fullImageHeight = false; + $this->ResetMargins(); + $this->pgwidth = $this->w - $this->lMargin - $this->rMargin; + $this->SetXY($save_x, $save_y); + $this->title2annots = $save_annots; // *ANNOTATIONS* + $this->InFooter = false; // turns back on autopagebreaks + $this->pageoutput[$this->page] = []; + $this->pageoutput[$this->page]['Font'] = ''; + /* -- COLUMNS -- */ + if ($save_cols) { + $this->SetColumns($save_nbcol, $this->colvAlign, $this->ColGap); + } + /* -- END COLUMNS -- */ + } + + /* -- END CSS-POSITION -- */ + + function initialiseBlock(&$blk) + { + $blk['margin_top'] = 0; + $blk['margin_left'] = 0; + $blk['margin_bottom'] = 0; + $blk['margin_right'] = 0; + $blk['padding_top'] = 0; + $blk['padding_left'] = 0; + $blk['padding_bottom'] = 0; + $blk['padding_right'] = 0; + $blk['border_top']['w'] = 0; + $blk['border_left']['w'] = 0; + $blk['border_bottom']['w'] = 0; + $blk['border_right']['w'] = 0; + $blk['direction'] = 'ltr'; + $blk['hide'] = false; + $blk['outer_left_margin'] = 0; + $blk['outer_right_margin'] = 0; + $blk['cascadeCSS'] = []; + $blk['block-align'] = false; + $blk['bgcolor'] = false; + $blk['page_break_after_avoid'] = false; + $blk['keep_block_together'] = false; + $blk['float'] = false; + $blk['line_height'] = ''; + $blk['margin_collapse'] = false; + } + + function border_details($bd) + { + $prop = preg_split('/\s+/', trim($bd)); + + if (isset($this->blk[$this->blklvl]['inner_width'])) { + $refw = $this->blk[$this->blklvl]['inner_width']; + } elseif (isset($this->blk[$this->blklvl - 1]['inner_width'])) { + $refw = $this->blk[$this->blklvl - 1]['inner_width']; + } else { + $refw = $this->w; + } + if (count($prop) == 1) { + $bsize = $this->sizeConverter->convert($prop[0], $refw, $this->FontSize, false); + if ($bsize > 0) { + return ['s' => 1, 'w' => $bsize, 'c' => $this->colorConverter->convert(0, $this->PDFAXwarnings), 'style' => 'solid']; + } else { + return ['w' => 0, 's' => 0]; + } + } elseif (count($prop) == 2) { + // 1px solid + if (in_array($prop[1], $this->borderstyles) || $prop[1] == 'none' || $prop[1] == 'hidden') { + $prop[2] = ''; + } // solid #000000 + elseif (in_array($prop[0], $this->borderstyles) || $prop[0] == 'none' || $prop[0] == 'hidden') { + $prop[0] = ''; + $prop[1] = $prop[0]; + $prop[2] = $prop[1]; + } // 1px #000000 + else { + $prop[1] = ''; + $prop[2] = $prop[1]; + } + } elseif (count($prop) == 3) { + // Change #000000 1px solid to 1px solid #000000 (proper) + if (substr($prop[0], 0, 1) == '#') { + $tmp = $prop[0]; + $prop[0] = $prop[1]; + $prop[1] = $prop[2]; + $prop[2] = $tmp; + } // Change solid #000000 1px to 1px solid #000000 (proper) + elseif (substr($prop[0], 1, 1) == '#') { + $tmp = $prop[1]; + $prop[0] = $prop[2]; + $prop[1] = $prop[0]; + $prop[2] = $tmp; + } // Change solid 1px #000000 to 1px solid #000000 (proper) + elseif (in_array($prop[0], $this->borderstyles) || $prop[0] == 'none' || $prop[0] == 'hidden') { + $tmp = $prop[0]; + $prop[0] = $prop[1]; + $prop[1] = $tmp; + } + } else { + return []; + } + // Size + $bsize = $this->sizeConverter->convert($prop[0], $refw, $this->FontSize, false); + // color + $coul = $this->colorConverter->convert($prop[2], $this->PDFAXwarnings); // returns array + // Style + $prop[1] = strtolower($prop[1]); + if (in_array($prop[1], $this->borderstyles) && $bsize > 0) { + $on = 1; + } elseif ($prop[1] == 'hidden') { + $on = 1; + $bsize = 0; + $coul = ''; + } elseif ($prop[1] == 'none') { + $on = 0; + $bsize = 0; + $coul = ''; + } else { + $on = 0; + $bsize = 0; + $coul = ''; + $prop[1] = ''; + } + return ['s' => $on, 'w' => $bsize, 'c' => $coul, 'style' => $prop[1], 'dom' => 0]; + } + + /* -- END HTML-CSS -- */ + + + /* -- BORDER-RADIUS -- */ + + function _borderPadding($a, $b, &$px, &$py) + { + // $px and py are padding long axis (x) and short axis (y) + $added = 0; // extra padding + + $x = $a - $px; + $y = $b - $py; + // Check if Falls within ellipse of border radius + if (( (($x + $added) * ($x + $added)) / ($a * $a) + (($y + $added) * ($y + $added)) / ($b * $b) ) <= 1) { + return false; + } + + $t = atan2($y, $x); + + $newx = $b / sqrt((($b * $b) / ($a * $a)) + ( tan($t) * tan($t) )); + $newy = $a / sqrt((($a * $a) / ($b * $b)) + ( (1 / tan($t)) * (1 / tan($t)) )); + $px = max($px, $a - $newx + $added); + $py = max($py, $b - $newy + $added); + } + + /* -- END BORDER-RADIUS -- */ + /* -- HTML-CSS -- */ + /* -- CSS-PAGE -- */ + + function SetPagedMediaCSS($name, $first, $oddEven) + { + if ($oddEven == 'E') { + if ($this->directionality == 'rtl') { + $side = 'R'; + } else { + $side = 'L'; + } + } else { + if ($this->directionality == 'rtl') { + $side = 'L'; + } else { + $side = 'R'; + } + } + $name = strtoupper($name); + $p = []; + $p['SIZE'] = 'AUTO'; + + // Uses mPDF original margins as default + $p['MARGIN-RIGHT'] = strval($this->orig_rMargin) . 'mm'; + $p['MARGIN-LEFT'] = strval($this->orig_lMargin) . 'mm'; + $p['MARGIN-TOP'] = strval($this->orig_tMargin) . 'mm'; + $p['MARGIN-BOTTOM'] = strval($this->orig_bMargin) . 'mm'; + $p['MARGIN-HEADER'] = strval($this->orig_hMargin) . 'mm'; + $p['MARGIN-FOOTER'] = strval($this->orig_fMargin) . 'mm'; + + // Basic page + selector + if (isset($this->cssManager->CSS['@PAGE'])) { + $zp = $this->cssManager->CSS['@PAGE']; + } else { + $zp = []; + } + if (is_array($zp) && !empty($zp)) { + $p = array_merge($p, $zp); + } + + if (isset($p['EVEN-HEADER-NAME']) && $oddEven == 'E') { + $p['HEADER'] = $p['EVEN-HEADER-NAME']; + unset($p['EVEN-HEADER-NAME']); + } + if (isset($p['ODD-HEADER-NAME']) && $oddEven != 'E') { + $p['HEADER'] = $p['ODD-HEADER-NAME']; + unset($p['ODD-HEADER-NAME']); + } + if (isset($p['EVEN-FOOTER-NAME']) && $oddEven == 'E') { + $p['FOOTER'] = $p['EVEN-FOOTER-NAME']; + unset($p['EVEN-FOOTER-NAME']); + } + if (isset($p['ODD-FOOTER-NAME']) && $oddEven != 'E') { + $p['FOOTER'] = $p['ODD-FOOTER-NAME']; + unset($p['ODD-FOOTER-NAME']); + } + + // If right/Odd page + if (isset($this->cssManager->CSS['@PAGE>>PSEUDO>>RIGHT']) && $side == 'R') { + $zp = $this->cssManager->CSS['@PAGE>>PSEUDO>>RIGHT']; + } else { + $zp = []; + } + if (isset($zp['SIZE'])) { + unset($zp['SIZE']); + } + if (isset($zp['SHEET-SIZE'])) { + unset($zp['SHEET-SIZE']); + } + // Disallow margin-left or -right on :LEFT or :RIGHT + if (isset($zp['MARGIN-LEFT'])) { + unset($zp['MARGIN-LEFT']); + } + if (isset($zp['MARGIN-RIGHT'])) { + unset($zp['MARGIN-RIGHT']); + } + if (is_array($zp) && !empty($zp)) { + $p = array_merge($p, $zp); + } + + // If left/Even page + if (isset($this->cssManager->CSS['@PAGE>>PSEUDO>>LEFT']) && $side == 'L') { + $zp = $this->cssManager->CSS['@PAGE>>PSEUDO>>LEFT']; + } else { + $zp = []; + } + if (isset($zp['SIZE'])) { + unset($zp['SIZE']); + } + if (isset($zp['SHEET-SIZE'])) { + unset($zp['SHEET-SIZE']); + } + // Disallow margin-left or -right on :LEFT or :RIGHT + if (isset($zp['MARGIN-LEFT'])) { + unset($zp['MARGIN-LEFT']); + } + if (isset($zp['MARGIN-RIGHT'])) { + unset($zp['MARGIN-RIGHT']); + } + if (is_array($zp) && !empty($zp)) { + $p = array_merge($p, $zp); + } + + // If first page + if (isset($this->cssManager->CSS['@PAGE>>PSEUDO>>FIRST']) && $first) { + $zp = $this->cssManager->CSS['@PAGE>>PSEUDO>>FIRST']; + } else { + $zp = []; + } + if (isset($zp['SIZE'])) { + unset($zp['SIZE']); + } + if (isset($zp['SHEET-SIZE'])) { + unset($zp['SHEET-SIZE']); + } + // Disallow margin-left or -right on :FIRST // mPDF 5.7.3 + if (isset($zp['MARGIN-LEFT'])) { + unset($zp['MARGIN-LEFT']); + } + if (isset($zp['MARGIN-RIGHT'])) { + unset($zp['MARGIN-RIGHT']); + } + if (is_array($zp) && !empty($zp)) { + $p = array_merge($p, $zp); + } + + // If named page + if ($name) { + if (isset($this->cssManager->CSS['@PAGE>>NAMED>>' . $name])) { + $zp = $this->cssManager->CSS['@PAGE>>NAMED>>' . $name]; + } else { + $zp = []; + } + if (is_array($zp) && !empty($zp)) { + $p = array_merge($p, $zp); + } + + if (isset($p['EVEN-HEADER-NAME']) && $oddEven == 'E') { + $p['HEADER'] = $p['EVEN-HEADER-NAME']; + unset($p['EVEN-HEADER-NAME']); + } + if (isset($p['ODD-HEADER-NAME']) && $oddEven != 'E') { + $p['HEADER'] = $p['ODD-HEADER-NAME']; + unset($p['ODD-HEADER-NAME']); + } + if (isset($p['EVEN-FOOTER-NAME']) && $oddEven == 'E') { + $p['FOOTER'] = $p['EVEN-FOOTER-NAME']; + unset($p['EVEN-FOOTER-NAME']); + } + if (isset($p['ODD-FOOTER-NAME']) && $oddEven != 'E') { + $p['FOOTER'] = $p['ODD-FOOTER-NAME']; + unset($p['ODD-FOOTER-NAME']); + } + + // If named right/Odd page + if (isset($this->cssManager->CSS['@PAGE>>NAMED>>' . $name . '>>PSEUDO>>RIGHT']) && $side == 'R') { + $zp = $this->cssManager->CSS['@PAGE>>NAMED>>' . $name . '>>PSEUDO>>RIGHT']; + } else { + $zp = []; + } + if (isset($zp['SIZE'])) { + unset($zp['SIZE']); + } + if (isset($zp['SHEET-SIZE'])) { + unset($zp['SHEET-SIZE']); + } + // Disallow margin-left or -right on :LEFT or :RIGHT + if (isset($zp['MARGIN-LEFT'])) { + unset($zp['MARGIN-LEFT']); + } + if (isset($zp['MARGIN-RIGHT'])) { + unset($zp['MARGIN-RIGHT']); + } + if (is_array($zp) && !empty($zp)) { + $p = array_merge($p, $zp); + } + + // If named left/Even page + if (isset($this->cssManager->CSS['@PAGE>>NAMED>>' . $name . '>>PSEUDO>>LEFT']) && $side == 'L') { + $zp = $this->cssManager->CSS['@PAGE>>NAMED>>' . $name . '>>PSEUDO>>LEFT']; + } else { + $zp = []; + } + if (isset($zp['SIZE'])) { + unset($zp['SIZE']); + } + if (isset($zp['SHEET-SIZE'])) { + unset($zp['SHEET-SIZE']); + } + // Disallow margin-left or -right on :LEFT or :RIGHT + if (isset($zp['MARGIN-LEFT'])) { + unset($zp['MARGIN-LEFT']); + } + if (isset($zp['MARGIN-RIGHT'])) { + unset($zp['MARGIN-RIGHT']); + } + if (is_array($zp) && !empty($zp)) { + $p = array_merge($p, $zp); + } + + // If named first page + if (isset($this->cssManager->CSS['@PAGE>>NAMED>>' . $name . '>>PSEUDO>>FIRST']) && $first) { + $zp = $this->cssManager->CSS['@PAGE>>NAMED>>' . $name . '>>PSEUDO>>FIRST']; + } else { + $zp = []; + } + if (isset($zp['SIZE'])) { + unset($zp['SIZE']); + } + if (isset($zp['SHEET-SIZE'])) { + unset($zp['SHEET-SIZE']); + } + // Disallow margin-left or -right on :FIRST // mPDF 5.7.3 + if (isset($zp['MARGIN-LEFT'])) { + unset($zp['MARGIN-LEFT']); + } + if (isset($zp['MARGIN-RIGHT'])) { + unset($zp['MARGIN-RIGHT']); + } + if (is_array($zp) && !empty($zp)) { + $p = array_merge($p, $zp); + } + } + + $orientation = $mgl = $mgr = $mgt = $mgb = $mgh = $mgf = ''; + $header = $footer = ''; + $resetpagenum = $pagenumstyle = $suppress = ''; + $marks = ''; + $bg = []; + + $newformat = ''; + + + if (isset($p['SHEET-SIZE']) && is_array($p['SHEET-SIZE'])) { + $newformat = $p['SHEET-SIZE']; + if ($newformat[0] > $newformat[1]) { // landscape + $newformat = array_reverse($newformat); + $p['ORIENTATION'] = 'L'; + } else { + $p['ORIENTATION'] = 'P'; + } + $this->_setPageSize($newformat, $p['ORIENTATION']); + } + + if (isset($p['SIZE']) && is_array($p['SIZE']) && !$newformat) { + if ($p['SIZE']['W'] > $p['SIZE']['H']) { + $p['ORIENTATION'] = 'L'; + } else { + $p['ORIENTATION'] = 'P'; + } + } + if (is_array($p['SIZE'])) { + if ($p['SIZE']['W'] > $this->fw) { + $p['SIZE']['W'] = $this->fw; + } // mPD 4.2 use fw not fPt + if ($p['SIZE']['H'] > $this->fh) { + $p['SIZE']['H'] = $this->fh; + } + if (($p['ORIENTATION'] == $this->DefOrientation && !$newformat) || ($newformat && $p['ORIENTATION'] == 'P')) { + $outer_width_LR = ($this->fw - $p['SIZE']['W']) / 2; + $outer_width_TB = ($this->fh - $p['SIZE']['H']) / 2; + } else { + $outer_width_LR = ($this->fh - $p['SIZE']['W']) / 2; + $outer_width_TB = ($this->fw - $p['SIZE']['H']) / 2; + } + $pgw = $p['SIZE']['W']; + $pgh = $p['SIZE']['H']; + } else { // AUTO LANDSCAPE PORTRAIT + $outer_width_LR = 0; + $outer_width_TB = 0; + if (!$newformat) { + if (strtoupper($p['SIZE']) == 'AUTO') { + $p['ORIENTATION'] = $this->DefOrientation; + } elseif (strtoupper($p['SIZE']) == 'LANDSCAPE') { + $p['ORIENTATION'] = 'L'; + } else { + $p['ORIENTATION'] = 'P'; + } + } + if (($p['ORIENTATION'] == $this->DefOrientation && !$newformat) || ($newformat && $p['ORIENTATION'] == 'P')) { + $pgw = $this->fw; + $pgh = $this->fh; + } else { + $pgw = $this->fh; + $pgh = $this->fw; + } + } + + if (isset($p['HEADER']) && $p['HEADER']) { + $header = $p['HEADER']; + } + if (isset($p['FOOTER']) && $p['FOOTER']) { + $footer = $p['FOOTER']; + } + if (isset($p['RESETPAGENUM']) && $p['RESETPAGENUM']) { + $resetpagenum = $p['RESETPAGENUM']; + } + if (isset($p['PAGENUMSTYLE']) && $p['PAGENUMSTYLE']) { + $pagenumstyle = $p['PAGENUMSTYLE']; + } + if (isset($p['SUPPRESS']) && $p['SUPPRESS']) { + $suppress = $p['SUPPRESS']; + } + + if (isset($p['MARKS'])) { + if (preg_match('/cross/i', $p['MARKS']) && preg_match('/crop/i', $p['MARKS'])) { + $marks = 'CROPCROSS'; + } elseif (strtoupper($p['MARKS']) == 'CROP') { + $marks = 'CROP'; + } elseif (strtoupper($p['MARKS']) == 'CROSS') { + $marks = 'CROSS'; + } + } + + if (isset($p['BACKGROUND-COLOR']) && $p['BACKGROUND-COLOR']) { + $bg['BACKGROUND-COLOR'] = $p['BACKGROUND-COLOR']; + } + /* -- BACKGROUNDS -- */ + if (isset($p['BACKGROUND-GRADIENT']) && $p['BACKGROUND-GRADIENT']) { + $bg['BACKGROUND-GRADIENT'] = $p['BACKGROUND-GRADIENT']; + } + if (isset($p['BACKGROUND-IMAGE']) && $p['BACKGROUND-IMAGE']) { + $bg['BACKGROUND-IMAGE'] = $p['BACKGROUND-IMAGE']; + } + if (isset($p['BACKGROUND-REPEAT']) && $p['BACKGROUND-REPEAT']) { + $bg['BACKGROUND-REPEAT'] = $p['BACKGROUND-REPEAT']; + } + if (isset($p['BACKGROUND-POSITION']) && $p['BACKGROUND-POSITION']) { + $bg['BACKGROUND-POSITION'] = $p['BACKGROUND-POSITION']; + } + if (isset($p['BACKGROUND-IMAGE-RESIZE']) && $p['BACKGROUND-IMAGE-RESIZE']) { + $bg['BACKGROUND-IMAGE-RESIZE'] = $p['BACKGROUND-IMAGE-RESIZE']; + } + if (isset($p['BACKGROUND-IMAGE-OPACITY'])) { + $bg['BACKGROUND-IMAGE-OPACITY'] = $p['BACKGROUND-IMAGE-OPACITY']; + } + /* -- END BACKGROUNDS -- */ + + if (isset($p['MARGIN-LEFT'])) { + $mgl = $this->sizeConverter->convert($p['MARGIN-LEFT'], $pgw) + $outer_width_LR; + } + if (isset($p['MARGIN-RIGHT'])) { + $mgr = $this->sizeConverter->convert($p['MARGIN-RIGHT'], $pgw) + $outer_width_LR; + } + if (isset($p['MARGIN-BOTTOM'])) { + $mgb = $this->sizeConverter->convert($p['MARGIN-BOTTOM'], $pgh) + $outer_width_TB; + } + if (isset($p['MARGIN-TOP'])) { + $mgt = $this->sizeConverter->convert($p['MARGIN-TOP'], $pgh) + $outer_width_TB; + } + if (isset($p['MARGIN-HEADER'])) { + $mgh = $this->sizeConverter->convert($p['MARGIN-HEADER'], $pgh) + $outer_width_TB; + } + if (isset($p['MARGIN-FOOTER'])) { + $mgf = $this->sizeConverter->convert($p['MARGIN-FOOTER'], $pgh) + $outer_width_TB; + } + + if (isset($p['ORIENTATION']) && $p['ORIENTATION']) { + $orientation = $p['ORIENTATION']; + } + $this->page_box['outer_width_LR'] = $outer_width_LR; // Used in MARKS:crop etc. + $this->page_box['outer_width_TB'] = $outer_width_TB; + + return [$orientation, $mgl, $mgr, $mgt, $mgb, $mgh, $mgf, $header, $footer, $bg, $resetpagenum, $pagenumstyle, $suppress, $marks, $newformat]; + } + + /* -- END CSS-PAGE -- */ + + + + /* -- CSS-FLOAT -- */ + + // Added mPDF 3.0 Float DIV - CLEAR + function ClearFloats($clear, $blklvl = 0) + { + list($l_exists, $r_exists, $l_max, $r_max, $l_width, $r_width) = $this->GetFloatDivInfo($blklvl, true); + $end = $currpos = ($this->page * 1000 + $this->y); + if ($clear == 'BOTH' && ($l_exists || $r_exists)) { + $this->pageoutput[$this->page] = []; + $end = max($l_max, $r_max, $currpos); + } elseif ($clear == 'RIGHT' && $r_exists) { + $this->pageoutput[$this->page] = []; + $end = max($r_max, $currpos); + } elseif ($clear == 'LEFT' && $l_exists) { + $this->pageoutput[$this->page] = []; + $end = max($l_max, $currpos); + } else { + return; + } + $old_page = $this->page; + $new_page = intval($end / 1000); + if ($old_page != $new_page) { + $s = $this->PrintPageBackgrounds(); + // Writes after the marker so not overwritten later by page background etc. + $this->pages[$this->page] = preg_replace('/(___BACKGROUND___PATTERNS' . $this->uniqstr . ')/', '\\1' . "\n" . $s . "\n", $this->pages[$this->page]); + $this->pageBackgrounds = []; + $this->page = $new_page; + } + $this->ResetMargins(); + $this->pageoutput[$this->page] = []; + $this->y = (($end * 1000) % 1000000) / 1000; // mod changes operands to integers before processing + } + + // Added mPDF 3.0 Float DIV + function GetFloatDivInfo($blklvl = 0, $clear = false) + { + // If blklvl specified, only returns floats at that level - for ClearFloats + $l_exists = false; + $r_exists = false; + $l_max = 0; + $r_max = 0; + $l_width = 0; + $r_width = 0; + if (count($this->floatDivs)) { + $currpos = ($this->page * 1000 + $this->y); + foreach ($this->floatDivs as $f) { + if (($clear && $f['blockContext'] == $this->blk[$blklvl]['blockContext']) || (!$clear && $currpos >= $f['startpos'] && $currpos < ($f['endpos'] - 0.001) && $f['blklvl'] > $blklvl && $f['blockContext'] == $this->blk[$blklvl]['blockContext'])) { + if ($f['side'] == 'L') { + $l_exists = true; + $l_max = max($l_max, $f['endpos']); + $l_width = max($l_width, $f['w']); + } + if ($f['side'] == 'R') { + $r_exists = true; + $r_max = max($r_max, $f['endpos']); + $r_width = max($r_width, $f['w']); + } + } + } + } + return [$l_exists, $r_exists, $l_max, $r_max, $l_width, $r_width]; + } + + /* -- END CSS-FLOAT -- */ + + // LIST MARKERS // mPDF 6 Lists + function _setListMarker($listitemtype, $listitemimage, $listitemposition) + { + // if position:inside (and NOT table) - output now as a textbuffer; (so if next is block, will move to new line) + // elseif position:outside (and NOT table) - output in front of first textbuffer output by setting listitem (cf. _saveTextBuffer) + $e = ''; + $this->listitem = ''; + $spacer = ' '; + // IMAGE + if ($listitemimage && $listitemimage != 'none') { + $listitemimage = trim(preg_replace('/url\(["\']*(.*?)["\']*\)/', '\\1', $listitemimage)); + + // ? Restrict maximum height/width of list marker?? + $maxWidth = 100; + $maxHeight = 100; + + $objattr = []; + $objattr['margin_top'] = 0; + $objattr['margin_bottom'] = 0; + $objattr['margin_left'] = 0; + $objattr['margin_right'] = 0; + $objattr['padding_top'] = 0; + $objattr['padding_bottom'] = 0; + $objattr['padding_left'] = 0; + $objattr['padding_right'] = 0; + $objattr['width'] = 0; + $objattr['height'] = 0; + $objattr['border_top']['w'] = 0; + $objattr['border_bottom']['w'] = 0; + $objattr['border_left']['w'] = 0; + $objattr['border_right']['w'] = 0; + $objattr['visibility'] = 'visible'; + $srcpath = $listitemimage; + $orig_srcpath = $listitemimage; + + $objattr['vertical-align'] = 'BS'; // vertical alignment of marker (baseline) + $w = 0; + $h = 0; + + // Image file + $info = $this->imageProcessor->getImage($srcpath, true, true, $orig_srcpath); + if (!$info) { + return; + } + + if ($info['w'] == 0 && $info['h'] == 0) { + $info['h'] = $this->sizeConverter->convert('1em', $this->blk[$this->blklvl]['inner_width'], $this->FontSize, false); + } + + $objattr['file'] = $srcpath; + + // Default width and height calculation if needed + if ($w == 0 and $h == 0) { + /* -- IMAGES-WMF -- */ + if ($info['type'] == 'wmf') { + // WMF units are twips (1/20pt) + // divide by 20 to get points + // divide by k to get user units + $w = abs($info['w']) / (20 * Mpdf::SCALE); + $h = abs($info['h']) / (20 * Mpdf::SCALE); + } else { /* -- END IMAGES-WMF -- */ + if ($info['type'] == 'svg') { + // SVG units are pixels + $w = abs($info['w']) / Mpdf::SCALE; + $h = abs($info['h']) / Mpdf::SCALE; + } else { + // Put image at default image dpi + $w = ($info['w'] / Mpdf::SCALE) * (72 / $this->img_dpi); + $h = ($info['h'] / Mpdf::SCALE) * (72 / $this->img_dpi); + } + } + } + // IF WIDTH OR HEIGHT SPECIFIED + if ($w == 0) { + $w = abs($h * $info['w'] / $info['h']); + } + if ($h == 0) { + $h = abs($w * $info['h'] / $info['w']); + } + + if ($w > $maxWidth) { + $w = $maxWidth; + $h = abs($w * $info['h'] / $info['w']); + } + + if ($h > $maxHeight) { + $h = $maxHeight; + $w = abs($h * $info['w'] / $info['h']); + } + + $objattr['type'] = 'image'; + $objattr['itype'] = $info['type']; + + $objattr['orig_h'] = $info['h']; + $objattr['orig_w'] = $info['w']; + + /* -- IMAGES-WMF -- */ + if ($info['type'] == 'wmf') { + $objattr['wmf_x'] = $info['x']; + $objattr['wmf_y'] = $info['y']; + } else { /* -- END IMAGES-WMF -- */ + if ($info['type'] == 'svg') { + $objattr['wmf_x'] = $info['x']; + $objattr['wmf_y'] = $info['y']; + } + } + + $objattr['height'] = $h; + $objattr['width'] = $w; + $objattr['image_height'] = $h; + $objattr['image_width'] = $w; + + $objattr['dir'] = (isset($this->blk[$this->blklvl]['direction']) ? $this->blk[$this->blklvl]['direction'] : 'ltr'); + $objattr['listmarker'] = true; + + $objattr['listmarkerposition'] = $listitemposition; + + $e = "\xbb\xa4\xactype=image,objattr=" . serialize($objattr) . "\xbb\xa4\xac"; + $this->_saveTextBuffer($e); + + if ($listitemposition == 'inside') { + $e = $spacer; + $this->_saveTextBuffer($e); + } + } elseif ($listitemtype == 'disc' || $listitemtype == 'circle' || $listitemtype == 'square') { // SYMBOL (needs new font) + $objattr = []; + $objattr['type'] = 'listmarker'; + $objattr['listmarkerposition'] = $listitemposition; + $objattr['width'] = 0; + $size = $this->sizeConverter->convert($this->list_symbol_size, $this->FontSize); + $objattr['size'] = $size; + $objattr['offset'] = $this->sizeConverter->convert($this->list_marker_offset, $this->FontSize); + + if ($listitemposition == 'inside') { + $objattr['width'] = $size + $objattr['offset']; + } + + $objattr['height'] = $this->FontSize; + $objattr['vertical-align'] = 'T'; + $objattr['text'] = ''; + $objattr['dir'] = (isset($this->blk[$this->blklvl]['direction']) ? $this->blk[$this->blklvl]['direction'] : 'ltr'); + $objattr['bullet'] = $listitemtype; + $objattr['colorarray'] = $this->colorarray; + $objattr['fontfamily'] = $this->FontFamily; + $objattr['fontsize'] = $this->FontSize; + $objattr['fontsizept'] = $this->FontSizePt; + $objattr['fontstyle'] = $this->FontStyle; + + $e = "\xbb\xa4\xactype=listmarker,objattr=" . serialize($objattr) . "\xbb\xa4\xac"; + $this->listitem = $this->_saveTextBuffer($e, '', '', true); // true returns array + + } elseif (preg_match('/U\+([a-fA-F0-9]+)/i', $listitemtype, $m)) { // SYMBOL 2 (needs new font) + + if ($this->_charDefined($this->CurrentFont['cw'], hexdec($m[1]))) { + $list_item_marker = UtfString::codeHex2utf($m[1]); + } else { + $list_item_marker = '-'; + } + if (preg_match('/rgb\(.*?\)/', $listitemtype, $m)) { + $list_item_color = $this->colorConverter->convert($m[0], $this->PDFAXwarnings); + } else { + $list_item_color = ''; + } + + // SAVE then SET COLR + $save_colorarray = $this->colorarray; + if ($list_item_color) { + $this->colorarray = $list_item_color; + } + + if ($listitemposition == 'inside') { + $e = $list_item_marker . $spacer; + $this->_saveTextBuffer($e); + } else { + $objattr = []; + $objattr['type'] = 'listmarker'; + $objattr['width'] = 0; + $objattr['height'] = $this->FontSize; + $objattr['vertical-align'] = 'T'; + $objattr['text'] = $list_item_marker; + $objattr['dir'] = (isset($this->blk[$this->blklvl]['direction']) ? $this->blk[$this->blklvl]['direction'] : 'ltr'); + $objattr['colorarray'] = $this->colorarray; + $objattr['fontfamily'] = $this->FontFamily; + $objattr['fontsize'] = $this->FontSize; + $objattr['fontsizept'] = $this->FontSizePt; + $objattr['fontstyle'] = $this->FontStyle; + $e = "\xbb\xa4\xactype=listmarker,objattr=" . serialize($objattr) . "\xbb\xa4\xac"; + $this->listitem = $this->_saveTextBuffer($e, '', '', true); // true returns array + } + + // RESET COLOR + $this->colorarray = $save_colorarray; + + } else { // TEXT + $counter = $this->listcounter[$this->listlvl]; + + if ($listitemtype == 'none') { + return; + } + + $num = $this->_getStyledNumber($counter, $listitemtype, true); + + if ($listitemposition == 'inside') { + $e = $num . $this->list_number_suffix . $spacer; + $this->_saveTextBuffer($e); + } else { + if (isset($this->blk[$this->blklvl]['direction']) && $this->blk[$this->blklvl]['direction'] == 'rtl') { + // REPLACE MIRRORED RTL $this->list_number_suffix e.g. ) -> ( (NB could use Ucdn::$mirror_pairs) + $m = strtr($this->list_number_suffix, ")]}", "([{") . $num; + } else { + $m = $num . $this->list_number_suffix; + } + + $objattr = []; + $objattr['type'] = 'listmarker'; + $objattr['width'] = 0; + $objattr['height'] = $this->FontSize; + $objattr['vertical-align'] = 'T'; + $objattr['text'] = $m; + $objattr['dir'] = (isset($this->blk[$this->blklvl]['direction']) ? $this->blk[$this->blklvl]['direction'] : 'ltr'); + $objattr['colorarray'] = $this->colorarray; + $objattr['fontfamily'] = $this->FontFamily; + $objattr['fontsize'] = $this->FontSize; + $objattr['fontsizept'] = $this->FontSizePt; + $objattr['fontstyle'] = $this->FontStyle; + $e = "\xbb\xa4\xactype=listmarker,objattr=" . serialize($objattr) . "\xbb\xa4\xac"; + + $this->listitem = $this->_saveTextBuffer($e, '', '', true); // true returns array + } + } + } + + // mPDF Lists + function _getListMarkerWidth(&$currblk, &$a, &$i) + { + $blt_width = 0; + + $markeroffset = $this->sizeConverter->convert($this->list_marker_offset, $this->FontSize); + + // Get Maximum number in the list + $maxnum = $this->listcounter[$this->listlvl]; + if ($currblk['list_style_type'] != 'disc' && $currblk['list_style_type'] != 'circle' && $currblk['list_style_type'] != 'square') { + $lvl = 1; + for ($j = $i + 2; $j < count($a); $j+=2) { + $e = $a[$j]; + if (!$e) { + continue; + } + if ($e[0] == '/') { // end tag + $e = strtoupper(substr($e, 1)); + if ($e == 'OL' || $e == 'UL') { + if ($lvl == 1) { + break; + } + $lvl--; + } + } else { // opening tag + if (strpos($e, ' ')) { + $e = substr($e, 0, strpos($e, ' ')); + } + $e = strtoupper($e); + if ($e == 'LI') { + if ($lvl == 1) { + $maxnum++; + } + } elseif ($e == 'OL' || $e == 'UL') { + $lvl++; + } + } + } + } + + $decToAlpha = new Conversion\DecToAlpha(); + $decToRoman = new Conversion\DecToRoman(); + $decToOther = new Conversion\DecToOther($this); + + switch ($currblk['list_style_type']) { + case 'decimal': + case '1': + $blt_width = $this->GetStringWidth(str_repeat('5', strlen($maxnum)) . $this->list_number_suffix); + break; + case 'none': + $blt_width = 0; + break; + case 'upper-alpha': + case 'upper-latin': + case 'A': + $maxnumA = $decToAlpha->convert($maxnum, true); + if ($maxnum < 13) { + $blt_width = $this->GetStringWidth('D' . $this->list_number_suffix); + } else { + $blt_width = $this->GetStringWidth(str_repeat('W', strlen($maxnumA)) . $this->list_number_suffix); + } + break; + case 'lower-alpha': + case 'lower-latin': + case 'a': + $maxnuma = $decToAlpha->convert($maxnum, false); + if ($maxnum < 13) { + $blt_width = $this->GetStringWidth('b' . $this->list_number_suffix); + } else { + $blt_width = $this->GetStringWidth(str_repeat('m', strlen($maxnuma)) . $this->list_number_suffix); + } + break; + case 'upper-roman': + case 'I': + if ($maxnum > 87) { + $bbit = 87; + } elseif ($maxnum > 86) { + $bbit = 86; + } elseif ($maxnum > 37) { + $bbit = 38; + } elseif ($maxnum > 36) { + $bbit = 37; + } elseif ($maxnum > 27) { + $bbit = 28; + } elseif ($maxnum > 26) { + $bbit = 27; + } elseif ($maxnum > 17) { + $bbit = 18; + } elseif ($maxnum > 16) { + $bbit = 17; + } elseif ($maxnum > 7) { + $bbit = 8; + } elseif ($maxnum > 6) { + $bbit = 7; + } elseif ($maxnum > 3) { + $bbit = 4; + } else { + $bbit = $maxnum; + } + + $maxlnum = $decToRoman->convert($bbit, true); + $blt_width = $this->GetStringWidth($maxlnum . $this->list_number_suffix); + + break; + case 'lower-roman': + case 'i': + if ($maxnum > 87) { + $bbit = 87; + } elseif ($maxnum > 86) { + $bbit = 86; + } elseif ($maxnum > 37) { + $bbit = 38; + } elseif ($maxnum > 36) { + $bbit = 37; + } elseif ($maxnum > 27) { + $bbit = 28; + } elseif ($maxnum > 26) { + $bbit = 27; + } elseif ($maxnum > 17) { + $bbit = 18; + } elseif ($maxnum > 16) { + $bbit = 17; + } elseif ($maxnum > 7) { + $bbit = 8; + } elseif ($maxnum > 6) { + $bbit = 7; + } elseif ($maxnum > 3) { + $bbit = 4; + } else { + $bbit = $maxnum; + } + $maxlnum = $decToRoman->convert($bbit, false); + $blt_width = $this->GetStringWidth($maxlnum . $this->list_number_suffix); + break; + + case 'disc': + case 'circle': + case 'square': + $size = $this->sizeConverter->convert($this->list_symbol_size, $this->FontSize); + $offset = $this->sizeConverter->convert($this->list_marker_offset, $this->FontSize); + $blt_width = $size + $offset; + break; + + case 'arabic-indic': + $blt_width = $this->GetStringWidth(str_repeat($decToOther->convert(3, 0x0660), strlen($maxnum)) . $this->list_number_suffix); + break; + case 'persian': + case 'urdu': + $blt_width = $this->GetStringWidth(str_repeat($decToOther->convert(3, 0x06F0), strlen($maxnum)) . $this->list_number_suffix); + break; + case 'bengali': + $blt_width = $this->GetStringWidth(str_repeat($decToOther->convert(3, 0x09E6), strlen($maxnum)) . $this->list_number_suffix); + break; + case 'devanagari': + $blt_width = $this->GetStringWidth(str_repeat($decToOther->convert(3, 0x0966), strlen($maxnum)) . $this->list_number_suffix); + break; + case 'gujarati': + $blt_width = $this->GetStringWidth(str_repeat($decToOther->convert(3, 0x0AE6), strlen($maxnum)) . $this->list_number_suffix); + break; + case 'gurmukhi': + $blt_width = $this->GetStringWidth(str_repeat($decToOther->convert(3, 0x0A66), strlen($maxnum)) . $this->list_number_suffix); + break; + case 'kannada': + $blt_width = $this->GetStringWidth(str_repeat($decToOther->convert(3, 0x0CE6), strlen($maxnum)) . $this->list_number_suffix); + break; + case 'malayalam': + $blt_width = $this->GetStringWidth(str_repeat($decToOther->convert(6, 0x0D66), strlen($maxnum)) . $this->list_number_suffix); + break; + case 'oriya': + $blt_width = $this->GetStringWidth(str_repeat($decToOther->convert(3, 0x0B66), strlen($maxnum)) . $this->list_number_suffix); + break; + case 'telugu': + $blt_width = $this->GetStringWidth(str_repeat($decToOther->convert(3, 0x0C66), strlen($maxnum)) . $this->list_number_suffix); + break; + case 'tamil': + $blt_width = $this->GetStringWidth(str_repeat($decToOther->convert(9, 0x0BE6), strlen($maxnum)) . $this->list_number_suffix); + break; + case 'thai': + $blt_width = $this->GetStringWidth(str_repeat($decToOther->convert(5, 0x0E50), strlen($maxnum)) . $this->list_number_suffix); + break; + default: + $blt_width = $this->GetStringWidth(str_repeat('5', strlen($maxnum)) . $this->list_number_suffix); + break; + } + + return ($blt_width + $markeroffset); + } + + function _saveTextBuffer($t, $link = '', $intlink = '', $return = false) + { + // mPDF 6 Lists + $arr = []; + $arr[0] = $t; + if (isset($link) && $link) { + $arr[1] = $link; + } + $arr[2] = $this->currentfontstyle; + if (isset($this->colorarray) && $this->colorarray) { + $arr[3] = $this->colorarray; + } + $arr[4] = $this->currentfontfamily; + $arr[5] = $this->currentLang; // mPDF 6 + if (isset($intlink) && $intlink) { + $arr[7] = $intlink; + } + // mPDF 6 + // If Kerning set for OTL, and useOTL has positive value, but has not set for this particular script, + // set for kerning via kern table + // e.g. Latin script when useOTL set as 0x80 + if (isset($this->OTLtags['Plus']) && strpos($this->OTLtags['Plus'], 'kern') !== false && empty($this->OTLdata['GPOSinfo'])) { + $this->textvar = ($this->textvar | TextVars::FC_KERNING); + } + $arr[8] = $this->textvar; // mPDF 5.7.1 + if (isset($this->textparam) && $this->textparam) { + $arr[9] = $this->textparam; + } + if (isset($this->spanbgcolorarray) && $this->spanbgcolorarray) { + $arr[10] = $this->spanbgcolorarray; + } + $arr[11] = $this->currentfontsize; + if (isset($this->ReqFontStyle) && $this->ReqFontStyle) { + $arr[12] = $this->ReqFontStyle; + } + if (isset($this->lSpacingCSS) && $this->lSpacingCSS) { + $arr[14] = $this->lSpacingCSS; + } + if (isset($this->wSpacingCSS) && $this->wSpacingCSS) { + $arr[15] = $this->wSpacingCSS; + } + if (isset($this->spanborddet) && $this->spanborddet) { + $arr[16] = $this->spanborddet; + } + if (isset($this->textshadow) && $this->textshadow) { + $arr[17] = $this->textshadow; + } + if (isset($this->OTLdata) && $this->OTLdata) { + $arr[18] = $this->OTLdata; + $this->OTLdata = []; + } // mPDF 5.7.1 + else { + $arr[18] = null; + } + // mPDF 6 Lists + if ($return) { + return ($arr); + } + if ($this->listitem) { + $this->textbuffer[] = $this->listitem; + $this->listitem = []; + } + $this->textbuffer[] = $arr; + } + + function _saveCellTextBuffer($t, $link = '', $intlink = '') + { + $arr = []; + $arr[0] = $t; + if (isset($link) && $link) { + $arr[1] = $link; + } + $arr[2] = $this->currentfontstyle; + if (isset($this->colorarray) && $this->colorarray) { + $arr[3] = $this->colorarray; + } + $arr[4] = $this->currentfontfamily; + if (isset($intlink) && $intlink) { + $arr[7] = $intlink; + } + // mPDF 6 + // If Kerning set for OTL, and useOTL has positive value, but has not set for this particular script, + // set for kerning via kern table + // e.g. Latin script when useOTL set as 0x80 + if (isset($this->OTLtags['Plus']) && strpos($this->OTLtags['Plus'], 'kern') !== false && empty($this->OTLdata['GPOSinfo'])) { + $this->textvar = ($this->textvar | TextVars::FC_KERNING); + } + $arr[8] = $this->textvar; // mPDF 5.7.1 + if (isset($this->textparam) && $this->textparam) { + $arr[9] = $this->textparam; + } + if (isset($this->spanbgcolorarray) && $this->spanbgcolorarray) { + $arr[10] = $this->spanbgcolorarray; + } + $arr[11] = $this->currentfontsize; + if (isset($this->ReqFontStyle) && $this->ReqFontStyle) { + $arr[12] = $this->ReqFontStyle; + } + if (isset($this->lSpacingCSS) && $this->lSpacingCSS) { + $arr[14] = $this->lSpacingCSS; + } + if (isset($this->wSpacingCSS) && $this->wSpacingCSS) { + $arr[15] = $this->wSpacingCSS; + } + if (isset($this->spanborddet) && $this->spanborddet) { + $arr[16] = $this->spanborddet; + } + if (isset($this->textshadow) && $this->textshadow) { + $arr[17] = $this->textshadow; + } + if (isset($this->OTLdata) && $this->OTLdata) { + $arr[18] = $this->OTLdata; + $this->OTLdata = []; + } // mPDF 5.7.1 + else { + $arr[18] = null; + } + $this->cell[$this->row][$this->col]['textbuffer'][] = $arr; + } + + function printbuffer($arrayaux, $blockstate = 0, $is_table = false, $table_draft = false, $cell_dir = '') + { + // $blockstate = 0; // NO margins/padding + // $blockstate = 1; // Top margins/padding only + // $blockstate = 2; // Bottom margins/padding only + // $blockstate = 3; // Top & bottom margins/padding + $this->spanbgcolorarray = ''; + $this->spanbgcolor = false; + $this->spanborder = false; + $this->spanborddet = []; + $paint_ht_corr = 0; + /* -- CSS-FLOAT -- */ + if (count($this->floatDivs)) { + list($l_exists, $r_exists, $l_max, $r_max, $l_width, $r_width) = $this->GetFloatDivInfo($this->blklvl); + if (($this->blk[$this->blklvl]['inner_width'] - $l_width - $r_width) < (2 * $this->GetCharWidth('W', false))) { + // Too narrow to fit - try to move down past L or R float + if ($l_max < $r_max && ($this->blk[$this->blklvl]['inner_width'] - $r_width) > (2 * $this->GetCharWidth('W', false))) { + $this->ClearFloats('LEFT', $this->blklvl); + } elseif ($r_max < $l_max && ($this->blk[$this->blklvl]['inner_width'] - $l_width) > (2 * $this->GetCharWidth('W', false))) { + $this->ClearFloats('RIGHT', $this->blklvl); + } else { + $this->ClearFloats('BOTH', $this->blklvl); + } + } + } + /* -- END CSS-FLOAT -- */ + $bak_y = $this->y; + $bak_x = $this->x; + $align = ''; + if (!$is_table) { + if (isset($this->blk[$this->blklvl]['align']) && $this->blk[$this->blklvl]['align']) { + $align = $this->blk[$this->blklvl]['align']; + } + // Block-align is set by e.g. <.. align="center"> Takes priority for this block but not inherited + if (isset($this->blk[$this->blklvl]['block-align']) && $this->blk[$this->blklvl]['block-align']) { + $align = $this->blk[$this->blklvl]['block-align']; + } + if (isset($this->blk[$this->blklvl]['direction'])) { + $blockdir = $this->blk[$this->blklvl]['direction']; + } else { + $blockdir = ""; + } + $this->divwidth = $this->blk[$this->blklvl]['width']; + } else { + $align = $this->cellTextAlign; + $blockdir = $cell_dir; + } + $oldpage = $this->page; + + // ADDED for Out of Block now done as Flowing Block + if ($this->divwidth == 0) { + $this->divwidth = $this->pgwidth; + } + + if (!$is_table) { + $this->SetLineHeight($this->FontSizePt, $this->blk[$this->blklvl]['line_height']); + } + $this->divheight = $this->lineheight; + $old_height = $this->divheight; + + // As a failsafe - if font has been set but not output to page + if (!$table_draft) { + $this->SetFont($this->default_font, '', $this->default_font_size, true, true); // force output to page + } + + $this->newFlowingBlock($this->divwidth, $this->divheight, $align, $is_table, $blockstate, true, $blockdir, $table_draft); + + $array_size = count($arrayaux); + + // Added - Otherwise

    did not output top margins/padding for 1st/2nd div + if ($array_size == 0) { + $this->finishFlowingBlock(true); + } // true = END of flowing block + // mPDF 6 + // ALL the chunks of textbuffer need to have at least basic OTLdata set + // First make sure each element/chunk has the OTLdata for Bidi set. + for ($i = 0; $i < $array_size; $i++) { + if (empty($arrayaux[$i][18])) { + if (substr($arrayaux[$i][0], 0, 3) == "\xbb\xa4\xac") { // object identifier has been identified! + $unicode = [0xFFFC]; // Object replacement character + } else { + $unicode = $this->UTF8StringToArray($arrayaux[$i][0], false); + } + $is_strong = false; + $this->getBasicOTLdata($arrayaux[$i][18], $unicode, $is_strong); + } + // Gets messed up if try and use core fonts inside a paragraph of text which needs to be BiDi re-ordered or OTLdata set + if (($blockdir == 'rtl' || $this->biDirectional) && isset($arrayaux[$i][4]) && in_array($arrayaux[$i][4], ['ccourier', 'ctimes', 'chelvetica', 'csymbol', 'czapfdingbats'])) { + throw new \Mpdf\MpdfException("You cannot use core fonts in a document which contains RTL text."); + } + } + // mPDF 6 + // Process bidirectional text ready for bidi-re-ordering (which is done after line-breaks are established in WriteFlowingBlock etc.) + if (($blockdir == 'rtl' || $this->biDirectional) && !$table_draft) { + if (empty($this->otl)) { + $this->otl = new Otl($this, $this->fontCache); + } + $this->otl->bidiPrepare($arrayaux, $blockdir); + $array_size = count($arrayaux); + } + + + // Remove empty items // mPDF 6 + for ($i = $array_size - 1; $i > 0; $i--) { + if (empty($arrayaux[$i][0]) && (isset($arrayaux[$i][16]) && $arrayaux[$i][16] !== '0') && empty($arrayaux[$i][7])) { + unset($arrayaux[$i]); + } + } + + // Correct adjoining borders for inline elements + if (isset($arrayaux[0][16])) { + $lastspanborder = $arrayaux[0][16]; + } else { + $lastspanborder = false; + } + for ($i = 1; $i < $array_size; $i++) { + if (isset($arrayaux[$i][16]) && $arrayaux[$i][16] == $lastspanborder && + ((!isset($arrayaux[$i][9]['bord-decoration']) && !isset($arrayaux[$i - 1][9]['bord-decoration'])) || + (isset($arrayaux[$i][9]['bord-decoration']) && isset($arrayaux[$i - 1][9]['bord-decoration']) && $arrayaux[$i][9]['bord-decoration'] == $arrayaux[$i - 1][9]['bord-decoration']) + ) + ) { + if (isset($arrayaux[$i][16]['R'])) { + $lastspanborder = $arrayaux[$i][16]; + } else { + $lastspanborder = false; + } + $arrayaux[$i][16]['L']['s'] = 0; + $arrayaux[$i][16]['L']['w'] = 0; + $arrayaux[$i - 1][16]['R']['s'] = 0; + $arrayaux[$i - 1][16]['R']['w'] = 0; + } else { + if (isset($arrayaux[$i][16]['R'])) { + $lastspanborder = $arrayaux[$i][16]; + } else { + $lastspanborder = false; + } + } + } + + for ($i = 0; $i < $array_size; $i++) { + // COLS + $oldcolumn = $this->CurrCol; + $vetor = isset($arrayaux[$i]) ? $arrayaux[$i] : null; + if ($i == 0 && $vetor[0] != "\n" && ! $this->ispre) { + $vetor[0] = ltrim($vetor[0]); + if (!empty($vetor[18])) { + $this->otl->trimOTLdata($vetor[18], true, false); + } // *OTL* + } + + // FIXED TO ALLOW IT TO SHOW '0' + if (empty($vetor[0]) && !($vetor[0] === '0') && empty($vetor[7])) { // Ignore empty text and not carrying an internal link + // Check if it is the last element. If so then finish printing the block + if ($i == ($array_size - 1)) { + $this->finishFlowingBlock(true); + } // true = END of flowing block + continue; + } + + + // Activating buffer properties + if (isset($vetor[11]) && $vetor[11] != '') { // Font Size + if ($is_table && $this->shrin_k) { + $this->SetFontSize($vetor[11] / $this->shrin_k, false); + } else { + $this->SetFontSize($vetor[11], false); + } + } + + if (isset($vetor[17]) && !empty($vetor[17])) { // TextShadow + $this->textshadow = $vetor[17]; + } + if (isset($vetor[16]) && !empty($vetor[16])) { // Border + $this->spanborddet = $vetor[16]; + $this->spanborder = true; + } + + if (isset($vetor[15])) { // Word spacing + $this->wSpacingCSS = $vetor[15]; + if ($this->wSpacingCSS && strtoupper($this->wSpacingCSS) != 'NORMAL') { + $this->minwSpacing = $this->sizeConverter->convert($this->wSpacingCSS, $this->FontSize) / $this->shrin_k; // mPDF 5.7.3 + } + } + if (isset($vetor[14])) { // Letter spacing + $this->lSpacingCSS = $vetor[14]; + if (($this->lSpacingCSS || $this->lSpacingCSS === '0') && strtoupper($this->lSpacingCSS) != 'NORMAL') { + $this->fixedlSpacing = $this->sizeConverter->convert($this->lSpacingCSS, $this->FontSize) / $this->shrin_k; // mPDF 5.7.3 + } + } + + + if (isset($vetor[10]) and ! empty($vetor[10])) { // Background color + $this->spanbgcolorarray = $vetor[10]; + $this->spanbgcolor = true; + } + if (isset($vetor[9]) and ! empty($vetor[9])) { // Text parameters - Outline + hyphens + $this->textparam = $vetor[9]; + $this->SetTextOutline($this->textparam); + // mPDF 5.7.3 inline text-decoration parameters + if ($is_table && $this->shrin_k) { + if (isset($this->textparam['text-baseline'])) { + $this->textparam['text-baseline'] /= $this->shrin_k; + } + if (isset($this->textparam['decoration-baseline'])) { + $this->textparam['decoration-baseline'] /= $this->shrin_k; + } + if (isset($this->textparam['decoration-fontsize'])) { + $this->textparam['decoration-fontsize'] /= $this->shrin_k; + } + } + } + if (isset($vetor[8])) { // mPDF 5.7.1 + $this->textvar = $vetor[8]; + } + if (isset($vetor[7]) and $vetor[7] != '') { // internal target: + $ily = $this->y; + if ($this->table_rotate) { + $this->internallink[$vetor[7]] = ["Y" => $ily, "PAGE" => $this->page, "tbrot" => true]; + } elseif ($this->kwt) { + $this->internallink[$vetor[7]] = ["Y" => $ily, "PAGE" => $this->page, "kwt" => true]; + } elseif ($this->ColActive) { + $this->internallink[$vetor[7]] = ["Y" => $ily, "PAGE" => $this->page, "col" => $this->CurrCol]; + } elseif (!$this->keep_block_together) { + $this->internallink[$vetor[7]] = ["Y" => $ily, "PAGE" => $this->page]; + } + if (empty($vetor[0])) { // Ignore empty text + // Check if it is the last element. If so then finish printing the block + if ($i == ($array_size - 1)) { + $this->finishFlowingBlock(true); + } // true = END of flowing block + continue; + } + } + if (isset($vetor[5]) and $vetor[5] != '') { // Language // mPDF 6 + $this->currentLang = $vetor[5]; + } + if (isset($vetor[4]) and $vetor[4] != '') { // Font Family + $font = $this->SetFont($vetor[4], $this->FontStyle, 0, false); + } + if (!empty($vetor[3])) { // Font Color + $cor = $vetor[3]; + $this->SetTColor($cor); + } + if (isset($vetor[2]) and $vetor[2] != '') { // Bold,Italic styles + $this->SetStyles($vetor[2]); + } + + if (isset($vetor[12]) and $vetor[12] != '') { // Requested Bold,Italic + $this->ReqFontStyle = $vetor[12]; + } + if (isset($vetor[1]) and $vetor[1] != '') { // LINK + if (strpos($vetor[1], ".") === false && strpos($vetor[1], "@") !== 0) { // assuming every external link has a dot indicating extension (e.g: .html .txt .zip www.somewhere.com etc.) + // Repeated reference to same anchor? + while (array_key_exists($vetor[1], $this->internallink)) { + $vetor[1] = "#" . $vetor[1]; + } + $this->internallink[$vetor[1]] = $this->AddLink(); + $vetor[1] = $this->internallink[$vetor[1]]; + } + $this->HREF = $vetor[1]; // HREF link style set here ****** + } + + // SPECIAL CONTENT - IMAGES & FORM OBJECTS + // Print-out special content + + if (substr($vetor[0], 0, 3) == "\xbb\xa4\xac") { // identifier has been identified! + $objattr = $this->_getObjAttr($vetor[0]); + + /* -- TABLES -- */ + if ($objattr['type'] == 'nestedtable') { + if ($objattr['nestedcontent']) { + $level = $objattr['level']; + $table = &$this->table[$level][$objattr['table']]; + + if ($table_draft) { + $this->y += $this->table[($level + 1)][$objattr['nestedcontent']]['h']; // nested table height + $this->finishFlowingBlock(false, 'nestedtable'); + } else { + $cell = &$table['cells'][$objattr['row']][$objattr['col']]; + $this->finishFlowingBlock(false, 'nestedtable'); + $save_dw = $this->divwidth; + $save_buffer = $this->cellBorderBuffer; + $this->cellBorderBuffer = []; + $ncx = $this->x; + list($dummyx, $w) = $this->_tableGetWidth($table, $objattr['row'], $objattr['col']); + $ntw = $this->table[($level + 1)][$objattr['nestedcontent']]['w']; // nested table width + if (!$this->simpleTables) { + if ($this->packTableData) { + list($bt, $br, $bb, $bl) = $this->_getBorderWidths($cell['borderbin']); + } else { + $br = $cell['border_details']['R']['w']; + $bl = $cell['border_details']['L']['w']; + } + if ($table['borders_separate']) { + $innerw = $w - $bl - $br - $cell['padding']['L'] - $cell['padding']['R'] - $table['border_spacing_H']; + } else { + $innerw = $w - $bl / 2 - $br / 2 - $cell['padding']['L'] - $cell['padding']['R']; + } + } elseif ($this->simpleTables) { + if ($table['borders_separate']) { + $innerw = $w - $table['simple']['border_details']['L']['w'] - $table['simple']['border_details']['R']['w'] - $cell['padding']['L'] - $cell['padding']['R'] - $table['border_spacing_H']; + } else { + $innerw = $w - $table['simple']['border_details']['L']['w'] / 2 - $table['simple']['border_details']['R']['w'] / 2 - $cell['padding']['L'] - $cell['padding']['R']; + } + } + if ($cell['a'] == 'C' || $this->table[($level + 1)][$objattr['nestedcontent']]['a'] == 'C') { + $ncx += ($innerw - $ntw) / 2; + } elseif ($cell['a'] == 'R' || $this->table[($level + 1)][$objattr['nestedcontent']]['a'] == 'R') { + $ncx += $innerw - $ntw; + } + $this->x = $ncx; + + $this->_tableWrite($this->table[($level + 1)][$objattr['nestedcontent']]); + $this->cellBorderBuffer = $save_buffer; + $this->x = $bak_x; + $this->divwidth = $save_dw; + } + + $this->newFlowingBlock($this->divwidth, $this->divheight, $align, $is_table, $blockstate, false, $blockdir, $table_draft); + } + } else { + /* -- END TABLES -- */ + if ($is_table) { // *TABLES* + $maxWidth = $this->divwidth; // *TABLES* + } // *TABLES* + else { // *TABLES* + $maxWidth = $this->divwidth - ($this->blk[$this->blklvl]['padding_left'] + $this->blk[$this->blklvl]['border_left']['w'] + $this->blk[$this->blklvl]['padding_right'] + $this->blk[$this->blklvl]['border_right']['w']); + } // *TABLES* + + /* -- CSS-IMAGE-FLOAT -- */ + // If float (already) exists at this level + if (isset($this->floatmargins['R']) && $this->y <= $this->floatmargins['R']['y1'] && $this->y >= $this->floatmargins['R']['y0']) { + $maxWidth -= $this->floatmargins['R']['w']; + } + if (isset($this->floatmargins['L']) && $this->y <= $this->floatmargins['L']['y1'] && $this->y >= $this->floatmargins['L']['y0']) { + $maxWidth -= $this->floatmargins['L']['w']; + } + /* -- END CSS-IMAGE-FLOAT -- */ + + list($skipln) = $this->inlineObject($objattr['type'], '', $this->y, $objattr, $this->lMargin, ($this->flowingBlockAttr['contentWidth'] / Mpdf::SCALE), $maxWidth, $this->flowingBlockAttr['height'], false, $is_table); + // 1 -> New line needed because of width + // -1 -> Will fit width on line but NEW PAGE REQUIRED because of height + // -2 -> Will not fit on line therefore needs new line but thus NEW PAGE REQUIRED + $iby = $this->y; + $oldpage = $this->page; + $oldcol = $this->CurrCol; + if (($skipln == 1 || $skipln == -2) && !isset($objattr['float'])) { + $this->finishFlowingBlock(false, $objattr['type']); + $this->newFlowingBlock($this->divwidth, $this->divheight, $align, $is_table, $blockstate, false, $blockdir, $table_draft); + } + + if (!$table_draft) { + $thispage = $this->page; + if ($this->CurrCol != $oldcol) { + $changedcol = true; + } else { + $changedcol = false; + } + + // the previous lines can already have triggered page break or column change + if (!$changedcol && $skipln < 0 && $this->AcceptPageBreak() && $thispage == $oldpage) { + $this->AddPage($this->CurOrientation); + + // Added to correct Images already set on line before page advanced + // i.e. if second inline image on line is higher than first and forces new page + if (count($this->objectbuffer)) { + $yadj = $iby - $this->y; + foreach ($this->objectbuffer as $ib => $val) { + if ($this->objectbuffer[$ib]['OUTER-Y']) { + $this->objectbuffer[$ib]['OUTER-Y'] -= $yadj; + } + if ($this->objectbuffer[$ib]['BORDER-Y']) { + $this->objectbuffer[$ib]['BORDER-Y'] -= $yadj; + } + if ($this->objectbuffer[$ib]['INNER-Y']) { + $this->objectbuffer[$ib]['INNER-Y'] -= $yadj; + } + } + } + } + + // Added to correct for OddEven Margins + if ($this->page != $oldpage) { + if (($this->page - $oldpage) % 2 == 1) { + $bak_x += $this->MarginCorrection; + } + $oldpage = $this->page; + $y = $this->tMargin - $paint_ht_corr; + $this->oldy = $this->tMargin - $paint_ht_corr; + $old_height = 0; + } + $this->x = $bak_x; + /* -- COLUMNS -- */ + // COLS + // OR COLUMN CHANGE + if ($this->CurrCol != $oldcolumn) { + if ($this->directionality == 'rtl') { // *OTL* + $bak_x -= ($this->CurrCol - $oldcolumn) * ($this->ColWidth + $this->ColGap); // *OTL* + } // *OTL* + else { // *OTL* + $bak_x += ($this->CurrCol - $oldcolumn) * ($this->ColWidth + $this->ColGap); + } // *OTL* + $this->x = $bak_x; + $oldcolumn = $this->CurrCol; + $y = $this->y0 - $paint_ht_corr; + $this->oldy = $this->y0 - $paint_ht_corr; + $old_height = 0; + } + /* -- END COLUMNS -- */ + } + + /* -- CSS-IMAGE-FLOAT -- */ + if ($objattr['type'] == 'image' && isset($objattr['float'])) { + $fy = $this->y; + + // DIV TOP MARGIN/BORDER/PADDING + if ($this->flowingBlockAttr['newblock'] && ($this->flowingBlockAttr['blockstate'] == 1 || $this->flowingBlockAttr['blockstate'] == 3) && $this->flowingBlockAttr['lineCount'] == 0) { + $fy += $this->blk[$this->blklvl]['margin_top'] + $this->blk[$this->blklvl]['padding_top'] + $this->blk[$this->blklvl]['border_top']['w']; + } + + if ($objattr['float'] == 'R') { + $fx = $this->w - $this->rMargin - $objattr['width'] - ($this->blk[$this->blklvl]['outer_right_margin'] + $this->blk[$this->blklvl]['border_right']['w'] + $this->blk[$this->blklvl]['padding_right']); + } elseif ($objattr['float'] == 'L') { + $fx = $this->lMargin + ($this->blk[$this->blklvl]['outer_left_margin'] + $this->blk[$this->blklvl]['border_left']['w'] + $this->blk[$this->blklvl]['padding_left']); + } + $w = $objattr['width']; + $h = abs($objattr['height']); + + $widthLeft = $maxWidth - ($this->flowingBlockAttr['contentWidth'] / Mpdf::SCALE); + $maxHeight = $this->h - ($this->tMargin + $this->margin_header + $this->bMargin + 10); + // For Images + $extraWidth = ($objattr['border_left']['w'] + $objattr['border_right']['w'] + $objattr['margin_left'] + $objattr['margin_right']); + $extraHeight = ($objattr['border_top']['w'] + $objattr['border_bottom']['w'] + $objattr['margin_top'] + $objattr['margin_bottom']); + + if ($objattr['itype'] == 'wmf' || $objattr['itype'] == 'svg') { + $file = $objattr['file']; + $info = $this->formobjects[$file]; + } else { + $file = $objattr['file']; + $info = $this->images[$file]; + } + $img_w = $w - $extraWidth; + $img_h = $h - $extraHeight; + if ($objattr['border_left']['w']) { + $objattr['BORDER-WIDTH'] = $img_w + (($objattr['border_left']['w'] + $objattr['border_right']['w']) / 2); + $objattr['BORDER-HEIGHT'] = $img_h + (($objattr['border_top']['w'] + $objattr['border_bottom']['w']) / 2); + $objattr['BORDER-X'] = $fx + $objattr['margin_left'] + (($objattr['border_left']['w']) / 2); + $objattr['BORDER-Y'] = $fy + $objattr['margin_top'] + (($objattr['border_top']['w']) / 2); + } + $objattr['INNER-WIDTH'] = $img_w; + $objattr['INNER-HEIGHT'] = $img_h; + $objattr['INNER-X'] = $fx + $objattr['margin_left'] + ($objattr['border_left']['w']); + $objattr['INNER-Y'] = $fy + $objattr['margin_top'] + ($objattr['border_top']['w']); + $objattr['ID'] = $info['i']; + $objattr['OUTER-WIDTH'] = $w; + $objattr['OUTER-HEIGHT'] = $h; + $objattr['OUTER-X'] = $fx; + $objattr['OUTER-Y'] = $fy; + if ($objattr['float'] == 'R') { + // If R float already exists at this level + $this->floatmargins['R']['skipline'] = false; + if (isset($this->floatmargins['R']['y1']) && $this->floatmargins['R']['y1'] > 0 && $fy < $this->floatmargins['R']['y1']) { + $this->WriteFlowingBlock($vetor[0], $vetor[18]); // mPDF 5.7.1 + } // If L float already exists at this level + elseif (isset($this->floatmargins['L']['y1']) && $this->floatmargins['L']['y1'] > 0 && $fy < $this->floatmargins['L']['y1']) { + // Final check distance between floats is not now too narrow to fit text + $mw = 2 * $this->GetCharWidth('W', false); + if (($this->blk[$this->blklvl]['inner_width'] - $w - $this->floatmargins['L']['w']) < $mw) { + $this->WriteFlowingBlock($vetor[0], $vetor[18]); // mPDF 5.7.1 + } else { + $this->floatmargins['R']['x'] = $fx; + $this->floatmargins['R']['w'] = $w; + $this->floatmargins['R']['y0'] = $fy; + $this->floatmargins['R']['y1'] = $fy + $h; + if ($skipln == 1) { + $this->floatmargins['R']['skipline'] = true; + $this->floatmargins['R']['id'] = count($this->floatbuffer) + 0; + $objattr['skipline'] = true; + } + $this->floatbuffer[] = $objattr; + } + } else { + $this->floatmargins['R']['x'] = $fx; + $this->floatmargins['R']['w'] = $w; + $this->floatmargins['R']['y0'] = $fy; + $this->floatmargins['R']['y1'] = $fy + $h; + if ($skipln == 1) { + $this->floatmargins['R']['skipline'] = true; + $this->floatmargins['R']['id'] = count($this->floatbuffer) + 0; + $objattr['skipline'] = true; + } + $this->floatbuffer[] = $objattr; + } + } elseif ($objattr['float'] == 'L') { + // If L float already exists at this level + $this->floatmargins['L']['skipline'] = false; + if (isset($this->floatmargins['L']['y1']) && $this->floatmargins['L']['y1'] > 0 && $fy < $this->floatmargins['L']['y1']) { + $this->floatmargins['L']['skipline'] = false; + $this->WriteFlowingBlock($vetor[0], $vetor[18]); // mPDF 5.7.1 + } // If R float already exists at this level + elseif (isset($this->floatmargins['R']['y1']) && $this->floatmargins['R']['y1'] > 0 && $fy < $this->floatmargins['R']['y1']) { + // Final check distance between floats is not now too narrow to fit text + $mw = 2 * $this->GetCharWidth('W', false); + if (($this->blk[$this->blklvl]['inner_width'] - $w - $this->floatmargins['R']['w']) < $mw) { + $this->WriteFlowingBlock($vetor[0], $vetor[18]); // mPDF 5.7.1 + } else { + $this->floatmargins['L']['x'] = $fx + $w; + $this->floatmargins['L']['w'] = $w; + $this->floatmargins['L']['y0'] = $fy; + $this->floatmargins['L']['y1'] = $fy + $h; + if ($skipln == 1) { + $this->floatmargins['L']['skipline'] = true; + $this->floatmargins['L']['id'] = count($this->floatbuffer) + 0; + $objattr['skipline'] = true; + } + $this->floatbuffer[] = $objattr; + } + } else { + $this->floatmargins['L']['x'] = $fx + $w; + $this->floatmargins['L']['w'] = $w; + $this->floatmargins['L']['y0'] = $fy; + $this->floatmargins['L']['y1'] = $fy + $h; + if ($skipln == 1) { + $this->floatmargins['L']['skipline'] = true; + $this->floatmargins['L']['id'] = count($this->floatbuffer) + 0; + $objattr['skipline'] = true; + } + $this->floatbuffer[] = $objattr; + } + } + } else { + /* -- END CSS-IMAGE-FLOAT -- */ + $this->WriteFlowingBlock($vetor[0], (isset($vetor[18]) ? $vetor[18] : null)); // mPDF 5.7.1 + /* -- CSS-IMAGE-FLOAT -- */ + } + /* -- END CSS-IMAGE-FLOAT -- */ + } // *TABLES* + } // END If special content + else { // THE text + if ($this->tableLevel) { + $paint_ht_corr = 0; + } // To move the y up when new column/page started if div border needed + else { + $paint_ht_corr = $this->blk[$this->blklvl]['border_top']['w']; + } + + if ($vetor[0] == "\n") { // We are reading a
    now turned into newline ("\n") + if ($this->flowingBlockAttr['content']) { + $this->finishFlowingBlock(false, 'br'); + } elseif ($is_table) { + $this->y+= $this->_computeLineheight($this->cellLineHeight); + } elseif (!$is_table) { + $this->DivLn($this->lineheight); + if ($this->ColActive) { + $this->breakpoints[$this->CurrCol][] = $this->y; + } // *COLUMNS* + } + // Added to correct for OddEven Margins + if ($this->page != $oldpage) { + if (($this->page - $oldpage) % 2 == 1) { + $bak_x += $this->MarginCorrection; + } + $oldpage = $this->page; + $y = $this->tMargin - $paint_ht_corr; + $this->oldy = $this->tMargin - $paint_ht_corr; + $old_height = 0; + } + $this->x = $bak_x; + /* -- COLUMNS -- */ + // COLS + // OR COLUMN CHANGE + if ($this->CurrCol != $oldcolumn) { + if ($this->directionality == 'rtl') { // *OTL* + $bak_x -= ($this->CurrCol - $oldcolumn) * ($this->ColWidth + $this->ColGap); // *OTL* + } // *OTL* + else { // *OTL* + $bak_x += ($this->CurrCol - $oldcolumn) * ($this->ColWidth + $this->ColGap); + } // *OTL* + $this->x = $bak_x; + $oldcolumn = $this->CurrCol; + $y = $this->y0 - $paint_ht_corr; + $this->oldy = $this->y0 - $paint_ht_corr; + $old_height = 0; + } + /* -- END COLUMNS -- */ + $this->newFlowingBlock($this->divwidth, $this->divheight, $align, $is_table, $blockstate, false, $blockdir, $table_draft); + } else { + $this->WriteFlowingBlock($vetor[0], $vetor[18]); // mPDF 5.7.1 + // Added to correct for OddEven Margins + if ($this->page != $oldpage) { + if (($this->page - $oldpage) % 2 == 1) { + $bak_x += $this->MarginCorrection; + $this->x = $bak_x; + } + $oldpage = $this->page; + $y = $this->tMargin - $paint_ht_corr; + $this->oldy = $this->tMargin - $paint_ht_corr; + $old_height = 0; + } + /* -- COLUMNS -- */ + // COLS + // OR COLUMN CHANGE + if ($this->CurrCol != $oldcolumn) { + if ($this->directionality == 'rtl') { // *OTL* + $bak_x -= ($this->CurrCol - $oldcolumn) * ($this->ColWidth + $this->ColGap); // *OTL* + } // *OTL* + else { // *OTL* + $bak_x += ($this->CurrCol - $oldcolumn) * ($this->ColWidth + $this->ColGap); + } // *OTL* + $this->x = $bak_x; + $oldcolumn = $this->CurrCol; + $y = $this->y0 - $paint_ht_corr; + $this->oldy = $this->y0 - $paint_ht_corr; + $old_height = 0; + } + /* -- END COLUMNS -- */ + } + } + + // Check if it is the last element. If so then finish printing the block + if ($i == ($array_size - 1)) { + $this->finishFlowingBlock(true); // true = END of flowing block + // Added to correct for OddEven Margins + if ($this->page != $oldpage) { + if (($this->page - $oldpage) % 2 == 1) { + $bak_x += $this->MarginCorrection; + $this->x = $bak_x; + } + $oldpage = $this->page; + $y = $this->tMargin - $paint_ht_corr; + $this->oldy = $this->tMargin - $paint_ht_corr; + $old_height = 0; + } + + /* -- COLUMNS -- */ + // COLS + // OR COLUMN CHANGE + if ($this->CurrCol != $oldcolumn) { + if ($this->directionality == 'rtl') { // *OTL* + $bak_x -= ($this->CurrCol - $oldcolumn) * ($this->ColWidth + $this->ColGap); // *OTL* + } // *OTL* + else { // *OTL* + $bak_x += ($this->CurrCol - $oldcolumn) * ($this->ColWidth + $this->ColGap); + } // *OTL* + $this->x = $bak_x; + $oldcolumn = $this->CurrCol; + $y = $this->y0 - $paint_ht_corr; + $this->oldy = $this->y0 - $paint_ht_corr; + $old_height = 0; + } + /* -- END COLUMNS -- */ + } + + // RESETTING VALUES + $this->SetTColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + $this->SetDColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + $this->SetFColor($this->colorConverter->convert(255, $this->PDFAXwarnings)); + $this->colorarray = ''; + $this->spanbgcolorarray = ''; + $this->spanbgcolor = false; + $this->spanborder = false; + $this->spanborddet = []; + $this->HREF = ''; + $this->textparam = []; + $this->SetTextOutline(); + + $this->textvar = 0x00; // mPDF 5.7.1 + $this->OTLtags = []; + $this->textshadow = ''; + + $this->currentfontfamily = ''; + $this->currentfontsize = ''; + $this->currentfontstyle = ''; + $this->currentLang = $this->default_lang; // mPDF 6 + $this->RestrictUnicodeFonts($this->default_available_fonts); // mPDF 6 + /* -- TABLES -- */ + if ($this->tableLevel) { + $this->SetLineHeight('', $this->table[1][1]['cellLineHeight']); // *TABLES* + } else { /* -- END TABLES -- */ + if (isset($this->blk[$this->blklvl]['line_height']) && $this->blk[$this->blklvl]['line_height']) { + $this->SetLineHeight('', $this->blk[$this->blklvl]['line_height']); // sets default line height + } + } + $this->ResetStyles(); + $this->lSpacingCSS = ''; + $this->wSpacingCSS = ''; + $this->fixedlSpacing = false; + $this->minwSpacing = 0; + $this->SetDash(); + $this->dash_on = false; + $this->dotted_on = false; + }//end of for(i=0;iReset(); // mPDF 6 + // PAINT DIV BORDER // DISABLED IN COLUMNS AS DOESN'T WORK WHEN BROKEN ACROSS COLS?? + if ((isset($this->blk[$this->blklvl]['border']) || isset($this->blk[$this->blklvl]['bgcolor']) || isset($this->blk[$this->blklvl]['box_shadow'])) && $blockstate && ($this->y != $this->oldy)) { + $bottom_y = $this->y; // Does not include Bottom Margin + if (isset($this->blk[$this->blklvl]['startpage']) && $this->blk[$this->blklvl]['startpage'] != $this->page && $blockstate != 1) { + $this->PaintDivBB('pagetop', $blockstate); + } elseif ($blockstate != 1) { + $this->PaintDivBB('', $blockstate); + } + $this->y = $bottom_y; + $this->x = $bak_x; + } + + // Reset Font + $this->SetFontSize($this->default_font_size, false); + if ($table_draft) { + $ch = $this->y - $bak_y; + $this->y = $bak_y; + $this->x = $bak_x; + return $ch; + } + } + + function _setDashBorder($style, $div, $cp, $side) + { + if ($style == 'dashed' && (($side == 'L' || $side == 'R') || ($side == 'T' && $div != 'pagetop' && !$cp) || ($side == 'B' && $div != 'pagebottom') )) { + $dashsize = 2; // final dash will be this + 1*linewidth + $dashsizek = 1.5; // ratio of Dash/Blank + $this->SetDash($dashsize, ($dashsize / $dashsizek) + ($this->LineWidth * 2)); + } elseif ($style == 'dotted' || ($side == 'T' && ($div == 'pagetop' || $cp)) || ($side == 'B' && $div == 'pagebottom')) { + // Round join and cap + $this->SetLineJoin(1); + $this->SetLineCap(1); + $this->SetDash(0.001, ($this->LineWidth * 3)); + } + } + + function _setBorderLine($b, $k = 1) + { + $this->SetLineWidth($b['w'] / $k); + $this->SetDColor($b['c']); + if ($b['c'][0] == 5) { // RGBa + $this->SetAlpha(ord($b['c'][4]) / 100, 'Normal', false, 'S'); // mPDF 5.7.2 + } elseif ($b['c'][0] == 6) { // CMYKa + $this->SetAlpha(ord($b['c'][5]) / 100, 'Normal', false, 'S'); // mPDF 5.7.2 + } + } + + function PaintDivBB($divider = '', $blockstate = 0, $blvl = 0) + { + // Borders & backgrounds are done elsewhere for columns - messes up the repositioning in printcolumnbuffer + if ($this->ColActive) { + return; + } // *COLUMNS* + if ($this->keep_block_together) { + return; + } // mPDF 6 + $save_y = $this->y; + if (!$blvl) { + $blvl = $this->blklvl; + } + $x0 = $x1 = $y0 = $y1 = 0; + + // Added mPDF 3.0 Float DIV + if (isset($this->blk[$blvl]['bb_painted'][$this->page]) && $this->blk[$blvl]['bb_painted'][$this->page]) { + return; + } // *CSS-FLOAT* + + if (isset($this->blk[$blvl]['x0'])) { + $x0 = $this->blk[$blvl]['x0']; + } // left + if (isset($this->blk[$blvl]['y1'])) { + $y1 = $this->blk[$blvl]['y1']; + } // bottom + // Added mPDF 3.0 Float DIV - ensures backgrounds/borders are drawn to bottom of page + if ($y1 == 0) { + if ($divider == 'pagebottom') { + $y1 = $this->h - $this->bMargin; + } else { + $y1 = $this->y; + } + } + + $continuingpage = (isset($this->blk[$blvl]['startpage']) && $this->blk[$blvl]['startpage'] != $this->page); + + if (isset($this->blk[$blvl]['y0'])) { + $y0 = $this->blk[$blvl]['y0']; + } + $h = $y1 - $y0; + $w = $this->blk[$blvl]['width']; + $x1 = $x0 + $w; + + // Set border-widths as used here + $border_top = $this->blk[$blvl]['border_top']['w']; + $border_bottom = $this->blk[$blvl]['border_bottom']['w']; + $border_left = $this->blk[$blvl]['border_left']['w']; + $border_right = $this->blk[$blvl]['border_right']['w']; + if (!$this->blk[$blvl]['border_top'] || $divider == 'pagetop' || $continuingpage) { + $border_top = 0; + } + if (!$this->blk[$blvl]['border_bottom'] || $blockstate == 1 || $divider == 'pagebottom') { + $border_bottom = 0; + } + + $brTL_H = 0; + $brTL_V = 0; + $brTR_H = 0; + $brTR_V = 0; + $brBL_H = 0; + $brBL_V = 0; + $brBR_H = 0; + $brBR_V = 0; + + $brset = false; + /* -- BORDER-RADIUS -- */ + if (isset($this->blk[$blvl]['border_radius_TL_H'])) { + $brTL_H = $this->blk[$blvl]['border_radius_TL_H']; + $brset = true; + } + if (isset($this->blk[$blvl]['border_radius_TL_V'])) { + $brTL_V = $this->blk[$blvl]['border_radius_TL_V']; + $brset = true; + } + if (isset($this->blk[$blvl]['border_radius_TR_H'])) { + $brTR_H = $this->blk[$blvl]['border_radius_TR_H']; + $brset = true; + } + if (isset($this->blk[$blvl]['border_radius_TR_V'])) { + $brTR_V = $this->blk[$blvl]['border_radius_TR_V']; + $brset = true; + } + if (isset($this->blk[$blvl]['border_radius_BR_H'])) { + $brBR_H = $this->blk[$blvl]['border_radius_BR_H']; + $brset = true; + } + if (isset($this->blk[$blvl]['border_radius_BR_V'])) { + $brBR_V = $this->blk[$blvl]['border_radius_BR_V']; + $brset = true; + } + if (isset($this->blk[$blvl]['border_radius_BL_H'])) { + $brBL_H = $this->blk[$blvl]['border_radius_BL_H']; + $brset = true; + } + if (isset($this->blk[$blvl]['border_radius_BL_V'])) { + $brBL_V = $this->blk[$blvl]['border_radius_BL_V']; + $brset = true; + } + + if (!$this->blk[$blvl]['border_top'] || $divider == 'pagetop' || $continuingpage) { + $brTL_H = 0; + $brTL_V = 0; + $brTR_H = 0; + $brTR_V = 0; + } + if (!$this->blk[$blvl]['border_bottom'] || $blockstate == 1 || $divider == 'pagebottom') { + $brBL_H = 0; + $brBL_V = 0; + $brBR_H = 0; + $brBR_V = 0; + } + + // Disallow border-radius if it is smaller than the border width. + if ($brTL_H < min($border_left, $border_top)) { + $brTL_H = $brTL_V = 0; + } + if ($brTL_V < min($border_left, $border_top)) { + $brTL_V = $brTL_H = 0; + } + if ($brTR_H < min($border_right, $border_top)) { + $brTR_H = $brTR_V = 0; + } + if ($brTR_V < min($border_right, $border_top)) { + $brTR_V = $brTR_H = 0; + } + if ($brBL_H < min($border_left, $border_bottom)) { + $brBL_H = $brBL_V = 0; + } + if ($brBL_V < min($border_left, $border_bottom)) { + $brBL_V = $brBL_H = 0; + } + if ($brBR_H < min($border_right, $border_bottom)) { + $brBR_H = $brBR_V = 0; + } + if ($brBR_V < min($border_right, $border_bottom)) { + $brBR_V = $brBR_H = 0; + } + + // CHECK FOR radii that sum to > width or height of div ******** + $f = min($h / ($brTL_V + $brBL_V + 0.001), $h / ($brTR_V + $brBR_V + 0.001), $w / ($brTL_H + $brTR_H + 0.001), $w / ($brBL_H + $brBR_H + 0.001)); + if ($f < 1) { + $brTL_H *= $f; + $brTL_V *= $f; + $brTR_H *= $f; + $brTR_V *= $f; + $brBL_H *= $f; + $brBL_V *= $f; + $brBR_H *= $f; + $brBR_V *= $f; + } + /* -- END BORDER-RADIUS -- */ + + $tbcol = $this->colorConverter->convert(255, $this->PDFAXwarnings); + for ($l = 0; $l <= $blvl; $l++) { + if ($this->blk[$l]['bgcolor']) { + $tbcol = $this->blk[$l]['bgcolorarray']; + } + } + + // BORDERS + if (isset($this->blk[$blvl]['y0']) && $this->blk[$blvl]['y0']) { + $y0 = $this->blk[$blvl]['y0']; + } + $h = $y1 - $y0; + $w = $this->blk[$blvl]['width']; + + if ($this->blk[$blvl]['border_top'] && $divider != 'pagetop' && !$continuingpage) { + $tbd = $this->blk[$blvl]['border_top']; + + $legend = ''; + $legbreakL = 0; + $legbreakR = 0; + // BORDER LEGEND + if (isset($this->blk[$blvl]['border_legend']) && $this->blk[$blvl]['border_legend']) { + $legend = $this->blk[$blvl]['border_legend']; // Same structure array as textbuffer + $txt = $legend[0] = ltrim($legend[0]); + if (!empty($legend[18])) { + $this->otl->trimOTLdata($legend[18], true, false); + } // *OTL* + // Set font, size, style, color + $this->SetFont($legend[4], $legend[2], $legend[11]); + if (isset($legend[3]) && $legend[3]) { + $cor = $legend[3]; + $this->SetTColor($cor); + } + $stringWidth = $this->GetStringWidth($txt, true, $legend[18], $legend[8]); + $save_x = $this->x; + $save_y = $this->y; + $save_currentfontfamily = $this->FontFamily; + $save_currentfontsize = $this->FontSizePt; + $save_currentfontstyle = $this->FontStyle; + $this->y = $y0 - $this->FontSize / 2 + $this->blk[$blvl]['border_top']['w'] / 2; + $this->x = $x0 + $this->blk[$blvl]['padding_left'] + $this->blk[$blvl]['border_left']['w']; + + // Set the distance from the border line to the text ? make configurable variable + $gap = 0.2 * $this->FontSize; + $legbreakL = $this->x - $gap; + $legbreakR = $this->x + $stringWidth + $gap; + $this->magic_reverse_dir($txt, $this->blk[$blvl]['direction'], $legend[18]); + $fill = ''; + $this->Cell($stringWidth, $this->FontSize, $txt, '', 0, 'C', $fill, '', 0, 0, 0, 'M', $fill, false, $legend[18], $legend[8]); + // Reset + $this->x = $save_x; + $this->y = $save_y; + $this->SetFont($save_currentfontfamily, $save_currentfontstyle, $save_currentfontsize); + $this->SetTColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + } + + if (isset($tbd['s']) && $tbd['s']) { + if (!$brset && $tbd['style'] != 'dotted' && $tbd['style'] != 'dashed') { + $this->writer->write('q'); + $this->SetLineWidth(0); + $this->writer->write(sprintf('%.3F %.3F m ', ($x0) * Mpdf::SCALE, ($this->h - ($y0)) * Mpdf::SCALE)); + $this->writer->write(sprintf('%.3F %.3F l ', ($x0 + $border_left) * Mpdf::SCALE, ($this->h - ($y0 + $border_top)) * Mpdf::SCALE)); + $this->writer->write(sprintf('%.3F %.3F l ', ($x0 + $w - $border_right) * Mpdf::SCALE, ($this->h - ($y0 + $border_top)) * Mpdf::SCALE)); + $this->writer->write(sprintf('%.3F %.3F l ', ($x0 + $w) * Mpdf::SCALE, ($this->h - ($y0)) * Mpdf::SCALE)); + $this->writer->write(' h W n '); // Ends path no-op & Sets the clipping path + } + + $this->_setBorderLine($tbd); + if ($tbd['style'] == 'dotted' || $tbd['style'] == 'dashed') { + $legbreakL -= $border_top / 2; // because line cap different + $legbreakR += $border_top / 2; + $this->_setDashBorder($tbd['style'], $divider, $continuingpage, 'T'); + } /* -- BORDER-RADIUS -- */ elseif (($brTL_V && $brTL_H) || ($brTR_V && $brTR_H) || $tbd['style'] == 'solid' || $tbd['style'] == 'double') { + $this->SetLineJoin(0); + $this->SetLineCap(0); + } + $s = ''; + if ($brTR_H && $brTR_V) { + $s .= ($this->_EllipseArc($x0 + $w - $brTR_H, $y0 + $brTR_V, $brTR_H - $border_top / 2, $brTR_V - $border_top / 2, 1, 2, true)) . "\n"; + } else { /* -- END BORDER-RADIUS -- */ + if ($tbd['style'] == 'solid' || $tbd['style'] == 'double') { + $s .= (sprintf('%.3F %.3F m ', ($x0 + $w) * Mpdf::SCALE, ($this->h - ($y0 + ($border_top / 2))) * Mpdf::SCALE)) . "\n"; + } else { + $s .= (sprintf('%.3F %.3F m ', ($x0 + $w - ($border_top / 2)) * Mpdf::SCALE, ($this->h - ($y0 + ($border_top / 2))) * Mpdf::SCALE)) . "\n"; + } + } + /* -- BORDER-RADIUS -- */ + if ($brTL_H && $brTL_V) { + if ($legend) { + if ($legbreakR < ($x0 + $w - $brTR_H)) { + $s .= (sprintf('%.3F %.3F l ', $legbreakR * Mpdf::SCALE, ($this->h - ($y0 + ($border_top / 2))) * Mpdf::SCALE)) . "\n"; + } + if ($legbreakL > ($x0 + $brTL_H )) { + $s .= (sprintf('%.3F %.3F m ', $legbreakL * Mpdf::SCALE, ($this->h - ($y0 + ($border_top / 2))) * Mpdf::SCALE)) . "\n"; + $s .= (sprintf('%.3F %.3F l ', ($x0 + $brTL_H ) * Mpdf::SCALE, ($this->h - ($y0 + ($border_top / 2))) * Mpdf::SCALE) . "\n"); + } else { + $s .= (sprintf('%.3F %.3F m ', ($x0 + $brTL_H ) * Mpdf::SCALE, ($this->h - ($y0 + ($border_top / 2))) * Mpdf::SCALE)) . "\n"; + } + } else { + $s .= (sprintf('%.3F %.3F l ', ($x0 + $brTL_H ) * Mpdf::SCALE, ($this->h - ($y0 + ($border_top / 2))) * Mpdf::SCALE)) . "\n"; + } + $s .= ($this->_EllipseArc($x0 + $brTL_H, $y0 + $brTL_V, $brTL_H - $border_top / 2, $brTL_V - $border_top / 2, 2, 1)) . "\n"; + } else { + /* -- END BORDER-RADIUS -- */ + if ($legend) { + if ($legbreakR < ($x0 + $w)) { + $s .= (sprintf('%.3F %.3F l ', $legbreakR * Mpdf::SCALE, ($this->h - ($y0 + ($border_top / 2))) * Mpdf::SCALE)) . "\n"; + } + if ($legbreakL > ($x0)) { + $s .= (sprintf('%.3F %.3F m ', $legbreakL * Mpdf::SCALE, ($this->h - ($y0 + ($border_top / 2))) * Mpdf::SCALE)) . "\n"; + if ($tbd['style'] == 'solid' || $tbd['style'] == 'double') { + $s .= (sprintf('%.3F %.3F l ', ($x0) * Mpdf::SCALE, ($this->h - ($y0 + ($border_top / 2))) * Mpdf::SCALE)) . "\n"; + } else { + $s .= (sprintf('%.3F %.3F l ', ($x0 + ($border_top / 2)) * Mpdf::SCALE, ($this->h - ($y0 + ($border_top / 2))) * Mpdf::SCALE)) . "\n"; + } + } elseif ($tbd['style'] == 'solid' || $tbd['style'] == 'double') { + $s .= (sprintf('%.3F %.3F m ', ($x0) * Mpdf::SCALE, ($this->h - ($y0 + ($border_top / 2))) * Mpdf::SCALE)) . "\n"; + } else { + $s .= (sprintf('%.3F %.3F m ', ($x0 + $border_top / 2) * Mpdf::SCALE, ($this->h - ($y0 + ($border_top / 2))) * Mpdf::SCALE)) . "\n"; + } + } elseif ($tbd['style'] == 'solid' || $tbd['style'] == 'double') { + $s .= (sprintf('%.3F %.3F l ', ($x0) * Mpdf::SCALE, ($this->h - ($y0 + ($border_top / 2))) * Mpdf::SCALE)) . "\n"; + } else { + $s .= (sprintf('%.3F %.3F l ', ($x0 + ($border_top / 2)) * Mpdf::SCALE, ($this->h - ($y0 + ($border_top / 2))) * Mpdf::SCALE)) . "\n"; + } + /* -- BORDER-RADIUS -- */ + } + /* -- END BORDER-RADIUS -- */ + $s .= 'S' . "\n"; + $this->writer->write($s); + + if ($tbd['style'] == 'double') { + $this->SetLineWidth($tbd['w'] / 3); + $this->SetDColor($tbcol); + $this->writer->write($s); + } + if (!$brset && $tbd['style'] != 'dotted' && $tbd['style'] != 'dashed') { + $this->writer->write('Q'); + } + + // Reset Corners and Dash off + $this->SetLineWidth(0.1); + $this->SetDColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + $this->SetLineJoin(2); + $this->SetLineCap(2); + $this->SetDash(); + } + } + // Reinstate line above for dotted line divider when block border crosses a page + // elseif ($divider == 'pagetop' || $continuingpage) { + + if ($this->blk[$blvl]['border_bottom'] && $blockstate != 1 && $divider != 'pagebottom') { + $tbd = $this->blk[$blvl]['border_bottom']; + if (isset($tbd['s']) && $tbd['s']) { + if (!$brset && $tbd['style'] != 'dotted' && $tbd['style'] != 'dashed') { + $this->writer->write('q'); + $this->SetLineWidth(0); + $this->writer->write(sprintf('%.3F %.3F m ', ($x0) * Mpdf::SCALE, ($this->h - ($y0 + $h)) * Mpdf::SCALE)); + $this->writer->write(sprintf('%.3F %.3F l ', ($x0 + $border_left) * Mpdf::SCALE, ($this->h - ($y0 + $h - $border_bottom)) * Mpdf::SCALE)); + $this->writer->write(sprintf('%.3F %.3F l ', ($x0 + $w - $border_right) * Mpdf::SCALE, ($this->h - ($y0 + $h - $border_bottom)) * Mpdf::SCALE)); + $this->writer->write(sprintf('%.3F %.3F l ', ($x0 + $w) * Mpdf::SCALE, ($this->h - ($y0 + $h)) * Mpdf::SCALE)); + $this->writer->write(' h W n '); // Ends path no-op & Sets the clipping path + } + + $this->_setBorderLine($tbd); + if ($tbd['style'] == 'dotted' || $tbd['style'] == 'dashed') { + $this->_setDashBorder($tbd['style'], $divider, $continuingpage, 'B'); + } /* -- BORDER-RADIUS -- */ elseif (($brBL_V && $brBL_H) || ($brBR_V && $brBR_H) || $tbd['style'] == 'solid' || $tbd['style'] == 'double') { + $this->SetLineJoin(0); + $this->SetLineCap(0); + } + $s = ''; + if ($brBL_H && $brBL_V) { + $s .= ($this->_EllipseArc($x0 + $brBL_H, $y0 + $h - $brBL_V, $brBL_H - $border_bottom / 2, $brBL_V - $border_bottom / 2, 3, 2, true)) . "\n"; + } else { /* -- END BORDER-RADIUS -- */ + if ($tbd['style'] == 'solid' || $tbd['style'] == 'double') { + $s .= (sprintf('%.3F %.3F m ', ($x0) * Mpdf::SCALE, ($this->h - ($y0 + $h - ($border_bottom / 2))) * Mpdf::SCALE)) . "\n"; + } else { + $s .= (sprintf('%.3F %.3F m ', ($x0 + ($border_bottom / 2)) * Mpdf::SCALE, ($this->h - ($y0 + $h - ($border_bottom / 2))) * Mpdf::SCALE)) . "\n"; + } + } + /* -- BORDER-RADIUS -- */ + if ($brBR_H && $brBR_V) { + $s .= (sprintf('%.3F %.3F l ', ($x0 + $w - ($border_bottom / 2) - $brBR_H ) * Mpdf::SCALE, ($this->h - ($y0 + $h - ($border_bottom / 2))) * Mpdf::SCALE)) . "\n"; + $s .= ($this->_EllipseArc($x0 + $w - $brBR_H, $y0 + $h - $brBR_V, $brBR_H - $border_bottom / 2, $brBR_V - $border_bottom / 2, 4, 1)) . "\n"; + } else { /* -- END BORDER-RADIUS -- */ + if ($tbd['style'] == 'solid' || $tbd['style'] == 'double') { + $s .= (sprintf('%.3F %.3F l ', ($x0 + $w) * Mpdf::SCALE, ($this->h - ($y0 + $h - ($border_bottom / 2))) * Mpdf::SCALE)) . "\n"; + } else { + $s .= (sprintf('%.3F %.3F l ', ($x0 + $w - ($border_bottom / 2)) * Mpdf::SCALE, ($this->h - ($y0 + $h - ($border_bottom / 2))) * Mpdf::SCALE)) . "\n"; + } + } + $s .= 'S' . "\n"; + $this->writer->write($s); + + if ($tbd['style'] == 'double') { + $this->SetLineWidth($tbd['w'] / 3); + $this->SetDColor($tbcol); + $this->writer->write($s); + } + if (!$brset && $tbd['style'] != 'dotted' && $tbd['style'] != 'dashed') { + $this->writer->write('Q'); + } + + // Reset Corners and Dash off + $this->SetLineWidth(0.1); + $this->SetDColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + $this->SetLineJoin(2); + $this->SetLineCap(2); + $this->SetDash(); + } + } + // Reinstate line below for dotted line divider when block border crosses a page + // elseif ($blockstate == 1 || $divider == 'pagebottom') { + + if ($this->blk[$blvl]['border_left']) { + $tbd = $this->blk[$blvl]['border_left']; + if (isset($tbd['s']) && $tbd['s']) { + if (!$brset && $tbd['style'] != 'dotted' && $tbd['style'] != 'dashed') { + $this->writer->write('q'); + $this->SetLineWidth(0); + $this->writer->write(sprintf('%.3F %.3F m ', ($x0) * Mpdf::SCALE, ($this->h - ($y0)) * Mpdf::SCALE)); + $this->writer->write(sprintf('%.3F %.3F l ', ($x0 + $border_left) * Mpdf::SCALE, ($this->h - ($y0 + $border_top)) * Mpdf::SCALE)); + $this->writer->write(sprintf('%.3F %.3F l ', ($x0 + $border_left) * Mpdf::SCALE, ($this->h - ($y0 + $h - $border_bottom)) * Mpdf::SCALE)); + $this->writer->write(sprintf('%.3F %.3F l ', ($x0) * Mpdf::SCALE, ($this->h - ($y0 + $h)) * Mpdf::SCALE)); + $this->writer->write(' h W n '); // Ends path no-op & Sets the clipping path + } + + $this->_setBorderLine($tbd); + if ($tbd['style'] == 'dotted' || $tbd['style'] == 'dashed') { + $this->_setDashBorder($tbd['style'], $divider, $continuingpage, 'L'); + } /* -- BORDER-RADIUS -- */ elseif (($brTL_V && $brTL_H) || ($brBL_V && $brBL_H) || $tbd['style'] == 'solid' || $tbd['style'] == 'double') { + $this->SetLineJoin(0); + $this->SetLineCap(0); + } + $s = ''; + if ($brTL_V && $brTL_H) { + $s .= ($this->_EllipseArc($x0 + $brTL_H, $y0 + $brTL_V, $brTL_H - $border_left / 2, $brTL_V - $border_left / 2, 2, 2, true)) . "\n"; + } else { /* -- END BORDER-RADIUS -- */ + if ($tbd['style'] == 'solid' || $tbd['style'] == 'double') { + $s .= (sprintf('%.3F %.3F m ', ($x0 + ($border_left / 2)) * Mpdf::SCALE, ($this->h - ($y0)) * Mpdf::SCALE)) . "\n"; + } else { + $s .= (sprintf('%.3F %.3F m ', ($x0 + ($border_left / 2)) * Mpdf::SCALE, ($this->h - ($y0 + ($border_left / 2))) * Mpdf::SCALE)) . "\n"; + } + } + /* -- BORDER-RADIUS -- */ + if ($brBL_V && $brBL_H) { + $s .= (sprintf('%.3F %.3F l ', ($x0 + ($border_left / 2)) * Mpdf::SCALE, ($this->h - ($y0 + $h - ($border_left / 2) - $brBL_V) ) * Mpdf::SCALE)) . "\n"; + $s .= ($this->_EllipseArc($x0 + $brBL_H, $y0 + $h - $brBL_V, $brBL_H - $border_left / 2, $brBL_V - $border_left / 2, 3, 1)) . "\n"; + } else { /* -- END BORDER-RADIUS -- */ + if ($tbd['style'] == 'solid' || $tbd['style'] == 'double') { + $s .= (sprintf('%.3F %.3F l ', ($x0 + ($border_left / 2)) * Mpdf::SCALE, ($this->h - ($y0 + $h) ) * Mpdf::SCALE)) . "\n"; + } else { + $s .= (sprintf('%.3F %.3F l ', ($x0 + ($border_left / 2)) * Mpdf::SCALE, ($this->h - ($y0 + $h - ($border_left / 2)) ) * Mpdf::SCALE)) . "\n"; + } + } + $s .= 'S' . "\n"; + $this->writer->write($s); + + if ($tbd['style'] == 'double') { + $this->SetLineWidth($tbd['w'] / 3); + $this->SetDColor($tbcol); + $this->writer->write($s); + } + if (!$brset && $tbd['style'] != 'dotted' && $tbd['style'] != 'dashed') { + $this->writer->write('Q'); + } + + // Reset Corners and Dash off + $this->SetLineWidth(0.1); + $this->SetDColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + $this->SetLineJoin(2); + $this->SetLineCap(2); + $this->SetDash(); + } + } + if ($this->blk[$blvl]['border_right']) { + $tbd = $this->blk[$blvl]['border_right']; + if (isset($tbd['s']) && $tbd['s']) { + if (!$brset && $tbd['style'] != 'dotted' && $tbd['style'] != 'dashed') { + $this->writer->write('q'); + $this->SetLineWidth(0); + $this->writer->write(sprintf('%.3F %.3F m ', ($x0 + $w) * Mpdf::SCALE, ($this->h - ($y0)) * Mpdf::SCALE)); + $this->writer->write(sprintf('%.3F %.3F l ', ($x0 + $w - $border_right) * Mpdf::SCALE, ($this->h - ($y0 + $border_top)) * Mpdf::SCALE)); + $this->writer->write(sprintf('%.3F %.3F l ', ($x0 + $w - $border_right) * Mpdf::SCALE, ($this->h - ($y0 + $h - $border_bottom)) * Mpdf::SCALE)); + $this->writer->write(sprintf('%.3F %.3F l ', ($x0 + $w) * Mpdf::SCALE, ($this->h - ($y0 + $h)) * Mpdf::SCALE)); + $this->writer->write(' h W n '); // Ends path no-op & Sets the clipping path + } + + $this->_setBorderLine($tbd); + if ($tbd['style'] == 'dotted' || $tbd['style'] == 'dashed') { + $this->_setDashBorder($tbd['style'], $divider, $continuingpage, 'R'); + } /* -- BORDER-RADIUS -- */ elseif (($brTR_V && $brTR_H) || ($brBR_V && $brBR_H) || $tbd['style'] == 'solid' || $tbd['style'] == 'double') { + $this->SetLineJoin(0); + $this->SetLineCap(0); + } + $s = ''; + if ($brBR_V && $brBR_H) { + $s .= ($this->_EllipseArc($x0 + $w - $brBR_H, $y0 + $h - $brBR_V, $brBR_H - $border_right / 2, $brBR_V - $border_right / 2, 4, 2, true)) . "\n"; + } else { /* -- END BORDER-RADIUS -- */ + if ($tbd['style'] == 'solid' || $tbd['style'] == 'double') { + $s .= (sprintf('%.3F %.3F m ', ($x0 + $w - ($border_right / 2)) * Mpdf::SCALE, ($this->h - ($y0 + $h)) * Mpdf::SCALE)) . "\n"; + } else { + $s .= (sprintf('%.3F %.3F m ', ($x0 + $w - ($border_right / 2)) * Mpdf::SCALE, ($this->h - ($y0 + $h - ($border_right / 2))) * Mpdf::SCALE)) . "\n"; + } + } + /* -- BORDER-RADIUS -- */ + if ($brTR_V && $brTR_H) { + $s .= (sprintf('%.3F %.3F l ', ($x0 + $w - ($border_right / 2)) * Mpdf::SCALE, ($this->h - ($y0 + ($border_right / 2) + $brTR_V) ) * Mpdf::SCALE)) . "\n"; + $s .= ($this->_EllipseArc($x0 + $w - $brTR_H, $y0 + $brTR_V, $brTR_H - $border_right / 2, $brTR_V - $border_right / 2, 1, 1)) . "\n"; + } else { /* -- END BORDER-RADIUS -- */ + if ($tbd['style'] == 'solid' || $tbd['style'] == 'double') { + $s .= (sprintf('%.3F %.3F l ', ($x0 + $w - ($border_right / 2)) * Mpdf::SCALE, ($this->h - ($y0) ) * Mpdf::SCALE)) . "\n"; + } else { + $s .= (sprintf('%.3F %.3F l ', ($x0 + $w - ($border_right / 2)) * Mpdf::SCALE, ($this->h - ($y0 + ($border_right / 2)) ) * Mpdf::SCALE)) . "\n"; + } + } + $s .= 'S' . "\n"; + $this->writer->write($s); + + if ($tbd['style'] == 'double') { + $this->SetLineWidth($tbd['w'] / 3); + $this->SetDColor($tbcol); + $this->writer->write($s); + } + if (!$brset && $tbd['style'] != 'dotted' && $tbd['style'] != 'dashed') { + $this->writer->write('Q'); + } + + // Reset Corners and Dash off + $this->SetLineWidth(0.1); + $this->SetDColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + $this->SetLineJoin(2); + $this->SetLineCap(2); + $this->SetDash(); + } + } + + + $this->SetDash(); + $this->y = $save_y; + + + // BACKGROUNDS are disabled in columns/kbt/headers - messes up the repositioning in printcolumnbuffer + if ($this->ColActive || $this->kwt || $this->keep_block_together) { + return; + } + + + $bgx0 = $x0; + $bgx1 = $x1; + $bgy0 = $y0; + $bgy1 = $y1; + + // Defined br values represent the radius of the outer curve - need to take border-width/2 from each radius for drawing the borders + if (isset($this->blk[$blvl]['background_clip']) && $this->blk[$blvl]['background_clip'] == 'padding-box') { + $brbgTL_H = max(0, $brTL_H - $this->blk[$blvl]['border_left']['w']); + $brbgTL_V = max(0, $brTL_V - $this->blk[$blvl]['border_top']['w']); + $brbgTR_H = max(0, $brTR_H - $this->blk[$blvl]['border_right']['w']); + $brbgTR_V = max(0, $brTR_V - $this->blk[$blvl]['border_top']['w']); + $brbgBL_H = max(0, $brBL_H - $this->blk[$blvl]['border_left']['w']); + $brbgBL_V = max(0, $brBL_V - $this->blk[$blvl]['border_bottom']['w']); + $brbgBR_H = max(0, $brBR_H - $this->blk[$blvl]['border_right']['w']); + $brbgBR_V = max(0, $brBR_V - $this->blk[$blvl]['border_bottom']['w']); + $bgx0 += $this->blk[$blvl]['border_left']['w']; + $bgx1 -= $this->blk[$blvl]['border_right']['w']; + if ($this->blk[$blvl]['border_top'] && $divider != 'pagetop' && !$continuingpage) { + $bgy0 += $this->blk[$blvl]['border_top']['w']; + } + if ($this->blk[$blvl]['border_bottom'] && $blockstate != 1 && $divider != 'pagebottom') { + $bgy1 -= $this->blk[$blvl]['border_bottom']['w']; + } + } elseif (isset($this->blk[$blvl]['background_clip']) && $this->blk[$blvl]['background_clip'] == 'content-box') { + $brbgTL_H = max(0, $brTL_H - $this->blk[$blvl]['border_left']['w'] - $this->blk[$blvl]['padding_left']); + $brbgTL_V = max(0, $brTL_V - $this->blk[$blvl]['border_top']['w'] - $this->blk[$blvl]['padding_top']); + $brbgTR_H = max(0, $brTR_H - $this->blk[$blvl]['border_right']['w'] - $this->blk[$blvl]['padding_right']); + $brbgTR_V = max(0, $brTR_V - $this->blk[$blvl]['border_top']['w'] - $this->blk[$blvl]['padding_top']); + $brbgBL_H = max(0, $brBL_H - $this->blk[$blvl]['border_left']['w'] - $this->blk[$blvl]['padding_left']); + $brbgBL_V = max(0, $brBL_V - $this->blk[$blvl]['border_bottom']['w'] - $this->blk[$blvl]['padding_bottom']); + $brbgBR_H = max(0, $brBR_H - $this->blk[$blvl]['border_right']['w'] - $this->blk[$blvl]['padding_right']); + $brbgBR_V = max(0, $brBR_V - $this->blk[$blvl]['border_bottom']['w'] - $this->blk[$blvl]['padding_bottom']); + $bgx0 += $this->blk[$blvl]['border_left']['w'] + $this->blk[$blvl]['padding_left']; + $bgx1 -= $this->blk[$blvl]['border_right']['w'] + $this->blk[$blvl]['padding_right']; + if (($this->blk[$blvl]['border_top']['w'] || $this->blk[$blvl]['padding_top']) && $divider != 'pagetop' && !$continuingpage) { + $bgy0 += $this->blk[$blvl]['border_top']['w'] + $this->blk[$blvl]['padding_top']; + } + if (($this->blk[$blvl]['border_bottom']['w'] || $this->blk[$blvl]['padding_bottom']) && $blockstate != 1 && $divider != 'pagebottom') { + $bgy1 -= $this->blk[$blvl]['border_bottom']['w'] + $this->blk[$blvl]['padding_bottom']; + } + } else { + $brbgTL_H = $brTL_H; + $brbgTL_V = $brTL_V; + $brbgTR_H = $brTR_H; + $brbgTR_V = $brTR_V; + $brbgBL_H = $brBL_H; + $brbgBL_V = $brBL_V; + $brbgBR_H = $brBR_H; + $brbgBR_V = $brBR_V; + } + + // Set clipping path + $s = ' q 0 w '; // Line width=0 + $s .= sprintf('%.3F %.3F m ', ($bgx0 + $brbgTL_H ) * Mpdf::SCALE, ($this->h - $bgy0) * Mpdf::SCALE); // start point TL before the arc + /* -- BORDER-RADIUS -- */ + if ($brbgTL_H || $brbgTL_V) { + $s .= $this->_EllipseArc($bgx0 + $brbgTL_H, $bgy0 + $brbgTL_V, $brbgTL_H, $brbgTL_V, 2); // segment 2 TL + } + /* -- END BORDER-RADIUS -- */ + $s .= sprintf('%.3F %.3F l ', ($bgx0) * Mpdf::SCALE, ($this->h - ($bgy1 - $brbgBL_V )) * Mpdf::SCALE); // line to BL + /* -- BORDER-RADIUS -- */ + if ($brbgBL_H || $brbgBL_V) { + $s .= $this->_EllipseArc($bgx0 + $brbgBL_H, $bgy1 - $brbgBL_V, $brbgBL_H, $brbgBL_V, 3); // segment 3 BL + } + /* -- END BORDER-RADIUS -- */ + $s .= sprintf('%.3F %.3F l ', ($bgx1 - $brbgBR_H ) * Mpdf::SCALE, ($this->h - ($bgy1)) * Mpdf::SCALE); // line to BR + /* -- BORDER-RADIUS -- */ + if ($brbgBR_H || $brbgBR_V) { + $s .= $this->_EllipseArc($bgx1 - $brbgBR_H, $bgy1 - $brbgBR_V, $brbgBR_H, $brbgBR_V, 4); // segment 4 BR + } + /* -- END BORDER-RADIUS -- */ + $s .= sprintf('%.3F %.3F l ', ($bgx1) * Mpdf::SCALE, ($this->h - ($bgy0 + $brbgTR_V)) * Mpdf::SCALE); // line to TR + /* -- BORDER-RADIUS -- */ + if ($brbgTR_H || $brbgTR_V) { + $s .= $this->_EllipseArc($bgx1 - $brbgTR_H, $bgy0 + $brbgTR_V, $brbgTR_H, $brbgTR_V, 1); // segment 1 TR + } + /* -- END BORDER-RADIUS -- */ + $s .= sprintf('%.3F %.3F l ', ($bgx0 + $brbgTL_H ) * Mpdf::SCALE, ($this->h - $bgy0) * Mpdf::SCALE); // line to TL + // Box Shadow + $shadow = ''; + if (isset($this->blk[$blvl]['box_shadow']) && $this->blk[$blvl]['box_shadow'] && $h > 0) { + foreach ($this->blk[$blvl]['box_shadow'] as $sh) { + // Colors + if ($sh['col'][0] == 1) { + $colspace = 'Gray'; + if ($sh['col'][2] == 1) { + $col1 = '1' . $sh['col'][1] . '1' . $sh['col'][3]; + } else { + $col1 = '1' . $sh['col'][1] . '1' . chr(100); + } + $col2 = '1' . $sh['col'][1] . '1' . chr(0); + } elseif ($sh['col'][0] == 4) { // CMYK + $colspace = 'CMYK'; + $col1 = '6' . $sh['col'][1] . $sh['col'][2] . $sh['col'][3] . $sh['col'][4] . chr(100); + $col2 = '6' . $sh['col'][1] . $sh['col'][2] . $sh['col'][3] . $sh['col'][4] . chr(0); + } elseif ($sh['col'][0] == 5) { // RGBa + $colspace = 'RGB'; + $col1 = '5' . $sh['col'][1] . $sh['col'][2] . $sh['col'][3] . $sh['col'][4]; + $col2 = '5' . $sh['col'][1] . $sh['col'][2] . $sh['col'][3] . chr(0); + } elseif ($sh['col'][0] == 6) { // CMYKa + $colspace = 'CMYK'; + $col1 = '6' . $sh['col'][1] . $sh['col'][2] . $sh['col'][3] . $sh['col'][4] . $sh['col'][5]; + $col2 = '6' . $sh['col'][1] . $sh['col'][2] . $sh['col'][3] . $sh['col'][4] . chr(0); + } else { + $colspace = 'RGB'; + $col1 = '5' . $sh['col'][1] . $sh['col'][2] . $sh['col'][3] . chr(100); + $col2 = '5' . $sh['col'][1] . $sh['col'][2] . $sh['col'][3] . chr(0); + } + + // Use clipping path as set above (and rectangle around page) to clip area outside box + $shadow .= $s; // Use the clipping path with W* + $shadow .= sprintf('0 %.3F m %.3F %.3F l ', $this->h * Mpdf::SCALE, $this->w * Mpdf::SCALE, $this->h * Mpdf::SCALE); + $shadow .= sprintf('%.3F 0 l 0 0 l 0 %.3F l ', $this->w * Mpdf::SCALE, $this->h * Mpdf::SCALE); + $shadow .= 'W n' . "\n"; + + $sh['blur'] = abs($sh['blur']); // cannot have negative blur value + // Ensure spread/blur do not make effective shadow width/height < 0 + // Could do more complex things but this just adjusts spread value + if (-$sh['spread'] + $sh['blur'] / 2 > min($w / 2, $h / 2)) { + $sh['spread'] = $sh['blur'] / 2 - min($w / 2, $h / 2) + 0.01; + } + // Shadow Offset + if ($sh['x'] || $sh['y']) { + $shadow .= sprintf(' q 1 0 0 1 %.4F %.4F cm', $sh['x'] * Mpdf::SCALE, -$sh['y'] * Mpdf::SCALE) . "\n"; + } + + // Set path for INNER shadow + $shadow .= ' q 0 w '; + $shadow .= $this->SetFColor($col1, true) . "\n"; + if ($col1[0] == 5 && ord($col1[4]) < 100) { // RGBa + $shadow .= $this->SetAlpha(ord($col1[4]) / 100, 'Normal', true, 'F') . "\n"; + } elseif ($col1[0] == 6 && ord($col1[5]) < 100) { // CMYKa + $shadow .= $this->SetAlpha(ord($col1[5]) / 100, 'Normal', true, 'F') . "\n"; + } elseif ($col1[0] == 1 && $col1[2] == 1 && ord($col1[3]) < 100) { // Gray + $shadow .= $this->SetAlpha(ord($col1[3]) / 100, 'Normal', true, 'F') . "\n"; + } + + // Blur edges + $mag = 0.551784; // Bezier Control magic number for 4-part spline for circle/ellipse + $mag2 = 0.551784; // Bezier Control magic number to fill in edge of blurred rectangle + $d1 = $sh['spread'] + $sh['blur'] / 2; + $d2 = $sh['spread'] - $sh['blur'] / 2; + $bl = $sh['blur']; + $x00 = $x0 - $d1; + $y00 = $y0 - $d1; + $w00 = $w + $d1 * 2; + $h00 = $h + $d1 * 2; + + // If any border-radius is greater width-negative spread(inner edge), ignore radii for shadow or screws up + $flatten = false; + if (max($brbgTR_H, $brbgTL_H, $brbgBR_H, $brbgBL_H) >= $w + $d2) { + $flatten = true; + } + if (max($brbgTR_V, $brbgTL_V, $brbgBR_V, $brbgBL_V) >= $h + $d2) { + $flatten = true; + } + + + // TOP RIGHT corner + $p1x = $x00 + $w00 - $d1 - $brbgTR_H; + $p1c2x = $p1x + ($d2 + $brbgTR_H) * $mag; + $p1y = $y00 + $bl; + $p2x = $x00 + $w00 - $d1 - $brbgTR_H; + $p2c2x = $p2x + ($d1 + $brbgTR_H) * $mag; + $p2y = $y00; + $p2c1y = $p2y + $bl / 2; + $p3x = $x00 + $w00; + $p3c2x = $p3x - $bl / 2; + $p3y = $y00 + $d1 + $brbgTR_V; + $p3c1y = $p3y - ($d1 + $brbgTR_V) * $mag; + $p4x = $x00 + $w00 - $bl; + $p4y = $y00 + $d1 + $brbgTR_V; + $p4c2y = $p4y - ($d2 + $brbgTR_V) * $mag; + if (-$d2 > min($brbgTR_H, $brbgTR_V) || $flatten) { + $p1x = $x00 + $w00 - $bl; + $p1c2x = $p1x; + $p2x = $x00 + $w00 - $bl; + $p2c2x = $p2x + $bl * $mag2; + $p3y = $y00 + $bl; + $p3c1y = $p3y - $bl * $mag2; + $p4y = $y00 + $bl; + $p4c2y = $p4y; + } + + $shadow .= sprintf('%.3F %.3F m ', ($p1x ) * Mpdf::SCALE, ($this->h - ($p1y )) * Mpdf::SCALE); + $shadow .= sprintf('%.3F %.3F %.3F %.3F %.3F %.3F c ', ($p1c2x) * Mpdf::SCALE, ($this->h - ($p1y)) * Mpdf::SCALE, ($p4x) * Mpdf::SCALE, ($this->h - ($p4c2y)) * Mpdf::SCALE, ($p4x) * Mpdf::SCALE, ($this->h - ($p4y)) * Mpdf::SCALE); + $patch_array[0]['f'] = 0; + $patch_array[0]['points'] = [$p1x, $p1y, $p1x, $p1y, + $p2x, $p2c1y, $p2x, $p2y, $p2c2x, $p2y, + $p3x, $p3c1y, $p3x, $p3y, $p3c2x, $p3y, + $p4x, $p4y, $p4x, $p4y, $p4x, $p4c2y, + $p1c2x, $p1y]; + $patch_array[0]['colors'] = [$col1, $col2, $col2, $col1]; + + + // RIGHT + $p1x = $x00 + $w00; // control point only matches p3 preceding + $p1y = $y00 + $d1 + $brbgTR_V; + $p2x = $x00 + $w00 - $bl; // control point only matches p4 preceding + $p2y = $y00 + $d1 + $brbgTR_V; + $p3x = $x00 + $w00 - $bl; + $p3y = $y00 + $h00 - $d1 - $brbgBR_V; + $p4x = $x00 + $w00; + $p4c1x = $p4x - $bl / 2; + $p4y = $y00 + $h00 - $d1 - $brbgBR_V; + if (-$d2 > min($brbgTR_H, $brbgTR_V) || $flatten) { + $p1y = $y00 + $bl; + $p2y = $y00 + $bl; + } + if (-$d2 > min($brbgBR_H, $brbgBR_V) || $flatten) { + $p3y = $y00 + $h00 - $bl; + $p4y = $y00 + $h00 - $bl; + } + + $shadow .= sprintf('%.3F %.3F l ', ($p3x ) * Mpdf::SCALE, ($this->h - ($p3y )) * Mpdf::SCALE); + $patch_array[1]['f'] = 2; + $patch_array[1]['points'] = [$p2x, $p2y, + $p3x, $p3y, $p3x, $p3y, $p3x, $p3y, + $p4c1x, $p4y, $p4x, $p4y, $p4x, $p4y, + $p1x, $p1y]; + $patch_array[1]['colors'] = [$col1, $col2]; + + + // BOTTOM RIGHT corner + $p1x = $x00 + $w00 - $bl; // control points only matches p3 preceding + $p1y = $y00 + $h00 - $d1 - $brbgBR_V; + $p1c2y = $p1y + ($d2 + $brbgBR_V) * $mag; + $p2x = $x00 + $w00; // control point only matches p4 preceding + $p2y = $y00 + $h00 - $d1 - $brbgBR_V; + $p2c2y = $p2y + ($d1 + $brbgBR_V) * $mag; + $p3x = $x00 + $w00 - $d1 - $brbgBR_H; + $p3c1x = $p3x + ($d1 + $brbgBR_H) * $mag; + $p3y = $y00 + $h00; + $p3c2y = $p3y - $bl / 2; + $p4x = $x00 + $w00 - $d1 - $brbgBR_H; + $p4c2x = $p4x + ($d2 + $brbgBR_H) * $mag; + $p4y = $y00 + $h00 - $bl; + + if (-$d2 > min($brbgBR_H, $brbgBR_V) || $flatten) { + $p1y = $y00 + $h00 - $bl; + $p1c2y = $p1y; + $p2y = $y00 + $h00 - $bl; + $p2c2y = $p2y + $bl * $mag2; + $p3x = $x00 + $w00 - $bl; + $p3c1x = $p3x + $bl * $mag2; + $p4x = $x00 + $w00 - $bl; + $p4c2x = $p4x; + } + + $shadow .= sprintf('%.3F %.3F %.3F %.3F %.3F %.3F c ', ($p1x) * Mpdf::SCALE, ($this->h - ($p1c2y)) * Mpdf::SCALE, ($p4c2x) * Mpdf::SCALE, ($this->h - ($p4y)) * Mpdf::SCALE, ($p4x) * Mpdf::SCALE, ($this->h - ($p4y)) * Mpdf::SCALE); + $patch_array[2]['f'] = 2; + $patch_array[2]['points'] = [$p2x, $p2c2y, + $p3c1x, $p3y, $p3x, $p3y, $p3x, $p3c2y, + $p4x, $p4y, $p4x, $p4y, $p4c2x, $p4y, + $p1x, $p1c2y]; + $patch_array[2]['colors'] = [$col2, $col1]; + + + + // BOTTOM + $p1x = $x00 + $w00 - $d1 - $brbgBR_H; // control point only matches p3 preceding + $p1y = $y00 + $h00; + $p2x = $x00 + $w00 - $d1 - $brbgBR_H; // control point only matches p4 preceding + $p2y = $y00 + $h00 - $bl; + $p3x = $x00 + $d1 + $brbgBL_H; + $p3y = $y00 + $h00 - $bl; + $p4x = $x00 + $d1 + $brbgBL_H; + $p4y = $y00 + $h00; + $p4c1y = $p4y - $bl / 2; + + if (-$d2 > min($brbgBR_H, $brbgBR_V) || $flatten) { + $p1x = $x00 + $w00 - $bl; + $p2x = $x00 + $w00 - $bl; + } + if (-$d2 > min($brbgBL_H, $brbgBL_V) || $flatten) { + $p3x = $x00 + $bl; + $p4x = $x00 + $bl; + } + + $shadow .= sprintf('%.3F %.3F l ', ($p3x ) * Mpdf::SCALE, ($this->h - ($p3y )) * Mpdf::SCALE); + $patch_array[3]['f'] = 2; + $patch_array[3]['points'] = [$p2x, $p2y, + $p3x, $p3y, $p3x, $p3y, $p3x, $p3y, + $p4x, $p4c1y, $p4x, $p4y, $p4x, $p4y, + $p1x, $p1y]; + $patch_array[3]['colors'] = [$col1, $col2]; + + // BOTTOM LEFT corner + $p1x = $x00 + $d1 + $brbgBL_H; + $p1c2x = $p1x - ($d2 + $brbgBL_H) * $mag; // control points only matches p3 preceding + $p1y = $y00 + $h00 - $bl; + $p2x = $x00 + $d1 + $brbgBL_H; + $p2c2x = $p2x - ($d1 + $brbgBL_H) * $mag; // control point only matches p4 preceding + $p2y = $y00 + $h00; + $p3x = $x00; + $p3c2x = $p3x + $bl / 2; + $p3y = $y00 + $h00 - $d1 - $brbgBL_V; + $p3c1y = $p3y + ($d1 + $brbgBL_V) * $mag; + $p4x = $x00 + $bl; + $p4y = $y00 + $h00 - $d1 - $brbgBL_V; + $p4c2y = $p4y + ($d2 + $brbgBL_V) * $mag; + if (-$d2 > min($brbgBL_H, $brbgBL_V) || $flatten) { + $p1x = $x00 + $bl; + $p1c2x = $p1x; + $p2x = $x00 + $bl; + $p2c2x = $p2x - $bl * $mag2; + $p3y = $y00 + $h00 - $bl; + $p3c1y = $p3y + $bl * $mag2; + $p4y = $y00 + $h00 - $bl; + $p4c2y = $p4y; + } + + $shadow .= sprintf('%.3F %.3F %.3F %.3F %.3F %.3F c ', ($p1c2x) * Mpdf::SCALE, ($this->h - ($p1y)) * Mpdf::SCALE, ($p4x) * Mpdf::SCALE, ($this->h - ($p4c2y)) * Mpdf::SCALE, ($p4x) * Mpdf::SCALE, ($this->h - ($p4y)) * Mpdf::SCALE); + $patch_array[4]['f'] = 2; + $patch_array[4]['points'] = [$p2c2x, $p2y, + $p3x, $p3c1y, $p3x, $p3y, $p3c2x, $p3y, + $p4x, $p4y, $p4x, $p4y, $p4x, $p4c2y, + $p1c2x, $p1y]; + $patch_array[4]['colors'] = [$col2, $col1]; + + + // LEFT - joins on the right (C3-C4 of previous): f = 2 + $p1x = $x00; // control point only matches p3 preceding + $p1y = $y00 + $h00 - $d1 - $brbgBL_V; + $p2x = $x00 + $bl; // control point only matches p4 preceding + $p2y = $y00 + $h00 - $d1 - $brbgBL_V; + $p3x = $x00 + $bl; + $p3y = $y00 + $d1 + $brbgTL_V; + $p4x = $x00; + $p4c1x = $p4x + $bl / 2; + $p4y = $y00 + $d1 + $brbgTL_V; + if (-$d2 > min($brbgBL_H, $brbgBL_V) || $flatten) { + $p1y = $y00 + $h00 - $bl; + $p2y = $y00 + $h00 - $bl; + } + if (-$d2 > min($brbgTL_H, $brbgTL_V) || $flatten) { + $p3y = $y00 + $bl; + $p4y = $y00 + $bl; + } + + $shadow .= sprintf('%.3F %.3F l ', ($p3x ) * Mpdf::SCALE, ($this->h - ($p3y )) * Mpdf::SCALE); + $patch_array[5]['f'] = 2; + $patch_array[5]['points'] = [$p2x, $p2y, + $p3x, $p3y, $p3x, $p3y, $p3x, $p3y, + $p4c1x, $p4y, $p4x, $p4y, $p4x, $p4y, + $p1x, $p1y]; + $patch_array[5]['colors'] = [$col1, $col2]; + + // TOP LEFT corner + $p1x = $x00 + $bl; // control points only matches p3 preceding + $p1y = $y00 + $d1 + $brbgTL_V; + $p1c2y = $p1y - ($d2 + $brbgTL_V) * $mag; + $p2x = $x00; // control point only matches p4 preceding + $p2y = $y00 + $d1 + $brbgTL_V; + $p2c2y = $p2y - ($d1 + $brbgTL_V) * $mag; + $p3x = $x00 + $d1 + $brbgTL_H; + $p3c1x = $p3x - ($d1 + $brbgTL_H) * $mag; + $p3y = $y00; + $p3c2y = $p3y + $bl / 2; + $p4x = $x00 + $d1 + $brbgTL_H; + $p4c2x = $p4x - ($d2 + $brbgTL_H) * $mag; + $p4y = $y00 + $bl; + + if (-$d2 > min($brbgTL_H, $brbgTL_V) || $flatten) { + $p1y = $y00 + $bl; + $p1c2y = $p1y; + $p2y = $y00 + $bl; + $p2c2y = $p2y - $bl * $mag2; + $p3x = $x00 + $bl; + $p3c1x = $p3x - $bl * $mag2; + $p4x = $x00 + $bl; + $p4c2x = $p4x; + } + + $shadow .= sprintf('%.3F %.3F %.3F %.3F %.3F %.3F c ', ($p1x) * Mpdf::SCALE, ($this->h - ($p1c2y)) * Mpdf::SCALE, ($p4c2x) * Mpdf::SCALE, ($this->h - ($p4y)) * Mpdf::SCALE, ($p4x) * Mpdf::SCALE, ($this->h - ($p4y)) * Mpdf::SCALE); + $patch_array[6]['f'] = 2; + $patch_array[6]['points'] = [$p2x, $p2c2y, + $p3c1x, $p3y, $p3x, $p3y, $p3x, $p3c2y, + $p4x, $p4y, $p4x, $p4y, $p4c2x, $p4y, + $p1x, $p1c2y]; + $patch_array[6]['colors'] = [$col2, $col1]; + + + // TOP - joins on the right (C3-C4 of previous): f = 2 + $p1x = $x00 + $d1 + $brbgTL_H; // control point only matches p3 preceding + $p1y = $y00; + $p2x = $x00 + $d1 + $brbgTL_H; // control point only matches p4 preceding + $p2y = $y00 + $bl; + $p3x = $x00 + $w00 - $d1 - $brbgTR_H; + $p3y = $y00 + $bl; + $p4x = $x00 + $w00 - $d1 - $brbgTR_H; + $p4y = $y00; + $p4c1y = $p4y + $bl / 2; + if (-$d2 > min($brbgTL_H, $brbgTL_V) || $flatten) { + $p1x = $x00 + $bl; + $p2x = $x00 + $bl; + } + if (-$d2 > min($brbgTR_H, $brbgTR_V) || $flatten) { + $p3x = $x00 + $w00 - $bl; + $p4x = $x00 + $w00 - $bl; + } + + $shadow .= sprintf('%.3F %.3F l ', ($p3x ) * Mpdf::SCALE, ($this->h - ($p3y )) * Mpdf::SCALE); + $patch_array[7]['f'] = 2; + $patch_array[7]['points'] = [$p2x, $p2y, + $p3x, $p3y, $p3x, $p3y, $p3x, $p3y, + $p4x, $p4c1y, $p4x, $p4y, $p4x, $p4y, + $p1x, $p1y]; + $patch_array[7]['colors'] = [$col1, $col2]; + + $shadow .= ' h f Q ' . "\n"; // Close path and Fill the inner solid shadow + + if ($bl) { + $shadow .= $this->gradient->CoonsPatchMesh($x00, $y00, $w00, $h00, $patch_array, $x00, $x00 + $w00, $y00, $y00 + $h00, $colspace, true); + } + + if ($sh['x'] || $sh['y']) { + $shadow .= ' Q' . "\n"; // Shadow Offset + } + $shadow .= ' Q' . "\n"; // Ends path no-op & Sets the clipping path + } + } + + $s .= ' W n '; // Ends path no-op & Sets the clipping path + + if ($this->blk[$blvl]['bgcolor']) { + $this->pageBackgrounds[$blvl][] = [ + 'x' => $x0, + 'y' => $y0, + 'w' => $w, + 'h' => $h, + 'col' => $this->blk[$blvl]['bgcolorarray'], + 'clippath' => $s, + 'visibility' => $this->visibility, + 'shadow' => $shadow, + 'z-index' => $this->current_layer, + ]; + } elseif ($shadow) { + $this->pageBackgrounds[$blvl][] = [ + 'x' => 0, + 'y' => 0, + 'w' => 0, + 'h' => 0, + 'shadowonly' => true, + 'col' => '', + 'clippath' => '', + 'visibility' => $this->visibility, + 'shadow' => $shadow, + 'z-index' => $this->current_layer, + ]; + } + + /* -- BACKGROUNDS -- */ + if (isset($this->blk[$blvl]['gradient'])) { + $g = $this->gradient->parseBackgroundGradient($this->blk[$blvl]['gradient']); + if ($g) { + $gx = $x0; + $gy = $y0; + $this->pageBackgrounds[$blvl][] = [ + 'gradient' => true, + 'x' => $gx, + 'y' => $gy, + 'w' => $w, + 'h' => $h, + 'gradtype' => $g['type'], + 'stops' => $g['stops'], + 'colorspace' => $g['colorspace'], + 'coords' => $g['coords'], + 'extend' => $g['extend'], + 'clippath' => $s, + 'visibility' => $this->visibility, + 'z-index' => $this->current_layer + ]; + } + } + + if (isset($this->blk[$blvl]['background-image'])) { + if (isset($this->blk[$blvl]['background-image']['gradient']) && $this->blk[$blvl]['background-image']['gradient'] && preg_match('/(-moz-)*(repeating-)*(linear|radial)-gradient/', $this->blk[$blvl]['background-image']['gradient'])) { + $g = $this->gradient->parseMozGradient($this->blk[$blvl]['background-image']['gradient']); + if ($g) { + $gx = $x0; + $gy = $y0; + // origin specifies the background-positioning-area (bpa) + if ($this->blk[$blvl]['background-image']['origin'] == 'padding-box') { + $gx += $this->blk[$blvl]['border_left']['w']; + $w -= ($this->blk[$blvl]['border_left']['w'] + $this->blk[$blvl]['border_right']['w']); + if ($this->blk[$blvl]['border_top'] && $divider != 'pagetop' && !$continuingpage) { + $gy += $this->blk[$blvl]['border_top']['w']; + } + if ($this->blk[$blvl]['border_bottom'] && $blockstate != 1 && $divider != 'pagebottom') { + $gy1 = $y1 - $this->blk[$blvl]['border_bottom']['w']; + } else { + $gy1 = $y1; + } + $h = $gy1 - $gy; + } elseif ($this->blk[$blvl]['background-image']['origin'] == 'content-box') { + $gx += $this->blk[$blvl]['border_left']['w'] + $this->blk[$blvl]['padding_left']; + $w -= ($this->blk[$blvl]['border_left']['w'] + $this->blk[$blvl]['padding_left'] + $this->blk[$blvl]['border_right']['w'] + $this->blk[$blvl]['padding_right']); + if ($this->blk[$blvl]['border_top'] && $divider != 'pagetop' && !$continuingpage) { + $gy += $this->blk[$blvl]['border_top']['w'] + $this->blk[$blvl]['padding_top']; + } + if ($this->blk[$blvl]['border_bottom'] && $blockstate != 1 && $divider != 'pagebottom') { + $gy1 = $y1 - ($this->blk[$blvl]['border_bottom']['w'] + $this->blk[$blvl]['padding_bottom']); + } else { + $gy1 = $y1 - $this->blk[$blvl]['padding_bottom']; + } + $h = $gy1 - $gy; + } + + if (isset($this->blk[$blvl]['background-image']['size']['w']) && $this->blk[$blvl]['background-image']['size']['w']) { + $size = $this->blk[$blvl]['background-image']['size']; + if ($size['w'] != 'contain' && $size['w'] != 'cover') { + if (stristr($size['w'], '%')) { + $size['w'] = (float) $size['w']; + $size['w'] /= 100; + $w *= $size['w']; + } elseif ($size['w'] != 'auto') { + $w = $size['w']; + } + if (stristr($size['h'], '%')) { + $size['h'] = (float) $size['h']; + $size['h'] /= 100; + $h *= $size['h']; + } elseif ($size['h'] != 'auto') { + $h = $size['h']; + } + } + } + $this->pageBackgrounds[$blvl][] = [ + 'gradient' => true, + 'x' => $gx, + 'y' => $gy, + 'w' => $w, + 'h' => $h, + 'gradtype' => $g['type'], + 'stops' => $g['stops'], + 'colorspace' => $g['colorspace'], + 'coords' => $g['coords'], + 'extend' => $g['extend'], + 'clippath' => $s, + 'visibility' => $this->visibility, + 'z-index' => $this->current_layer + ]; + } + + } else { + + $image_id = $this->blk[$blvl]['background-image']['image_id']; + $orig_w = $this->blk[$blvl]['background-image']['orig_w']; + $orig_h = $this->blk[$blvl]['background-image']['orig_h']; + $x_pos = $this->blk[$blvl]['background-image']['x_pos']; + $y_pos = $this->blk[$blvl]['background-image']['y_pos']; + $x_repeat = $this->blk[$blvl]['background-image']['x_repeat']; + $y_repeat = $this->blk[$blvl]['background-image']['y_repeat']; + $resize = $this->blk[$blvl]['background-image']['resize']; + $opacity = $this->blk[$blvl]['background-image']['opacity']; + $itype = $this->blk[$blvl]['background-image']['itype']; + $size = $this->blk[$blvl]['background-image']['size']; + // origin specifies the background-positioning-area (bpa) + + $bpa = ['x' => $x0, 'y' => $y0, 'w' => $w, 'h' => $h]; + + if ($this->blk[$blvl]['background-image']['origin'] == 'padding-box') { + + $bpa['x'] = $x0 + $this->blk[$blvl]['border_left']['w']; + $bpa['w'] = $w - ($this->blk[$blvl]['border_left']['w'] + $this->blk[$blvl]['border_right']['w']); + if ($this->blk[$blvl]['border_top'] && $divider != 'pagetop' && !$continuingpage) { + $bpa['y'] = $y0 + $this->blk[$blvl]['border_top']['w']; + } else { + $bpa['y'] = $y0; + } + if ($this->blk[$blvl]['border_bottom'] && $blockstate != 1 && $divider != 'pagebottom') { + $bpay = $y1 - $this->blk[$blvl]['border_bottom']['w']; + } else { + $bpay = $y1; + } + $bpa['h'] = $bpay - $bpa['y']; + + } elseif ($this->blk[$blvl]['background-image']['origin'] == 'content-box') { + + $bpa['x'] = $x0 + $this->blk[$blvl]['border_left']['w'] + $this->blk[$blvl]['padding_left']; + $bpa['w'] = $w - ($this->blk[$blvl]['border_left']['w'] + $this->blk[$blvl]['padding_left'] + $this->blk[$blvl]['border_right']['w'] + $this->blk[$blvl]['padding_right']); + if ($this->blk[$blvl]['border_top'] && $divider != 'pagetop' && !$continuingpage) { + $bpa['y'] = $y0 + $this->blk[$blvl]['border_top']['w'] + $this->blk[$blvl]['padding_top']; + } else { + $bpa['y'] = $y0 + $this->blk[$blvl]['padding_top']; + } + if ($this->blk[$blvl]['border_bottom'] && $blockstate != 1 && $divider != 'pagebottom') { + $bpay = $y1 - ($this->blk[$blvl]['border_bottom']['w'] + $this->blk[$blvl]['padding_bottom']); + } else { + $bpay = $y1 - $this->blk[$blvl]['padding_bottom']; + } + $bpa['h'] = $bpay - $bpa['y']; + + } + + $this->pageBackgrounds[$blvl][] = [ + 'x' => $x0, + 'y' => $y0, + 'w' => $w, + 'h' => $h, + 'image_id' => $image_id, + 'orig_w' => $orig_w, + 'orig_h' => $orig_h, + 'x_pos' => $x_pos, + 'y_pos' => $y_pos, + 'x_repeat' => $x_repeat, + 'y_repeat' => $y_repeat, + 'clippath' => $s, + 'resize' => $resize, + 'opacity' => $opacity, + 'itype' => $itype, + 'visibility' => $this->visibility, + 'z-index' => $this->current_layer, + 'size' => $size, + 'bpa' => $bpa + ]; + } + } + /* -- END BACKGROUNDS -- */ + + // Float DIV + $this->blk[$blvl]['bb_painted'][$this->page] = true; + } + /* -- BORDER-RADIUS -- */ + + function _EllipseArc($x0, $y0, $rx, $ry, $seg = 1, $part = false, $start = false) + { + // Anticlockwise segment 1-4 TR-TL-BL-BR (part=1 or 2) + $s = ''; + + if ($rx < 0) { + $rx = 0; + } + + if ($ry < 0) { + $ry = 0; + } + + $rx *= Mpdf::SCALE; + $ry *= Mpdf::SCALE; + + $astart = 0; + + if ($seg == 1) { // Top Right + $afinish = 90; + $nSeg = 4; + } elseif ($seg == 2) { // Top Left + $afinish = 180; + $nSeg = 8; + } elseif ($seg == 3) { // Bottom Left + $afinish = 270; + $nSeg = 12; + } else { // Bottom Right + $afinish = 360; + $nSeg = 16; + } + + $astart = deg2rad((float) $astart); + $afinish = deg2rad((float) $afinish); + + $totalAngle = $afinish - $astart; + $dt = $totalAngle / $nSeg; // segment angle + $dtm = $dt / 3; + $x0 *= Mpdf::SCALE; + $y0 = ($this->h - $y0) * Mpdf::SCALE; + $t1 = $astart; + $a0 = $x0 + ($rx * cos($t1)); + $b0 = $y0 + ($ry * sin($t1)); + $c0 = -$rx * sin($t1); + $d0 = $ry * cos($t1); + $op = false; + + for ($i = 1; $i <= $nSeg; $i++) { + // Draw this bit of the total curve + $t1 = ($i * $dt) + $astart; + $a1 = $x0 + ($rx * cos($t1)); + $b1 = $y0 + ($ry * sin($t1)); + $c1 = -$rx * sin($t1); + $d1 = $ry * cos($t1); + if ($i > ($nSeg - 4) && (!$part || ($part == 1 && $i <= $nSeg - 2) || ($part == 2 && $i > $nSeg - 2))) { + if ($start && !$op) { + $s .= sprintf('%.3F %.3F m ', $a0, $b0); + } + $s .= sprintf('%.3F %.3F %.3F %.3F %.3F %.3F c ', ($a0 + ($c0 * $dtm)), ($b0 + ($d0 * $dtm)), ($a1 - ($c1 * $dtm)), ($b1 - ($d1 * $dtm)), $a1, $b1); + $op = true; + } + $a0 = $a1; + $b0 = $b1; + $c0 = $c1; + $d0 = $d1; + } + + return $s; + } + + /* -- END BORDER-RADIUS -- */ + + function PaintDivLnBorder($state = 0, $blvl = 0, $h = 0) + { + // $state = 0 normal; 1 top; 2 bottom; 3 top and bottom + $this->ColDetails[$this->CurrCol]['bottom_margin'] = $this->y + $h; + + $save_y = $this->y; + + $w = $this->blk[$blvl]['width']; + $x0 = $this->x; // left + $y0 = $this->y; // top + $x1 = $this->x + $w; // bottom + $y1 = $this->y + $h; // bottom + $continuingpage = (isset($this->blk[$blvl]['startpage']) && $this->blk[$blvl]['startpage'] != $this->page); + + if ($this->blk[$blvl]['border_top'] && ($state == 1 || $state == 3)) { + $tbd = $this->blk[$blvl]['border_top']; + if (isset($tbd['s']) && $tbd['s']) { + $this->_setBorderLine($tbd); + $this->y = $y0 + ($tbd['w'] / 2); + if ($tbd['style'] == 'dotted' || $tbd['style'] == 'dashed') { + $this->_setDashBorder($tbd['style'], '', $continuingpage, 'T'); + $this->Line($x0 + ($tbd['w'] / 2), $this->y, $x0 + $w - ($tbd['w'] / 2), $this->y); + } else { + $this->SetLineJoin(0); + $this->SetLineCap(0); + $this->Line($x0, $this->y, $x0 + $w, $this->y); + } + $this->y += $tbd['w']; + // Reset Corners and Dash off + $this->SetLineJoin(2); + $this->SetLineCap(2); + $this->SetDash(); + } + } + if ($this->blk[$blvl]['border_left']) { + $tbd = $this->blk[$blvl]['border_left']; + if (isset($tbd['s']) && $tbd['s']) { + $this->_setBorderLine($tbd); + if ($tbd['style'] == 'dotted' || $tbd['style'] == 'dashed') { + $this->y = $y0 + ($tbd['w'] / 2); + $this->_setDashBorder($tbd['style'], '', $continuingpage, 'L'); + $this->Line($x0 + ($tbd['w'] / 2), $this->y, $x0 + ($tbd['w'] / 2), $y0 + $h - ($tbd['w'] / 2)); + } else { + $this->y = $y0; + $this->SetLineJoin(0); + $this->SetLineCap(0); + $this->Line($x0 + ($tbd['w'] / 2), $this->y, $x0 + ($tbd['w'] / 2), $y0 + $h); + } + $this->y += $tbd['w']; + // Reset Corners and Dash off + $this->SetLineJoin(2); + $this->SetLineCap(2); + $this->SetDash(); + } + } + if ($this->blk[$blvl]['border_right']) { + $tbd = $this->blk[$blvl]['border_right']; + if (isset($tbd['s']) && $tbd['s']) { + $this->_setBorderLine($tbd); + if ($tbd['style'] == 'dotted' || $tbd['style'] == 'dashed') { + $this->y = $y0 + ($tbd['w'] / 2); + $this->_setDashBorder($tbd['style'], '', $continuingpage, 'R'); + $this->Line($x0 + $w - ($tbd['w'] / 2), $this->y, $x0 + $w - ($tbd['w'] / 2), $y0 + $h - ($tbd['w'] / 2)); + } else { + $this->y = $y0; + $this->SetLineJoin(0); + $this->SetLineCap(0); + $this->Line($x0 + $w - ($tbd['w'] / 2), $this->y, $x0 + $w - ($tbd['w'] / 2), $y0 + $h); + } + $this->y += $tbd['w']; + // Reset Corners and Dash off + $this->SetLineJoin(2); + $this->SetLineCap(2); + $this->SetDash(); + } + } + if ($this->blk[$blvl]['border_bottom'] && $state > 1) { + $tbd = $this->blk[$blvl]['border_bottom']; + if (isset($tbd['s']) && $tbd['s']) { + $this->_setBorderLine($tbd); + $this->y = $y0 + $h - ($tbd['w'] / 2); + if ($tbd['style'] == 'dotted' || $tbd['style'] == 'dashed') { + $this->_setDashBorder($tbd['style'], '', $continuingpage, 'B'); + $this->Line($x0 + ($tbd['w'] / 2), $this->y, $x0 + $w - ($tbd['w'] / 2), $this->y); + } else { + $this->SetLineJoin(0); + $this->SetLineCap(0); + $this->Line($x0, $this->y, $x0 + $w, $this->y); + } + $this->y += $tbd['w']; + // Reset Corners and Dash off + $this->SetLineJoin(2); + $this->SetLineCap(2); + $this->SetDash(); + } + } + $this->SetDash(); + $this->y = $save_y; + } + + function PaintImgBorder($objattr, $is_table) + { + // Borders are disabled in columns - messes up the repositioning in printcolumnbuffer + if ($this->ColActive) { + return; + } // *COLUMNS* + if ($is_table) { + $k = $this->shrin_k; + } else { + $k = 1; + } + $h = (isset($objattr['BORDER-HEIGHT']) ? $objattr['BORDER-HEIGHT'] : 0); + $w = (isset($objattr['BORDER-WIDTH']) ? $objattr['BORDER-WIDTH'] : 0); + $x0 = (isset($objattr['BORDER-X']) ? $objattr['BORDER-X'] : 0); + $y0 = (isset($objattr['BORDER-Y']) ? $objattr['BORDER-Y'] : 0); + + // BORDERS + if ($objattr['border_top']) { + $tbd = $objattr['border_top']; + if (!empty($tbd['s'])) { + $this->_setBorderLine($tbd, $k); + if ($tbd['style'] == 'dotted' || $tbd['style'] == 'dashed') { + $this->_setDashBorder($tbd['style'], '', '', 'T'); + } + $this->Line($x0, $y0, $x0 + $w, $y0); + // Reset Corners and Dash off + $this->SetLineJoin(2); + $this->SetLineCap(2); + $this->SetDash(); + } + } + if ($objattr['border_left']) { + $tbd = $objattr['border_left']; + if (!empty($tbd['s'])) { + $this->_setBorderLine($tbd, $k); + if ($tbd['style'] == 'dotted' || $tbd['style'] == 'dashed') { + $this->_setDashBorder($tbd['style'], '', '', 'L'); + } + $this->Line($x0, $y0, $x0, $y0 + $h); + // Reset Corners and Dash off + $this->SetLineJoin(2); + $this->SetLineCap(2); + $this->SetDash(); + } + } + if ($objattr['border_right']) { + $tbd = $objattr['border_right']; + if (!empty($tbd['s'])) { + $this->_setBorderLine($tbd, $k); + if ($tbd['style'] == 'dotted' || $tbd['style'] == 'dashed') { + $this->_setDashBorder($tbd['style'], '', '', 'R'); + } + $this->Line($x0 + $w, $y0, $x0 + $w, $y0 + $h); + // Reset Corners and Dash off + $this->SetLineJoin(2); + $this->SetLineCap(2); + $this->SetDash(); + } + } + if ($objattr['border_bottom']) { + $tbd = $objattr['border_bottom']; + if (!empty($tbd['s'])) { + $this->_setBorderLine($tbd, $k); + if ($tbd['style'] == 'dotted' || $tbd['style'] == 'dashed') { + $this->_setDashBorder($tbd['style'], '', '', 'B'); + } + $this->Line($x0, $y0 + $h, $x0 + $w, $y0 + $h); + // Reset Corners and Dash off + $this->SetLineJoin(2); + $this->SetLineCap(2); + $this->SetDash(); + } + } + $this->SetDash(); + $this->SetAlpha(1); + } + + /* -- END HTML-CSS -- */ + + function Reset() + { + $this->SetTColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + $this->SetDColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + $this->SetFColor($this->colorConverter->convert(255, $this->PDFAXwarnings)); + $this->SetAlpha(1); + $this->colorarray = ''; + + $this->spanbgcolorarray = ''; + $this->spanbgcolor = false; + $this->spanborder = false; + $this->spanborddet = []; + + $this->ResetStyles(); + + $this->HREF = ''; + $this->textparam = []; + $this->SetTextOutline(); + + $this->textvar = 0x00; // mPDF 5.7.1 + $this->OTLtags = []; + $this->textshadow = ''; + + $this->currentLang = $this->default_lang; // mPDF 6 + $this->RestrictUnicodeFonts($this->default_available_fonts); // mPDF 6 + $this->SetFont($this->default_font, '', 0, false); + $this->SetFontSize($this->default_font_size, false); + + $this->currentfontfamily = ''; + $this->currentfontsize = ''; + $this->currentfontstyle = ''; + + /* -- TABLES -- */ + if ($this->tableLevel && isset($this->table[1][1]['cellLineHeight'])) { + $this->SetLineHeight('', $this->table[1][1]['cellLineHeight']); // *TABLES* + } else { /* -- END TABLES -- */ + if (isset($this->blk[$this->blklvl]['line_height']) && $this->blk[$this->blklvl]['line_height']) { + $this->SetLineHeight('', $this->blk[$this->blklvl]['line_height']); // sets default line height + } + } + + $this->lSpacingCSS = ''; + $this->wSpacingCSS = ''; + $this->fixedlSpacing = false; + $this->minwSpacing = 0; + $this->SetDash(); // restore to no dash + $this->dash_on = false; + $this->dotted_on = false; + $this->divwidth = 0; + $this->divheight = 0; + $this->cellTextAlign = ''; + $this->cellLineHeight = ''; + $this->cellLineStackingStrategy = ''; + $this->cellLineStackingShift = ''; + $this->oldy = -1; + + $bodystyle = []; + if (isset($this->cssManager->CSS['BODY']['FONT-STYLE'])) { + $bodystyle['FONT-STYLE'] = $this->cssManager->CSS['BODY']['FONT-STYLE']; + } + if (isset($this->cssManager->CSS['BODY']['FONT-WEIGHT'])) { + $bodystyle['FONT-WEIGHT'] = $this->cssManager->CSS['BODY']['FONT-WEIGHT']; + } + if (isset($this->cssManager->CSS['BODY']['COLOR'])) { + $bodystyle['COLOR'] = $this->cssManager->CSS['BODY']['COLOR']; + } + if (isset($bodystyle)) { + $this->setCSS($bodystyle, 'BLOCK', 'BODY'); + } + } + + /* -- HTML-CSS -- */ + + function ReadMetaTags($html) + { + // changes anykey=anyvalue to anykey="anyvalue" (only do this when this happens inside tags) + $regexp = '/ (\\w+?)=([^\\s>"]+)/si'; + $html = preg_replace($regexp, " \$1=\"\$2\"", $html); + if (preg_match('/(.*?)<\/title>/si', $html, $m)) { + $this->SetTitle($m[1]); + } + preg_match_all('/<meta [^>]*?(name|content)="([^>]*?)" [^>]*?(name|content)="([^>]*?)".*?>/si', $html, $aux); + $firstattr = $aux[1]; + $secondattr = $aux[3]; + for ($i = 0; $i < count($aux[0]); $i++) { + $name = ( strtoupper($firstattr[$i]) == "NAME" ) ? strtoupper($aux[2][$i]) : strtoupper($aux[4][$i]); + $content = ( strtoupper($firstattr[$i]) == "CONTENT" ) ? $aux[2][$i] : $aux[4][$i]; + switch ($name) { + case "KEYWORDS": + $this->SetKeywords($content); + break; + case "AUTHOR": + $this->SetAuthor($content); + break; + case "DESCRIPTION": + $this->SetSubject($content); + break; + } + } + } + + function ReadCharset($html) + { + // Charset conversion + if ($this->allow_charset_conversion) { + if (preg_match('/<head.*charset=([^\'\"\s]*).*<\/head>/si', $html, $m)) { + if (strtoupper($m[1]) != 'UTF-8') { + $this->charset_in = strtoupper($m[1]); + } + } + } + } + + function setCSS($arrayaux, $type = '', $tag = '') + { + // type= INLINE | BLOCK | TABLECELL // tag= BODY + if (!is_array($arrayaux)) { + return; // Removes PHP Warning + } + + // mPDF 5.7.3 inline text-decoration parameters + $preceeding_fontkey = $this->FontFamily . $this->FontStyle; + $preceeding_fontsize = $this->FontSize; + $spanbordset = false; + $spanbgset = false; + // mPDF 6 + $prevlevel = (($this->blklvl == 0) ? 0 : $this->blklvl - 1); + + // Set font size first so that e.g. MARGIN 0.83em works on font size for this element + if (isset($arrayaux['FONT-SIZE'])) { + $v = $arrayaux['FONT-SIZE']; + if (is_numeric($v[0]) || ($v[0] === '.')) { + if ($type == 'BLOCK' && $this->blklvl > 0 && isset($this->blk[$this->blklvl - 1]['InlineProperties']) && isset($this->blk[$this->blklvl - 1]['InlineProperties']['size'])) { + $mmsize = $this->sizeConverter->convert($v, $this->blk[$this->blklvl - 1]['InlineProperties']['size']); + } elseif ($type == 'TABLECELL') { + $mmsize = $this->sizeConverter->convert($v, $this->default_font_size / Mpdf::SCALE); + } else { + $mmsize = $this->sizeConverter->convert($v, $this->FontSize); + } + $this->SetFontSize($mmsize * (Mpdf::SCALE), false); // Get size in points (pt) + } else { + $v = strtoupper($v); + if (isset($this->fontsizes[$v])) { + $this->SetFontSize($this->fontsizes[$v] * $this->default_font_size, false); + } + } + if ($tag == 'BODY') { + $this->SetDefaultFontSize($this->FontSizePt); + } + } + + // mPDF 6 + if (isset($arrayaux['LANG']) && $arrayaux['LANG']) { + if ($this->autoLangToFont && !$this->usingCoreFont) { + if ($arrayaux['LANG'] != $this->default_lang && $arrayaux['LANG'] != 'UTF-8') { + list ($coreSuitable, $mpdf_pdf_unifont) = $this->languageToFont->getLanguageOptions($arrayaux['LANG'], $this->useAdobeCJK); + if ($mpdf_pdf_unifont) { + $arrayaux['FONT-FAMILY'] = $mpdf_pdf_unifont; + } + if ($tag == 'BODY') { + $this->default_lang = $arrayaux['LANG']; + } + } + } + $this->currentLang = $arrayaux['LANG']; + } + + // FOR INLINE and BLOCK OR 'BODY' + if (isset($arrayaux['FONT-FAMILY'])) { + $v = $arrayaux['FONT-FAMILY']; + // If it is a font list, get all font types + $aux_fontlist = explode(",", $v); + $found = 0; + foreach ($aux_fontlist as $f) { + $fonttype = trim($f); + $fonttype = preg_replace('/["\']*(.*?)["\']*/', '\\1', $fonttype); + $fonttype = preg_replace('/ /', '', $fonttype); + $v = strtolower(trim($fonttype)); + if (isset($this->fonttrans[$v]) && $this->fonttrans[$v]) { + $v = $this->fonttrans[$v]; + } + if ((!$this->onlyCoreFonts && in_array($v, $this->available_unifonts)) || + in_array($v, ['ccourier', 'ctimes', 'chelvetica']) || + ($this->onlyCoreFonts && in_array($v, ['courier', 'times', 'helvetica', 'arial'])) || + in_array($v, ['sjis', 'uhc', 'big5', 'gb'])) { + $fonttype = $v; + $found = 1; + break; + } + } + if (!$found) { + foreach ($aux_fontlist as $f) { + $fonttype = trim($f); + $fonttype = preg_replace('/["\']*(.*?)["\']*/', '\\1', $fonttype); + $fonttype = preg_replace('/ /', '', $fonttype); + $v = strtolower(trim($fonttype)); + if (isset($this->fonttrans[$v]) && $this->fonttrans[$v]) { + $v = $this->fonttrans[$v]; + } + if (in_array($v, $this->sans_fonts) || in_array($v, $this->serif_fonts) || in_array($v, $this->mono_fonts)) { + $fonttype = $v; + break; + } + } + } + + if ($tag == 'BODY') { + $this->SetDefaultFont($fonttype); + } + $this->SetFont($fonttype, $this->currentfontstyle, 0, false); + } else { + $this->SetFont($this->currentfontfamily, $this->currentfontstyle, 0, false); + } + + foreach ($arrayaux as $k => $v) { + if ($type != 'INLINE' && $tag != 'BODY' && $type != 'TABLECELL') { + switch ($k) { + // BORDERS + case 'BORDER-TOP': + $this->blk[$this->blklvl]['border_top'] = $this->border_details($v); + if ($this->blk[$this->blklvl]['border_top']['s']) { + $this->blk[$this->blklvl]['border'] = 1; + } + break; + case 'BORDER-BOTTOM': + $this->blk[$this->blklvl]['border_bottom'] = $this->border_details($v); + if ($this->blk[$this->blklvl]['border_bottom']['s']) { + $this->blk[$this->blklvl]['border'] = 1; + } + break; + case 'BORDER-LEFT': + $this->blk[$this->blklvl]['border_left'] = $this->border_details($v); + if ($this->blk[$this->blklvl]['border_left']['s']) { + $this->blk[$this->blklvl]['border'] = 1; + } + break; + case 'BORDER-RIGHT': + $this->blk[$this->blklvl]['border_right'] = $this->border_details($v); + if ($this->blk[$this->blklvl]['border_right']['s']) { + $this->blk[$this->blklvl]['border'] = 1; + } + break; + + // PADDING + case 'PADDING-TOP': + $this->blk[$this->blklvl]['padding_top'] = $this->sizeConverter->convert($v, $this->blk[$prevlevel]['inner_width'], $this->FontSize, false); + break; + case 'PADDING-BOTTOM': + $this->blk[$this->blklvl]['padding_bottom'] = $this->sizeConverter->convert($v, $this->blk[$prevlevel]['inner_width'], $this->FontSize, false); + break; + case 'PADDING-LEFT': + if (($tag == 'UL' || $tag == 'OL') && $v == 'auto') { + $this->blk[$this->blklvl]['padding_left'] = 'auto'; + break; + } + $this->blk[$this->blklvl]['padding_left'] = $this->sizeConverter->convert($v, $this->blk[$prevlevel]['inner_width'], $this->FontSize, false); + break; + case 'PADDING-RIGHT': + if (($tag == 'UL' || $tag == 'OL') && $v == 'auto') { + $this->blk[$this->blklvl]['padding_right'] = 'auto'; + break; + } + $this->blk[$this->blklvl]['padding_right'] = $this->sizeConverter->convert($v, $this->blk[$prevlevel]['inner_width'], $this->FontSize, false); + break; + + // MARGINS + case 'MARGIN-TOP': + $tmp = $this->sizeConverter->convert($v, $this->blk[$prevlevel]['inner_width'], $this->FontSize, false); + if (isset($this->blk[$this->blklvl]['lastbottommargin'])) { + if ($tmp > $this->blk[$this->blklvl]['lastbottommargin']) { + $tmp -= $this->blk[$this->blklvl]['lastbottommargin']; + } else { + $tmp = 0; + } + } + $this->blk[$this->blklvl]['margin_top'] = $tmp; + break; + case 'MARGIN-BOTTOM': + $this->blk[$this->blklvl]['margin_bottom'] = $this->sizeConverter->convert($v, $this->blk[$prevlevel]['inner_width'], $this->FontSize, false); + break; + case 'MARGIN-LEFT': + $this->blk[$this->blklvl]['margin_left'] = $this->sizeConverter->convert($v, $this->blk[$prevlevel]['inner_width'], $this->FontSize, false); + break; + case 'MARGIN-RIGHT': + $this->blk[$this->blklvl]['margin_right'] = $this->sizeConverter->convert($v, $this->blk[$prevlevel]['inner_width'], $this->FontSize, false); + break; + + /* -- BORDER-RADIUS -- */ + case 'BORDER-TOP-LEFT-RADIUS-H': + $this->blk[$this->blklvl]['border_radius_TL_H'] = $this->sizeConverter->convert($v, $this->blk[$prevlevel]['inner_width'], $this->FontSize, false); + break; + case 'BORDER-TOP-LEFT-RADIUS-V': + $this->blk[$this->blklvl]['border_radius_TL_V'] = $this->sizeConverter->convert($v, $this->blk[$prevlevel]['inner_width'], $this->FontSize, false); + break; + case 'BORDER-TOP-RIGHT-RADIUS-H': + $this->blk[$this->blklvl]['border_radius_TR_H'] = $this->sizeConverter->convert($v, $this->blk[$prevlevel]['inner_width'], $this->FontSize, false); + break; + case 'BORDER-TOP-RIGHT-RADIUS-V': + $this->blk[$this->blklvl]['border_radius_TR_V'] = $this->sizeConverter->convert($v, $this->blk[$prevlevel]['inner_width'], $this->FontSize, false); + break; + case 'BORDER-BOTTOM-LEFT-RADIUS-H': + $this->blk[$this->blklvl]['border_radius_BL_H'] = $this->sizeConverter->convert($v, $this->blk[$prevlevel]['inner_width'], $this->FontSize, false); + break; + case 'BORDER-BOTTOM-LEFT-RADIUS-V': + $this->blk[$this->blklvl]['border_radius_BL_V'] = $this->sizeConverter->convert($v, $this->blk[$prevlevel]['inner_width'], $this->FontSize, false); + break; + case 'BORDER-BOTTOM-RIGHT-RADIUS-H': + $this->blk[$this->blklvl]['border_radius_BR_H'] = $this->sizeConverter->convert($v, $this->blk[$prevlevel]['inner_width'], $this->FontSize, false); + break; + case 'BORDER-BOTTOM-RIGHT-RADIUS-V': + $this->blk[$this->blklvl]['border_radius_BR_V'] = $this->sizeConverter->convert($v, $this->blk[$prevlevel]['inner_width'], $this->FontSize, false); + break; + /* -- END BORDER-RADIUS -- */ + + case 'BOX-SHADOW': + $bs = $this->cssManager->setCSSboxshadow($v); + if ($bs) { + $this->blk[$this->blklvl]['box_shadow'] = $bs; + } + break; + + case 'BACKGROUND-CLIP': + if (strtoupper($v) == 'PADDING-BOX') { + $this->blk[$this->blklvl]['background_clip'] = 'padding-box'; + } elseif (strtoupper($v) == 'CONTENT-BOX') { + $this->blk[$this->blklvl]['background_clip'] = 'content-box'; + } + break; + + case 'PAGE-BREAK-AFTER': + if (strtoupper($v) == 'AVOID') { + $this->blk[$this->blklvl]['page_break_after_avoid'] = true; + } elseif (strtoupper($v) == 'ALWAYS' || strtoupper($v) == 'LEFT' || strtoupper($v) == 'RIGHT') { + $this->blk[$this->blklvl]['page_break_after'] = strtoupper($v); + } + break; + + // mPDF 6 pagebreaktype + case 'BOX-DECORATION-BREAK': + if (strtoupper($v) == 'CLONE') { + $this->blk[$this->blklvl]['box_decoration_break'] = 'clone'; + } elseif (strtoupper($v) == 'SLICE') { + $this->blk[$this->blklvl]['box_decoration_break'] = 'slice'; + } + break; + + case 'WIDTH': + if (strtoupper($v) != 'AUTO') { + $this->blk[$this->blklvl]['css_set_width'] = $this->sizeConverter->convert($v, $this->blk[$prevlevel]['inner_width'], $this->FontSize, false); + } + break; + + // mPDF 6 Lists + // LISTS + case 'LIST-STYLE-TYPE': + $this->blk[$this->blklvl]['list_style_type'] = strtolower($v); + break; + case 'LIST-STYLE-IMAGE': + $this->blk[$this->blklvl]['list_style_image'] = strtolower($v); + break; + case 'LIST-STYLE-POSITION': + $this->blk[$this->blklvl]['list_style_position'] = strtolower($v); + break; + }//end of switch($k) + } + + + if ($type != 'INLINE' && $type != 'TABLECELL') { // All block-level, including BODY tag + switch ($k) { + case 'TEXT-INDENT': + // Computed value - to inherit + $this->blk[$this->blklvl]['text_indent'] = $this->sizeConverter->convert($v, $this->blk[$prevlevel]['inner_width'], $this->FontSize, false) . 'mm'; + break; + + case 'MARGIN-COLLAPSE': // Custom tag to collapse margins at top and bottom of page + if (strtoupper($v) == 'COLLAPSE') { + $this->blk[$this->blklvl]['margin_collapse'] = true; + } + break; + + case 'LINE-HEIGHT': + $this->blk[$this->blklvl]['line_height'] = $this->fixLineheight($v); + if (!$this->blk[$this->blklvl]['line_height']) { + $this->blk[$this->blklvl]['line_height'] = 'N'; + } // mPDF 6 + break; + + // mPDF 6 + case 'LINE-STACKING-STRATEGY': + $this->blk[$this->blklvl]['line_stacking_strategy'] = strtolower($v); + break; + + case 'LINE-STACKING-SHIFT': + $this->blk[$this->blklvl]['line_stacking_shift'] = strtolower($v); + break; + + case 'TEXT-ALIGN': // left right center justify + switch (strtoupper($v)) { + case 'LEFT': + $this->blk[$this->blklvl]['align'] = "L"; + break; + case 'CENTER': + $this->blk[$this->blklvl]['align'] = "C"; + break; + case 'RIGHT': + $this->blk[$this->blklvl]['align'] = "R"; + break; + case 'JUSTIFY': + $this->blk[$this->blklvl]['align'] = "J"; + break; + } + break; + + /* -- BACKGROUNDS -- */ + case 'BACKGROUND-GRADIENT': + if ($type == 'BLOCK') { + $this->blk[$this->blklvl]['gradient'] = $v; + } + break; + /* -- END BACKGROUNDS -- */ + + case 'DIRECTION': + if ($v) { + $this->blk[$this->blklvl]['direction'] = strtolower($v); + } + break; + } + } + + // FOR INLINE ONLY + if ($type == 'INLINE') { + switch ($k) { + case 'DISPLAY': + if (strtoupper($v) == 'NONE') { + $this->inlineDisplayOff = true; + } + break; + case 'DIRECTION': + break; + } + } + // FOR INLINE ONLY + if ($type == 'INLINE') { + switch ($k) { + // BORDERS + case 'BORDER-TOP': + $this->spanborddet['T'] = $this->border_details($v); + $this->spanborder = true; + $spanbordset = true; + break; + case 'BORDER-BOTTOM': + $this->spanborddet['B'] = $this->border_details($v); + $this->spanborder = true; + $spanbordset = true; + break; + case 'BORDER-LEFT': + $this->spanborddet['L'] = $this->border_details($v); + $this->spanborder = true; + $spanbordset = true; + break; + case 'BORDER-RIGHT': + $this->spanborddet['R'] = $this->border_details($v); + $this->spanborder = true; + $spanbordset = true; + break; + case 'VISIBILITY': // block is set in OpenTag + $v = strtolower($v); + if ($v == 'visible' || $v == 'hidden' || $v == 'printonly' || $v == 'screenonly') { + $this->textparam['visibility'] = $v; + } + break; + }//end of switch($k) + } + + if ($type != 'TABLECELL') { + // FOR INLINE and BLOCK + switch ($k) { + case 'TEXT-ALIGN': // left right center justify + if (strtoupper($v) == 'NOJUSTIFY' && $this->blk[$this->blklvl]['align'] == "J") { + $this->blk[$this->blklvl]['align'] = ""; + } + break; + // bgcolor only - to stay consistent with original html2fpdf + case 'BACKGROUND': + case 'BACKGROUND-COLOR': + $cor = $this->colorConverter->convert($v, $this->PDFAXwarnings); + if ($cor) { + if ($tag == 'BODY') { + $this->bodyBackgroundColor = $cor; + } elseif ($type == 'INLINE') { + $this->spanbgcolorarray = $cor; + $this->spanbgcolor = true; + $spanbgset = true; + } else { + $this->blk[$this->blklvl]['bgcolorarray'] = $cor; + $this->blk[$this->blklvl]['bgcolor'] = true; + } + } elseif ($type != 'INLINE') { + if ($this->ColActive) { + $this->blk[$this->blklvl]['bgcolorarray'] = $this->blk[$prevlevel]['bgcolorarray']; + $this->blk[$this->blklvl]['bgcolor'] = $this->blk[$prevlevel]['bgcolor']; + } + } + break; + + case 'VERTICAL-ALIGN': // super and sub only dealt with here e.g. <SUB> and <SUP> + switch (strtoupper($v)) { + case 'SUPER': + $this->textvar = ($this->textvar | TextVars::FA_SUPERSCRIPT); // mPDF 5.7.1 + $this->textvar = ($this->textvar & ~TextVars::FA_SUBSCRIPT); + // mPDF 5.7.3 inline text-decoration parameters + if (isset($this->textparam['text-baseline'])) { + $this->textparam['text-baseline'] += ($this->baselineSup) * $preceeding_fontsize; + } else { + $this->textparam['text-baseline'] = ($this->baselineSup) * $preceeding_fontsize; + } + break; + case 'SUB': + $this->textvar = ($this->textvar | TextVars::FA_SUBSCRIPT); + $this->textvar = ($this->textvar & ~TextVars::FA_SUPERSCRIPT); + // mPDF 5.7.3 inline text-decoration parameters + if (isset($this->textparam['text-baseline'])) { + $this->textparam['text-baseline'] += ($this->baselineSub) * $preceeding_fontsize; + } else { + $this->textparam['text-baseline'] = ($this->baselineSub) * $preceeding_fontsize; + } + break; + case 'BASELINE': + $this->textvar = ($this->textvar & ~TextVars::FA_SUBSCRIPT); + $this->textvar = ($this->textvar & ~TextVars::FA_SUPERSCRIPT); + // mPDF 5.7.3 inline text-decoration parameters + if (isset($this->textparam['text-baseline'])) { + unset($this->textparam['text-baseline']); + } + break; + // mPDF 5.7.3 inline text-decoration parameters + default: + $lh = $this->_computeLineheight($this->blk[$this->blklvl]['line_height']); + $sz = $this->sizeConverter->convert($v, $lh, $this->FontSize, false); + $this->textvar = ($this->textvar & ~TextVars::FA_SUBSCRIPT); + $this->textvar = ($this->textvar & ~TextVars::FA_SUPERSCRIPT); + if ($sz) { + if ($sz > 0) { + $this->textvar = ($this->textvar | TextVars::FA_SUPERSCRIPT); + } else { + $this->textvar = ($this->textvar | TextVars::FA_SUBSCRIPT); + } + if (isset($this->textparam['text-baseline'])) { + $this->textparam['text-baseline'] += $sz; + } else { + $this->textparam['text-baseline'] = $sz; + } + } + } + break; + }//end of switch($k) + } + + + // FOR ALL + switch ($k) { + case 'LETTER-SPACING': + $this->lSpacingCSS = $v; + if (($this->lSpacingCSS || $this->lSpacingCSS === '0') && strtoupper($this->lSpacingCSS) != 'NORMAL') { + $this->fixedlSpacing = $this->sizeConverter->convert($this->lSpacingCSS, $this->FontSize); + } + break; + + case 'WORD-SPACING': + $this->wSpacingCSS = $v; + if ($this->wSpacingCSS && strtoupper($this->wSpacingCSS) != 'NORMAL') { + $this->minwSpacing = $this->sizeConverter->convert($this->wSpacingCSS, $this->FontSize); + } + break; + + case 'FONT-STYLE': // italic normal oblique + switch (strtoupper($v)) { + case 'ITALIC': + case 'OBLIQUE': + $this->SetStyle('I', true); + break; + case 'NORMAL': + $this->SetStyle('I', false); + break; + } + break; + + case 'FONT-WEIGHT': // normal bold // Does not support: bolder, lighter, 100..900(step value=100) + switch (strtoupper($v)) { + case 'BOLD': + $this->SetStyle('B', true); + break; + case 'NORMAL': + $this->SetStyle('B', false); + break; + } + break; + + case 'FONT-KERNING': + if (strtoupper($v) == 'NORMAL' || (strtoupper($v) == 'AUTO' && $this->useKerning)) { + /* -- OTL -- */ + if ($this->CurrentFont['haskernGPOS']) { + if (isset($this->OTLtags['Plus'])) { + $this->OTLtags['Plus'] .= ' kern'; + } else { + $this->OTLtags['Plus'] = ' kern'; + } + } /* -- END OTL -- */ else { // *OTL* + $this->textvar = ($this->textvar | TextVars::FC_KERNING); + } // *OTL* + } elseif (strtoupper($v) == 'NONE' || (strtoupper($v) == 'AUTO' && !$this->useKerning)) { + if (isset($this->OTLtags['Plus'])) { + $this->OTLtags['Plus'] = str_replace('kern', '', $this->OTLtags['Plus']); // *OTL* + } + if (isset($this->OTLtags['FFPlus'])) { + $this->OTLtags['FFPlus'] = preg_replace('/kern[\d]*/', '', $this->OTLtags['FFPlus']); + } + $this->textvar = ($this->textvar & ~TextVars::FC_KERNING); + } + break; + + /* -- OTL -- */ + case 'FONT-LANGUAGE-OVERRIDE': + $v = strtoupper($v); + if (strpos($v, 'NORMAL') !== false) { + $this->fontLanguageOverride = ''; + } else { + $this->fontLanguageOverride = trim($v); + } + break; + + + case 'FONT-VARIANT-POSITION': + if (isset($this->OTLtags['Plus'])) { + $this->OTLtags['Plus'] = str_replace(['sups', 'subs'], '', $this->OTLtags['Plus']); + } + switch (strtoupper($v)) { + case 'SUPER': + $this->OTLtags['Plus'] .= ' sups'; + break; + case 'SUB': + $this->OTLtags['Plus'] .= ' subs'; + break; + case 'NORMAL': + break; + } + break; + + case 'FONT-VARIANT-CAPS': + $v = strtoupper($v); + if (!isset($this->OTLtags['Plus'])) { + $this->OTLtags['Plus'] = ''; + } + $this->OTLtags['Plus'] = str_replace(['c2sc', 'smcp', 'c2pc', 'pcap', 'unic', 'titl'], '', $this->OTLtags['Plus']); + $this->textvar = ($this->textvar & ~TextVars::FC_SMALLCAPS); // ?????????????? <small-caps> + if (strpos($v, 'ALL-SMALL-CAPS') !== false) { + $this->OTLtags['Plus'] .= ' c2sc smcp'; + } elseif (strpos($v, 'SMALL-CAPS') !== false) { + if (isset($this->CurrentFont['hassmallcapsGSUB']) && $this->CurrentFont['hassmallcapsGSUB']) { + $this->OTLtags['Plus'] .= ' smcp'; + } else { + $this->textvar = ($this->textvar | TextVars::FC_SMALLCAPS); + } + } elseif (strpos($v, 'ALL-PETITE-CAPS') !== false) { + $this->OTLtags['Plus'] .= ' c2pc pcap'; + } elseif (strpos($v, 'PETITE-CAPS') !== false) { + $this->OTLtags['Plus'] .= ' pcap'; + } elseif (strpos($v, 'UNICASE') !== false) { + $this->OTLtags['Plus'] .= ' unic'; + } elseif (strpos($v, 'TITLING-CAPS') !== false) { + $this->OTLtags['Plus'] .= ' titl'; + } + break; + + case 'FONT-VARIANT-LIGATURES': + $v = strtoupper($v); + if (!isset($this->OTLtags['Plus'])) { + $this->OTLtags['Plus'] = ''; + } + if (!isset($this->OTLtags['Minus'])) { + $this->OTLtags['Minus'] = ''; + } + if (strpos($v, 'NORMAL') !== false) { + $this->OTLtags['Minus'] = str_replace(['liga', 'clig', 'calt'], '', $this->OTLtags['Minus']); + $this->OTLtags['Plus'] = str_replace(['dlig', 'hlig'], '', $this->OTLtags['Plus']); + } elseif (strpos($v, 'NONE') !== false) { + $this->OTLtags['Minus'] .= ' liga clig calt'; + $this->OTLtags['Plus'] = str_replace(['dlig', 'hlig'], '', $this->OTLtags['Plus']); + } + if (strpos($v, 'NO-COMMON-LIGATURES') !== false) { + $this->OTLtags['Minus'] .= ' liga clig'; + } elseif (strpos($v, 'COMMON-LIGATURES') !== false) { + $this->OTLtags['Minus'] = str_replace(['liga', 'clig'], '', $this->OTLtags['Minus']); + } + if (strpos($v, 'NO-CONTEXTUAL') !== false) { + $this->OTLtags['Minus'] .= ' calt'; + } elseif (strpos($v, 'CONTEXTUAL') !== false) { + $this->OTLtags['Minus'] = str_replace('calt', '', $this->OTLtags['Minus']); + } + if (strpos($v, 'NO-DISCRETIONARY-LIGATURES') !== false) { + $this->OTLtags['Plus'] = str_replace('dlig', '', $this->OTLtags['Plus']); + } elseif (strpos($v, 'DISCRETIONARY-LIGATURES') !== false) { + $this->OTLtags['Plus'] .= ' dlig'; + } + if (strpos($v, 'NO-HISTORICAL-LIGATURES') !== false) { + $this->OTLtags['Plus'] = str_replace('hlig', '', $this->OTLtags['Plus']); + } elseif (strpos($v, 'HISTORICAL-LIGATURES') !== false) { + $this->OTLtags['Plus'] .= ' hlig'; + } + + break; + + case 'FONT-VARIANT-NUMERIC': + $v = strtoupper($v); + if (!isset($this->OTLtags['Plus'])) { + $this->OTLtags['Plus'] = ''; + } + if (strpos($v, 'NORMAL') !== false) { + $this->OTLtags['Plus'] = str_replace(['ordn', 'zero', 'lnum', 'onum', 'pnum', 'tnum', 'frac', 'afrc'], '', $this->OTLtags['Plus']); + } + if (strpos($v, 'ORDINAL') !== false) { + $this->OTLtags['Plus'] .= ' ordn'; + } + if (strpos($v, 'SLASHED-ZERO') !== false) { + $this->OTLtags['Plus'] .= ' zero'; + } + if (strpos($v, 'LINING-NUMS') !== false) { + $this->OTLtags['Plus'] .= ' lnum'; + $this->OTLtags['Plus'] = str_replace('onum', '', $this->OTLtags['Plus']); + } elseif (strpos($v, 'OLDSTYLE-NUMS') !== false) { + $this->OTLtags['Plus'] .= ' onum'; + $this->OTLtags['Plus'] = str_replace('lnum', '', $this->OTLtags['Plus']); + } + if (strpos($v, 'PROPORTIONAL-NUMS') !== false) { + $this->OTLtags['Plus'] .= ' pnum'; + $this->OTLtags['Plus'] = str_replace('tnum', '', $this->OTLtags['Plus']); + } elseif (strpos($v, 'TABULAR-NUMS') !== false) { + $this->OTLtags['Plus'] .= ' tnum'; + $this->OTLtags['Plus'] = str_replace('pnum', '', $this->OTLtags['Plus']); + } + if (strpos($v, 'DIAGONAL-FRACTIONS') !== false) { + $this->OTLtags['Plus'] .= ' frac'; + $this->OTLtags['Plus'] = str_replace('afrc', '', $this->OTLtags['Plus']); + } elseif (strpos($v, 'STACKED-FRACTIONS') !== false) { + $this->OTLtags['Plus'] .= ' afrc'; + $this->OTLtags['Plus'] = str_replace('frac', '', $this->OTLtags['Plus']); + } + break; + + case 'FONT-VARIANT-ALTERNATES': // Only supports historical-forms + $v = strtoupper($v); + if (!isset($this->OTLtags['Plus'])) { + $this->OTLtags['Plus'] = ''; + } + if (strpos($v, 'NORMAL') !== false) { + $this->OTLtags['Plus'] = str_replace('hist', '', $this->OTLtags['Plus']); + } + if (strpos($v, 'HISTORICAL-FORMS') !== false) { + $this->OTLtags['Plus'] .= ' hist'; + } + break; + + + case 'FONT-FEATURE-SETTINGS': + $v = strtolower($v); + if (strpos($v, 'normal') !== false) { + $this->OTLtags['FFMinus'] = ''; + $this->OTLtags['FFPlus'] = ''; + } else { + if (!isset($this->OTLtags['FFPlus'])) { + $this->OTLtags['FFPlus'] = ''; + } + if (!isset($this->OTLtags['FFMinus'])) { + $this->OTLtags['FFMinus'] = ''; + } + $tags = preg_split('/[,]/', $v); + foreach ($tags as $t) { + if (preg_match('/[\"\']([a-zA-Z0-9]{4})[\"\']\s*(on|off|\d*){0,1}/', $t, $m)) { + if ($m[2] == 'off' || $m[2] === '0') { + if (strpos($this->OTLtags['FFMinus'], $m[1]) === false) { + $this->OTLtags['FFMinus'] .= ' ' . $m[1]; + } + $this->OTLtags['FFPlus'] = preg_replace('/' . $m[1] . '[\d]*/', '', $this->OTLtags['FFPlus']); + } else { + if ($m[2] == 'on') { + $m[2] = '1'; + } + if (strpos($this->OTLtags['FFPlus'], $m[1]) === false) { + $this->OTLtags['FFPlus'] .= ' ' . $m[1] . $m[2]; + } + $this->OTLtags['FFMinus'] = str_replace($m[1], '', $this->OTLtags['FFMinus']); + } + } + } + } + break; + /* -- END OTL -- */ + + + case 'TEXT-TRANSFORM': // none uppercase lowercase // Does support: capitalize + switch (strtoupper($v)) { // Not working 100% + case 'CAPITALIZE': + $this->textvar = ($this->textvar | TextVars::FT_CAPITALIZE); // mPDF 5.7.1 + $this->textvar = ($this->textvar & ~TextVars::FT_UPPERCASE); // mPDF 5.7.1 + $this->textvar = ($this->textvar & ~TextVars::FT_LOWERCASE); // mPDF 5.7.1 + break; + case 'UPPERCASE': + $this->textvar = ($this->textvar | TextVars::FT_UPPERCASE); // mPDF 5.7.1 + $this->textvar = ($this->textvar & ~TextVars::FT_LOWERCASE); // mPDF 5.7.1 + $this->textvar = ($this->textvar & ~TextVars::FT_CAPITALIZE); // mPDF 5.7.1 + break; + case 'LOWERCASE': + $this->textvar = ($this->textvar | TextVars::FT_LOWERCASE); // mPDF 5.7.1 + $this->textvar = ($this->textvar & ~TextVars::FT_UPPERCASE); // mPDF 5.7.1 + $this->textvar = ($this->textvar & ~TextVars::FT_CAPITALIZE); // mPDF 5.7.1 + break; + case 'NONE': + break; + $this->textvar = ($this->textvar & ~TextVars::FT_UPPERCASE); // mPDF 5.7.1 + $this->textvar = ($this->textvar & ~TextVars::FT_LOWERCASE); // mPDF 5.7.1 + $this->textvar = ($this->textvar & ~TextVars::FT_CAPITALIZE); // mPDF 5.7.1 + } + break; + + case 'TEXT-SHADOW': + $ts = $this->cssManager->setCSStextshadow($v); + if ($ts) { + $this->textshadow = $ts; + } + break; + + case 'HYPHENS': + if (strtoupper($v) == 'NONE') { + $this->textparam['hyphens'] = 2; + } elseif (strtoupper($v) == 'AUTO') { + $this->textparam['hyphens'] = 1; + } elseif (strtoupper($v) == 'MANUAL') { + $this->textparam['hyphens'] = 0; + } + break; + + case 'TEXT-OUTLINE': + if (strtoupper($v) == 'NONE') { + $this->textparam['outline-s'] = false; + } + break; + + case 'TEXT-OUTLINE-WIDTH': + case 'OUTLINE-WIDTH': + switch (strtoupper($v)) { + case 'THIN': + $v = '0.03em'; + break; + case 'MEDIUM': + $v = '0.05em'; + break; + case 'THICK': + $v = '0.07em'; + break; + } + $w = $this->sizeConverter->convert($v, $this->FontSize, $this->FontSize); + if ($w) { + $this->textparam['outline-WIDTH'] = $w; + $this->textparam['outline-s'] = true; + } else { + $this->textparam['outline-s'] = false; + } + break; + + case 'TEXT-OUTLINE-COLOR': + case 'OUTLINE-COLOR': + if (strtoupper($v) == 'INVERT') { + if ($this->colorarray) { + $cor = $this->colorarray; + $this->textparam['outline-COLOR'] = $this->colorConverter->invert($cor); + } else { + $this->textparam['outline-COLOR'] = $this->colorConverter->convert(255, $this->PDFAXwarnings); + } + } else { + $cor = $this->colorConverter->convert($v, $this->PDFAXwarnings); + if ($cor) { + $this->textparam['outline-COLOR'] = $cor; + } + } + break; + + case 'COLOR': // font color + $cor = $this->colorConverter->convert($v, $this->PDFAXwarnings); + if ($cor) { + $this->colorarray = $cor; + $this->SetTColor($cor); + } + break; + }//end of switch($k) + }//end of foreach + // mPDF 5.7.3 inline text-decoration parameters + // Needs to be set at the end - after vertical-align = super/sub, so that textparam['text-baseline'] is set + if (isset($arrayaux['TEXT-DECORATION'])) { + $v = $arrayaux['TEXT-DECORATION']; // none underline line-through (strikeout) // Does not support: blink + if (stristr($v, 'LINE-THROUGH')) { + $this->textvar = ($this->textvar | TextVars::FD_LINETHROUGH); + // mPDF 5.7.3 inline text-decoration parameters + if (isset($this->textparam['text-baseline'])) { + $this->textparam['s-decoration']['baseline'] = $this->textparam['text-baseline']; + } else { + $this->textparam['s-decoration']['baseline'] = 0; + } + $this->textparam['s-decoration']['fontkey'] = $this->FontFamily . $this->FontStyle; + $this->textparam['s-decoration']['fontsize'] = $this->FontSize; + $this->textparam['s-decoration']['color'] = strtoupper($this->TextColor); // change 0 0 0 rg to 0 0 0 RG + } + if (stristr($v, 'UNDERLINE')) { + $this->textvar = ($this->textvar | TextVars::FD_UNDERLINE); + // mPDF 5.7.3 inline text-decoration parameters + if (isset($this->textparam['text-baseline'])) { + $this->textparam['u-decoration']['baseline'] = $this->textparam['text-baseline']; + } else { + $this->textparam['u-decoration']['baseline'] = 0; + } + $this->textparam['u-decoration']['fontkey'] = $this->FontFamily . $this->FontStyle; + $this->textparam['u-decoration']['fontsize'] = $this->FontSize; + $this->textparam['u-decoration']['color'] = strtoupper($this->TextColor); // change 0 0 0 rg to 0 0 0 RG + } + if (stristr($v, 'OVERLINE')) { + $this->textvar = ($this->textvar | TextVars::FD_OVERLINE); + // mPDF 5.7.3 inline text-decoration parameters + if (isset($this->textparam['text-baseline'])) { + $this->textparam['o-decoration']['baseline'] = $this->textparam['text-baseline']; + } else { + $this->textparam['o-decoration']['baseline'] = 0; + } + $this->textparam['o-decoration']['fontkey'] = $this->FontFamily . $this->FontStyle; + $this->textparam['o-decoration']['fontsize'] = $this->FontSize; + $this->textparam['o-decoration']['color'] = strtoupper($this->TextColor); // change 0 0 0 rg to 0 0 0 RG + } + if (stristr($v, 'NONE')) { + $this->textvar = ($this->textvar & ~TextVars::FD_UNDERLINE); + $this->textvar = ($this->textvar & ~TextVars::FD_LINETHROUGH); + $this->textvar = ($this->textvar & ~TextVars::FD_OVERLINE); + // mPDF 5.7.3 inline text-decoration parameters + if (isset($this->textparam['u-decoration'])) { + unset($this->textparam['u-decoration']); + } + if (isset($this->textparam['s-decoration'])) { + unset($this->textparam['s-decoration']); + } + if (isset($this->textparam['o-decoration'])) { + unset($this->textparam['o-decoration']); + } + } + } + // mPDF 6 + if ($spanbordset) { // BORDER has been set on this INLINE element + if (isset($this->textparam['text-baseline'])) { + $this->textparam['bord-decoration']['baseline'] = $this->textparam['text-baseline']; + } else { + $this->textparam['bord-decoration']['baseline'] = 0; + } + $this->textparam['bord-decoration']['fontkey'] = $this->FontFamily . $this->FontStyle; + $this->textparam['bord-decoration']['fontsize'] = $this->FontSize; + } + if ($spanbgset) { // BACKGROUND[-COLOR] has been set on this INLINE element + if (isset($this->textparam['text-baseline'])) { + $this->textparam['bg-decoration']['baseline'] = $this->textparam['text-baseline']; + } else { + $this->textparam['bg-decoration']['baseline'] = 0; + } + $this->textparam['bg-decoration']['fontkey'] = $this->FontFamily . $this->FontStyle; + $this->textparam['bg-decoration']['fontsize'] = $this->FontSize; + } + } + + /* -- END HTML-CSS -- */ + + function SetStyle($tag, $enable) + { + $this->$tag = $enable; + $style = ''; + foreach (['B', 'I'] as $s) { + if ($this->$s) { + $style .= $s; + } + } + $this->currentfontstyle = $style; + $this->SetFont('', $style, 0, false); + } + + // Set multiple styles at one time + function SetStylesArray($arr) + { + $style = ''; + foreach (['B', 'I'] as $s) { + if (isset($arr[$s])) { + if ($arr[$s]) { + $this->$s = true; + $style .= $s; + } else { + $this->$s = false; + } + } elseif ($this->$s) { + $style .= $s; + } + } + $this->currentfontstyle = $style; + $this->SetFont('', $style, 0, false); + } + + // Set multiple styles at one $str e.g. "BI" + function SetStyles($str) + { + $style = ''; + foreach (['B', 'I'] as $s) { + if (strpos($str, $s) !== false) { + $this->$s = true; + $style .= $s; + } else { + $this->$s = false; + } + } + $this->currentfontstyle = $style; + $this->SetFont('', $style, 0, false); + } + + function ResetStyles() + { + foreach (['B', 'I'] as $s) { + $this->$s = false; + } + $this->currentfontstyle = ''; + $this->SetFont('', '', 0, false); + } + + function DisableTags($str = '') + { + if ($str == '') { // enable all tags + // Insert new supported tags in the long string below. + $this->enabledtags = "<a><acronym><address><article><aside><b><bdi><bdo><big><blockquote><br><caption><center><cite><code><del><details><dd><div><dl><dt><em><fieldset><figcaption><figure><font><form><h1><h2><h3><h4><h5><h6><hgroup><hr><i><img><input><ins><kbd><legend><li><main><mark><meter><nav><ol><option><p><pre><progress><q><s><samp><section><select><small><span><strike><strong><sub><summary><sup><table><tbody><td><template><textarea><tfoot><th><thead><time><tr><tt><u><ul><var><footer><header><annotation><bookmark><textcircle><barcode><dottab><indexentry><indexinsert><watermarktext><watermarkimage><tts><ttz><tta><column_break><columnbreak><newcolumn><newpage><page_break><pagebreak><formfeed><columns><toc><tocentry><tocpagebreak><pageheader><pagefooter><setpageheader><setpagefooter><sethtmlpageheader><sethtmlpagefooter>"; + } else { + $str = explode(",", $str); + foreach ($str as $v) { + $this->enabledtags = str_replace(trim($v), '', $this->enabledtags); + } + } + } + + /* -- TABLES -- */ + + function TableCheckMinWidth($maxwidth, $forcewrap = 0, $textbuffer = [], $checkletter = false) + { + // mPDF 6 + $acclength = 0; // mPDF 6 (accumulated length across > 1 chunk) + $acclongest = 0; // mPDF 6 (accumulated length max across > 1 chunk) + $biggestword = 0; + $toonarrow = false; + if ((count($textbuffer) == 0) or ( (count($textbuffer) == 1) && ($textbuffer[0][0] == ''))) { + return 0; + } + + foreach ($textbuffer as $chunk) { + $line = $chunk[0]; + $OTLdata = (isset($chunk[18]) ? $chunk[18] : null); + + // mPDF ITERATION + if ($this->iterationCounter) { + $line = preg_replace('/{iteration ([a-zA-Z0-9_]+)}/', '\\1', $line); + } + + // IMAGES & FORM ELEMENTS + if (substr($line, 0, 3) == "\xbb\xa4\xac") { // inline object - FORM element or IMAGE! + $objattr = $this->_getObjAttr($line); + if ($objattr['type'] != 'hr' && isset($objattr['width']) && ($objattr['width'] / $this->shrin_k) > ($maxwidth + 0.0001)) { + if (($objattr['width'] / $this->shrin_k) > $biggestword) { + $biggestword = ($objattr['width'] / $this->shrin_k); + } + $toonarrow = true; + } + continue; + } + + if ($line == "\n") { + $acclength = 0; // mPDF 6 (accumulated length across > 1 chunk) + continue; + } + $line = trim($line); + if (!empty($OTLdata)) { + $this->otl->trimOTLdata($OTLdata, true, true); + } // *OTL* + // SET FONT SIZE/STYLE from $chunk[n] + // FONTSIZE + if (isset($chunk[11]) and $chunk[11] != '') { + if ($this->shrin_k) { + $this->SetFontSize($chunk[11] / $this->shrin_k, false); + } else { + $this->SetFontSize($chunk[11], false); + } + } + // FONTFAMILY + if (isset($chunk[4]) and $chunk[4] != '') { + $font = $this->SetFont($chunk[4], $this->FontStyle, 0, false); + } + // B I + if (isset($chunk[2]) and $chunk[2] != '') { + $this->SetStyles($chunk[2]); + } + + $lbw = $rbw = 0; // Border widths + if (isset($chunk[16]) && !empty($chunk[16])) { // Border + $this->spanborddet = $chunk[16]; + $lbw = (isset($this->spanborddet['L']['w']) ? $this->spanborddet['L']['w'] : 0); + $rbw = (isset($this->spanborddet['R']['w']) ? $this->spanborddet['R']['w'] : 0); + } + if (isset($chunk[15])) { // Word spacing + $this->wSpacingCSS = $chunk[15]; + if ($this->wSpacingCSS && strtoupper($this->wSpacingCSS) != 'NORMAL') { + $this->minwSpacing = $this->sizeConverter->convert($this->wSpacingCSS, $this->FontSize) / $this->shrin_k; // mPDF 5.7.3 + } + } + if (isset($chunk[14])) { // Letter spacing + $this->lSpacingCSS = $chunk[14]; + if (($this->lSpacingCSS || $this->lSpacingCSS === '0') && strtoupper($this->lSpacingCSS) != 'NORMAL') { + $this->fixedlSpacing = $this->sizeConverter->convert($this->lSpacingCSS, $this->FontSize) / $this->shrin_k; // mPDF 5.7.3 + } + } + if (isset($chunk[8])) { // mPDF 5.7.1 + $this->textvar = $chunk[8]; + } + + // mPDF 6 + // If overflow==wrap ($checkletter) OR (No word breaks and contains CJK) + if ($checkletter || (!preg_match('/(\xe2\x80\x8b| )/', trim($line)) && preg_match("/([" . $this->pregCJKchars . "])/u", $line) )) { + if (preg_match("/([" . $this->pregCJKchars . "])/u", $line)) { + $checkCJK = true; + } else { + $checkCJK = false; + } + + $letters = preg_split('//u', $line); + foreach ($letters as $k => $letter) { + // mPDF 6 + if ($checkCJK) { + if (preg_match("/[" . $this->CJKleading . "]/u", $letter) && $k > 0) { + $letter = $letters[$k - 1] . $letter; + } + if (preg_match("/[" . $this->CJKfollowing . "]/u", $letter) && $k < (count($letters) - 1)) { + $letter = $letter . $letters[$k + 1]; + } + } + + $letterwidth = $this->GetStringWidth($letter, false, false, $chunk[8]); // Pass $textvar ($chunk[8]), but do OTLdata here + // so don't have to split OTLdata for each word + if ($k == 0) { + $letterwidth += $lbw; + } + if ($k == (count($letters) - 1)) { + $letterwidth += $rbw; + } + + // Warn user that maxwidth is insufficient + if ($letterwidth > $maxwidth + 0.0001) { + if ($letterwidth > $biggestword) { + $biggestword = $letterwidth; + } + $toonarrow = true; + } + } + } else { + // mPDF 6 + // Need to account for any XAdvance in GPOSinfo (OTLdata = $chunk[18]) + $wordXAdvance = []; + if (isset($chunk[18]) && $chunk[18]) { + preg_match_all('/(\xe2\x80\x8b| )/', $line, $spaces, PREG_OFFSET_CAPTURE); // U+200B Zero Width word boundary, or space + $lastoffset = 0; + $k = -1; // Added so that if no spaces found, "last word" later is calculated for the one and only word + foreach ($spaces[0] as $k => $m) { + $offset = $m[1]; + // ...TableCheckMinWidth... + // At this point, BIDI not applied, Writing direction is not set, and XAdvanceL balances XAdvanceR + for ($n = $lastoffset; $n < $offset; $n++) { + if (isset($chunk[18]['GPOSinfo'][$n]['XAdvanceL'])) { + if (isset($wordXAdvance[$k])) { + $wordXAdvance[$k] += $chunk[18]['GPOSinfo'][$n]['XAdvanceL']; + } else { + $wordXAdvance[$k] = $chunk[18]['GPOSinfo'][$n]['XAdvanceL']; + } + } + } + $lastoffset = $offset + 1; + } + + $k++; // last word + foreach ($chunk[18]['GPOSinfo'] as $n => $gpos) { + if ($n >= $lastoffset && isset($chunk[18]['GPOSinfo'][$n]['XAdvanceL'])) { + if (isset($wordXAdvance[$k])) { + $wordXAdvance[$k] += $chunk[18]['GPOSinfo'][$n]['XAdvanceL']; + } else { + $wordXAdvance[$k] = $chunk[18]['GPOSinfo'][$n]['XAdvanceL']; + } + } + } + } + + $words = preg_split('/(\xe2\x80\x8b| )/', $line); // U+200B Zero Width word boundary, or space + foreach ($words as $k => $word) { + $word = trim($word); + $wordwidth = $this->GetStringWidth($word, false, false, $chunk[8]); // Pass $textvar ($chunk[8]), but do OTLdata here + // so don't have to split OTLdata for each word + if (isset($wordXAdvance[$k])) { + $wordwidth += ($wordXAdvance[$k] * 1000 / $this->CurrentFont['unitsPerEm']) * ($this->FontSize / 1000); + } + if ($k == 0) { + $wordwidth += $lbw; + } + if ($k == (count($words) - 1)) { + $wordwidth += $rbw; + } + + // mPDF 6 + if (count($words) == 1 && substr($chunk[0], 0, 1) != ' ') { + $acclength += $wordwidth; + } elseif (count($words) > 1 && $k == 0 && substr($chunk[0], 0, 1) != ' ') { + $acclength += $wordwidth; + } else { + $acclength = $wordwidth; + } + $acclongest = max($acclongest, $acclength); + if (count($words) == 1 && substr($chunk[0], -1, 1) == ' ') { + $acclength = 0; + } elseif (count($words) > 1 && ($k != (count($words) - 1) || substr($chunk[0], -1, 1) == ' ')) { + $acclength = 0; + } + + // Warn user that maxwidth is insufficient + if ($wordwidth > $maxwidth + 0.0001) { + if ($wordwidth > $biggestword) { + $biggestword = $wordwidth; + } + $toonarrow = true; + } + } + } + + // mPDF 6 Accumulated length of biggest word - across multiple chunks + if ($acclongest > $maxwidth + 0.0001) { + if ($acclongest > $biggestword) { + $biggestword = $acclongest; + } + $toonarrow = true; + } + + // RESET FONT SIZE/STYLE + // RESETTING VALUES + // Now we must deactivate what we have used + if (isset($chunk[2]) and $chunk[2] != '') { + $this->ResetStyles(); + } + if (isset($chunk[4]) and $chunk[4] != '') { + $this->SetFont($this->default_font, $this->FontStyle, 0, false); + } + if (isset($chunk[11]) and $chunk[11] != '') { + $this->SetFontSize($this->default_font_size, false); + } + $this->spanborddet = []; + $this->textvar = 0x00; // mPDF 5.7.1 + $this->OTLtags = []; + $this->lSpacingCSS = ''; + $this->wSpacingCSS = ''; + $this->fixedlSpacing = false; + $this->minwSpacing = 0; + } + + // Return -(wordsize) if word is bigger than maxwidth + // ADDED + if (($toonarrow) && ($this->table_error_report)) { + throw new \Mpdf\MpdfException("Word is too long to fit in table - " . $this->table_error_report_param); + } + if ($toonarrow) { + return -$biggestword; + } else { + return 1; + } + } + + function shrinkTable(&$table, $k) + { + $table['border_spacing_H'] /= $k; + $table['border_spacing_V'] /= $k; + + $table['padding']['T'] /= $k; + $table['padding']['R'] /= $k; + $table['padding']['B'] /= $k; + $table['padding']['L'] /= $k; + + $table['margin']['T'] /= $k; + $table['margin']['R'] /= $k; + $table['margin']['B'] /= $k; + $table['margin']['L'] /= $k; + + $table['border_details']['T']['w'] /= $k; + $table['border_details']['R']['w'] /= $k; + $table['border_details']['B']['w'] /= $k; + $table['border_details']['L']['w'] /= $k; + + if (isset($table['max_cell_border_width']['T'])) { + $table['max_cell_border_width']['T'] /= $k; + } + if (isset($table['max_cell_border_width']['R'])) { + $table['max_cell_border_width']['R'] /= $k; + } + if (isset($table['max_cell_border_width']['B'])) { + $table['max_cell_border_width']['B'] /= $k; + } + if (isset($table['max_cell_border_width']['L'])) { + $table['max_cell_border_width']['L'] /= $k; + } + + if ($this->simpleTables) { + $table['simple']['border_details']['T']['w'] /= $k; + $table['simple']['border_details']['R']['w'] /= $k; + $table['simple']['border_details']['B']['w'] /= $k; + $table['simple']['border_details']['L']['w'] /= $k; + } + + $table['miw'] /= $k; + $table['maw'] /= $k; + + for ($j = 0; $j < $table['nc']; $j++) { // columns + + $table['wc'][$j]['miw'] = isset($table['wc'][$j]['miw']) ? $table['wc'][$j]['miw'] : 0; + $table['wc'][$j]['maw'] = isset($table['wc'][$j]['maw']) ? $table['wc'][$j]['maw'] : 0; + + $table['wc'][$j]['miw'] /= $k; + $table['wc'][$j]['maw'] /= $k; + + if (isset($table['decimal_align'][$j]['maxs0']) && $table['decimal_align'][$j]['maxs0']) { + $table['decimal_align'][$j]['maxs0'] /= $k; + } + + if (isset($table['decimal_align'][$j]['maxs1']) && $table['decimal_align'][$j]['maxs1']) { + $table['decimal_align'][$j]['maxs1'] /= $k; + } + + if (isset($table['wc'][$j]['absmiw']) && $table['wc'][$j]['absmiw']) { + $table['wc'][$j]['absmiw'] /= $k; + } + + for ($i = 0; $i < $table['nr']; $i++) { // rows + + $c = &$table['cells'][$i][$j]; + + if (isset($c) && $c) { + + if (!$this->simpleTables) { + + if ($this->packTableData) { + + $cell = $this->_unpackCellBorder($c['borderbin']); + + $cell['border_details']['T']['w'] /= $k; + $cell['border_details']['R']['w'] /= $k; + $cell['border_details']['B']['w'] /= $k; + $cell['border_details']['L']['w'] /= $k; + $cell['border_details']['mbw']['TL'] /= $k; + $cell['border_details']['mbw']['TR'] /= $k; + $cell['border_details']['mbw']['BL'] /= $k; + $cell['border_details']['mbw']['BR'] /= $k; + $cell['border_details']['mbw']['LT'] /= $k; + $cell['border_details']['mbw']['LB'] /= $k; + $cell['border_details']['mbw']['RT'] /= $k; + $cell['border_details']['mbw']['RB'] /= $k; + + $c['borderbin'] = $this->_packCellBorder($cell); + + } else { + + $c['border_details']['T']['w'] /= $k; + $c['border_details']['R']['w'] /= $k; + $c['border_details']['B']['w'] /= $k; + $c['border_details']['L']['w'] /= $k; + $c['border_details']['mbw']['TL'] /= $k; + $c['border_details']['mbw']['TR'] /= $k; + $c['border_details']['mbw']['BL'] /= $k; + $c['border_details']['mbw']['BR'] /= $k; + $c['border_details']['mbw']['LT'] /= $k; + $c['border_details']['mbw']['LB'] /= $k; + $c['border_details']['mbw']['RT'] /= $k; + $c['border_details']['mbw']['RB'] /= $k; + } + } + + $c['padding']['T'] /= $k; + $c['padding']['R'] /= $k; + $c['padding']['B'] /= $k; + $c['padding']['L'] /= $k; + + $c['maxs'] = isset($c['maxs']) ? $c['maxs'] /= $k : null; + $c['w'] = isset($c['w']) ? $c['w'] /= $k : null; + + $c['s'] = isset($c['s']) ? $c['s'] /= $k : 0; + $c['h'] = isset($c['h']) ? $c['h'] /= $k : null; + + $c['miw'] = isset($c['miw']) ? $c['miw'] /= $k : 0; + $c['maw'] = isset($c['maw']) ? $c['maw'] /= $k : 0; + + $c['absmiw'] = isset($c['absmiw']) ? $c['absmiw'] /= $k : null; + + $c['nestedmaw'] = isset($c['nestedmaw']) ? $c['nestedmaw'] /= $k : null; + $c['nestedmiw'] = isset($c['nestedmiw']) ? $c['nestedmiw'] /= $k : null; + + if (isset($c['textbuffer'])) { + foreach ($c['textbuffer'] as $n => $tb) { + if (!empty($tb[16])) { + !isset($c['textbuffer'][$n][16]['T']) || $c['textbuffer'][$n][16]['T']['w'] /= $k; + !isset($c['textbuffer'][$n][16]['B']) || $c['textbuffer'][$n][16]['B']['w'] /= $k; + !isset($c['textbuffer'][$n][16]['L']) || $c['textbuffer'][$n][16]['L']['w'] /= $k; + !isset($c['textbuffer'][$n][16]['R']) || $c['textbuffer'][$n][16]['R']['w'] /= $k; + } + } + } + + unset($c); + } + + } // rows + } // columns + } + + function read_short(&$fh) + { + $s = fread($fh, 2); + $a = (ord($s[0]) << 8) + ord($s[1]); + if ($a & (1 << 15)) { + $a = ($a - (1 << 16)); + } + return $a; + } + + function _packCellBorder($cell) + { + if (!is_array($cell) || !isset($cell)) { + return ''; + } + + if (!$this->packTableData) { + return $cell; + } + // = 186 bytes + $bindata = pack("nnda6A10nnda6A10nnda6A10nnda6A10nd9", $cell['border'], $cell['border_details']['R']['s'], $cell['border_details']['R']['w'], $cell['border_details']['R']['c'], $cell['border_details']['R']['style'], $cell['border_details']['R']['dom'], $cell['border_details']['L']['s'], $cell['border_details']['L']['w'], $cell['border_details']['L']['c'], $cell['border_details']['L']['style'], $cell['border_details']['L']['dom'], $cell['border_details']['T']['s'], $cell['border_details']['T']['w'], $cell['border_details']['T']['c'], $cell['border_details']['T']['style'], $cell['border_details']['T']['dom'], $cell['border_details']['B']['s'], $cell['border_details']['B']['w'], $cell['border_details']['B']['c'], $cell['border_details']['B']['style'], $cell['border_details']['B']['dom'], $cell['border_details']['mbw']['BL'], $cell['border_details']['mbw']['BR'], $cell['border_details']['mbw']['RT'], $cell['border_details']['mbw']['RB'], $cell['border_details']['mbw']['TL'], $cell['border_details']['mbw']['TR'], $cell['border_details']['mbw']['LT'], $cell['border_details']['mbw']['LB'], (isset($cell['border_details']['cellposdom']) ? $cell['border_details']['cellposdom'] : 0)); + return $bindata; + } + + function _getBorderWidths($bindata) + { + if (!$bindata) { + return [0, 0, 0, 0]; + } + if (!$this->packTableData) { + return [$bindata['border_details']['T']['w'], $bindata['border_details']['R']['w'], $bindata['border_details']['B']['w'], $bindata['border_details']['L']['w']]; + } + + $bd = unpack("nbord/nrs/drw/a6rca/A10rst/nrd/nls/dlw/a6lca/A10lst/nld/nts/dtw/a6tca/A10tst/ntd/nbs/dbw/a6bca/A10bst/nbd/dmbl/dmbr/dmrt/dmrb/dmtl/dmtr/dmlt/dmlb/dcpd", $bindata); + $cell['border_details']['R']['w'] = $bd['rw']; + $cell['border_details']['L']['w'] = $bd['lw']; + $cell['border_details']['T']['w'] = $bd['tw']; + $cell['border_details']['B']['w'] = $bd['bw']; + return [$bd['tw'], $bd['rw'], $bd['bw'], $bd['lw']]; + } + + function _unpackCellBorder($bindata) + { + if (!$bindata) { + return []; + } + if (!$this->packTableData) { + return $bindata; + } + + $bd = unpack("nbord/nrs/drw/a6rca/A10rst/nrd/nls/dlw/a6lca/A10lst/nld/nts/dtw/a6tca/A10tst/ntd/nbs/dbw/a6bca/A10bst/nbd/dmbl/dmbr/dmrt/dmrb/dmtl/dmtr/dmlt/dmlb/dcpd", $bindata); + + $cell['border'] = $bd['bord']; + $cell['border_details']['R']['s'] = $bd['rs']; + $cell['border_details']['R']['w'] = $bd['rw']; + $cell['border_details']['R']['c'] = str_pad($bd['rca'], 6, "\x00"); + $cell['border_details']['R']['style'] = trim($bd['rst']); + $cell['border_details']['R']['dom'] = $bd['rd']; + + $cell['border_details']['L']['s'] = $bd['ls']; + $cell['border_details']['L']['w'] = $bd['lw']; + $cell['border_details']['L']['c'] = str_pad($bd['lca'], 6, "\x00"); + $cell['border_details']['L']['style'] = trim($bd['lst']); + $cell['border_details']['L']['dom'] = $bd['ld']; + + $cell['border_details']['T']['s'] = $bd['ts']; + $cell['border_details']['T']['w'] = $bd['tw']; + $cell['border_details']['T']['c'] = str_pad($bd['tca'], 6, "\x00"); + $cell['border_details']['T']['style'] = trim($bd['tst']); + $cell['border_details']['T']['dom'] = $bd['td']; + + $cell['border_details']['B']['s'] = $bd['bs']; + $cell['border_details']['B']['w'] = $bd['bw']; + $cell['border_details']['B']['c'] = str_pad($bd['bca'], 6, "\x00"); + $cell['border_details']['B']['style'] = trim($bd['bst']); + $cell['border_details']['B']['dom'] = $bd['bd']; + + $cell['border_details']['mbw']['BL'] = $bd['mbl']; + $cell['border_details']['mbw']['BR'] = $bd['mbr']; + $cell['border_details']['mbw']['RT'] = $bd['mrt']; + $cell['border_details']['mbw']['RB'] = $bd['mrb']; + $cell['border_details']['mbw']['TL'] = $bd['mtl']; + $cell['border_details']['mbw']['TR'] = $bd['mtr']; + $cell['border_details']['mbw']['LT'] = $bd['mlt']; + $cell['border_details']['mbw']['LB'] = $bd['mlb']; + $cell['border_details']['cellposdom'] = $bd['cpd']; + + + return($cell); + } + + ////////////////////////TABLE CODE (from PDFTable)///////////////////////////////////// + ////////////////////////TABLE CODE (from PDFTable)///////////////////////////////////// + ////////////////////////TABLE CODE (from PDFTable)///////////////////////////////////// + // table Array of (w, h, bc, nr, wc, hr, cells) + // w Width of table + // h Height of table + // nc Number column + // nr Number row + // hr List of height of each row + // wc List of width of each column + // cells List of cells of each rows, cells[i][j] is a cell in the table + function _tableColumnWidth(&$table, $firstpass = false) + { + $cs = &$table['cells']; + + $nc = $table['nc']; + $nr = $table['nr']; + $listspan = []; + + if ($table['borders_separate']) { + $tblbw = $table['border_details']['L']['w'] + $table['border_details']['R']['w'] + $table['margin']['L'] + $table['margin']['R'] + $table['padding']['L'] + $table['padding']['R'] + $table['border_spacing_H']; + } else { + $tblbw = $table['max_cell_border_width']['L'] / 2 + $table['max_cell_border_width']['R'] / 2 + $table['margin']['L'] + $table['margin']['R']; + } + + // ADDED table['l'][colno] + // = total length of text approx (using $c['s']) in that column - used to approximately distribute col widths in _tableWidth + // + for ($j = 0; $j < $nc; $j++) { // columns + $wc = &$table['wc'][$j]; + for ($i = 0; $i < $nr; $i++) { // rows + if (isset($cs[$i][$j]) && $cs[$i][$j]) { + $c = &$cs[$i][$j]; + + if ($this->simpleTables) { + if ($table['borders_separate']) { // NB twice border width + $extrcw = $table['simple']['border_details']['L']['w'] + $table['simple']['border_details']['R']['w'] + $c['padding']['L'] + $c['padding']['R'] + $table['border_spacing_H']; + } else { + $extrcw = $table['simple']['border_details']['L']['w'] / 2 + $table['simple']['border_details']['R']['w'] / 2 + $c['padding']['L'] + $c['padding']['R']; + } + } else { + if ($this->packTableData) { + list($bt, $br, $bb, $bl) = $this->_getBorderWidths($c['borderbin']); + } else { + $br = $c['border_details']['R']['w']; + $bl = $c['border_details']['L']['w']; + } + if ($table['borders_separate']) { // NB twice border width + $extrcw = $bl + $br + $c['padding']['L'] + $c['padding']['R'] + $table['border_spacing_H']; + } else { + $extrcw = $bl / 2 + $br / 2 + $c['padding']['L'] + $c['padding']['R']; + } + } + + // $mw = $this->GetStringWidth('W') + $extrcw ; + $mw = $extrcw; // mPDF 6 + if (substr($c['a'], 0, 1) == 'D') { + $mw = $table['decimal_align'][$j]['maxs0'] + $table['decimal_align'][$j]['maxs1'] + $extrcw; + } + + $c['absmiw'] = $mw; + + if (isset($c['R']) && $c['R']) { + $c['maw'] = $c['miw'] = $this->FontSize + $extrcw; + if (isset($c['w'])) { // If cell width is specified + if ($c['miw'] < $c['w']) { + $c['miw'] = $c['w']; + } + } + if (!isset($c['colspan'])) { + if ($wc['miw'] < $c['miw']) { + $wc['miw'] = $c['miw']; + } + if ($wc['maw'] < $c['maw']) { + $wc['maw'] = $c['maw']; + } + + if ($firstpass) { + if (isset($table['l'][$j])) { + $table['l'][$j] += $c['miw']; + } else { + $table['l'][$j] = $c['miw']; + } + } + } + if ($c['miw'] > $wc['miw']) { + $wc['miw'] = $c['miw']; + } + if ($wc['miw'] > $wc['maw']) { + $wc['maw'] = $wc['miw']; + } + continue; + } + + if ($firstpass) { + if (isset($c['s'])) { + $c['s'] += $extrcw; + } + if (isset($c['maxs'])) { + $c['maxs'] += $extrcw; + } + if (isset($c['nestedmiw'])) { + $c['nestedmiw'] += $extrcw; + } + if (isset($c['nestedmaw'])) { + $c['nestedmaw'] += $extrcw; + } + } + + + // If minimum width has already been set by a nested table or inline object (image/form), use it + if (isset($c['nestedmiw']) && (!isset($this->table[1][1]['overflow']) || $this->table[1][1]['overflow'] != 'visible')) { + $miw = $c['nestedmiw']; + } else { + $miw = $mw; + } + + if (isset($c['maxs']) && $c['maxs'] != '') { + $c['s'] = $c['maxs']; + } + + // If maximum width has already been set by a nested table, use it + if (isset($c['nestedmaw'])) { + $c['maw'] = $c['nestedmaw']; + } else { + $c['maw'] = $c['s']; + } + + if (isset($table['overflow']) && $table['overflow'] == 'visible' && $table['level'] == 1) { + if (($c['maw'] + $tblbw) > $this->blk[$this->blklvl]['inner_width']) { + $c['maw'] = $this->blk[$this->blklvl]['inner_width'] - $tblbw; + } + } + + if (isset($c['nowrap']) && $c['nowrap']) { + $miw = $c['maw']; + } + + if (isset($c['wpercent']) && $firstpass) { + if (isset($c['colspan'])) { // Not perfect - but % set on colspan is shared equally on cols. + for ($k = 0; $k < $c['colspan']; $k++) { + $table['wc'][($j + $k)]['wpercent'] = $c['wpercent'] / $c['colspan']; + } + } else { + if (isset($table['w']) && $table['w']) { + $c['w'] = $c['wpercent'] / 100 * ($table['w'] - $tblbw ); + } + $wc['wpercent'] = $c['wpercent']; + } + } + + if (isset($table['overflow']) && $table['overflow'] == 'visible' && $table['level'] == 1) { + if (isset($c['w']) && ($c['w'] + $tblbw) > $this->blk[$this->blklvl]['inner_width']) { + $c['w'] = $this->blk[$this->blklvl]['inner_width'] - $tblbw; + } + } + + + if (isset($c['w'])) { // If cell width is specified + if ($miw < $c['w']) { + $c['miw'] = $c['w']; + } // Cell min width = that specified + if ($miw > $c['w']) { + $c['miw'] = $c['w'] = $miw; + } // If width specified is less than minimum allowed (W) increase it + // mPDF 5.7.4 Do not set column width in colspan + // cf. http://www.mpdf1.com/forum/discussion/2221/colspan-bug + if (!isset($c['colspan'])) { + if (!isset($wc['w'])) { + $wc['w'] = 1; + } // If the Col width is not specified = set it to 1 + } + // mPDF 5.7.3 cf. http://www.mpdf1.com/forum/discussion/1648/nested-table-bug- + $c['maw'] = $c['w']; + } else { + $c['miw'] = $miw; + } // If cell width not specified -> set Cell min width it to minimum allowed (W) + + if (isset($c['miw']) && $c['maw'] < $c['miw']) { + $c['maw'] = $c['miw']; + } // If Cell max width < Minwidth - increase it to = + if (!isset($c['colspan'])) { + if (isset($c['miw']) && $wc['miw'] < $c['miw']) { + $wc['miw'] = $c['miw']; + } // Update Col Minimum and maximum widths + if ($wc['maw'] < $c['maw']) { + $wc['maw'] = $c['maw']; + } + if ((isset($wc['absmiw']) && $wc['absmiw'] < $c['absmiw']) || !isset($wc['absmiw'])) { + $wc['absmiw'] = $c['absmiw']; + } // Update Col Minimum and maximum widths + + if (isset($table['l'][$j])) { + $table['l'][$j] += $c['s']; + } else { + $table['l'][$j] = $c['s']; + } + } else { + $listspan[] = [$i, $j]; + } + + // Check if minimum width of the whole column is big enough for largest word to fit + // mPDF 6 + if (isset($c['textbuffer'])) { + if (isset($table['overflow']) && $table['overflow'] == 'wrap') { + $letter = true; + } // check for maximum width of letters + else { + $letter = false; + } + $minwidth = $this->TableCheckMinWidth($wc['miw'] - $extrcw, 0, $c['textbuffer'], $letter); + } else { + $minwidth = 0; + } + if ($minwidth < 0) { + // increase minimum width + if (!isset($c['colspan'])) { + $wc['miw'] = max((isset($wc['miw']) ? $wc['miw'] : 0), ((-$minwidth) + $extrcw)); + } else { + $c['miw'] = max((isset($c['miw']) ? $c['miw'] : 0), ((-$minwidth) + $extrcw)); + } + } + if (!isset($c['colspan'])) { + if ($wc['miw'] > $wc['maw']) { + $wc['maw'] = $wc['miw']; + } // update maximum width, if needed + } + } + unset($c); + }//rows + }//columns + // COLUMN SPANS + $wc = &$table['wc']; + foreach ($listspan as $span) { + list($i, $j) = $span; + $c = &$cs[$i][$j]; + $lc = $j + $c['colspan']; + if ($lc > $nc) { + $lc = $nc; + } + $wis = $wisa = 0; + $was = $wasa = 0; + $list = []; + for ($k = $j; $k < $lc; $k++) { + if (isset($table['l'][$k])) { + if ($c['R']) { + $table['l'][$k] += $c['miw'] / $c['colspan']; + } else { + $table['l'][$k] += $c['s'] / $c['colspan']; + } + } else { + if ($c['R']) { + $table['l'][$k] = $c['miw'] / $c['colspan']; + } else { + $table['l'][$k] = $c['s'] / $c['colspan']; + } + } + $wis += $wc[$k]['miw']; // $wis is the sum of the column miw in the colspan + $was += $wc[$k]['maw']; // $was is the sum of the column maw in the colspan + if (!isset($c['w'])) { + $list[] = $k; + $wisa += $wc[$k]['miw']; // $wisa is the sum of the column miw in cells with no width specified in the colspan + $wasa += $wc[$k]['maw']; // $wasa is the sum of the column maw in cells with no width specified in the colspan + } + } + if ($c['miw'] > $wis) { + if (!$wis) { + for ($k = $j; $k < $lc; $k++) { + $wc[$k]['miw'] = $c['miw'] / $c['colspan']; + } + } elseif (!count($list) && $wis != 0) { + $wi = $c['miw'] - $wis; + for ($k = $j; $k < $lc; $k++) { + $wc[$k]['miw'] += ($wc[$k]['miw'] / $wis) * $wi; + } + } else { + $wi = $c['miw'] - $wis; + // mPDF 5.7.2 Extra min width distributed proportionately to all cells in colspan without a specified width + // cf. http://www.mpdf1.com/forum/discussion/1607#Item_4 + foreach ($list as $k) { + if (!isset($wc[$k]['w']) || !$wc[$k]['w']) { + $wc[$k]['miw'] += ($wc[$k]['miw'] / $wisa) * $wi; + } + } // mPDF 5.7.2 + } + } + if ($c['maw'] > $was) { + if (!$wis) { + for ($k = $j; $k < $lc; $k++) { + $wc[$k]['maw'] = $c['maw'] / $c['colspan']; + } + } elseif (!count($list) && $was != 0) { + $wi = $c['maw'] - $was; + for ($k = $j; $k < $lc; $k++) { + $wc[$k]['maw'] += ($wc[$k]['maw'] / $was) * $wi; + } + } else { + $wi = $c['maw'] - $was; + // mPDF 5.7.4 Extra max width distributed evenly to all cells in colspan without a specified width + // cf. http://www.mpdf1.com/forum/discussion/2221/colspan-bug + foreach ($list as $k) { + $wc[$k]['maw'] += $wi / count($list); + } + } + } + unset($c); + } + + $checkminwidth = 0; + $checkmaxwidth = 0; + $totallength = 0; + + for ($i = 0; $i < $nc; $i++) { + $checkminwidth += $table['wc'][$i]['miw']; + $checkmaxwidth += $table['wc'][$i]['maw']; + $totallength += isset($table['l']) ? $table['l'][$i] : 0; + } + + if (!isset($table['w']) && $firstpass) { + $sumpc = 0; + $notset = 0; + for ($i = 0; $i < $nc; $i++) { + if (isset($table['wc'][$i]['wpercent']) && $table['wc'][$i]['wpercent']) { + $sumpc += $table['wc'][$i]['wpercent']; + } else { + $notset++; + } + } + + // If sum of widths as % >= 100% and not all columns are set + // Set a nominal width of 1% for unset columns + if ($sumpc >= 100 && $notset) { + for ($i = 0; $i < $nc; $i++) { + if ((!isset($table['wc'][$i]['wpercent']) || !$table['wc'][$i]['wpercent']) && + (!isset($table['wc'][$i]['w']) || !$table['wc'][$i]['w'])) { + $table['wc'][$i]['wpercent'] = 1; + } + } + } + + + if ($sumpc) { // if any percents are set + $sumnonpc = (100 - $sumpc); + $sumpc = max($sumpc, 100); + $miwleft = 0; + $miwleftcount = 0; + $miwsurplusnonpc = 0; + $maxcalcmiw = 0; + $mawleft = 0; + $mawleftcount = 0; + $mawsurplusnonpc = 0; + $maxcalcmaw = 0; + $mawnon = 0; + $miwnon = 0; + for ($i = 0; $i < $nc; $i++) { + if (isset($table['wc'][$i]['wpercent'])) { + $maxcalcmiw = max($maxcalcmiw, ($table['wc'][$i]['miw'] * $sumpc / $table['wc'][$i]['wpercent'])); + $maxcalcmaw = max($maxcalcmaw, ($table['wc'][$i]['maw'] * $sumpc / $table['wc'][$i]['wpercent'])); + } else { + $miwleft += $table['wc'][$i]['miw']; + $mawleft += $table['wc'][$i]['maw']; + if (!isset($table['wc'][$i]['w'])) { + $miwleftcount++; + $mawleftcount++; + } + } + } + if ($miwleft && $sumnonpc > 0) { + $miwnon = $miwleft * 100 / $sumnonpc; + } + if ($mawleft && $sumnonpc > 0) { + $mawnon = $mawleft * 100 / $sumnonpc; + } + if (($miwnon > $checkminwidth || $maxcalcmiw > $checkminwidth) && $this->keep_table_proportions) { + if ($miwnon > $maxcalcmiw) { + $miwsurplusnonpc = round((($miwnon * $sumnonpc / 100) - $miwleft), 3); + $checkminwidth = $miwnon; + } else { + $checkminwidth = $maxcalcmiw; + } + for ($i = 0; $i < $nc; $i++) { + if (isset($table['wc'][$i]['wpercent'])) { + $newmiw = $checkminwidth * $table['wc'][$i]['wpercent'] / 100; + if ($table['wc'][$i]['miw'] < $newmiw) { + $table['wc'][$i]['miw'] = $newmiw; + } + $table['wc'][$i]['w'] = 1; + } elseif ($miwsurplusnonpc && !$table['wc'][$i]['w']) { + $table['wc'][$i]['miw'] += $miwsurplusnonpc / $miwleftcount; + } + } + } + if (($mawnon > $checkmaxwidth || $maxcalcmaw > $checkmaxwidth)) { + if ($mawnon > $maxcalcmaw) { + $mawsurplusnonpc = round((($mawnon * $sumnonpc / 100) - $mawleft), 3); + $checkmaxwidth = $mawnon; + } else { + $checkmaxwidth = $maxcalcmaw; + } + for ($i = 0; $i < $nc; $i++) { + if (isset($table['wc'][$i]['wpercent'])) { + $newmaw = $checkmaxwidth * $table['wc'][$i]['wpercent'] / 100; + if ($table['wc'][$i]['maw'] < $newmaw) { + $table['wc'][$i]['maw'] = $newmaw; + } + $table['wc'][$i]['w'] = 1; + } elseif ($mawsurplusnonpc && !$table['wc'][$i]['w']) { + $table['wc'][$i]['maw'] += $mawsurplusnonpc / $mawleftcount; + } + if ($table['wc'][$i]['maw'] < $table['wc'][$i]['miw']) { + $table['wc'][$i]['maw'] = $table['wc'][$i]['miw']; + } + } + } + if ($checkminwidth > $checkmaxwidth) { + $checkmaxwidth = $checkminwidth; + } + } + } + + if (isset($table['wpercent']) && $table['wpercent']) { + $checkminwidth *= (100 / $table['wpercent']); + $checkmaxwidth *= (100 / $table['wpercent']); + } + + + $checkminwidth += $tblbw; + $checkmaxwidth += $tblbw; + + // Table['miw'] set by percent in first pass may be larger than sum of column miw + if ((isset($table['miw']) && $checkminwidth > $table['miw']) || !isset($table['miw'])) { + $table['miw'] = $checkminwidth; + } + if ((isset($table['maw']) && $checkmaxwidth > $table['maw']) || !isset($table['maw'])) { + $table['maw'] = $checkmaxwidth; + } + $table['tl'] = $totallength; + + // mPDF 6 + if ($this->table_rotate) { + $mxw = $this->tbrot_maxw; + } else { + $mxw = $this->blk[$this->blklvl]['inner_width']; + } + + if (!isset($table['overflow'])) { + $table['overflow'] = null; + } + + if ($table['overflow'] == 'visible') { + return [0, 0]; + } elseif ($table['overflow'] == 'hidden' && !$this->table_rotate && !$this->ColActive && $checkminwidth > $mxw) { + $table['w'] = $table['miw']; + return [0, 0]; + } + // elseif ($table['overflow']=='wrap') { return array(0,0); } // mPDF 6 + + if (isset($table['w']) && $table['w']) { + + if ($table['w'] >= $checkminwidth && $table['w'] <= $mxw) { + $table['maw'] = $mxw = $table['w']; + } elseif ($table['w'] >= $checkminwidth && $table['w'] > $mxw && $this->keep_table_proportions) { + $checkminwidth = $table['w']; + } elseif ($table['w'] < $checkminwidth && $checkminwidth < $mxw && $this->keep_table_proportions) { + $table['maw'] = $table['w'] = $checkminwidth; + } else { + unset($table['w']); + } + } + + $ratio = $checkminwidth / $mxw; + + if ($checkminwidth > $mxw) { + return [($ratio + 0.001), $checkminwidth]; // 0.001 to allow for rounded numbers when resizing + } + + unset($cs); + + return [0, 0]; + } + + function _tableWidth(&$table) + { + $widthcols = &$table['wc']; + $numcols = $table['nc']; + $tablewidth = 0; + + if ($table['borders_separate']) { + $tblbw = $table['border_details']['L']['w'] + $table['border_details']['R']['w'] + $table['margin']['L'] + $table['margin']['R'] + $table['padding']['L'] + $table['padding']['R'] + $table['border_spacing_H']; + } else { + $tblbw = $table['max_cell_border_width']['L'] / 2 + $table['max_cell_border_width']['R'] / 2 + $table['margin']['L'] + $table['margin']['R']; + } + + if ($table['level'] > 1 && isset($table['w'])) { + + if (isset($table['wpercent']) && $table['wpercent']) { + $table['w'] = $temppgwidth = (($table['w'] - $tblbw) * $table['wpercent'] / 100) + $tblbw; + } else { + $temppgwidth = $table['w']; + } + + } elseif ($this->table_rotate) { + + $temppgwidth = $this->tbrot_maxw; + + // If it is less than 1/20th of the remaining page height to finish the DIV (i.e. DIV padding + table bottom margin) then allow for this + $enddiv = $this->blk[$this->blklvl]['padding_bottom'] + $this->blk[$this->blklvl]['border_bottom']['w']; + + if ($enddiv / $temppgwidth < 0.05) { + $temppgwidth -= $enddiv; + } + + } else { + + if (isset($table['w']) && $table['w'] < $this->blk[$this->blklvl]['inner_width']) { + $notfullwidth = 1; + $temppgwidth = $table['w']; + } elseif ($table['overflow'] == 'visible' && $table['level'] == 1) { + $temppgwidth = null; + } elseif ($table['overflow'] == 'hidden' && !$this->ColActive && isset($table['w']) && $table['w'] > $this->blk[$this->blklvl]['inner_width'] && $table['w'] == $table) { + // $temppgwidth = $this->blk[$this->blklvl]['inner_width']; + $temppgwidth = $table['w']; + } else { + $temppgwidth = $this->blk[$this->blklvl]['inner_width']; + } + + } + + $totaltextlength = 0; // Added - to sum $table['l'][colno] + $totalatextlength = 0; // Added - to sum $table['l'][colno] for those columns where width not set + $percentages_set = 0; + + for ($i = 0; $i < $numcols; $i++) { + if (isset($widthcols[$i]['wpercent'])) { + $tablewidth += $widthcols[$i]['maw']; + $percentages_set = 1; + } elseif (isset($widthcols[$i]['w'])) { + $tablewidth += $widthcols[$i]['miw']; + } else { + $tablewidth += $widthcols[$i]['maw']; + } + $totaltextlength += isset($table['l']) ? $table['l'][$i] : 0; + } + + if (!$totaltextlength) { + $totaltextlength = 1; + } + + $tablewidth += $tblbw; // Outer half of table borders + + if ($tablewidth > $temppgwidth) { + $table['w'] = $temppgwidth; + } elseif ($tablewidth < $temppgwidth && !isset($table['w']) && $percentages_set) { // if any widths set as percentages and max width fits < page width + $table['w'] = $table['maw']; + } + + // if table width is set and is > allowed width + if (isset($table['w']) && $table['w'] > $temppgwidth) { + $table['w'] = $temppgwidth; + } + + // IF the table width is now set - Need to distribute columns widths + // mPDF 5.7.3 + // If the table width is already set to the maximum width (e.g. nested table), then use maximum column widths exactly + if (isset($table['w']) && ($table['w'] == $tablewidth) && !$percentages_set) { + + // This sets the columns all to maximum width + for ($i = 0; $i < $numcols; $i++) { + $widthcols[$i] = $widthcols[$i]['maw']; + } + + } elseif (isset($table['w'])) { // elseif the table width is set distribute width using algorithm + + $wis = $wisa = 0; + $list = []; + $notsetlist = []; + + for ($i = 0; $i < $numcols; $i++) { + $wis += $widthcols[$i]['miw']; + if (!isset($widthcols[$i]['w']) || ($widthcols[$i]['w'] && $table['w'] > $temppgwidth && !$this->keep_table_proportions && !$notfullwidth )) { + $list[] = $i; + $wisa += $widthcols[$i]['miw']; + $totalatextlength += $table['l'][$i]; + } + } + + if (!$totalatextlength) { + $totalatextlength = 1; + } + + // Allocate spare (more than col's minimum width) across the cols according to their approx total text length + // Do it by setting minimum width here + if ($table['w'] > $wis + $tblbw) { + + // First set any cell widths set as percentages + if ($table['w'] < $temppgwidth || $this->keep_table_proportions) { + for ($k = 0; $k < $numcols; $k++) { + if (isset($widthcols[$k]['wpercent'])) { + $curr = $widthcols[$k]['miw']; + $widthcols[$k]['miw'] = ($table['w'] - $tblbw) * $widthcols[$k]['wpercent'] / 100; + $wis += $widthcols[$k]['miw'] - $curr; + $wisa += $widthcols[$k]['miw'] - $curr; + } + } + } + + // Now allocate surplus up to maximum width of each column + $surplus = 0; + $ttl = 0; // number of surplus columns + + if (!count($list)) { + + $wi = ($table['w'] - ($wis + $tblbw)); // i.e. extra space to distribute + + for ($k = 0; $k < $numcols; $k++) { + + $spareratio = ($table['l'][$k] / $totaltextlength); // gives ratio to divide up free space + + // Don't allocate more than Maximum required width - save rest in surplus + if ($widthcols[$k]['miw'] + ($wi * $spareratio) >= $widthcols[$k]['maw']) { // mPDF 5.7.3 + $surplus += ($wi * $spareratio) - ($widthcols[$k]['maw'] - $widthcols[$k]['miw']); + $widthcols[$k]['miw'] = $widthcols[$k]['maw']; + } else { + $notsetlist[] = $k; + $ttl += $table['l'][$k]; + $widthcols[$k]['miw'] += ($wi * $spareratio); + } + } + + } else { + + $wi = ($table['w'] - ($wis + $tblbw)); // i.e. extra space to distribute + + foreach ($list as $k) { + + $spareratio = ($table['l'][$k] / $totalatextlength); // gives ratio to divide up free space + + // Don't allocate more than Maximum required width - save rest in surplus + if ($widthcols[$k]['miw'] + ($wi * $spareratio) >= $widthcols[$k]['maw']) { // mPDF 5.7.3 + $surplus += ($wi * $spareratio) - ($widthcols[$k]['maw'] - $widthcols[$k]['miw']); + $widthcols[$k]['miw'] = $widthcols[$k]['maw']; + } else { + $notsetlist[] = $k; + $ttl += $table['l'][$k]; + $widthcols[$k]['miw'] += ($wi * $spareratio); + } + } + } + + // If surplus still left over apportion it across columns + if ($surplus) { + + if (count($notsetlist) && count($notsetlist) < $numcols) { // if some are set only add to remaining - otherwise add to all of them + foreach ($notsetlist as $i) { + if ($ttl) { + $widthcols[$i]['miw'] += $surplus * $table['l'][$i] / $ttl; + } + } + } elseif (count($list) && count($list) < $numcols) { // If some widths are defined, and others have been added up to their maxmum + foreach ($list as $i) { + $widthcols[$i]['miw'] += $surplus / count($list); + } + } elseif ($numcols) { // If all columns + $ttl = array_sum($table['l']); + if ($ttl) { + for ($i = 0; $i < $numcols; $i++) { + $widthcols[$i]['miw'] += $surplus * $table['l'][$i] / $ttl; + } + } + } + } + } + + // This sets the columns all to minimum width (which has been increased above if appropriate) + for ($i = 0; $i < $numcols; $i++) { + $widthcols[$i] = $widthcols[$i]['miw']; + } + + // TABLE NOT WIDE ENOUGH EVEN FOR MINIMUM CONTENT WIDTH + // If sum of column widths set are too wide for table + $checktablewidth = 0; + for ($i = 0; $i < $numcols; $i++) { + $checktablewidth += $widthcols[$i]; + } + + if ($checktablewidth > ($temppgwidth + 0.001 - $tblbw)) { + + $usedup = 0; + $numleft = 0; + + for ($i = 0; $i < $numcols; $i++) { + if ((isset($widthcols[$i]) && $widthcols[$i] > (($temppgwidth - $tblbw) / $numcols)) && (!isset($widthcols[$i]['w']))) { + $numleft++; + unset($widthcols[$i]); + } else { + $usedup += $widthcols[$i]; + } + } + + for ($i = 0; $i < $numcols; $i++) { + if (!isset($widthcols[$i]) || !$widthcols[$i]) { + $widthcols[$i] = ((($temppgwidth - $tblbw) - $usedup) / ($numleft)); + } + } + } + + } else { // table has no width defined + + $table['w'] = $tablewidth; + + for ($i = 0; $i < $numcols; $i++) { + + if (isset($widthcols[$i]['wpercent']) && $this->keep_table_proportions) { + $colwidth = $widthcols[$i]['maw']; + } elseif (isset($widthcols[$i]['w'])) { + $colwidth = $widthcols[$i]['miw']; + } else { + $colwidth = $widthcols[$i]['maw']; + } + + unset($widthcols[$i]); + $widthcols[$i] = $colwidth; + + } + } + + if ($table['overflow'] === 'visible' && $table['level'] == 1) { + + if ($tablewidth > $this->blk[$this->blklvl]['inner_width']) { + + for ($j = 0; $j < $numcols; $j++) { // columns + + for ($i = 0; $i < $table['nr']; $i++) { // rows + + if (isset($table['cells'][$i][$j]) && $table['cells'][$i][$j]) { + + $colspan = (isset($table['cells'][$i][$j]['colspan']) ? $table['cells'][$i][$j]['colspan'] : 1); + + if ($colspan > 1) { + $w = 0; + + for ($c = $j; $c < ($j + $colspan); $c++) { + $w += $widthcols[$c]; + } + + if ($w > $this->blk[$this->blklvl]['inner_width']) { + $diff = $w - ($this->blk[$this->blklvl]['inner_width'] - $tblbw); + for ($c = $j; $c < ($j + $colspan); $c++) { + $widthcols[$c] -= $diff * ($widthcols[$c] / $w); + } + $table['w'] -= $diff; + $table['csp'][$j] = $w - $diff; + } + } + } + } + } + } + + $pgNo = 0; + $currWc = 0; + + for ($i = 0; $i < $numcols; $i++) { // columns + + if (isset($table['csp'][$i])) { + $w = $table['csp'][$i]; + unset($table['csp'][$i]); + } else { + $w = $widthcols[$i]; + } + + if (($currWc + $w + $tblbw) > $this->blk[$this->blklvl]['inner_width']) { + $pgNo++; + $currWc = $widthcols[$i]; + } else { + $currWc += $widthcols[$i]; + } + + $table['colPg'][$i] = $pgNo; + } + } + } + + function _tableHeight(&$table) + { + $level = $table['level']; + $levelid = $table['levelid']; + $cells = &$table['cells']; + $numcols = $table['nc']; + $numrows = $table['nr']; + $listspan = []; + $checkmaxheight = 0; + $headerrowheight = 0; + $checkmaxheightplus = 0; + $headerrowheightplus = 0; + $firstrowheight = 0; + + $footerrowheight = 0; + $footerrowheightplus = 0; + if ($this->table_rotate) { + $temppgheight = $this->tbrot_maxh; + $remainingpage = $this->tbrot_maxh; + } else { + $temppgheight = ($this->h - $this->bMargin - $this->tMargin) - $this->kwt_height; + $remainingpage = ($this->h - $this->bMargin - $this->y) - $this->kwt_height; + + // If it is less than 1/20th of the remaining page height to finish the DIV (i.e. DIV padding + table bottom margin) + // then allow for this + $enddiv = $this->blk[$this->blklvl]['padding_bottom'] + $this->blk[$this->blklvl]['border_bottom']['w'] + $table['margin']['B']; + if ($remainingpage > $enddiv && $enddiv / $remainingpage < 0.05) { + $remainingpage -= $enddiv; + } elseif ($remainingpage == 0) { + $remainingpage = 0.001; + } + if ($temppgheight > $enddiv && $enddiv / $temppgheight < 0.05) { + $temppgheight -= $enddiv; + } elseif ($temppgheight == 0) { + $temppgheight = 0.001; + } + } + if ($remainingpage < 0) { + $remainingpage = 0.001; + } + if ($temppgheight < 0) { + $temppgheight = 0.001; + } + + for ($i = 0; $i < $numrows; $i++) { // rows + $heightrow = &$table['hr'][$i]; + for ($j = 0; $j < $numcols; $j++) { // columns + if (isset($cells[$i][$j]) && $cells[$i][$j]) { + $c = &$cells[$i][$j]; + + if ($this->simpleTables) { + if ($table['borders_separate']) { // NB twice border width + $extraWLR = ($table['simple']['border_details']['L']['w'] + $table['simple']['border_details']['R']['w']) + ($c['padding']['L'] + $c['padding']['R']) + $table['border_spacing_H']; + $extrh = ($table['simple']['border_details']['T']['w'] + $table['simple']['border_details']['B']['w']) + ($c['padding']['T'] + $c['padding']['B']) + $table['border_spacing_V']; + } else { + $extraWLR = ($table['simple']['border_details']['L']['w'] + $table['simple']['border_details']['R']['w']) / 2 + ($c['padding']['L'] + $c['padding']['R']); + $extrh = ($table['simple']['border_details']['T']['w'] + $table['simple']['border_details']['B']['w']) / 2 + ($c['padding']['T'] + $c['padding']['B']); + } + } else { + if ($this->packTableData) { + list($bt, $br, $bb, $bl) = $this->_getBorderWidths($c['borderbin']); + } else { + $bt = $c['border_details']['T']['w']; + $bb = $c['border_details']['B']['w']; + $br = $c['border_details']['R']['w']; + $bl = $c['border_details']['L']['w']; + } + if ($table['borders_separate']) { // NB twice border width + $extraWLR = $bl + $br + $c['padding']['L'] + $c['padding']['R'] + $table['border_spacing_H']; + $extrh = $bt + $bb + $c['padding']['T'] + $c['padding']['B'] + $table['border_spacing_V']; + } else { + $extraWLR = $bl / 2 + $br / 2 + $c['padding']['L'] + $c['padding']['R']; + $extrh = $bt / 2 + $bb / 2 + $c['padding']['T'] + $c['padding']['B']; + } + } + + if ($table['overflow'] == 'visible' && $level == 1) { + list($x, $cw) = $this->_splitTableGetWidth($table, $i, $j); + } else { + list($x, $cw) = $this->_tableGetWidth($table, $i, $j); + } + + + // Get CELL HEIGHT + // ++ extra parameter forces wrap to break word + if ($c['R'] && isset($c['textbuffer'])) { + $str = ''; + foreach ($c['textbuffer'] as $t) { + $str .= $t[0] . ' '; + } + $str = rtrim($str); + $s_fs = $this->FontSizePt; + $s_f = $this->FontFamily; + $s_st = $this->FontStyle; + $this->SetFont($c['textbuffer'][0][4], $c['textbuffer'][0][2], $c['textbuffer'][0][11] / $this->shrin_k, true, true); + $tempch = $this->GetStringWidth($str, true, $c['textbuffer'][0][18], $c['textbuffer'][0][8]); + if ($c['R'] >= 45 && $c['R'] < 90) { + $tempch = ((sin(deg2rad($c['R']))) * $tempch ) + ((sin(deg2rad($c['R']))) * (($c['textbuffer'][0][11] / Mpdf::SCALE) / $this->shrin_k)); + } + $this->SetFont($s_f, $s_st, $s_fs, true, true); + $ch = ($tempch ) + $extrh; + } else { + if (isset($c['textbuffer']) && !empty($c['textbuffer'])) { + $this->cellLineHeight = $c['cellLineHeight']; + $this->cellLineStackingStrategy = $c['cellLineStackingStrategy']; + $this->cellLineStackingShift = $c['cellLineStackingShift']; + $this->divwidth = $cw - $extraWLR; + $tempch = $this->printbuffer($c['textbuffer'], '', true, true); + } else { + $tempch = 0; + } + + // Added cellpadding top and bottom. (Lineheight already adjusted) + $ch = $tempch + $extrh; + } + // If height is defined and it is bigger than calculated $ch then update values + if (isset($c['h']) && $c['h'] > $ch) { + $c['mih'] = $ch; // in order to keep valign working + $ch = $c['h']; + } else { + $c['mih'] = $ch; + } + if (isset($c['rowspan'])) { + $listspan[] = [$i, $j]; + } elseif ($heightrow < $ch) { + $heightrow = $ch; + } + + // this is the extra used in _tableWrite to determine whether to trigger a page change + if ($table['borders_separate']) { + if ($i == ($numrows - 1) || (isset($c['rowspan']) && ($i + $c['rowspan']) == ($numrows))) { + $extra = $table['margin']['B'] + $table['padding']['B'] + $table['border_details']['B']['w'] + $table['border_spacing_V'] / 2; + } else { + $extra = $table['border_spacing_V'] / 2; + } + } else { + if (!$this->simpleTables) { + $extra = $bb / 2; + } elseif ($this->simpleTables) { + $extra = $table['simple']['border_details']['B']['w'] / 2; + } + } + if (isset($table['is_thead'][$i]) && $table['is_thead'][$i]) { + if ($j == 0) { + $headerrowheight += $ch; + $headerrowheightplus += $ch + $extra; + } + } elseif (isset($table['is_tfoot'][$i]) && $table['is_tfoot'][$i]) { + if ($j == 0) { + $footerrowheight += $ch; + $footerrowheightplus += $ch + $extra; + } + } else { + $checkmaxheight = max($checkmaxheight, $ch); + $checkmaxheightplus = max($checkmaxheightplus, $ch + $extra); + } + if ($this->tableLevel == 1 && $i == (isset($table['headernrows']) ? $table['headernrows'] : 0)) { + $firstrowheight = max($ch, $firstrowheight); + } + unset($c); + } + }//end of columns + }//end of rows + + $heightrow = &$table['hr']; + foreach ($listspan as $span) { + list($i, $j) = $span; + $c = &$cells[$i][$j]; + $lr = $i + $c['rowspan']; + if ($lr > $numrows) { + $lr = $numrows; + } + $hs = $hsa = 0; + $list = []; + for ($k = $i; $k < $lr; $k++) { + $hs += $heightrow[$k]; + // mPDF 6 + $sh = false; // specified height + for ($m = 0; $m < $numcols; $m++) { // columns + $tc = &$cells[$k][$m]; + if (isset($tc['rowspan'])) { + continue; + } + if (isset($tc['h'])) { + $sh = true; + break; + } + } + if (!$sh) { + $list[] = $k; + } + } + + if ($table['borders_separate']) { + if ($i == ($numrows - 1) || ($i + $c['rowspan']) == ($numrows)) { + $extra = $table['margin']['B'] + $table['padding']['B'] + $table['border_details']['B']['w'] + $table['border_spacing_V'] / 2; + } else { + $extra = $table['border_spacing_V'] / 2; + } + } else { + if (!$this->simpleTables) { + if ($this->packTableData) { + list($bt, $br, $bb, $bl) = $this->_getBorderWidths($c['borderbin']); + } else { + $bb = $c['border_details']['B']['w']; + } + $extra = $bb / 2; + } elseif ($this->simpleTables) { + $extra = $table['simple']['border_details']['B']['w'] / 2; + } + } + if (!empty($table['is_thead'][$i])) { + $headerrowheight = max($headerrowheight, $hs); + $headerrowheightplus = max($headerrowheightplus, $hs + $extra); + } elseif (!empty($table['is_tfoot'][$i])) { + $footerrowheight = max($footerrowheight, $hs); + $footerrowheightplus = max($footerrowheightplus, $hs + $extra); + } else { + $checkmaxheight = max($checkmaxheight, $hs); + $checkmaxheightplus = max($checkmaxheightplus, $hs + $extra); + } + if ($this->tableLevel == 1 && $i == (isset($table['headernrows']) ? $table['headernrows'] : 0)) { + $firstrowheight = max($hs, $firstrowheight); + } + + if ($c['mih'] > $hs) { + if (!$hs) { + for ($k = $i; $k < $lr; $k++) { + $heightrow[$k] = $c['mih'] / $c['rowspan']; + } + } elseif (!count($list)) { // no rows in the rowspan have a height specified, so share amongst all rows equally + $hi = $c['mih'] - $hs; + for ($k = $i; $k < $lr; $k++) { + $heightrow[$k] += ($heightrow[$k] / $hs) * $hi; + } + } else { + $hi = $c['mih'] - $hs; // mPDF 6 + foreach ($list as $k) { + $heightrow[$k] += $hi / (count($list)); // mPDF 6 + } + } + } + unset($c); + + // If rowspans overlap so that one or more rows do not have a height set... + // i.e. for one or more rows, the only cells (explicit) in that row have rowspan>1 + // so heightrow is still == 0 + if ($heightrow[$i] == 0) { + // Get row extent to analyse above and below + $top = $i; + foreach ($listspan as $checkspan) { + list($cki, $ckj) = $checkspan; + $c = &$cells[$cki][$ckj]; + if (isset($c['rowspan']) && $c['rowspan'] > 1) { + if (($cki + $c['rowspan'] - 1) >= $i) { + $top = min($top, $cki); + } + } + } + $bottom = $i + $c['rowspan'] - 1; + // Check for overconstrained conditions + for ($k = $top; $k <= $bottom; $k++) { + // if ['hr'] for any of the others is also 0, then abort (too complicated) + if ($k != $i && $heightrow[$k] == 0) { + break(1); + } + // check again that top and bottom are not crossed by rowspans - or abort (too complicated) + if ($k == $top) { + // ???? take account of colspan as well??? + for ($m = 0; $m < $numcols; $m++) { // columns + if (!isset($cells[$k][$m]) || $cells[$k][$m] == 0) { + break(2); + } + } + } elseif ($k == $bottom) { + // ???? take account of colspan as well??? + for ($m = 0; $m < $numcols; $m++) { // columns + $c = &$cells[$k][$m]; + if (isset($c['rowspan']) && $c['rowspan'] > 1) { + break(2); + } + } + } + } + // By columns add up col height using ['h'] if set or ['mih'] if not + // Intentionally do not substract border-spacing + $colH = []; + $extH = 0; + $newhr = []; + for ($m = 0; $m < $numcols; $m++) { // columns + for ($k = $top; $k <= $bottom; $k++) { + if (isset($cells[$k][$m]) && $cells[$k][$m] != 0) { + $c = &$cells[$k][$m]; + if (isset($c['h']) && $c['h']) { + $useh = $c['h']; + } // ???? take account of colspan as well??? + else { + $useh = $c['mih']; + } + if (isset($colH[$m])) { + $colH[$m] += $useh; + } else { + $colH[$m] = $useh; + } + if (!isset($c['rowspan']) || $c['rowspan'] < 2) { + $newhr[$k] = max((isset($newhr[$k]) ? $newhr[$k] : 0), $useh); + } + } + } + $extH = max($extH, $colH[$m]); // mPDF 6 + } + $newhr[$i] = $extH - array_sum($newhr); + for ($k = $top; $k <= $bottom; $k++) { + $heightrow[$k] = $newhr[$k]; + } + } + + + unset($c); + } + + $table['h'] = array_sum($heightrow); + unset($heightrow); + + if ($table['borders_separate']) { + $table['h'] += $table['margin']['T'] + $table['margin']['B'] + $table['border_details']['T']['w'] + $table['border_details']['B']['w'] + $table['border_spacing_V'] + $table['padding']['T'] + $table['padding']['B']; + } else { + $table['h'] += $table['margin']['T'] + $table['margin']['B'] + $table['max_cell_border_width']['T'] / 2 + $table['max_cell_border_width']['B'] / 2; + } + + $maxrowheight = $checkmaxheightplus + $headerrowheightplus + $footerrowheightplus; + $maxfirstrowheight = $firstrowheight + $headerrowheightplus + $footerrowheightplus; // includes thead, 1st row and tfoot + return [$table['h'], $maxrowheight, $temppgheight, $remainingpage, $maxfirstrowheight]; + } + + function _tableGetWidth(&$table, $i, $j) + { + $cell = &$table['cells'][$i][$j]; + if ($cell) { + if (isset($cell['x0'])) { + return [$cell['x0'], $cell['w0']]; + } + $x = 0; + $widthcols = &$table['wc']; + for ($k = 0; $k < $j; $k++) { + $x += $widthcols[$k]; + } + $w = $widthcols[$j]; + if (isset($cell['colspan'])) { + for ($k = $j + $cell['colspan'] - 1; $k > $j; $k--) { + $w += $widthcols[$k]; + } + } + $cell['x0'] = $x; + $cell['w0'] = $w; + return [$x, $w]; + } + return [0, 0]; + } + + function _splitTableGetWidth(&$table, $i, $j) + { + $cell = &$table['cells'][$i][$j]; + if ($cell) { + if (isset($cell['x0'])) { + return [$cell['x0'], $cell['w0']]; + } + $x = 0; + $widthcols = &$table['wc']; + $pg = $table['colPg'][$j]; + for ($k = 0; $k < $j; $k++) { + if ($table['colPg'][$k] == $pg) { + $x += $widthcols[$k]; + } + } + $w = $widthcols[$j]; + if (isset($cell['colspan'])) { + for ($k = $j + $cell['colspan'] - 1; $k > $j; $k--) { + if ($table['colPg'][$k] == $pg) { + $w += $widthcols[$k]; + } + } + } + $cell['x0'] = $x; + $cell['w0'] = $w; + return [$x, $w]; + } + return [0, 0]; + } + + function _tableGetHeight(&$table, $i, $j) + { + $cell = &$table['cells'][$i][$j]; + if ($cell) { + if (isset($cell['y0'])) { + return [$cell['y0'], $cell['h0']]; + } + $y = 0; + $heightrow = &$table['hr']; + for ($k = 0; $k < $i; $k++) { + $y += $heightrow[$k]; + } + $h = $heightrow[$i]; + if (isset($cell['rowspan'])) { + for ($k = $i + $cell['rowspan'] - 1; $k > $i; $k--) { + if (array_key_exists($k, $heightrow)) { + $h += $heightrow[$k]; + } else { + $this->logger->debug('Possible non-wellformed HTML markup in a table', ['context' => LogContext::HTML_MARKUP]); + } + } + } + $cell['y0'] = $y; + $cell['h0'] = $h; + return [$y, $h]; + } + return [0, 0]; + } + + function _tableGetMaxRowHeight($table, $row) + { + if ($row == $table['nc'] - 1) { + return $table['hr'][$row]; + } + $maxrowheight = $table['hr'][$row]; + for ($i = $row + 1; $i < $table['nr']; $i++) { + $cellsset = 0; + for ($j = 0; $j < $table['nc']; $j++) { + if ($table['cells'][$i][$j]) { + if (isset($table['cells'][$i][$j]['colspan'])) { + $cellsset += $table['cells'][$i][$j]['colspan']; + } else { + $cellsset += 1; + } + } + } + if ($cellsset == $table['nc']) { + return $maxrowheight; + } else { + $maxrowheight += $table['hr'][$i]; + } + } + return $maxrowheight; + } + + // CHANGED TO ALLOW TABLE BORDER TO BE SPECIFIED CORRECTLY - added border_details + function _tableRect($x, $y, $w, $h, $bord = -1, $details = [], $buffer = false, $bSeparate = false, $cort = 'cell', $tablecorner = '', $bsv = 0, $bsh = 0) + { + $cellBorderOverlay = []; + + if ($bord == -1) { + $this->Rect($x, $y, $w, $h); + } elseif ($this->simpleTables && ($cort == 'cell')) { + $this->SetLineWidth($details['L']['w']); + if ($details['L']['c']) { + $this->SetDColor($details['L']['c']); + } else { + $this->SetDColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + } + $this->SetLineJoin(0); + $this->Rect($x, $y, $w, $h); + } elseif ($bord) { + if (!$bSeparate && $buffer) { + $priority = 'LRTB'; + for ($p = 0; $p < strlen($priority); $p++) { + $side = $priority[$p]; + $details['p'] = $side; + + $dom = 0; + if (isset($details[$side]['w'])) { + $dom += ($details[$side]['w'] * 100000); + } + if (isset($details[$side]['style'])) { + $dom += (array_search($details[$side]['style'], $this->borderstyles) * 100); + } + if (isset($details[$side]['dom'])) { + $dom += ($details[$side]['dom'] * 10); + } + + // Precedence to darker colours at joins + $coldom = 0; + if (isset($details[$side]['c']) && is_array($details[$side]['c'])) { + if ($details[$side]['c'][0] == 3) { // RGB + $coldom = 10 - (((ord($details[$side]['c'][1]) * 1.00) + (ord($details[$side]['c'][2]) * 1.00) + (ord($details[$side]['c'][3]) * 1.00)) / 76.5); + } + } // 10 black - 0 white + if ($coldom) { + $dom += $coldom; + } + // Lastly precedence to RIGHT and BOTTOM cells at joins + if (isset($details['cellposdom'])) { + $dom += $details['cellposdom']; + } + + $save = false; + if ($side == 'T' && $this->issetBorder($bord, Border::TOP)) { + $cbord = Border::TOP; + $save = true; + } elseif ($side == 'L' && $this->issetBorder($bord, Border::LEFT)) { + $cbord = Border::LEFT; + $save = true; + } elseif ($side == 'R' && $this->issetBorder($bord, Border::RIGHT)) { + $cbord = Border::RIGHT; + $save = true; + } elseif ($side == 'B' && $this->issetBorder($bord, Border::BOTTOM)) { + $cbord = Border::BOTTOM; + $save = true; + } + + if ($save) { + $this->cellBorderBuffer[] = pack("A16nCnda6A10d14", str_pad(sprintf("%08.7f", $dom), 16, "0", STR_PAD_LEFT), $cbord, ord($side), $details[$side]['s'], $details[$side]['w'], $details[$side]['c'], $details[$side]['style'], $x, $y, $w, $h, $details['mbw']['BL'], $details['mbw']['BR'], $details['mbw']['RT'], $details['mbw']['RB'], $details['mbw']['TL'], $details['mbw']['TR'], $details['mbw']['LT'], $details['mbw']['LB'], $details['cellposdom'], 0); + if ($details[$side]['style'] == 'ridge' || $details[$side]['style'] == 'groove' || $details[$side]['style'] == 'inset' || $details[$side]['style'] == 'outset' || $details[$side]['style'] == 'double') { + $details[$side]['overlay'] = true; + $this->cellBorderBuffer[] = pack("A16nCnda6A10d14", str_pad(sprintf("%08.7f", ($dom + 4)), 16, "0", STR_PAD_LEFT), $cbord, ord($side), $details[$side]['s'], $details[$side]['w'], $details[$side]['c'], $details[$side]['style'], $x, $y, $w, $h, $details['mbw']['BL'], $details['mbw']['BR'], $details['mbw']['RT'], $details['mbw']['RB'], $details['mbw']['TL'], $details['mbw']['TR'], $details['mbw']['LT'], $details['mbw']['LB'], $details['cellposdom'], 1); + } + } + } + return; + } + + if (isset($details['p']) && strlen($details['p']) > 1) { + $priority = $details['p']; + } else { + $priority = 'LTRB'; + } + $Tw = 0; + $Rw = 0; + $Bw = 0; + $Lw = 0; + if (isset($details['T']['w'])) { + $Tw = $details['T']['w']; + } + if (isset($details['R']['w'])) { + $Rw = $details['R']['w']; + } + if (isset($details['B']['w'])) { + $Bw = $details['B']['w']; + } + if (isset($details['L']['w'])) { + $Lw = $details['L']['w']; + } + + $x2 = $x + $w; + $y2 = $y + $h; + $oldlinewidth = $this->LineWidth; + + for ($p = 0; $p < strlen($priority); $p++) { + $side = $priority[$p]; + $xadj = 0; + $xadj2 = 0; + $yadj = 0; + $yadj2 = 0; + $print = false; + if ($Tw && $side == 'T' && $this->issetBorder($bord, Border::TOP)) { // TOP + $ly1 = $y; + $ly2 = $y; + $lx1 = $x; + $lx2 = $x2; + $this->SetLineWidth($Tw); + if ($cort == 'cell' || strpos($tablecorner, 'L') !== false) { + if ($Tw > $Lw) { + $xadj = ($Tw - $Lw) / 2; + } + if ($Tw < $Lw) { + $xadj = ($Tw + $Lw) / 2; + } + } else { + $xadj = $Tw / 2 - $bsh / 2; + } + if ($cort == 'cell' || strpos($tablecorner, 'R') !== false) { + if ($Tw > $Rw) { + $xadj2 = ($Tw - $Rw) / 2; + } + if ($Tw < $Rw) { + $xadj2 = ($Tw + $Rw) / 2; + } + } else { + $xadj2 = $Tw / 2 - $bsh / 2; + } + if (!$bSeparate && !empty($details['mbw']) && !empty($details['mbw']['TL'])) { + $xadj = ($Tw - $details['mbw']['TL']) / 2; + } + if (!$bSeparate && !empty($details['mbw']) && !empty($details['mbw']['TR'])) { + $xadj2 = ($Tw - $details['mbw']['TR']) / 2; + } + $print = true; + } + if ($Lw && $side == 'L' && $this->issetBorder($bord, Border::LEFT)) { // LEFT + $ly1 = $y; + $ly2 = $y2; + $lx1 = $x; + $lx2 = $x; + $this->SetLineWidth($Lw); + if ($cort == 'cell' || strpos($tablecorner, 'T') !== false) { + if ($Lw > $Tw) { + $yadj = ($Lw - $Tw) / 2; + } + if ($Lw < $Tw) { + $yadj = ($Lw + $Tw) / 2; + } + } else { + $yadj = $Lw / 2 - $bsv / 2; + } + if ($cort == 'cell' || strpos($tablecorner, 'B') !== false) { + if ($Lw > $Bw) { + $yadj2 = ($Lw - $Bw) / 2; + } + if ($Lw < $Bw) { + $yadj2 = ($Lw + $Bw) / 2; + } + } else { + $yadj2 = $Lw / 2 - $bsv / 2; + } + if (!$bSeparate && $details['mbw']['LT']) { + $yadj = ($Lw - $details['mbw']['LT']) / 2; + } + if (!$bSeparate && $details['mbw']['LB']) { + $yadj2 = ($Lw - $details['mbw']['LB']) / 2; + } + $print = true; + } + if ($Rw && $side == 'R' && $this->issetBorder($bord, Border::RIGHT)) { // RIGHT + $ly1 = $y; + $ly2 = $y2; + $lx1 = $x2; + $lx2 = $x2; + $this->SetLineWidth($Rw); + if ($cort == 'cell' || strpos($tablecorner, 'T') !== false) { + if ($Rw < $Tw) { + $yadj = ($Rw + $Tw) / 2; + } + if ($Rw > $Tw) { + $yadj = ($Rw - $Tw) / 2; + } + } else { + $yadj = $Rw / 2 - $bsv / 2; + } + + if ($cort == 'cell' || strpos($tablecorner, 'B') !== false) { + if ($Rw > $Bw) { + $yadj2 = ($Rw - $Bw) / 2; + } + if ($Rw < $Bw) { + $yadj2 = ($Rw + $Bw) / 2; + } + } else { + $yadj2 = $Rw / 2 - $bsv / 2; + } + + if (!$bSeparate && !empty($details['mbw']) && !empty($details['mbw']['RT'])) { + $yadj = ($Rw - $details['mbw']['RT']) / 2; + } + if (!$bSeparate && !empty($details['mbw']) && !empty($details['mbw']['RB'])) { + $yadj2 = ($Rw - $details['mbw']['RB']) / 2; + } + $print = true; + } + if ($Bw && $side == 'B' && $this->issetBorder($bord, Border::BOTTOM)) { // BOTTOM + $ly1 = $y2; + $ly2 = $y2; + $lx1 = $x; + $lx2 = $x2; + $this->SetLineWidth($Bw); + if ($cort == 'cell' || strpos($tablecorner, 'L') !== false) { + if ($Bw > $Lw) { + $xadj = ($Bw - $Lw) / 2; + } + if ($Bw < $Lw) { + $xadj = ($Bw + $Lw) / 2; + } + } else { + $xadj = $Bw / 2 - $bsh / 2; + } + if ($cort == 'cell' || strpos($tablecorner, 'R') !== false) { + if ($Bw > $Rw) { + $xadj2 = ($Bw - $Rw) / 2; + } + if ($Bw < $Rw) { + $xadj2 = ($Bw + $Rw) / 2; + } + } else { + $xadj2 = $Bw / 2 - $bsh / 2; + } + if (!$bSeparate && isset($details['mbw']) && isset($details['mbw']['BL'])) { + $xadj = ($Bw - $details['mbw']['BL']) / 2; + } + if (!$bSeparate && isset($details['mbw']) && isset($details['mbw']['BR'])) { + $xadj2 = ($Bw - $details['mbw']['BR']) / 2; + } + $print = true; + } + + // Now draw line + if ($print) { + /* -- TABLES-ADVANCED-BORDERS -- */ + if ($details[$side]['style'] == 'double') { + if (!isset($details[$side]['overlay']) || !$details[$side]['overlay'] || $bSeparate) { + if ($details[$side]['c']) { + $this->SetDColor($details[$side]['c']); + } else { + $this->SetDColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + } + $this->Line($lx1 + $xadj, $ly1 + $yadj, $lx2 - $xadj2, $ly2 - $yadj2); + } + if ((isset($details[$side]['overlay']) && $details[$side]['overlay']) || $bSeparate) { + if ($bSeparate && $cort == 'table') { + if ($side == 'T') { + $xadj -= $this->LineWidth / 2; + $xadj2 -= $this->LineWidth; + if ($this->issetBorder($bord, Border::LEFT)) { + $xadj += $this->LineWidth / 2; + } + if ($this->issetBorder($bord, Border::RIGHT)) { + $xadj2 += $this->LineWidth; + } + } + if ($side == 'L') { + $yadj -= $this->LineWidth / 2; + $yadj2 -= $this->LineWidth; + if ($this->issetBorder($bord, Border::TOP)) { + $yadj += $this->LineWidth / 2; + } + if ($this->issetBorder($bord, Border::BOTTOM)) { + $yadj2 += $this->LineWidth; + } + } + if ($side == 'B') { + $xadj -= $this->LineWidth / 2; + $xadj2 -= $this->LineWidth; + if ($this->issetBorder($bord, Border::LEFT)) { + $xadj += $this->LineWidth / 2; + } + if ($this->issetBorder($bord, Border::RIGHT)) { + $xadj2 += $this->LineWidth; + } + } + if ($side == 'R') { + $yadj -= $this->LineWidth / 2; + $yadj2 -= $this->LineWidth; + if ($this->issetBorder($bord, Border::TOP)) { + $yadj += $this->LineWidth / 2; + } + if ($this->issetBorder($bord, Border::BOTTOM)) { + $yadj2 += $this->LineWidth; + } + } + } + + $this->SetLineWidth($this->LineWidth / 3); + + $tbcol = $this->colorConverter->convert(255, $this->PDFAXwarnings); + for ($l = 0; $l <= $this->blklvl; $l++) { + if ($this->blk[$l]['bgcolor']) { + $tbcol = ($this->blk[$l]['bgcolorarray']); + } + } + + if ($bSeparate) { + $cellBorderOverlay[] = [ + 'x' => $lx1 + $xadj, + 'y' => $ly1 + $yadj, + 'x2' => $lx2 - $xadj2, + 'y2' => $ly2 - $yadj2, + 'col' => $tbcol, + 'lw' => $this->LineWidth, + ]; + } else { + $this->SetDColor($tbcol); + $this->Line($lx1 + $xadj, $ly1 + $yadj, $lx2 - $xadj2, $ly2 - $yadj2); + } + } + } elseif (isset($details[$side]['style']) && ($details[$side]['style'] == 'ridge' || $details[$side]['style'] == 'groove' || $details[$side]['style'] == 'inset' || $details[$side]['style'] == 'outset')) { + if (!isset($details[$side]['overlay']) || !$details[$side]['overlay'] || $bSeparate) { + if ($details[$side]['c']) { + $this->SetDColor($details[$side]['c']); + } else { + $this->SetDColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + } + if ($details[$side]['style'] == 'outset' || $details[$side]['style'] == 'groove') { + $nc = $this->colorConverter->darken($details[$side]['c']); + $this->SetDColor($nc); + } elseif ($details[$side]['style'] == 'ridge' || $details[$side]['style'] == 'inset') { + $nc = $this->colorConverter->lighten($details[$side]['c']); + $this->SetDColor($nc); + } + $this->Line($lx1 + $xadj, $ly1 + $yadj, $lx2 - $xadj2, $ly2 - $yadj2); + } + if ((isset($details[$side]['overlay']) && $details[$side]['overlay']) || $bSeparate) { + if ($details[$side]['c']) { + $this->SetDColor($details[$side]['c']); + } else { + $this->SetDColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + } + $doubleadj = ($this->LineWidth) / 3; + $this->SetLineWidth($this->LineWidth / 2); + $xadj3 = $yadj3 = $wadj3 = $hadj3 = 0; + + if ($details[$side]['style'] == 'ridge' || $details[$side]['style'] == 'inset') { + $nc = $this->colorConverter->darken($details[$side]['c']); + + if ($bSeparate && $cort == 'table') { + if ($side == 'T') { + $yadj3 = $this->LineWidth / 2; + $xadj3 = -$this->LineWidth / 2; + $wadj3 = $this->LineWidth; + if ($this->issetBorder($bord, Border::LEFT)) { + $xadj3 += $this->LineWidth; + $wadj3 -= $this->LineWidth; + } + if ($this->issetBorder($bord, Border::RIGHT)) { + $wadj3 -= $this->LineWidth * 2; + } + } + if ($side == 'L') { + $xadj3 = $this->LineWidth / 2; + $yadj3 = -$this->LineWidth / 2; + $hadj3 = $this->LineWidth; + if ($this->issetBorder($bord, Border::TOP)) { + $yadj3 += $this->LineWidth; + $hadj3 -= $this->LineWidth; + } + if ($this->issetBorder($bord, Border::BOTTOM)) { + $hadj3 -= $this->LineWidth * 2; + } + } + if ($side == 'B') { + $yadj3 = $this->LineWidth / 2; + $xadj3 = -$this->LineWidth / 2; + $wadj3 = $this->LineWidth; + } + if ($side == 'R') { + $xadj3 = $this->LineWidth / 2; + $yadj3 = -$this->LineWidth / 2; + $hadj3 = $this->LineWidth; + } + } elseif ($side == 'T') { + $yadj3 = $this->LineWidth / 2; + $xadj3 = $this->LineWidth / 2; + $wadj3 = -$this->LineWidth * 2; + } elseif ($side == 'L') { + $xadj3 = $this->LineWidth / 2; + $yadj3 = $this->LineWidth / 2; + $hadj3 = -$this->LineWidth * 2; + } elseif ($side == 'B' && $bSeparate) { + $yadj3 = $this->LineWidth / 2; + $wadj3 = $this->LineWidth / 2; + } elseif ($side == 'R' && $bSeparate) { + $xadj3 = $this->LineWidth / 2; + $hadj3 = $this->LineWidth / 2; + } elseif ($side == 'B') { + $yadj3 = $this->LineWidth / 2; + $xadj3 = $this->LineWidth / 2; + } elseif ($side == 'R') { + $xadj3 = $this->LineWidth / 2; + $yadj3 = $this->LineWidth / 2; + } + } else { + $nc = $this->colorConverter->lighten($details[$side]['c']); + + if ($bSeparate && $cort == 'table') { + if ($side == 'T') { + $yadj3 = $this->LineWidth / 2; + $xadj3 = -$this->LineWidth / 2; + $wadj3 = $this->LineWidth; + if ($this->issetBorder($bord, Border::LEFT)) { + $xadj3 += $this->LineWidth; + $wadj3 -= $this->LineWidth; + } + } + if ($side == 'L') { + $xadj3 = $this->LineWidth / 2; + $yadj3 = -$this->LineWidth / 2; + $hadj3 = $this->LineWidth; + if ($this->issetBorder($bord, Border::TOP)) { + $yadj3 += $this->LineWidth; + $hadj3 -= $this->LineWidth; + } + } + if ($side == 'B') { + $yadj3 = $this->LineWidth / 2; + $xadj3 = -$this->LineWidth / 2; + $wadj3 = $this->LineWidth; + if ($this->issetBorder($bord, Border::LEFT)) { + $xadj3 += $this->LineWidth; + $wadj3 -= $this->LineWidth; + } + } + if ($side == 'R') { + $xadj3 = $this->LineWidth / 2; + $yadj3 = -$this->LineWidth / 2; + $hadj3 = $this->LineWidth; + if ($this->issetBorder($bord, Border::TOP)) { + $yadj3 += $this->LineWidth; + $hadj3 -= $this->LineWidth; + } + } + } elseif ($side == 'T') { + $yadj3 = $this->LineWidth / 2; + $xadj3 = $this->LineWidth / 2; + } elseif ($side == 'L') { + $xadj3 = $this->LineWidth / 2; + $yadj3 = $this->LineWidth / 2; + } elseif ($side == 'B' && $bSeparate) { + $yadj3 = $this->LineWidth / 2; + $xadj3 = $this->LineWidth / 2; + } elseif ($side == 'R' && $bSeparate) { + $xadj3 = $this->LineWidth / 2; + $yadj3 = $this->LineWidth / 2; + } elseif ($side == 'B') { + $yadj3 = $this->LineWidth / 2; + $xadj3 = -$this->LineWidth / 2; + $wadj3 = $this->LineWidth; + } elseif ($side == 'R') { + $xadj3 = $this->LineWidth / 2; + $yadj3 = -$this->LineWidth / 2; + $hadj3 = $this->LineWidth; + } + } + + if ($bSeparate) { + $cellBorderOverlay[] = [ + 'x' => $lx1 + $xadj + $xadj3, + 'y' => $ly1 + $yadj + $yadj3, + 'x2' => $lx2 - $xadj2 + $xadj3 + $wadj3, + 'y2' => $ly2 - $yadj2 + $yadj3 + $hadj3, + 'col' => $nc, + 'lw' => $this->LineWidth, + ]; + } else { + $this->SetDColor($nc); + $this->Line($lx1 + $xadj + $xadj3, $ly1 + $yadj + $yadj3, $lx2 - $xadj2 + $xadj3 + $wadj3, $ly2 - $yadj2 + $yadj3 + $hadj3); + } + } + } else { + /* -- END TABLES-ADVANCED-BORDERS -- */ + if ($details[$side]['style'] == 'dashed') { + $dashsize = 2; // final dash will be this + 1*linewidth + $dashsizek = 1.5; // ratio of Dash/Blank + $this->SetDash($dashsize, ($dashsize / $dashsizek) + ($this->LineWidth * 2)); + } elseif ($details[$side]['style'] == 'dotted') { + $this->SetLineJoin(1); + $this->SetLineCap(1); + $this->SetDash(0.001, ($this->LineWidth * 2)); + } + if ($details[$side]['c']) { + $this->SetDColor($details[$side]['c']); + } else { + $this->SetDColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + } + $this->Line($lx1 + $xadj, $ly1 + $yadj, $lx2 - $xadj2, $ly2 - $yadj2); + /* -- TABLES-ADVANCED-BORDERS -- */ + } + /* -- END TABLES-ADVANCED-BORDERS -- */ + + // Reset Corners + $this->SetDash(); + // BUTT style line cap + $this->SetLineCap(2); + } + } + + if ($bSeparate && count($cellBorderOverlay)) { + foreach ($cellBorderOverlay as $cbo) { + $this->SetLineWidth($cbo['lw']); + $this->SetDColor($cbo['col']); + $this->Line($cbo['x'], $cbo['y'], $cbo['x2'], $cbo['y2']); + } + } + + // $this->SetLineWidth($oldlinewidth); + // $this->SetDColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + } + } + + /* -- TABLES -- */ + /* -- TABLES-ADVANCED-BORDERS -- */ + + /* -- END TABLES-ADVANCED-BORDERS -- */ + + function setBorder(&$var, $flag, $set = true) + { + $flag = intval($flag); + if ($set) { + $set = true; + } + $var = intval($var); + $var = $set ? ($var | $flag) : ($var & ~$flag); + } + + function issetBorder($var, $flag) + { + $flag = intval($flag); + $var = intval($var); + return (($var & $flag) == $flag); + } + + function _table2cellBorder(&$tableb, &$cbdb, &$cellb, $bval) + { + if ($tableb && $tableb['w'] > $cbdb['w']) { + $cbdb = $tableb; + $this->setBorder($cellb, $bval); + } elseif ($tableb && $tableb['w'] == $cbdb['w'] && array_search($tableb['style'], $this->borderstyles) > array_search($cbdb['style'], $this->borderstyles)) { + $cbdb = $tableb; + $this->setBorder($cellb, $bval); + } + } + + // FIX BORDERS ******************************************** + function _fixTableBorders(&$table) + { + if (!$table['borders_separate'] && $table['border_details']['L']['w']) { + $table['max_cell_border_width']['L'] = $table['border_details']['L']['w']; + } + if (!$table['borders_separate'] && $table['border_details']['R']['w']) { + $table['max_cell_border_width']['R'] = $table['border_details']['R']['w']; + } + if (!$table['borders_separate'] && $table['border_details']['T']['w']) { + $table['max_cell_border_width']['T'] = $table['border_details']['T']['w']; + } + if (!$table['borders_separate'] && $table['border_details']['B']['w']) { + $table['max_cell_border_width']['B'] = $table['border_details']['B']['w']; + } + if ($this->simpleTables) { + return; + } + $cells = &$table['cells']; + $numcols = $table['nc']; + $numrows = $table['nr']; + /* -- TABLES-ADVANCED-BORDERS -- */ + if (isset($table['topntail']) && $table['topntail']) { + $tntborddet = $this->border_details($table['topntail']); + } + if (isset($table['thead-underline']) && $table['thead-underline']) { + $thuborddet = $this->border_details($table['thead-underline']); + } + /* -- END TABLES-ADVANCED-BORDERS -- */ + + for ($i = 0; $i < $numrows; $i++) { // Rows + for ($j = 0; $j < $numcols; $j++) { // Columns + if (isset($cells[$i][$j]) && $cells[$i][$j]) { + $cell = &$cells[$i][$j]; + if ($this->packTableData) { + $cbord = $this->_unpackCellBorder($cell['borderbin']); + } else { + $cbord = &$cells[$i][$j]; + } + + // mPDF 5.7.3 + if (!$cbord['border'] && $cbord['border'] !== 0 && isset($table['border']) && $table['border'] && $this->table_border_attr_set) { + $cbord['border'] = $table['border']; + $cbord['border_details'] = $table['border_details']; + } + + if (isset($cell['colspan']) && $cell['colspan'] > 1) { + $ccolsp = $cell['colspan']; + } else { + $ccolsp = 1; + } + if (isset($cell['rowspan']) && $cell['rowspan'] > 1) { + $crowsp = $cell['rowspan']; + } else { + $crowsp = 1; + } + + $cbord['border_details']['cellposdom'] = ((($i + 1) / $numrows) / 10000 ) + ((($j + 1) / $numcols) / 10 ); + // Inherit Cell border from Table border + if ($this->table_border_css_set && !$table['borders_separate']) { + if ($i == 0) { + $this->_table2cellBorder($table['border_details']['T'], $cbord['border_details']['T'], $cbord['border'], Border::TOP); + } + if ($i == ($numrows - 1) || ($i + $crowsp) == ($numrows)) { + $this->_table2cellBorder($table['border_details']['B'], $cbord['border_details']['B'], $cbord['border'], Border::BOTTOM); + } + if ($j == 0) { + $this->_table2cellBorder($table['border_details']['L'], $cbord['border_details']['L'], $cbord['border'], Border::LEFT); + } + if ($j == ($numcols - 1) || ($j + $ccolsp) == ($numcols)) { + $this->_table2cellBorder($table['border_details']['R'], $cbord['border_details']['R'], $cbord['border'], Border::RIGHT); + } + } + + /* -- TABLES-ADVANCED-BORDERS -- */ + $fixbottom = true; + if (isset($table['topntail']) && $table['topntail']) { + if ($i == 0) { + $cbord['border_details']['T'] = $tntborddet; + $this->setBorder($cbord['border'], Border::TOP); + } + if ($this->tableLevel == 1 && $table['headernrows'] > 0 && $i == $table['headernrows'] - 1) { + $cbord['border_details']['B'] = $tntborddet; + $this->setBorder($cbord['border'], Border::BOTTOM); + $fixbottom = false; + } elseif ($this->tableLevel == 1 && $table['headernrows'] > 0 && $i == $table['headernrows']) { + if (!$table['borders_separate']) { + $cbord['border_details']['T'] = $tntborddet; + $this->setBorder($cbord['border'], Border::TOP); + } + } + if ($this->tableLevel == 1 && $table['footernrows'] > 0 && $i == ($numrows - $table['footernrows'] - 1)) { + if (!$table['borders_separate']) { + $cbord['border_details']['B'] = $tntborddet; + $this->setBorder($cbord['border'], Border::BOTTOM); + $fixbottom = false; + } + } elseif ($this->tableLevel == 1 && $table['footernrows'] > 0 && $i == ($numrows - $table['footernrows'])) { + $cbord['border_details']['T'] = $tntborddet; + $this->setBorder($cbord['border'], Border::TOP); + } + if ($this->tabletheadjustfinished) { // $this->tabletheadjustfinished called from tableheader + if (!$table['borders_separate']) { + $cbord['border_details']['T'] = $tntborddet; + $this->setBorder($cbord['border'], Border::TOP); + } + } + if ($i == ($numrows - 1) || ($i + $crowsp) == ($numrows)) { + $cbord['border_details']['B'] = $tntborddet; + $this->setBorder($cbord['border'], Border::BOTTOM); + } + } + if (isset($table['thead-underline']) && $table['thead-underline']) { + if ($table['borders_separate']) { + if ($i == 0) { + $cbord['border_details']['B'] = $thuborddet; + $this->setBorder($cbord['border'], Border::BOTTOM); + $fixbottom = false; + } + } else { + if ($this->tableLevel == 1 && $table['headernrows'] > 0 && $i == $table['headernrows'] - 1) { + $cbord['border_details']['T'] = $thuborddet; + $this->setBorder($cbord['border'], Border::TOP); + } elseif ($this->tabletheadjustfinished) { // $this->tabletheadjustfinished called from tableheader + $cbord['border_details']['T'] = $thuborddet; + $this->setBorder($cbord['border'], Border::TOP); + } + } + } + + // Collapse Border - Algorithm for conflicting borders + // Hidden >> Width >> double>solid>dashed>dotted... >> style set on cell>table >> top/left>bottom/right + // Do not turn off border which is overridden + // Needed for page break for TOP/BOTTOM both to be defined in Collapsed borders + // Means it is painted twice. (Left/Right can still disable overridden border) + if (!$table['borders_separate']) { + + if (($i < ($numrows - 1) || ($i + $crowsp) < $numrows ) && $fixbottom) { // Bottom + + for ($cspi = 0; $cspi < $ccolsp; $cspi++) { + + // already defined Top for adjacent cell below + if (isset($cells[($i + $crowsp)][$j + $cspi])) { + if ($this->packTableData) { + $adjc = $cells[($i + $crowsp)][$j + $cspi]; + $celladj = $this->_unpackCellBorder($adjc['borderbin']); + } else { + $celladj = & $cells[($i + $crowsp)][$j + $cspi]; + } + } else { + $celladj = false; + } + + if (isset($celladj['border_details']['T']['s']) && $celladj['border_details']['T']['s'] == 1) { + + $csadj = $celladj['border_details']['T']['w']; + $csthis = $cbord['border_details']['B']['w']; + + // Hidden + if ($cbord['border_details']['B']['style'] == 'hidden') { + + $celladj['border_details']['T'] = $cbord['border_details']['B']; + $this->setBorder($celladj['border'], Border::TOP, false); + $this->setBorder($cbord['border'], Border::BOTTOM, false); + + } elseif ($celladj['border_details']['T']['style'] == 'hidden') { + + $cbord['border_details']['B'] = $celladj['border_details']['T']; + $this->setBorder($cbord['border'], Border::BOTTOM, false); + $this->setBorder($celladj['border'], Border::TOP, false); + + } elseif ($csthis > $csadj) { // Width + + if (!isset($cells[($i + $crowsp)][$j + $cspi]['colspan']) || (isset($cells[($i + $crowsp)][$j + $cspi]['colspan']) && $cells[($i + $crowsp)][$j + $cspi]['colspan'] < 2)) { // don't overwrite bordering cells that span + $celladj['border_details']['T'] = $cbord['border_details']['B']; + $this->setBorder($cbord['border'], Border::BOTTOM); + } + + } elseif ($csadj > $csthis) { + + if ($ccolsp < 2) { // don't overwrite this cell if it spans + $cbord['border_details']['B'] = $celladj['border_details']['T']; + $this->setBorder($celladj['border'], Border::TOP); + } + + } elseif (array_search($cbord['border_details']['B']['style'], $this->borderstyles) > array_search($celladj['border_details']['T']['style'], $this->borderstyles)) { // double>solid>dashed>dotted... + + if (!isset($cells[($i + $crowsp)][$j + $cspi]['colspan']) || (isset($cells[($i + $crowsp)][$j + $cspi]['colspan']) && $cells[($i + $crowsp)][$j + $cspi]['colspan'] < 2)) { // don't overwrite bordering cells that span + $celladj['border_details']['T'] = $cbord['border_details']['B']; + $this->setBorder($cbord['border'], Border::BOTTOM); + } + + } elseif (array_search($celladj['border_details']['T']['style'], $this->borderstyles) > array_search($cbord['border_details']['B']['style'], $this->borderstyles)) { + + if ($ccolsp < 2) { // don't overwrite this cell if it spans + $cbord['border_details']['B'] = $celladj['border_details']['T']; + $this->setBorder($celladj['border'], Border::TOP); + } + + } elseif ($celladj['border_details']['T']['dom'] > $celladj['border_details']['B']['dom']) { // Style set on cell vs. table + + if ($ccolsp < 2) { // don't overwrite this cell if it spans + $cbord['border_details']['B'] = $celladj['border_details']['T']; + $this->setBorder($celladj['border'], Border::TOP); + } + + } else { // Style set on cell vs. table - OR - LEFT/TOP (cell) in preference to BOTTOM/RIGHT + + if (!isset($cells[($i + $crowsp)][$j + $cspi]['colspan']) || (isset($cells[($i + $crowsp)][$j + $cspi]['colspan']) && $cells[($i + $crowsp)][$j + $cspi]['colspan'] < 2)) { // don't overwrite bordering cells that span + $celladj['border_details']['T'] = $cbord['border_details']['B']; + $this->setBorder($cbord['border'], Border::BOTTOM); + } + + } + + } elseif ($celladj) { + + if (!isset($cells[($i + $crowsp)][$j + $cspi]['colspan']) || (isset($cells[($i + $crowsp)][$j + $cspi]['colspan']) && $cells[($i + $crowsp)][$j + $cspi]['colspan'] < 2)) { // don't overwrite bordering cells that span + $celladj['border_details']['T'] = $cbord['border_details']['B']; + } + + } + + // mPDF 5.7.4 + if ($celladj && $this->packTableData) { + $cells[$i + $crowsp][$j + $cspi]['borderbin'] = $this->_packCellBorder($celladj); + } + + unset($celladj); + } + } + + if ($j < ($numcols - 1) || ($j + $ccolsp) < $numcols) { // Right-Left + + for ($cspi = 0; $cspi < $crowsp; $cspi++) { + + // already defined Left for adjacent cell to R + if (isset($cells[($i + $cspi)][$j + $ccolsp])) { + if ($this->packTableData) { + $adjc = $cells[($i + $cspi)][$j + $ccolsp]; + $celladj = $this->_unpackCellBorder($adjc['borderbin']); + } else { + $celladj = & $cells[$i + $cspi][$j + $ccolsp]; + } + } else { + $celladj = false; + } + if ($celladj && $celladj['border_details']['L']['s'] == 1) { + $csadj = $celladj['border_details']['L']['w']; + $csthis = $cbord['border_details']['R']['w']; + // Hidden + if ($cbord['border_details']['R']['style'] == 'hidden') { + $celladj['border_details']['L'] = $cbord['border_details']['R']; + $this->setBorder($celladj['border'], Border::LEFT, false); + $this->setBorder($cbord['border'], Border::RIGHT, false); + } elseif ($celladj['border_details']['L']['style'] == 'hidden') { + $cbord['border_details']['R'] = $celladj['border_details']['L']; + $this->setBorder($cbord['border'], Border::RIGHT, false); + $this->setBorder($celladj['border'], Border::LEFT, false); + } // Width + elseif ($csthis > $csadj) { + if (!isset($cells[($i + $cspi)][$j + $ccolsp]['rowspan']) || (isset($cells[($i + $cspi)][$j + $ccolsp]['rowspan']) && $cells[($i + $cspi)][$j + $ccolsp]['rowspan'] < 2)) { // don't overwrite bordering cells that span + $celladj['border_details']['L'] = $cbord['border_details']['R']; + $this->setBorder($cbord['border'], Border::RIGHT); + $this->setBorder($celladj['border'], Border::LEFT, false); + } + } elseif ($csadj > $csthis) { + if ($crowsp < 2) { // don't overwrite this cell if it spans + $cbord['border_details']['R'] = $celladj['border_details']['L']; + $this->setBorder($cbord['border'], Border::RIGHT, false); + $this->setBorder($celladj['border'], Border::LEFT); + } + } // double>solid>dashed>dotted... + elseif (array_search($cbord['border_details']['R']['style'], $this->borderstyles) > array_search($celladj['border_details']['L']['style'], $this->borderstyles)) { + if (!isset($cells[($i + $cspi)][$j + $ccolsp]['rowspan']) || (isset($cells[($i + $cspi)][$j + $ccolsp]['rowspan']) && $cells[($i + $cspi)][$j + $ccolsp]['rowspan'] < 2)) { // don't overwrite bordering cells that span + $celladj['border_details']['L'] = $cbord['border_details']['R']; + $this->setBorder($celladj['border'], Border::LEFT, false); + $this->setBorder($cbord['border'], Border::RIGHT); + } + } elseif (array_search($celladj['border_details']['L']['style'], $this->borderstyles) > array_search($cbord['border_details']['R']['style'], $this->borderstyles)) { + if ($crowsp < 2) { // don't overwrite this cell if it spans + $cbord['border_details']['R'] = $celladj['border_details']['L']; + $this->setBorder($cbord['border'], Border::RIGHT, false); + $this->setBorder($celladj['border'], Border::LEFT); + } + } // Style set on cell vs. table + elseif ($celladj['border_details']['L']['dom'] > $cbord['border_details']['R']['dom']) { + if ($crowsp < 2) { // don't overwrite this cell if it spans + $cbord['border_details']['R'] = $celladj['border_details']['L']; + $this->setBorder($celladj['border'], Border::LEFT); + } + } // Style set on cell vs. table - OR - LEFT/TOP (cell) in preference to BOTTOM/RIGHT + else { + if (!isset($cells[($i + $cspi)][$j + $ccolsp]['rowspan']) || (isset($cells[($i + $cspi)][$j + $ccolsp]['rowspan']) && $cells[($i + $cspi)][$j + $ccolsp]['rowspan'] < 2)) { // don't overwrite bordering cells that span + $celladj['border_details']['L'] = $cbord['border_details']['R']; + $this->setBorder($cbord['border'], Border::RIGHT); + } + } + } elseif ($celladj) { + // if right-cell border is not set + if (!isset($cells[($i + $cspi)][$j + $ccolsp]['rowspan']) || (isset($cells[($i + $cspi)][$j + $ccolsp]['rowspan']) && $cells[($i + $cspi)][$j + $ccolsp]['rowspan'] < 2)) { // don't overwrite bordering cells that span + $celladj['border_details']['L'] = $cbord['border_details']['R']; + } + } + // mPDF 5.7.4 + if ($celladj && $this->packTableData) { + $cells[$i + $cspi][$j + $ccolsp]['borderbin'] = $this->_packCellBorder($celladj); + } + unset($celladj); + } + } + } + + + // Set maximum cell border width meeting at LRTB edges of cell - used for extended cell border + // ['border_details']['mbw']['LT'] = meeting border width - Left border - Top end + if (!$table['borders_separate']) { + + $cbord['border_details']['mbw']['BL'] = max($cbord['border_details']['mbw']['BL'], $cbord['border_details']['L']['w']); + $cbord['border_details']['mbw']['BR'] = max($cbord['border_details']['mbw']['BR'], $cbord['border_details']['R']['w']); + $cbord['border_details']['mbw']['RT'] = max($cbord['border_details']['mbw']['RT'], $cbord['border_details']['T']['w']); + $cbord['border_details']['mbw']['RB'] = max($cbord['border_details']['mbw']['RB'], $cbord['border_details']['B']['w']); + $cbord['border_details']['mbw']['TL'] = max($cbord['border_details']['mbw']['TL'], $cbord['border_details']['L']['w']); + $cbord['border_details']['mbw']['TR'] = max($cbord['border_details']['mbw']['TR'], $cbord['border_details']['R']['w']); + $cbord['border_details']['mbw']['LT'] = max($cbord['border_details']['mbw']['LT'], $cbord['border_details']['T']['w']); + $cbord['border_details']['mbw']['LB'] = max($cbord['border_details']['mbw']['LB'], $cbord['border_details']['B']['w']); + + if (($i + $crowsp) < $numrows && isset($cells[$i + $crowsp][$j])) { // Has Bottom adjoining cell + + if ($this->packTableData) { + $adjc = $cells[$i + $crowsp][$j]; + $celladj = $this->_unpackCellBorder($adjc['borderbin']); + } else { + $celladj = & $cells[$i + $crowsp][$j]; + } + + $cbord['border_details']['mbw']['BL'] = max( + $cbord['border_details']['mbw']['BL'], + $celladj ? $celladj['border_details']['L']['w'] : 0, + $celladj ? $celladj['border_details']['mbw']['TL']: 0 + ); + + $cbord['border_details']['mbw']['BR'] = max( + $cbord['border_details']['mbw']['BR'], + $celladj ? $celladj['border_details']['R']['w'] : 0, + $celladj ? $celladj['border_details']['mbw']['TR']: 0 + ); + + $cbord['border_details']['mbw']['LB'] = max( + $cbord['border_details']['mbw']['LB'], + $celladj ? $celladj['border_details']['mbw']['LT'] : 0 + ); + + $cbord['border_details']['mbw']['RB'] = max( + $cbord['border_details']['mbw']['RB'], + $celladj ? $celladj['border_details']['mbw']['RT'] : 0 + ); + + unset($celladj); + } + + if (($j + $ccolsp) < $numcols && isset($cells[$i][$j + $ccolsp])) { // Has Right adjoining cell + + if ($this->packTableData) { + $adjc = $cells[$i][$j + $ccolsp]; + $celladj = $this->_unpackCellBorder($adjc['borderbin']); + } else { + $celladj = & $cells[$i][$j + $ccolsp]; + } + + $cbord['border_details']['mbw']['RT'] = max( + $cbord['border_details']['mbw']['RT'], + $celladj ? $celladj['border_details']['T']['w'] : 0, + $celladj ? $celladj['border_details']['mbw']['LT'] : 0 + ); + + $cbord['border_details']['mbw']['RB'] = max( + $cbord['border_details']['mbw']['RB'], + $celladj ? $celladj['border_details']['B']['w'] : 0, + $celladj ? $celladj['border_details']['mbw']['LB'] : 0 + ); + + $cbord['border_details']['mbw']['TR'] = max( + $cbord['border_details']['mbw']['TR'], + $celladj ? $celladj['border_details']['mbw']['TL'] : 0 + ); + + $cbord['border_details']['mbw']['BR'] = max( + $cbord['border_details']['mbw']['BR'], + $celladj ? $celladj['border_details']['mbw']['BL'] : 0 + ); + + unset($celladj); + } + + if ($i > 0 && isset($cells[$i - 1][$j]) && is_array($cells[$i - 1][$j]) && (($this->packTableData && $cells[$i - 1][$j]['borderbin']) || $cells[$i - 1][$j]['border'])) { // Has Top adjoining cell + + if ($this->packTableData) { + $adjc = $cells[$i - 1][$j]; + $celladj = $this->_unpackCellBorder($adjc['borderbin']); + } else { + $celladj = & $cells[$i - 1][$j]; + } + + $cbord['border_details']['mbw']['TL'] = max( + $cbord['border_details']['mbw']['TL'], + $celladj ? $celladj['border_details']['L']['w'] : 0, + $celladj ? $celladj['border_details']['mbw']['BL'] : 0 + ); + + $cbord['border_details']['mbw']['TR'] = max( + $cbord['border_details']['mbw']['TR'], + $celladj ? $celladj['border_details']['R']['w'] : 0, + $celladj ? $celladj['border_details']['mbw']['BR'] : 0 + ); + + $cbord['border_details']['mbw']['LT'] = max( + $cbord['border_details']['mbw']['LT'], + $celladj ? $celladj['border_details']['mbw']['LB'] : 0 + ); + + $cbord['border_details']['mbw']['RT'] = max( + $cbord['border_details']['mbw']['RT'], + $celladj ? $celladj['border_details']['mbw']['RB'] : 0 + ); + + if ($celladj['border_details']['mbw']['BL']) { + $celladj['border_details']['mbw']['BL'] = max($cbord['border_details']['mbw']['TL'], $celladj['border_details']['mbw']['BL']); + } + + if ($celladj['border_details']['mbw']['BR']) { + $celladj['border_details']['mbw']['BR'] = max($celladj['border_details']['mbw']['BR'], $cbord['border_details']['mbw']['TR']); + } + + if ($this->packTableData) { + $cells[$i - 1][$j]['borderbin'] = $this->_packCellBorder($celladj); + } + unset($celladj); + } + + if ($j > 0 && isset($cells[$i][$j - 1]) && is_array($cells[$i][$j - 1]) && (($this->packTableData && $cells[$i][$j - 1]['borderbin']) || $cells[$i][$j - 1]['border'])) { // Has Left adjoining cell + + if ($this->packTableData) { + $adjc = $cells[$i][$j - 1]; + $celladj = $this->_unpackCellBorder($adjc['borderbin']); + } else { + $celladj = & $cells[$i][$j - 1]; + } + + $cbord['border_details']['mbw']['LT'] = max( + $cbord['border_details']['mbw']['LT'], + $celladj ? $celladj['border_details']['T']['w'] : 0, + $celladj ? $celladj['border_details']['mbw']['RT'] : 0 + ); + + $cbord['border_details']['mbw']['LB'] = max( + $cbord['border_details']['mbw']['LB'], + $celladj ? $celladj['border_details']['B']['w'] : 0, + $celladj ? $celladj['border_details']['mbw']['RB'] : 0 + ); + + $cbord['border_details']['mbw']['BL'] = max( + $cbord['border_details']['mbw']['BL'], + $celladj ? $celladj['border_details']['mbw']['BR'] : 0 + ); + + $cbord['border_details']['mbw']['TL'] = max( + $cbord['border_details']['mbw']['TL'], + $celladj ? $celladj['border_details']['mbw']['TR'] : 0 + ); + + if ($celladj['border_details']['mbw']['RT']) { + $celladj['border_details']['mbw']['RT'] = max($celladj['border_details']['mbw']['RT'], $cbord['border_details']['mbw']['LT']); + } + + if ($celladj['border_details']['mbw']['RB']) { + $celladj['border_details']['mbw']['RB'] = max($celladj['border_details']['mbw']['RB'], $cbord['border_details']['mbw']['LB']); + } + + if ($this->packTableData) { + $cells[$i][$j - 1]['borderbin'] = $this->_packCellBorder($celladj); + } + + unset($celladj); + } + + + // Update maximum cell border width at LRTB edges of table - used for overall table width + if ($j == 0 && $cbord['border_details']['L']['w']) { + $table['max_cell_border_width']['L'] = max($table['max_cell_border_width']['L'], $cbord['border_details']['L']['w']); + } + if (($j == ($numcols - 1) || ($j + $ccolsp) == $numcols ) && $cbord['border_details']['R']['w']) { + $table['max_cell_border_width']['R'] = max($table['max_cell_border_width']['R'], $cbord['border_details']['R']['w']); + } + if ($i == 0 && $cbord['border_details']['T']['w']) { + $table['max_cell_border_width']['T'] = max($table['max_cell_border_width']['T'], $cbord['border_details']['T']['w']); + } + if (($i == ($numrows - 1) || ($i + $crowsp) == $numrows ) && $cbord['border_details']['B']['w']) { + $table['max_cell_border_width']['B'] = max($table['max_cell_border_width']['B'], $cbord['border_details']['B']['w']); + } + } + /* -- END TABLES-ADVANCED-BORDERS -- */ + + if ($this->packTableData) { + $cell['borderbin'] = $this->_packCellBorder($cbord); + } + + unset($cbord); + + unset($cell); + } + } + } + unset($cell); + } + + // END FIX BORDERS ************************************************************************************ + + function _reverseTableDir(&$table) + { + $cells = &$table['cells']; + $numcols = $table['nc']; + $numrows = $table['nr']; + for ($i = 0; $i < $numrows; $i++) { // Rows + $row = []; + for ($j = ($numcols - 1); $j >= 0; $j--) { // Columns + if (isset($cells[$i][$j]) && $cells[$i][$j]) { + $cell = &$cells[$i][$j]; + $col = $numcols - $j - 1; + if (isset($cell['colspan']) && $cell['colspan'] > 1) { + $col -= ($cell['colspan'] - 1); + } + // Nested content + if (isset($cell['textbuffer'])) { + for ($n = 0; $n < count($cell['textbuffer']); $n++) { + $t = $cell['textbuffer'][$n][0]; + if (substr($t, 0, 19) == "\xbb\xa4\xactype=nestedtable") { + $objattr = $this->_getObjAttr($t); + $objattr['col'] = $col; + $cell['textbuffer'][$n][0] = "\xbb\xa4\xactype=nestedtable,objattr=" . serialize($objattr) . "\xbb\xa4\xac"; + $this->table[($this->tableLevel + 1)][$objattr['nestedcontent']]['nestedpos'][1] = $col; + } + } + } + $row[$col] = $cells[$i][$j]; + unset($cell); + } + } + for ($f = 0; $f < $numcols; $f++) { + if (!isset($row[$f])) { + $row[$f] = 0; + } + } + $table['cells'][$i] = $row; + } + } + + function _tableWrite(&$table, $split = false, $startrow = 0, $startcol = 0, $splitpg = 0, $rety = 0) + { + $level = $table['level']; + $levelid = $table['levelid']; + + $cells = &$table['cells']; + $numcols = $table['nc']; + $numrows = $table['nr']; + $maxbwtop = 0; + if ($this->ColActive && $level == 1) { + $this->breakpoints[$this->CurrCol][] = $this->y; + } // *COLUMNS* + + if (!$split || ($startrow == 0 && $splitpg == 0) || $startrow > 0) { + // TABLE TOP MARGIN + if ($table['margin']['T']) { + if (!$this->table_rotate && $level == 1) { + $this->DivLn($table['margin']['T'], $this->blklvl, true, 1); // collapsible + } else { + $this->y += ($table['margin']['T']); + } + } + // Advance down page by half width of top border + if ($table['borders_separate']) { + if ($startrow > 0 && (!isset($table['is_thead']) || count($table['is_thead']) == 0)) { + $adv = $table['border_spacing_V'] / 2; + } else { + $adv = $table['padding']['T'] + $table['border_details']['T']['w'] + $table['border_spacing_V'] / 2; + } + } else { + $adv = $table['max_cell_border_width']['T'] / 2; + } + if (!$this->table_rotate && $level == 1) { + $this->DivLn($adv); + } else { + $this->y += $adv; + } + } + + if ($level == 1) { + $this->x = $this->lMargin + $this->blk[$this->blklvl]['outer_left_margin'] + $this->blk[$this->blklvl]['padding_left'] + $this->blk[$this->blklvl]['border_left']['w']; + $x0 = $this->x; + $y0 = $this->y; + $right = $x0 + $this->blk[$this->blklvl]['inner_width']; + $outerfilled = $this->y; // Keep track of how far down the outer DIV bgcolor is painted (NB rowspans) + $this->outerfilled = $this->y; + $this->colsums = []; + } else { + $x0 = $this->x; + $y0 = $this->y; + $right = $x0 + $table['w']; + } + + if ($this->table_rotate) { + $temppgwidth = $this->tbrot_maxw; + $this->PageBreakTrigger = $pagetrigger = $y0 + ($this->blk[$this->blklvl]['inner_width']); + if ($level == 1) { + $this->tbrot_y0 = $this->y - $adv - $table['margin']['T']; + $this->tbrot_x0 = $this->x; + $this->tbrot_w = $table['w']; + if ($table['borders_separate']) { + $this->tbrot_h = $table['margin']['T'] + $table['padding']['T'] + $table['border_details']['T']['w'] + $table['border_spacing_V'] / 2; + } else { + $this->tbrot_h = $table['margin']['T'] + $table['padding']['T'] + $table['max_cell_border_width']['T']; + } + } + } else { + $this->PageBreakTrigger = $pagetrigger = ($this->h - $this->bMargin); + if ($level == 1) { + $temppgwidth = $this->blk[$this->blklvl]['inner_width']; + if (isset($table['a']) and ( $table['w'] < $this->blk[$this->blklvl]['inner_width'])) { + if ($table['a'] == 'C') { + $x0 += ((($right - $x0) - $table['w']) / 2); + } elseif ($table['a'] == 'R') { + $x0 = $right - $table['w']; + } + } + } else { + $temppgwidth = $table['w']; + } + } + if (!isset($table['overflow'])) { + $table['overflow'] = null; + } + if ($table['overflow'] == 'hidden' && $level == 1 && !$this->table_rotate && !$this->ColActive) { + // Bounding rectangle to clip + $this->tableClipPath = sprintf('q %.3F %.3F %.3F %.3F re W n', $x0 * Mpdf::SCALE, $this->h * Mpdf::SCALE, $this->blk[$this->blklvl]['inner_width'] * Mpdf::SCALE, -$this->h * Mpdf::SCALE); + $this->writer->write($this->tableClipPath); + } else { + $this->tableClipPath = ''; + } + + + if ($table['borders_separate']) { + $indent = $table['margin']['L'] + $table['border_details']['L']['w'] + $table['padding']['L'] + $table['border_spacing_H'] / 2; + } else { + $indent = $table['margin']['L'] + $table['max_cell_border_width']['L'] / 2; + } + $x0 += $indent; + + $returny = 0; + $lastCol = 0; + $tableheader = []; + $tablefooter = []; + $tableheaderrowheight = 0; + $tablefooterrowheight = 0; + $footery = 0; + + // mPD 3.0 Set the Page & Column where table starts + if (($this->mirrorMargins) && (($this->page) % 2 == 0)) { // EVEN + $tablestartpage = 'EVEN'; + } elseif (($this->mirrorMargins) && (($this->page) % 2 == 1)) { // ODD + $tablestartpage = 'ODD'; + } else { + $tablestartpage = ''; + } + if ($this->ColActive) { + $tablestartcolumn = $this->CurrCol; + } else { + $tablestartcolumn = ''; + } + + $y = $h = 0; + for ($i = 0; $i < $numrows; $i++) { // Rows + if (isset($table['is_tfoot'][$i]) && $table['is_tfoot'][$i] && $level == 1) { + $tablefooterrowheight += $table['hr'][$i]; + $tablefooter[$i][0]['trbackground-images'] = $table['trbackground-images'][$i]; + $tablefooter[$i][0]['trgradients'] = $table['trgradients'][$i]; + $tablefooter[$i][0]['trbgcolor'] = $table['bgcolor'][$i]; + for ($j = $startcol; $j < $numcols; $j++) { // Columns + if (isset($cells[$i][$j]) && $cells[$i][$j]) { + $cell = &$cells[$i][$j]; + if ($split) { + if ($table['colPg'][$j] != $splitpg) { + continue; + } + list($x, $w) = $this->_splitTableGetWidth($table, $i, $j); + $js = $j - $startcol; + } else { + list($x, $w) = $this->_tableGetWidth($table, $i, $j); + $js = $j; + } + + list($y, $h) = $this->_tableGetHeight($table, $i, $j); + $x += $x0; + $y += $y0; + // Get info of tfoot ==>> table footer + $tablefooter[$i][$js]['x'] = $x; + $tablefooter[$i][$js]['y'] = $y; + $tablefooter[$i][$js]['h'] = $h; + $tablefooter[$i][$js]['w'] = $w; + if (isset($cell['textbuffer'])) { + $tablefooter[$i][$js]['textbuffer'] = $cell['textbuffer']; + } else { + $tablefooter[$i][$js]['textbuffer'] = ''; + } + $tablefooter[$i][$js]['a'] = $cell['a']; + $tablefooter[$i][$js]['R'] = $cell['R']; + $tablefooter[$i][$js]['va'] = $cell['va']; + $tablefooter[$i][$js]['mih'] = $cell['mih']; + if (isset($cell['gradient'])) { + $tablefooter[$i][$js]['gradient'] = $cell['gradient']; // *BACKGROUNDS* + } + if (isset($cell['background-image'])) { + $tablefooter[$i][$js]['background-image'] = $cell['background-image']; // *BACKGROUNDS* + } + + // CELL FILL BGCOLOR + if (!$this->simpleTables) { + if ($this->packTableData) { + $c = $this->_unpackCellBorder($cell['borderbin']); + $tablefooter[$i][$js]['border'] = $c['border']; + $tablefooter[$i][$js]['border_details'] = $c['border_details']; + } else { + $tablefooter[$i][$js]['border'] = $cell['border']; + $tablefooter[$i][$js]['border_details'] = $cell['border_details']; + } + } elseif ($this->simpleTables) { + $tablefooter[$i][$js]['border'] = $table['simple']['border']; + $tablefooter[$i][$js]['border_details'] = $table['simple']['border_details']; + } + $tablefooter[$i][$js]['bgcolor'] = $cell['bgcolor']; + $tablefooter[$i][$js]['padding'] = $cell['padding']; + if (isset($cell['rowspan'])) { + $tablefooter[$i][$js]['rowspan'] = $cell['rowspan']; + } + if (isset($cell['colspan'])) { + $tablefooter[$i][$js]['colspan'] = $cell['colspan']; + } + if (isset($cell['direction'])) { + $tablefooter[$i][$js]['direction'] = $cell['direction']; + } + if (isset($cell['cellLineHeight'])) { + $tablefooter[$i][$js]['cellLineHeight'] = $cell['cellLineHeight']; + } + if (isset($cell['cellLineStackingStrategy'])) { + $tablefooter[$i][$js]['cellLineStackingStrategy'] = $cell['cellLineStackingStrategy']; + } + if (isset($cell['cellLineStackingShift'])) { + $tablefooter[$i][$js]['cellLineStackingShift'] = $cell['cellLineStackingShift']; + } + } + } + } + } + + if ($level == 1) { + $this->writer->write('___TABLE___BACKGROUNDS' . $this->uniqstr); + } + $tableheaderadj = 0; + $tablefooteradj = 0; + + $tablestartpageno = $this->page; + + // Draw Table Contents and Borders + for ($i = 0; $i < $numrows; $i++) { // Rows + if ($split && $startrow > 0) { + $thnr = (isset($table['is_thead']) ? count($table['is_thead']) : 0); + if ($i >= $thnr && $i < $startrow) { + continue; + } + if ($i == $startrow) { + $returny = $rety - $tableheaderrowheight; + } + } + + // Get Maximum row/cell height in row - including rowspan>1 + 1 overlapping + $maxrowheight = $this->_tableGetMaxRowHeight($table, $i); + + $skippage = false; + $newpagestarted = false; + for ($j = $startcol; $j < $numcols; $j++) { // Columns + if ($split) { + if ($table['colPg'][$j] > $splitpg) { + break; + } + $lastCol = $j; + } + if (isset($cells[$i][$j]) && $cells[$i][$j]) { + $cell = &$cells[$i][$j]; + if ($split) { + $lastCol = $j + (isset($cell['colspan']) ? ($cell['colspan'] - 1) : 0); + list($x, $w) = $this->_splitTableGetWidth($table, $i, $j); + } else { + list($x, $w) = $this->_tableGetWidth($table, $i, $j); + } + + list($y, $h) = $this->_tableGetHeight($table, $i, $j); + $x += $x0; + $y += $y0; + $y -= $returny; + + if ($table['borders_separate']) { + if (!empty($tablefooter) || $i == ($numrows - 1) || (isset($cell['rowspan']) && ($i + $cell['rowspan']) == $numrows) || (!isset($cell['rowspan']) && ($i + 1) == $numrows)) { + $extra = $table['padding']['B'] + $table['border_details']['B']['w'] + $table['border_spacing_V'] / 2; + // $extra = $table['margin']['B'] + $table['padding']['B'] + $table['border_details']['B']['w'] + $table['border_spacing_V']/2; + } else { + $extra = $table['border_spacing_V'] / 2; + } + } else { + $extra = $table['max_cell_border_width']['B'] / 2; + } + + if ($j == $startcol && ((($y + $maxrowheight + $extra ) > ($pagetrigger + 0.001)) || (($this->keepColumns || !$this->ColActive) && !empty($tablefooter) && ($y + $maxrowheight + $tablefooterrowheight + $extra) > $pagetrigger) && ($this->tableLevel == 1 && $i < ($numrows - $table['headernrows']))) && ($y0 > 0 || $x0 > 0) && !$this->InFooter && $this->autoPageBreak) { + if (!$skippage) { + $finalSpread = true; + $firstSpread = true; + if ($split) { + for ($t = $startcol; $t < $numcols; $t++) { + // Are there more columns to print on a next page? + if ($table['colPg'][$t] > $splitpg) { + $finalSpread = false; + break; + } + } + if ($startcol > 0) { + $firstSpread = false; + } + } + + if (($this->keepColumns || !$this->ColActive) && !empty($tablefooter) && $i > 0) { + $this->y = $y; + $ya = $this->y; + $this->TableHeaderFooter($tablefooter, $tablestartpage, $tablestartcolumn, 'F', $level, $firstSpread, $finalSpread); + if ($this->table_rotate) { + $this->tbrot_h += $this->y - $ya; + } + $tablefooteradj = $this->y - $ya; + } + $y -= $y0; + $returny += $y; + + $oldcolumn = $this->CurrCol; + if ($this->AcceptPageBreak()) { + $newpagestarted = true; + $this->y = $y + $y0; + + // Move down to account for border-spacing or + // extra half border width in case page breaks in middle + if ($i > 0 && !$this->table_rotate && $level == 1 && !$this->ColActive) { + if ($table['borders_separate']) { + $adv = $table['border_spacing_V'] / 2; + // If table footer + if (($this->keepColumns || !$this->ColActive) && !empty($tablefooter) && $i > 0) { + $adv += ($table['padding']['B'] + $table['border_details']['B']['w']); + } + } else { + $maxbwtop = 0; + $maxbwbottom = 0; + if (!$this->simpleTables) { + if (!empty($tablefooter)) { + $maxbwbottom = $table['max_cell_border_width']['B']; + } else { + $brow = $i - 1; + for ($ctj = 0; $ctj < $numcols; $ctj++) { + if (isset($cells[$brow][$ctj]) && $cells[$brow][$ctj]) { + if ($this->packTableData) { + list($bt, $br, $bb, $bl) = $this->_getBorderWidths($cells[$brow][$ctj]['borderbin']); + } else { + $bb = $cells[$brow][$ctj]['border_details']['B']['w']; + } + $maxbwbottom = max($maxbwbottom, $bb); + } + } + } + if (!empty($tableheader)) { + $maxbwtop = $table['max_cell_border_width']['T']; + } else { + $trow = $i - 1; + for ($ctj = 0; $ctj < $numcols; $ctj++) { + if (isset($cells[$trow][$ctj]) && $cells[$trow][$ctj]) { + if ($this->packTableData) { + list($bt, $br, $bb, $bl) = $this->_getBorderWidths($cells[$trow][$ctj]['borderbin']); + } else { + $bt = $cells[$trow][$ctj]['border_details']['T']['w']; + } + $maxbwtop = max($maxbwtop, $bt); + } + } + } + } elseif ($this->simpleTables) { + $maxbwtop = $table['simple']['border_details']['T']['w']; + $maxbwbottom = $table['simple']['border_details']['B']['w']; + } + $adv = $maxbwbottom / 2; + } + $this->y += $adv; + } + + // Rotated table split over pages - needs this->y for borders/backgrounds + if ($i > 0 && $this->table_rotate && $level == 1) { + // $this->y = $y0 + $this->tbrot_w; + } + + if ($this->tableClipPath) { + $this->writer->write("Q"); + } + + $bx = $x0; + $by = $y0; + + if ($table['borders_separate']) { + $bx -= ($table['padding']['L'] + $table['border_details']['L']['w'] + $table['border_spacing_H'] / 2); + if ($tablestartpageno != $this->page) { // IF already broken across a previous pagebreak + $by += $table['max_cell_border_width']['T'] / 2; + if (empty($tableheader)) { + $by -= ($table['border_spacing_V'] / 2); + } + } else { + $by -= ($table['padding']['T'] + $table['border_details']['T']['w'] + $table['border_spacing_V'] / 2); + } + } elseif ($tablestartpageno != $this->page && !empty($tableheader)) { + $by += $maxbwtop / 2; + } + + $by -= $tableheaderadj; + $bh = $this->y - $by + $tablefooteradj; + if (!$table['borders_separate']) { + $bh -= $adv; + } + if ($split) { + $bw = 0; + for ($t = $startcol; $t < $numcols; $t++) { + if ($table['colPg'][$t] == $splitpg) { + $bw += $table['wc'][$t]; + } + if ($table['colPg'][$t] > $splitpg) { + break; + } + } + if ($table['borders_separate']) { + if ($firstSpread) { + $bw += $table['padding']['L'] + $table['border_details']['L']['w'] + $table['border_spacing_H']; + } else { + $bx += ($table['padding']['L'] + $table['border_details']['L']['w']); + $bw += $table['border_spacing_H']; + } + if ($finalSpread) { + $bw += $table['padding']['R'] + $table['border_details']['R']['w'] / 2 + $table['border_spacing_H']; + } + } + } else { + $bw = $table['w'] - ($table['max_cell_border_width']['L'] / 2) - ($table['max_cell_border_width']['R'] / 2) - $table['margin']['L'] - $table['margin']['R']; + } + + if ($this->splitTableBorderWidth && ($this->keepColumns || !$this->ColActive) && empty($tablefooter) && $i > 0 && $table['border_details']['B']['w']) { + $prevDrawColor = $this->DrawColor; + $lw = $this->LineWidth; + $this->SetLineWidth($this->splitTableBorderWidth); + $this->SetDColor($table['border_details']['B']['c']); + $this->SetLineJoin(0); + $this->SetLineCap(0); + $blx = $bx; + $blw = $bw; + if (!$table['borders_separate']) { + $blx -= ($table['max_cell_border_width']['L'] / 2); + $blw += ($table['max_cell_border_width']['L'] / 2 + $table['max_cell_border_width']['R'] / 2); + } + $this->Line($blx, $this->y + ($this->splitTableBorderWidth / 2), $blx + $blw, $this->y + ($this->splitTableBorderWidth / 2)); + $this->DrawColor = $prevDrawColor; + $this->writer->write($this->DrawColor); + $this->SetLineWidth($lw); + $this->SetLineJoin(2); + $this->SetLineCap(2); + } + + if (!$this->ColActive && ($i > 0 || $j > 0)) { + if (isset($table['bgcolor'][-1])) { + $color = $this->colorConverter->convert($table['bgcolor'][-1], $this->PDFAXwarnings); + if ($color) { + if (!$table['borders_separate']) { + $bh -= $table['max_cell_border_width']['B'] / 2; + } + $this->tableBackgrounds[$level * 9][] = ['gradient' => false, 'x' => $bx, 'y' => $by, 'w' => $bw, 'h' => $bh, 'col' => $color]; + } + } + + /* -- BACKGROUNDS -- */ + if (isset($table['gradient'])) { + $g = $this->gradient->parseBackgroundGradient($table['gradient']); + if ($g) { + $this->tableBackgrounds[$level * 9 + 1][] = ['gradient' => true, 'x' => $bx, 'y' => $by, 'w' => $bw, 'h' => $bh, 'gradtype' => $g['type'], 'stops' => $g['stops'], 'colorspace' => $g['colorspace'], 'coords' => $g['coords'], 'extend' => $g['extend'], 'clippath' => '']; + } + } + + if (isset($table['background-image'])) { + if ($table['background-image']['gradient'] && preg_match('/(-moz-)*(repeating-)*(linear|radial)-gradient/', $table['background-image']['gradient'])) { + $g = $this->gradient->parseMozGradient($table['background-image']['gradient']); + if ($g) { + $this->tableBackgrounds[$level * 9 + 1][] = ['gradient' => true, 'x' => $bx, 'y' => $by, 'w' => $bw, 'h' => $bh, 'gradtype' => $g['type'], 'stops' => $g['stops'], 'colorspace' => $g['colorspace'], 'coords' => $g['coords'], 'extend' => $g['extend'], 'clippath' => '']; + } + } else { + $image_id = $table['background-image']['image_id']; + $orig_w = $table['background-image']['orig_w']; + $orig_h = $table['background-image']['orig_h']; + $x_pos = $table['background-image']['x_pos']; + $y_pos = $table['background-image']['y_pos']; + $x_repeat = $table['background-image']['x_repeat']; + $y_repeat = $table['background-image']['y_repeat']; + $resize = $table['background-image']['resize']; + $opacity = $table['background-image']['opacity']; + $itype = $table['background-image']['itype']; + $this->tableBackgrounds[$level * 9 + 2][] = ['x' => $bx, 'y' => $by, 'w' => $bw, 'h' => $bh, 'image_id' => $image_id, 'orig_w' => $orig_w, 'orig_h' => $orig_h, 'x_pos' => $x_pos, 'y_pos' => $y_pos, 'x_repeat' => $x_repeat, 'y_repeat' => $y_repeat, 'clippath' => '', 'resize' => $resize, 'opacity' => $opacity, 'itype' => $itype]; + } + } + /* -- END BACKGROUNDS -- */ + } + + // $this->AcceptPageBreak() has moved tablebuffer to $this->pages content + if ($this->tableBackgrounds) { + $s = $this->PrintTableBackgrounds(); + if ($this->bufferoutput) { + $this->headerbuffer = preg_replace('/(___TABLE___BACKGROUNDS' . $this->uniqstr . ')/', '\\1' . "\n" . $s . "\n", $this->headerbuffer); + $this->headerbuffer = preg_replace('/(___TABLE___BACKGROUNDS' . $this->uniqstr . ')/', " ", $this->headerbuffer); + } else { + $this->pages[$this->page] = preg_replace('/(___TABLE___BACKGROUNDS' . $this->uniqstr . ')/', '\\1' . "\n" . $s . "\n", $this->pages[$this->page]); + $this->pages[$this->page] = preg_replace('/(___TABLE___BACKGROUNDS' . $this->uniqstr . ')/', " ", $this->pages[$this->page]); + } + $this->tableBackgrounds = []; + } + + if ($split) { + if ($i == 0 && $j == 0) { + $y0 = -1; + } elseif ($finalSpread) { + $splitpg = 0; + $startcol = 0; + $startrow = $i; + } else { + $splitpg++; + $startcol = $t; + $returny -= $y; + } + return [false, $startrow, $startcol, $splitpg, $returny, $y0]; + } + + $this->AddPage($this->CurOrientation); + + $this->writer->write('___TABLE___BACKGROUNDS' . $this->uniqstr); + + + if ($this->tableClipPath) { + $this->writer->write($this->tableClipPath); + } + + // Added to correct for OddEven Margins + $x = $x + $this->MarginCorrection; + $x0 = $x0 + $this->MarginCorrection; + + if ($this->splitTableBorderWidth && ($this->keepColumns || !$this->ColActive) && empty($tableheader) && $i > 0 && $table['border_details']['T']['w']) { + $prevDrawColor = $this->DrawColor; + $lw = $this->LineWidth; + $this->SetLineWidth($this->splitTableBorderWidth); + $this->SetDColor($table['border_details']['T']['c']); + $this->SetLineJoin(0); + $this->SetLineCap(0); + $blx += $this->MarginCorrection; + $this->Line($blx, $this->y - ($this->splitTableBorderWidth / 2), $blx + $blw, $this->y - ($this->splitTableBorderWidth / 2)); + $this->DrawColor = $prevDrawColor; + $this->writer->write($this->DrawColor); + $this->SetLineWidth($lw); + $this->SetLineJoin(2); + $this->SetLineCap(2); + } + + // Move down to account for half of top border-spacing or + // extra half border width in case page was broken in middle + if ($i > 0 && !$this->table_rotate && $level == 1 && $table['headernrows'] == 0) { + if ($table['borders_separate']) { + $adv = $table['border_spacing_V'] / 2; + } else { + $maxbwtop = 0; + for ($ctj = 0; $ctj < $numcols; $ctj++) { + if (isset($cells[$i][$ctj]) && $cells[$i][$ctj]) { + if (!$this->simpleTables) { + if ($this->packTableData) { + list($bt, $br, $bb, $bl) = $this->_getBorderWidths($cells[$i][$ctj]['borderbin']); + } else { + $bt = $cells[$i][$ctj]['border_details']['T']['w']; + } + $maxbwtop = max($maxbwtop, $bt); + } elseif ($this->simpleTables) { + $maxbwtop = max($maxbwtop, $table['simple']['border_details']['T']['w']); + } + } + } + $adv = $maxbwtop / 2; + } + $this->y += $adv; + } + + + if ($this->table_rotate) { + $this->tbrot_x0 = $this->lMargin + $this->blk[$this->blklvl]['outer_left_margin'] + $this->blk[$this->blklvl]['padding_left'] + $this->blk[$this->blklvl]['border_left']['w']; + if ($table['borders_separate']) { + $this->tbrot_h = $table['margin']['T'] + $table['padding']['T'] + $table['border_details']['T']['w'] + $table['border_spacing_V'] / 2; + } else { + $this->tbrot_h = $table['margin']['T'] + $table['max_cell_border_width']['T']; + } + $this->tbrot_y0 = $this->y; + $pagetrigger = $y0 - $tableheaderadj + ($this->blk[$this->blklvl]['inner_width']); + } else { + $pagetrigger = $this->PageBreakTrigger; + } + + if ($this->kwt_saved && $level == 1) { + $this->kwt_moved = true; + } + + + if (!empty($tableheader)) { + $ya = $this->y; + $this->TableHeaderFooter($tableheader, $tablestartpage, $tablestartcolumn, 'H', $level); + if ($this->table_rotate) { + $this->tbrot_h = $this->y - $ya; + } + $tableheaderadj = $this->y - $ya; + } elseif ($i == 0 && !$this->table_rotate && $level == 1 && !$this->ColActive) { + // Advance down page + if ($table['borders_separate']) { + $adv = $table['border_spacing_V'] / 2 + $table['border_details']['T']['w'] + $table['padding']['T']; + } else { + $adv = $table['max_cell_border_width']['T'] / 2; + } + if ($adv) { + if ($this->table_rotate) { + $this->y += ($adv); + } else { + $this->DivLn($adv, $this->blklvl, true); + } + } + } + + $outerfilled = 0; + $y = $y0 = $this->y; + } + + /* -- COLUMNS -- */ + // COLS + // COLUMN CHANGE + if ($this->CurrCol != $oldcolumn) { + // Added to correct for Columns + $x += $this->ChangeColumn * ($this->ColWidth + $this->ColGap); + $x0 += $this->ChangeColumn * ($this->ColWidth + $this->ColGap); + if ($this->CurrCol == 0) { // just added a page - possibly with tableheader + $y0 = $this->y; // this->y0 is global used by Columns - $y0 is internal to tablewrite + } else { + $y0 = $this->y0; // this->y0 is global used by Columns - $y0 is internal to tablewrite + } + $y = $y0; + $outerfilled = 0; + if ($this->CurrCol != 0 && ($this->keepColumns && $this->ColActive) && !empty($tableheader) && $i > 0) { + $this->x = $x; + $this->y = $y; + $this->TableHeaderFooter($tableheader, $tablestartpage, $tablestartcolumn, 'H', $level); + $y0 = $y = $this->y; + } + } + /* -- END COLUMNS -- */ + } + $skippage = true; + } + + $this->x = $x; + $this->y = $y; + + if ($this->kwt_saved && $level == 1) { + $this->printkwtbuffer(); + $x0 = $x = $this->x; + $y0 = $y = $this->y; + $this->kwt_moved = false; + $this->kwt_saved = false; + } + + + // Set the Page & Column where table actually starts + if ($i == 0 && $j == 0 && $level == 1) { + if (($this->mirrorMargins) && (($this->page) % 2 == 0)) { // EVEN + $tablestartpage = 'EVEN'; + } elseif (($this->mirrorMargins) && (($this->page) % 2 == 1)) { // ODD + $tablestartpage = 'ODD'; + } else { + $tablestartpage = ''; + } + $tablestartpageno = $this->page; + if ($this->ColActive) { + $tablestartcolumn = $this->CurrCol; + } // *COLUMNS* + } + + // ALIGN + $align = $cell['a']; + + /* -- COLUMNS -- */ + // If outside columns, this is done in PaintDivBB + if ($this->ColActive) { + // OUTER FILL BGCOLOR of DIVS + if ($this->blklvl > 0 && ($j == 0) && !$this->table_rotate && $level == 1) { + $firstblockfill = $this->GetFirstBlockFill(); + if ($firstblockfill && $this->blklvl >= $firstblockfill) { + $divh = $maxrowheight; + // Last row + if ((!isset($cell['rowspan']) && $i == $numrows - 1) || (isset($cell['rowspan']) && (($i == $numrows - 1 && $cell['rowspan'] < 2) || ($cell['rowspan'] > 1 && ($i + $cell['rowspan'] - 1) == $numrows - 1)))) { + if ($table['borders_separate']) { + $adv = $table['margin']['B'] + $table['padding']['B'] + $table['border_details']['B']['w'] + $table['border_spacing_V'] / 2; + } else { + $adv = $table['margin']['B'] + $table['max_cell_border_width']['B'] / 2; + } + $divh += $adv; // last row: fill bottom half of bottom border (y advanced at end) + } + + if (($this->y + $divh) > $outerfilled) { // if not already painted by previous rowspan + $bak_x = $this->x; + $bak_y = $this->y; + if ($outerfilled > $this->y) { + $divh = ($this->y + $divh) - $outerfilled; + $this->y = $outerfilled; + } + + $this->DivLn($divh, -3, false); + $outerfilled = $this->y + $divh; + // Reset current block fill + $bcor = $this->blk[$this->blklvl]['bgcolorarray']; + if ($bcor) { + $this->SetFColor($bcor); + } + $this->x = $bak_x; + $this->y = $bak_y; + } + } + } + } + + // TABLE BACKGROUND FILL BGCOLOR - for cellSpacing + if ($this->ColActive) { + if ($table['borders_separate']) { + $fill = isset($table['bgcolor'][-1]) ? $table['bgcolor'][-1] : 0; + if ($fill) { + $color = $this->colorConverter->convert($fill, $this->PDFAXwarnings); + if ($color) { + $xadj = ($table['border_spacing_H'] / 2); + $yadj = ($table['border_spacing_V'] / 2); + $wadj = $table['border_spacing_H']; + $hadj = $table['border_spacing_V']; + if ($i == 0) { // Top + $yadj += $table['padding']['T'] + $table['border_details']['T']['w']; + $hadj += $table['padding']['T'] + $table['border_details']['T']['w']; + } + if ($j == 0) { // Left + $xadj += $table['padding']['L'] + $table['border_details']['L']['w']; + $wadj += $table['padding']['L'] + $table['border_details']['L']['w']; + } + if ($i == ($numrows - 1) || (isset($cell['rowspan']) && ($i + $cell['rowspan']) == $numrows) || (!isset($cell['rowspan']) && ($i + 1) == $numrows)) { // Bottom + $hadj += $table['padding']['B'] + $table['border_details']['B']['w']; + } + if ($j == ($numcols - 1) || (isset($cell['colspan']) && ($j + $cell['colspan']) == $numcols) || (!isset($cell['colspan']) && ($j + 1) == $numcols)) { // Right + $wadj += $table['padding']['R'] + $table['border_details']['R']['w']; + } + $this->SetFColor($color); + $this->Rect($x - $xadj, $y - $yadj, $w + $wadj, $h + $hadj, 'F'); + } + } + } + } + /* -- END COLUMNS -- */ + + if ($table['empty_cells'] != 'hide' || !empty($cell['textbuffer']) || (isset($cell['nestedcontent']) && $cell['nestedcontent']) || !$table['borders_separate']) { + $paintcell = true; + } else { + $paintcell = false; + } + + // Set Borders + $bord = 0; + $bord_det = []; + + if (!$this->simpleTables) { + if ($this->packTableData) { + $c = $this->_unpackCellBorder($cell['borderbin']); + $bord = $c['border']; + $bord_det = $c['border_details']; + } else { + $bord = $cell['border']; + $bord_det = $cell['border_details']; + } + } elseif ($this->simpleTables) { + $bord = $table['simple']['border']; + $bord_det = $table['simple']['border_details']; + } + + // TABLE ROW OR CELL FILL BGCOLOR + $fill = 0; + if (isset($cell['bgcolor']) && $cell['bgcolor'] && $cell['bgcolor'] != 'transparent') { + $fill = $cell['bgcolor']; + $leveladj = 6; + } elseif (isset($table['bgcolor'][$i]) && $table['bgcolor'][$i] && $table['bgcolor'][$i] != 'transparent') { // Row color + $fill = $table['bgcolor'][$i]; + $leveladj = 3; + } + if ($fill && $paintcell) { + $color = $this->colorConverter->convert($fill, $this->PDFAXwarnings); + if ($color) { + if ($table['borders_separate']) { + if ($this->ColActive) { + $this->SetFColor($color); + $this->Rect($x + ($table['border_spacing_H'] / 2), $y + ($table['border_spacing_V'] / 2), $w - $table['border_spacing_H'], $h - $table['border_spacing_V'], 'F'); + } else { + $this->tableBackgrounds[$level * 9 + $leveladj][] = ['gradient' => false, 'x' => ($x + ($table['border_spacing_H'] / 2)), 'y' => ($y + ($table['border_spacing_V'] / 2)), 'w' => ($w - $table['border_spacing_H']), 'h' => ($h - $table['border_spacing_V']), 'col' => $color]; + } + } else { + if ($this->ColActive) { + $this->SetFColor($color); + $this->Rect($x, $y, $w, $h, 'F'); + } else { + $this->tableBackgrounds[$level * 9 + $leveladj][] = ['gradient' => false, 'x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'col' => $color]; + } + } + } + } + + /* -- BACKGROUNDS -- */ + if (isset($cell['gradient']) && $cell['gradient'] && $paintcell) { + $g = $this->gradient->parseBackgroundGradient($cell['gradient']); + if ($g) { + if ($table['borders_separate']) { + $px = $x + ($table['border_spacing_H'] / 2); + $py = $y + ($table['border_spacing_V'] / 2); + $pw = $w - $table['border_spacing_H']; + $ph = $h - $table['border_spacing_V']; + } else { + $px = $x; + $py = $y; + $pw = $w; + $ph = $h; + } + if ($this->ColActive) { + $this->gradient->Gradient($px, $py, $pw, $ph, $g['type'], $g['stops'], $g['colorspace'], $g['coords'], $g['extend']); + } else { + $this->tableBackgrounds[$level * 9 + 7][] = ['gradient' => true, 'x' => $px, 'y' => $py, 'w' => $pw, 'h' => $ph, 'gradtype' => $g['type'], 'stops' => $g['stops'], 'colorspace' => $g['colorspace'], 'coords' => $g['coords'], 'extend' => $g['extend'], 'clippath' => '']; + } + } + } + + if (isset($cell['background-image']) && $paintcell) { + if (isset($cell['background-image']['gradient']) && $cell['background-image']['gradient'] && preg_match('/(-moz-)*(repeating-)*(linear|radial)-gradient/', $cell['background-image']['gradient'])) { + $g = $this->gradient->parseMozGradient($cell['background-image']['gradient']); + if ($g) { + if ($table['borders_separate']) { + $px = $x + ($table['border_spacing_H'] / 2); + $py = $y + ($table['border_spacing_V'] / 2); + $pw = $w - $table['border_spacing_H']; + $ph = $h - $table['border_spacing_V']; + } else { + $px = $x; + $py = $y; + $pw = $w; + $ph = $h; + } + if ($this->ColActive) { + $this->gradient->Gradient($px, $py, $pw, $ph, $g['type'], $g['stops'], $g['colorspace'], $g['coords'], $g['extend']); + } else { + $this->tableBackgrounds[$level * 9 + 7][] = ['gradient' => true, 'x' => $px, 'y' => $py, 'w' => $pw, 'h' => $ph, 'gradtype' => $g['type'], 'stops' => $g['stops'], 'colorspace' => $g['colorspace'], 'coords' => $g['coords'], 'extend' => $g['extend'], 'clippath' => '']; + } + } + } elseif (isset($cell['background-image']['image_id']) && $cell['background-image']['image_id']) { // Background pattern + $n = count($this->patterns) + 1; + if ($table['borders_separate']) { + $px = $x + ($table['border_spacing_H'] / 2); + $py = $y + ($table['border_spacing_V'] / 2); + $pw = $w - $table['border_spacing_H']; + $ph = $h - $table['border_spacing_V']; + } else { + $px = $x; + $py = $y; + $pw = $w; + $ph = $h; + } + if ($this->ColActive) { + list($orig_w, $orig_h, $x_repeat, $y_repeat) = $this->_resizeBackgroundImage($cell['background-image']['orig_w'], $cell['background-image']['orig_h'], $pw, $ph, $cell['background-image']['resize'], $cell['background-image']['x_repeat'], $cell['background-image']['y_repeat']); + $this->patterns[$n] = ['x' => $px, 'y' => $py, 'w' => $pw, 'h' => $ph, 'pgh' => $this->h, 'image_id' => $cell['background-image']['image_id'], 'orig_w' => $orig_w, 'orig_h' => $orig_h, 'x_pos' => $cell['background-image']['x_pos'], 'y_pos' => $cell['background-image']['y_pos'], 'x_repeat' => $x_repeat, 'y_repeat' => $y_repeat]; + if ($cell['background-image']['opacity'] > 0 && $cell['background-image']['opacity'] < 1) { + $opac = $this->SetAlpha($cell['background-image']['opacity'], 'Normal', true); + } else { + $opac = ''; + } + $this->writer->write(sprintf('q /Pattern cs /P%d scn %s %.3F %.3F %.3F %.3F re f Q', $n, $opac, $px * Mpdf::SCALE, ($this->h - $py) * Mpdf::SCALE, $pw * Mpdf::SCALE, -$ph * Mpdf::SCALE)); + } else { + $image_id = $cell['background-image']['image_id']; + $orig_w = $cell['background-image']['orig_w']; + $orig_h = $cell['background-image']['orig_h']; + $x_pos = $cell['background-image']['x_pos']; + $y_pos = $cell['background-image']['y_pos']; + $x_repeat = $cell['background-image']['x_repeat']; + $y_repeat = $cell['background-image']['y_repeat']; + $resize = $cell['background-image']['resize']; + $opacity = $cell['background-image']['opacity']; + $itype = $cell['background-image']['itype']; + $this->tableBackgrounds[$level * 9 + 8][] = ['x' => $px, 'y' => $py, 'w' => $pw, 'h' => $ph, 'image_id' => $image_id, 'orig_w' => $orig_w, 'orig_h' => $orig_h, 'x_pos' => $x_pos, 'y_pos' => $y_pos, 'x_repeat' => $x_repeat, 'y_repeat' => $y_repeat, 'clippath' => '', 'resize' => $resize, 'opacity' => $opacity, 'itype' => $itype]; + } + } + } + /* -- END BACKGROUNDS -- */ + + if (isset($cell['colspan']) && $cell['colspan'] > 1) { + $ccolsp = $cell['colspan']; + } else { + $ccolsp = 1; + } + if (isset($cell['rowspan']) && $cell['rowspan'] > 1) { + $crowsp = $cell['rowspan']; + } else { + $crowsp = 1; + } + + + // but still need to do this for repeated headers... + if (!$table['borders_separate'] && $this->tabletheadjustfinished && !$this->simpleTables) { + if (isset($table['topntail']) && $table['topntail']) { + $bord_det['T'] = $this->border_details($table['topntail']); + $bord_det['T']['w'] /= $this->shrin_k; + $this->setBorder($bord, Border::TOP); + } + if (isset($table['thead-underline']) && $table['thead-underline']) { + $bord_det['T'] = $this->border_details($table['thead-underline']); + $bord_det['T']['w'] /= $this->shrin_k; + $this->setBorder($bord, Border::TOP); + } + } + + + // Get info of first row ==>> table header + // Use > 1 row if THEAD + if (isset($table['is_thead'][$i]) && $table['is_thead'][$i] && $level == 1) { + if ($j == 0) { + $tableheaderrowheight += $table['hr'][$i]; + } + $tableheader[$i][0]['trbackground-images'] = (isset($table['trbackground-images'][$i]) ? $table['trbackground-images'][$i] : null); + $tableheader[$i][0]['trgradients'] = (isset($table['trgradients'][$i]) ? $table['trgradients'][$i] : null); + $tableheader[$i][0]['trbgcolor'] = (isset($table['bgcolor'][$i]) ? $table['bgcolor'][$i] : null); + $tableheader[$i][$j]['x'] = $x; + $tableheader[$i][$j]['y'] = $y; + $tableheader[$i][$j]['h'] = $h; + $tableheader[$i][$j]['w'] = $w; + if (isset($cell['textbuffer'])) { + $tableheader[$i][$j]['textbuffer'] = $cell['textbuffer']; + } else { + $tableheader[$i][$j]['textbuffer'] = ''; + } + $tableheader[$i][$j]['a'] = $cell['a']; + $tableheader[$i][$j]['R'] = $cell['R']; + + $tableheader[$i][$j]['va'] = $cell['va']; + $tableheader[$i][$j]['mih'] = $cell['mih']; + $tableheader[$i][$j]['gradient'] = (isset($cell['gradient']) ? $cell['gradient'] : null); // *BACKGROUNDS* + $tableheader[$i][$j]['background-image'] = (isset($cell['background-image']) ? $cell['background-image'] : null); // *BACKGROUNDS* + $tableheader[$i][$j]['rowspan'] = (isset($cell['rowspan']) ? $cell['rowspan'] : null); + $tableheader[$i][$j]['colspan'] = (isset($cell['colspan']) ? $cell['colspan'] : null); + $tableheader[$i][$j]['bgcolor'] = $cell['bgcolor']; + + if (!$this->simpleTables) { + $tableheader[$i][$j]['border'] = $bord; + $tableheader[$i][$j]['border_details'] = $bord_det; + } elseif ($this->simpleTables) { + $tableheader[$i][$j]['border'] = $table['simple']['border']; + $tableheader[$i][$j]['border_details'] = $table['simple']['border_details']; + } + $tableheader[$i][$j]['padding'] = $cell['padding']; + if (isset($cell['direction'])) { + $tableheader[$i][$j]['direction'] = $cell['direction']; + } + if (isset($cell['cellLineHeight'])) { + $tableheader[$i][$j]['cellLineHeight'] = $cell['cellLineHeight']; + } + if (isset($cell['cellLineStackingStrategy'])) { + $tableheader[$i][$j]['cellLineStackingStrategy'] = $cell['cellLineStackingStrategy']; + } + if (isset($cell['cellLineStackingShift'])) { + $tableheader[$i][$j]['cellLineStackingShift'] = $cell['cellLineStackingShift']; + } + } + + // CELL BORDER + if ($bord) { + if ($table['borders_separate'] && $paintcell) { + $this->_tableRect($x + ($table['border_spacing_H'] / 2) + ($bord_det['L']['w'] / 2), $y + ($table['border_spacing_V'] / 2) + ($bord_det['T']['w'] / 2), $w - $table['border_spacing_H'] - ($bord_det['L']['w'] / 2) - ($bord_det['R']['w'] / 2), $h - $table['border_spacing_V'] - ($bord_det['T']['w'] / 2) - ($bord_det['B']['w'] / 2), $bord, $bord_det, false, $table['borders_separate']); + } elseif (!$table['borders_separate']) { + $this->_tableRect($x, $y, $w, $h, $bord, $bord_det, true, $table['borders_separate']); // true causes buffer + } + } + + // VERTICAL ALIGN + if ($cell['R'] && intval($cell['R']) > 0 && intval($cell['R']) < 90 && isset($cell['va']) && $cell['va'] != 'B') { + $cell['va'] = 'B'; + } + if (!isset($cell['va']) || $cell['va'] == 'M') { + $this->y += ($h - $cell['mih']) / 2; + } elseif (isset($cell['va']) && $cell['va'] == 'B') { + $this->y += $h - $cell['mih']; + } + + // NESTED CONTENT + // TEXT (and nested tables) + + $this->divwidth = $w; + if (!empty($cell['textbuffer'])) { + $this->cellTextAlign = $align; + $this->cellLineHeight = $cell['cellLineHeight']; + $this->cellLineStackingStrategy = $cell['cellLineStackingStrategy']; + $this->cellLineStackingShift = $cell['cellLineStackingShift']; + if ($level == 1) { + if (isset($table['is_tfoot'][$i]) && $table['is_tfoot'][$i]) { + if (preg_match('/{colsum([0-9]*)[_]*}/', $cell['textbuffer'][0][0], $m)) { + $rep = sprintf("%01." . intval($m[1]) . "f", $this->colsums[$j]); + $cell['textbuffer'][0][0] = preg_replace('/{colsum[0-9_]*}/', $rep, $cell['textbuffer'][0][0]); + } + } elseif (!isset($table['is_thead'][$i])) { + if (isset($this->colsums[$j])) { + $this->colsums[$j] += $this->toFloat($cell['textbuffer'][0][0]); + } else { + $this->colsums[$j] = $this->toFloat($cell['textbuffer'][0][0]); + } + } + } + $opy = $this->y; + // mPDF ITERATION + if ($this->iterationCounter) { + foreach ($cell['textbuffer'] as $k => $t) { + if (preg_match('/{iteration ([a-zA-Z0-9_]+)}/', $t[0], $m)) { + $vname = '__' . $m[1] . '_'; + if (!isset($this->$vname)) { + $this->$vname = 1; + } else { + $this->$vname++; + } + $cell['textbuffer'][$k][0] = preg_replace('/{iteration ' . $m[1] . '}/', $this->$vname, $cell['textbuffer'][$k][0]); + } + } + } + + + if ($cell['R']) { + $cellPtSize = $cell['textbuffer'][0][11] / $this->shrin_k; + if (!$cellPtSize) { + $cellPtSize = $this->default_font_size; + } + $cellFontHeight = ($cellPtSize / Mpdf::SCALE); + $opx = $this->x; + $angle = intval($cell['R']); + // Only allow 45 to 89 degrees (when bottom-aligned) or exactly 90 or -90 + if ($angle > 90) { + $angle = 90; + } elseif ($angle > 0 && $angle < 45) { + $angle = 45; + } elseif ($angle < 0) { + $angle = -90; + } + $offset = ((sin(deg2rad($angle))) * 0.37 * $cellFontHeight); + if (isset($cell['a']) && $cell['a'] == 'R') { + $this->x += ($w) + ($offset) - ($cellFontHeight / 3) - ($cell['padding']['R'] + ($table['border_spacing_H'] / 2)); + } elseif (!isset($cell['a']) || $cell['a'] == 'C') { + $this->x += ($w / 2) + ($offset); + } else { + $this->x += ($offset) + ($cellFontHeight / 3) + ($cell['padding']['L'] + ($table['border_spacing_H'] / 2)); + } + $str = ''; + foreach ($cell['textbuffer'] as $t) { + $str .= $t[0] . ' '; + } + $str = rtrim($str); + if (!isset($cell['va']) || $cell['va'] == 'M') { + $this->y -= ($h - $cell['mih']) / 2; // Undo what was added earlier VERTICAL ALIGN + if ($angle > 0) { + $this->y += (($h - $cell['mih']) / 2) + $cell['padding']['T'] + ($cell['mih'] - ($cell['padding']['T'] + $cell['padding']['B'])); + } elseif ($angle < 0) { + $this->y += (($h - $cell['mih']) / 2) + ($cell['padding']['T'] + ($table['border_spacing_V'] / 2)); + } + } elseif (isset($cell['va']) && $cell['va'] == 'B') { + $this->y -= $h - $cell['mih']; // Undo what was added earlier VERTICAL ALIGN + if ($angle > 0) { + $this->y += $h - ($cell['padding']['B'] + ($table['border_spacing_V'] / 2)); + } elseif ($angle < 0) { + $this->y += $h - $cell['mih'] + ($cell['padding']['T'] + ($table['border_spacing_V'] / 2)); + } + } elseif (isset($cell['va']) && $cell['va'] == 'T') { + if ($angle > 0) { + $this->y += $cell['mih'] - ($cell['padding']['B'] + ($table['border_spacing_V'] / 2)); + } elseif ($angle < 0) { + $this->y += ($cell['padding']['T'] + ($table['border_spacing_V'] / 2)); + } + } + $this->Rotate($angle, $this->x, $this->y); + $s_fs = $this->FontSizePt; + $s_f = $this->FontFamily; + $s_st = $this->FontStyle; + if (!empty($cell['textbuffer'][0][3])) { // Font Color + $cor = $cell['textbuffer'][0][3]; + $this->SetTColor($cor); + } + $this->SetFont($cell['textbuffer'][0][4], $cell['textbuffer'][0][2], $cellPtSize, true, true); + + $this->magic_reverse_dir($str, $this->directionality, $cell['textbuffer'][0][18]); + $this->Text($this->x, $this->y, $str, $cell['textbuffer'][0][18], $cell['textbuffer'][0][8]); // textvar + $this->Rotate(0); + $this->SetFont($s_f, $s_st, $s_fs, true, true); + $this->SetTColor(0); + $this->x = $opx; + } else { + if (!$this->simpleTables) { + if ($bord_det) { + $btlw = $bord_det['L']['w']; + $btrw = $bord_det['R']['w']; + $bttw = $bord_det['T']['w']; + } else { + $btlw = 0; + $btrw = 0; + $bttw = 0; + } + if ($table['borders_separate']) { + $xadj = $btlw + $cell['padding']['L'] + ($table['border_spacing_H'] / 2); + $wadj = $btlw + $btrw + $cell['padding']['L'] + $cell['padding']['R'] + $table['border_spacing_H']; + $yadj = $bttw + $cell['padding']['T'] + ($table['border_spacing_H'] / 2); + } else { + $xadj = $btlw / 2 + $cell['padding']['L']; + $wadj = ($btlw + $btrw) / 2 + $cell['padding']['L'] + $cell['padding']['R']; + $yadj = $bttw / 2 + $cell['padding']['T']; + } + } elseif ($this->simpleTables) { + if ($table['borders_separate']) { // NB twice border width + $xadj = $table['simple']['border_details']['L']['w'] + $cell['padding']['L'] + ($table['border_spacing_H'] / 2); + $wadj = $table['simple']['border_details']['L']['w'] + $table['simple']['border_details']['R']['w'] + $cell['padding']['L'] + $cell['padding']['R'] + $table['border_spacing_H']; + $yadj = $table['simple']['border_details']['T']['w'] + $cell['padding']['T'] + ($table['border_spacing_H'] / 2); + } else { + $xadj = $table['simple']['border_details']['L']['w'] / 2 + $cell['padding']['L']; + $wadj = ($table['simple']['border_details']['L']['w'] + $table['simple']['border_details']['R']['w']) / 2 + $cell['padding']['L'] + $cell['padding']['R']; + $yadj = $table['simple']['border_details']['T']['w'] / 2 + $cell['padding']['T']; + } + } + $this->decimal_offset = 0; + if (substr($cell['a'], 0, 1) == 'D') { + if (isset($cell['colspan']) && $cell['colspan'] > 1) { + $this->cellTextAlign = $c['a'] = substr($cell['a'], 2, 1); + } else { + $smax = $table['decimal_align'][$j]['maxs0']; + $d_content = $table['decimal_align'][$j]['maxs0'] + $table['decimal_align'][$j]['maxs1']; + $this->decimal_offset = $smax; + $extra = ($w - $d_content - $wadj); + if ($extra > 0) { + if (substr($cell['a'], 2, 1) == 'R') { + $this->decimal_offset += $extra; + } elseif (substr($cell['a'], 2, 1) == 'C') { + $this->decimal_offset += ($extra) / 2; + } + } + } + } + $this->divwidth = $w - $wadj; + if ($this->divwidth == 0) { + $this->divwidth = 0.0001; + } + $this->x += $xadj; + $this->y += $yadj; + $this->printbuffer($cell['textbuffer'], '', true, false, $cell['direction']); + } + $this->y = $opy; + } + + /* -- BACKGROUNDS -- */ + if (!$this->ColActive) { + if (isset($table['trgradients'][$i]) && ($j == 0 || $table['borders_separate'])) { + $g = $this->gradient->parseBackgroundGradient($table['trgradients'][$i]); + if ($g) { + $gx = $x0; + $gy = $y; + $gh = $h; + $gw = $table['w'] - ($table['max_cell_border_width']['L'] / 2) - ($table['max_cell_border_width']['R'] / 2) - $table['margin']['L'] - $table['margin']['R']; + if ($table['borders_separate']) { + $gw -= ($table['padding']['L'] + $table['border_details']['L']['w'] + $table['padding']['R'] + $table['border_details']['R']['w'] + $table['border_spacing_H']); + $clx = $x + ($table['border_spacing_H'] / 2); + $cly = $y + ($table['border_spacing_V'] / 2); + $clw = $w - $table['border_spacing_H']; + $clh = $h - $table['border_spacing_V']; + // Set clipping path + $s = $this->_setClippingPath($clx, $cly, $clw, $clh); // mPDF 6 + $this->tableBackgrounds[$level * 9 + 4][] = ['gradient' => true, 'x' => $gx + ($table['border_spacing_H'] / 2), 'y' => $gy + ($table['border_spacing_V'] / 2), 'w' => $gw - $table['border_spacing_V'], 'h' => $gh - $table['border_spacing_H'], 'gradtype' => $g['type'], 'stops' => $g['stops'], 'colorspace' => $g['colorspace'], 'coords' => $g['coords'], 'extend' => $g['extend'], 'clippath' => $s]; + } else { + $this->tableBackgrounds[$level * 9 + 4][] = ['gradient' => true, 'x' => $gx, 'y' => $gy, 'w' => $gw, 'h' => $gh, 'gradtype' => $g['type'], 'stops' => $g['stops'], 'colorspace' => $g['colorspace'], 'coords' => $g['coords'], 'extend' => $g['extend'], 'clippath' => '']; + } + } + } + if (isset($table['trbackground-images'][$i]) && ($j == 0 || $table['borders_separate'])) { + if (isset($table['trbackground-images'][$i]['gradient']) && preg_match('/(-moz-)*(repeating-)*(linear|radial)-gradient/', $table['trbackground-images'][$i]['gradient'])) { + $g = $this->gradient->parseMozGradient($table['trbackground-images'][$i]['gradient']); + if ($g) { + $gx = $x0; + $gy = $y; + $gh = $h; + $gw = $table['w'] - ($table['max_cell_border_width']['L'] / 2) - ($table['max_cell_border_width']['R'] / 2) - $table['margin']['L'] - $table['margin']['R']; + if ($table['borders_separate']) { + $gw -= ($table['padding']['L'] + $table['border_details']['L']['w'] + $table['padding']['R'] + $table['border_details']['R']['w'] + $table['border_spacing_H']); + $clx = $x + ($table['border_spacing_H'] / 2); + $cly = $y + ($table['border_spacing_V'] / 2); + $clw = $w - $table['border_spacing_H']; + $clh = $h - $table['border_spacing_V']; + // Set clipping path + $s = $this->_setClippingPath($clx, $cly, $clw, $clh); // mPDF 6 + $this->tableBackgrounds[$level * 9 + 4][] = ['gradient' => true, 'x' => $gx + ($table['border_spacing_H'] / 2), 'y' => $gy + ($table['border_spacing_V'] / 2), 'w' => $gw - $table['border_spacing_V'], 'h' => $gh - $table['border_spacing_H'], 'gradtype' => $g['type'], 'stops' => $g['stops'], 'colorspace' => $g['colorspace'], 'coords' => $g['coords'], 'extend' => $g['extend'], 'clippath' => $s]; + } else { + $this->tableBackgrounds[$level * 9 + 4][] = ['gradient' => true, 'x' => $gx, 'y' => $gy, 'w' => $gw, 'h' => $gh, 'gradtype' => $g['type'], 'stops' => $g['stops'], 'colorspace' => $g['colorspace'], 'coords' => $g['coords'], 'extend' => $g['extend'], 'clippath' => '']; + } + } + } else { + $image_id = $table['trbackground-images'][$i]['image_id']; + $orig_w = $table['trbackground-images'][$i]['orig_w']; + $orig_h = $table['trbackground-images'][$i]['orig_h']; + $x_pos = $table['trbackground-images'][$i]['x_pos']; + $y_pos = $table['trbackground-images'][$i]['y_pos']; + $x_repeat = $table['trbackground-images'][$i]['x_repeat']; + $y_repeat = $table['trbackground-images'][$i]['y_repeat']; + $resize = $table['trbackground-images'][$i]['resize']; + $opacity = $table['trbackground-images'][$i]['opacity']; + $itype = $table['trbackground-images'][$i]['itype']; + $clippath = ''; + $gx = $x0; + $gy = $y; + $gh = $h; + $gw = $table['w'] - ($table['max_cell_border_width']['L'] / 2) - ($table['max_cell_border_width']['R'] / 2) - $table['margin']['L'] - $table['margin']['R']; + if ($table['borders_separate']) { + $gw -= ($table['padding']['L'] + $table['border_details']['L']['w'] + $table['padding']['R'] + $table['border_details']['R']['w'] + $table['border_spacing_H']); + $clx = $x + ($table['border_spacing_H'] / 2); + $cly = $y + ($table['border_spacing_V'] / 2); + $clw = $w - $table['border_spacing_H']; + $clh = $h - $table['border_spacing_V']; + // Set clipping path + $s = $this->_setClippingPath($clx, $cly, $clw, $clh); // mPDF 6 + $this->tableBackgrounds[$level * 9 + 5][] = ['x' => $gx + ($table['border_spacing_H'] / 2), 'y' => $gy + ($table['border_spacing_V'] / 2), 'w' => $gw - $table['border_spacing_V'], 'h' => $gh - $table['border_spacing_H'], 'image_id' => $image_id, 'orig_w' => $orig_w, 'orig_h' => $orig_h, 'x_pos' => $x_pos, 'y_pos' => $y_pos, 'x_repeat' => $x_repeat, 'y_repeat' => $y_repeat, 'clippath' => $s, 'resize' => $resize, 'opacity' => $opacity, 'itype' => $itype]; + } else { + $this->tableBackgrounds[$level * 9 + 5][] = ['x' => $gx, 'y' => $gy, 'w' => $gw, 'h' => $gh, 'image_id' => $image_id, 'orig_w' => $orig_w, 'orig_h' => $orig_h, 'x_pos' => $x_pos, 'y_pos' => $y_pos, 'x_repeat' => $x_repeat, 'y_repeat' => $y_repeat, 'clippath' => '', 'resize' => $resize, 'opacity' => $opacity, 'itype' => $itype]; + } + } + } + } + + /* -- END BACKGROUNDS -- */ + + // TABLE BORDER - if separate + if (($table['borders_separate'] || ($this->simpleTables && !$table['simple']['border'])) && $table['border']) { + $halfspaceL = $table['padding']['L'] + ($table['border_spacing_H'] / 2); + $halfspaceR = $table['padding']['R'] + ($table['border_spacing_H'] / 2); + $halfspaceT = $table['padding']['T'] + ($table['border_spacing_V'] / 2); + $halfspaceB = $table['padding']['B'] + ($table['border_spacing_V'] / 2); + $tbx = $x; + $tby = $y; + $tbw = $w; + $tbh = $h; + $tab_bord = 0; + + $corner = ''; + if ($i == 0) { // Top + $tby -= $halfspaceT + ($table['border_details']['T']['w'] / 2); + $tbh += $halfspaceT + ($table['border_details']['T']['w'] / 2); + $this->setBorder($tab_bord, Border::TOP); + $corner .= 'T'; + } + if ($i == ($numrows - 1) || (isset($cell['rowspan']) && ($i + $cell['rowspan']) == $numrows)) { // Bottom + $tbh += $halfspaceB + ($table['border_details']['B']['w'] / 2); + $this->setBorder($tab_bord, Border::BOTTOM); + $corner .= 'B'; + } + if ($j == 0) { // Left + $tbx -= $halfspaceL + ($table['border_details']['L']['w'] / 2); + $tbw += $halfspaceL + ($table['border_details']['L']['w'] / 2); + $this->setBorder($tab_bord, Border::LEFT); + $corner .= 'L'; + } + if ($j == ($numcols - 1) || (isset($cell['colspan']) && ($j + $cell['colspan']) == $numcols)) { // Right + $tbw += $halfspaceR + ($table['border_details']['R']['w'] / 2); + $this->setBorder($tab_bord, Border::RIGHT); + $corner .= 'R'; + } + $this->_tableRect($tbx, $tby, $tbw, $tbh, $tab_bord, $table['border_details'], false, $table['borders_separate'], 'table', $corner, $table['border_spacing_V'], $table['border_spacing_H']); + } + + unset($cell); + // Reset values + $this->Reset(); + }//end of (if isset(cells)...) + }// end of columns + + $newpagestarted = false; + $this->tabletheadjustfinished = false; + + /* -- COLUMNS -- */ + if ($this->ColActive) { + if (!$this->table_keep_together && $i < $numrows - 1 && $level == 1) { + $this->breakpoints[$this->CurrCol][] = $y + $h; + } // mPDF 6 + if (count($this->cellBorderBuffer)) { + $this->printcellbuffer(); + } + } + /* -- END COLUMNS -- */ + + if ($i == $numrows - 1) { + $this->y = $y + $h; + } // last row jump (update this->y position) + if ($this->table_rotate && $level == 1) { + $this->tbrot_h += $h; + } + } // end of rows + + if (count($this->cellBorderBuffer)) { + $this->printcellbuffer(); + } + + + if ($this->tableClipPath) { + $this->writer->write("Q"); + } + $this->tableClipPath = ''; + + // Advance down page by half width of bottom border + if ($table['borders_separate']) { + $this->y += $table['padding']['B'] + $table['border_details']['B']['w'] + $table['border_spacing_V'] / 2; + } else { + $this->y += $table['max_cell_border_width']['B'] / 2; + } + + if ($table['borders_separate'] && $level == 1) { + $this->tbrot_h += $table['margin']['B'] + $table['padding']['B'] + $table['border_details']['B']['w'] + $table['border_spacing_V'] / 2; + } elseif ($level == 1) { + $this->tbrot_h += $table['margin']['B'] + $table['max_cell_border_width']['B'] / 2; + } + + $bx = $x0; + $by = $y0; + if ($table['borders_separate']) { + $bx -= ($table['padding']['L'] + $table['border_details']['L']['w'] + $table['border_spacing_H'] / 2); + if ($tablestartpageno != $this->page) { // IF broken across page + $by += $table['max_cell_border_width']['T'] / 2; + if (empty($tableheader)) { + $by -= ($table['border_spacing_V'] / 2); + } + } elseif ($split && $startrow > 0 && empty($tableheader)) { + $by -= ($table['border_spacing_V'] / 2); + } else { + $by -= ($table['padding']['T'] + $table['border_details']['T']['w'] + $table['border_spacing_V'] / 2); + } + } elseif ($tablestartpageno != $this->page && !empty($tableheader)) { + $by += $maxbwtop / 2; + } + $by -= $tableheaderadj; + $bh = $this->y - $by; + if (!$table['borders_separate']) { + $bh -= $table['max_cell_border_width']['B'] / 2; + } + + if ($split) { + $bw = 0; + $finalSpread = true; + for ($t = $startcol; $t < $numcols; $t++) { + if ($table['colPg'][$t] == $splitpg) { + $bw += $table['wc'][$t]; + } + if ($table['colPg'][$t] > $splitpg) { + $finalSpread = false; + break; + } + } + if ($startcol == 0) { + $firstSpread = true; + } else { + $firstSpread = false; + } + if ($table['borders_separate']) { + $bw += $table['border_spacing_H']; + if ($firstSpread) { + $bw += $table['padding']['L'] + $table['border_details']['L']['w']; + } else { + $bx += ($table['padding']['L'] + $table['border_details']['L']['w']); + } + if ($finalSpread) { + $bw += $table['padding']['R'] + $table['border_details']['R']['w']; + } + } + } else { + $bw = $table['w'] - ($table['max_cell_border_width']['L'] / 2) - ($table['max_cell_border_width']['R'] / 2) - $table['margin']['L'] - $table['margin']['R']; + } + + if (!$this->ColActive) { + if (isset($table['bgcolor'][-1])) { + $color = $this->colorConverter->convert($table['bgcolor'][-1], $this->PDFAXwarnings); + if ($color) { + $this->tableBackgrounds[$level * 9][] = ['gradient' => false, 'x' => $bx, 'y' => $by, 'w' => $bw, 'h' => $bh, 'col' => $color]; + } + } + + /* -- BACKGROUNDS -- */ + if (isset($table['gradient'])) { + $g = $this->gradient->parseBackgroundGradient($table['gradient']); + if ($g) { + $this->tableBackgrounds[$level * 9 + 1][] = ['gradient' => true, 'x' => $bx, 'y' => $by, 'w' => $bw, 'h' => $bh, 'gradtype' => $g['type'], 'stops' => $g['stops'], 'colorspace' => $g['colorspace'], 'coords' => $g['coords'], 'extend' => $g['extend'], 'clippath' => '']; + } + } + + if (isset($table['background-image'])) { + if (isset($table['background-image']['gradient']) && $table['background-image']['gradient'] && preg_match('/(-moz-)*(repeating-)*(linear|radial)-gradient/', $table['background-image']['gradient'])) { + $g = $this->gradient->parseMozGradient($table['background-image']['gradient']); + if ($g) { + $this->tableBackgrounds[$level * 9 + 1][] = ['gradient' => true, 'x' => $bx, 'y' => $by, 'w' => $bw, 'h' => $bh, 'gradtype' => $g['type'], 'stops' => $g['stops'], 'colorspace' => $g['colorspace'], 'coords' => $g['coords'], 'extend' => $g['extend'], 'clippath' => '']; + } + } else { + $image_id = $table['background-image']['image_id']; + $orig_w = $table['background-image']['orig_w']; + $orig_h = $table['background-image']['orig_h']; + $x_pos = $table['background-image']['x_pos']; + $y_pos = $table['background-image']['y_pos']; + $x_repeat = $table['background-image']['x_repeat']; + $y_repeat = $table['background-image']['y_repeat']; + $resize = $table['background-image']['resize']; + $opacity = $table['background-image']['opacity']; + $itype = $table['background-image']['itype']; + $this->tableBackgrounds[$level * 9 + 2][] = ['x' => $bx, 'y' => $by, 'w' => $bw, 'h' => $bh, 'image_id' => $image_id, 'orig_w' => $orig_w, 'orig_h' => $orig_h, 'x_pos' => $x_pos, 'y_pos' => $y_pos, 'x_repeat' => $x_repeat, 'y_repeat' => $y_repeat, 'clippath' => '', 'resize' => $resize, 'opacity' => $opacity, 'itype' => $itype]; + } + } + /* -- END BACKGROUNDS -- */ + } + + if ($this->tableBackgrounds && $level == 1) { + $s = $this->PrintTableBackgrounds(); + if ($this->table_rotate && !$this->processingHeader && !$this->processingFooter) { + $this->tablebuffer = preg_replace('/(___TABLE___BACKGROUNDS' . $this->uniqstr . ')/', '\\1' . "\n" . $s . "\n", $this->tablebuffer); + if ($level == 1) { + $this->tablebuffer = preg_replace('/(___TABLE___BACKGROUNDS' . $this->uniqstr . ')/', " ", $this->tablebuffer); + } + } elseif ($this->bufferoutput) { + $this->headerbuffer = preg_replace('/(___TABLE___BACKGROUNDS' . $this->uniqstr . ')/', '\\1' . "\n" . $s . "\n", $this->headerbuffer); + if ($level == 1) { + $this->headerbuffer = preg_replace('/(___TABLE___BACKGROUNDS' . $this->uniqstr . ')/', " ", $this->headerbuffer); + } + } else { + $this->pages[$this->page] = preg_replace('/(___TABLE___BACKGROUNDS' . $this->uniqstr . ')/', '\\1' . "\n" . $s . "\n", $this->pages[$this->page]); + if ($level == 1) { + $this->pages[$this->page] = preg_replace('/(___TABLE___BACKGROUNDS' . $this->uniqstr . ')/', " ", $this->pages[$this->page]); + } + } + $this->tableBackgrounds = []; + } + + + // TABLE BOTTOM MARGIN + if ($table['margin']['B']) { + if (!$this->table_rotate && $level == 1) { + $this->DivLn($table['margin']['B'], $this->blklvl, true); // collapsible + } else { + $this->y += ($table['margin']['B']); + } + } + + if ($this->ColActive && $level == 1) { + $this->breakpoints[$this->CurrCol][] = $this->y; + } // *COLUMNS* + + if ($split) { + // Are there more columns to print on a next page? + if ($lastCol < $numcols - 1) { + $splitpg++; + $startcol = $lastCol + 1; + return [false, $startrow, $startcol, $splitpg, $returny, $y0]; + } else { + return [true, 0, 0, 0, false, false]; + } + } + } + + // END OF FUNCTION _tableWrite() + /////////////////////////END OF TABLE CODE////////////////////////////////// + /* -- END TABLES -- */ + + function _putextgstates() + { + for ($i = 1; $i <= count($this->extgstates); $i++) { + $this->writer->object(); + $this->extgstates[$i]['n'] = $this->n; + $this->writer->write('<</Type /ExtGState'); + foreach ($this->extgstates[$i]['parms'] as $k => $v) { + $this->writer->write('/' . $k . ' ' . $v); + } + $this->writer->write('>>'); + $this->writer->write('endobj'); + } + } + + function SetProtection($permissions = [], $user_pass = '', $owner_pass = null, $length = 40) + { + $this->encrypted = $this->protection->setProtection($permissions, $user_pass, $owner_pass, $length); + } + + // ========================================= + // FROM class PDF_Bookmark + function Bookmark($txt, $level = 0, $y = 0) + { + $txt = $this->purify_utf8_text($txt); + if ($this->text_input_as_HTML) { + $txt = $this->all_entities_to_utf8($txt); + } + if ($y == -1) { + if (!$this->ColActive) { + $y = $this->y; + } else { + $y = $this->y0; + } // If columns are on - mark top of columns + } + + // else y is used as set, or =0 i.e. top of page + // DIRECTIONALITY RTL + $bmo = ['t' => $txt, 'l' => $level, 'y' => $y, 'p' => $this->page]; + + if ($this->keep_block_together) { + // do nothing + } elseif ($this->table_rotate) { + $this->tbrot_BMoutlines[] = $bmo; + } elseif ($this->kwt) { + $this->kwt_BMoutlines[] = $bmo; + } elseif ($this->ColActive) { + $this->col_BMoutlines[] = $bmo; + } else { + $this->BMoutlines[] = $bmo; + } + } + + /** + * Initiate, and Mark a place for the Table of Contents to be inserted + */ + function TOC( + $tocfont = '', + $tocfontsize = 0, + $tocindent = 0, + $resetpagenum = '', + $pagenumstyle = '', + $suppress = '', + $toc_orientation = '', + $TOCusePaging = true, + $TOCuseLinking = false, + $toc_id = 0, + $tocoutdent = '' + ) { + + $this->tableOfContents->TOC( + $tocfont, + $tocfontsize, + $tocindent, + $resetpagenum, + $pagenumstyle, + $suppress, + $toc_orientation, + $TOCusePaging, + $TOCuseLinking, + $toc_id, + $tocoutdent + ); + } + + function TOCpagebreakByArray($a) + { + if (!is_array($a)) { + $a = []; + } + $tocoutdent = (isset($a['tocoutdent']) ? $a['tocoutdent'] : (isset($a['outdent']) ? $a['outdent'] : '')); + $TOCusePaging = (isset($a['TOCusePaging']) ? $a['TOCusePaging'] : (isset($a['paging']) ? $a['paging'] : true)); + $TOCuseLinking = (isset($a['TOCuseLinking']) ? $a['TOCuseLinking'] : (isset($a['links']) ? $a['links'] : '')); + $toc_orientation = (isset($a['toc_orientation']) ? $a['toc_orientation'] : (isset($a['toc-orientation']) ? $a['toc-orientation'] : '')); + $toc_mgl = (isset($a['toc_mgl']) ? $a['toc_mgl'] : (isset($a['toc-margin-left']) ? $a['toc-margin-left'] : '')); + $toc_mgr = (isset($a['toc_mgr']) ? $a['toc_mgr'] : (isset($a['toc-margin-right']) ? $a['toc-margin-right'] : '')); + $toc_mgt = (isset($a['toc_mgt']) ? $a['toc_mgt'] : (isset($a['toc-margin-top']) ? $a['toc-margin-top'] : '')); + $toc_mgb = (isset($a['toc_mgb']) ? $a['toc_mgb'] : (isset($a['toc-margin-bottom']) ? $a['toc-margin-bottom'] : '')); + $toc_mgh = (isset($a['toc_mgh']) ? $a['toc_mgh'] : (isset($a['toc-margin-header']) ? $a['toc-margin-header'] : '')); + $toc_mgf = (isset($a['toc_mgf']) ? $a['toc_mgf'] : (isset($a['toc-margin-footer']) ? $a['toc-margin-footer'] : '')); + $toc_ohname = (isset($a['toc_ohname']) ? $a['toc_ohname'] : (isset($a['toc-odd-header-name']) ? $a['toc-odd-header-name'] : '')); + $toc_ehname = (isset($a['toc_ehname']) ? $a['toc_ehname'] : (isset($a['toc-even-header-name']) ? $a['toc-even-header-name'] : '')); + $toc_ofname = (isset($a['toc_ofname']) ? $a['toc_ofname'] : (isset($a['toc-odd-footer-name']) ? $a['toc-odd-footer-name'] : '')); + $toc_efname = (isset($a['toc_efname']) ? $a['toc_efname'] : (isset($a['toc-even-footer-name']) ? $a['toc-even-footer-name'] : '')); + $toc_ohvalue = (isset($a['toc_ohvalue']) ? $a['toc_ohvalue'] : (isset($a['toc-odd-header-value']) ? $a['toc-odd-header-value'] : 0)); + $toc_ehvalue = (isset($a['toc_ehvalue']) ? $a['toc_ehvalue'] : (isset($a['toc-even-header-value']) ? $a['toc-even-header-value'] : 0)); + $toc_ofvalue = (isset($a['toc_ofvalue']) ? $a['toc_ofvalue'] : (isset($a['toc-odd-footer-value']) ? $a['toc-odd-footer-value'] : 0)); + $toc_efvalue = (isset($a['toc_efvalue']) ? $a['toc_efvalue'] : (isset($a['toc-even-footer-value']) ? $a['toc-even-footer-value'] : 0)); + $toc_preHTML = (isset($a['toc_preHTML']) ? $a['toc_preHTML'] : (isset($a['toc-preHTML']) ? $a['toc-preHTML'] : '')); + $toc_postHTML = (isset($a['toc_postHTML']) ? $a['toc_postHTML'] : (isset($a['toc-postHTML']) ? $a['toc-postHTML'] : '')); + $toc_bookmarkText = (isset($a['toc_bookmarkText']) ? $a['toc_bookmarkText'] : (isset($a['toc-bookmarkText']) ? $a['toc-bookmarkText'] : '')); + $resetpagenum = (isset($a['resetpagenum']) ? $a['resetpagenum'] : ''); + $pagenumstyle = (isset($a['pagenumstyle']) ? $a['pagenumstyle'] : ''); + $suppress = (isset($a['suppress']) ? $a['suppress'] : ''); + $orientation = (isset($a['orientation']) ? $a['orientation'] : ''); + $mgl = (isset($a['mgl']) ? $a['mgl'] : (isset($a['margin-left']) ? $a['margin-left'] : '')); + $mgr = (isset($a['mgr']) ? $a['mgr'] : (isset($a['margin-right']) ? $a['margin-right'] : '')); + $mgt = (isset($a['mgt']) ? $a['mgt'] : (isset($a['margin-top']) ? $a['margin-top'] : '')); + $mgb = (isset($a['mgb']) ? $a['mgb'] : (isset($a['margin-bottom']) ? $a['margin-bottom'] : '')); + $mgh = (isset($a['mgh']) ? $a['mgh'] : (isset($a['margin-header']) ? $a['margin-header'] : '')); + $mgf = (isset($a['mgf']) ? $a['mgf'] : (isset($a['margin-footer']) ? $a['margin-footer'] : '')); + $ohname = (isset($a['ohname']) ? $a['ohname'] : (isset($a['odd-header-name']) ? $a['odd-header-name'] : '')); + $ehname = (isset($a['ehname']) ? $a['ehname'] : (isset($a['even-header-name']) ? $a['even-header-name'] : '')); + $ofname = (isset($a['ofname']) ? $a['ofname'] : (isset($a['odd-footer-name']) ? $a['odd-footer-name'] : '')); + $efname = (isset($a['efname']) ? $a['efname'] : (isset($a['even-footer-name']) ? $a['even-footer-name'] : '')); + $ohvalue = (isset($a['ohvalue']) ? $a['ohvalue'] : (isset($a['odd-header-value']) ? $a['odd-header-value'] : 0)); + $ehvalue = (isset($a['ehvalue']) ? $a['ehvalue'] : (isset($a['even-header-value']) ? $a['even-header-value'] : 0)); + $ofvalue = (isset($a['ofvalue']) ? $a['ofvalue'] : (isset($a['odd-footer-value']) ? $a['odd-footer-value'] : 0)); + $efvalue = (isset($a['efvalue']) ? $a['efvalue'] : (isset($a['even-footer-value']) ? $a['even-footer-value'] : 0)); + $toc_id = (isset($a['toc_id']) ? $a['toc_id'] : (isset($a['name']) ? $a['name'] : 0)); + $pagesel = (isset($a['pagesel']) ? $a['pagesel'] : (isset($a['pageselector']) ? $a['pageselector'] : '')); + $toc_pagesel = (isset($a['toc_pagesel']) ? $a['toc_pagesel'] : (isset($a['toc-pageselector']) ? $a['toc-pageselector'] : '')); + $sheetsize = (isset($a['sheetsize']) ? $a['sheetsize'] : (isset($a['sheet-size']) ? $a['sheet-size'] : '')); + $toc_sheetsize = (isset($a['toc_sheetsize']) ? $a['toc_sheetsize'] : (isset($a['toc-sheet-size']) ? $a['toc-sheet-size'] : '')); + + $this->TOCpagebreak('', '', '', $TOCusePaging, $TOCuseLinking, $toc_orientation, $toc_mgl, $toc_mgr, $toc_mgt, $toc_mgb, $toc_mgh, $toc_mgf, $toc_ohname, $toc_ehname, $toc_ofname, $toc_efname, $toc_ohvalue, $toc_ehvalue, $toc_ofvalue, $toc_efvalue, $toc_preHTML, $toc_postHTML, $toc_bookmarkText, $resetpagenum, $pagenumstyle, $suppress, $orientation, $mgl, $mgr, $mgt, $mgb, $mgh, $mgf, $ohname, $ehname, $ofname, $efname, $ohvalue, $ehvalue, $ofvalue, $efvalue, $toc_id, $pagesel, $toc_pagesel, $sheetsize, $toc_sheetsize, $tocoutdent); + } + + function TOCpagebreak($tocfont = '', $tocfontsize = '', $tocindent = '', $TOCusePaging = true, $TOCuseLinking = '', $toc_orientation = '', $toc_mgl = '', $toc_mgr = '', $toc_mgt = '', $toc_mgb = '', $toc_mgh = '', $toc_mgf = '', $toc_ohname = '', $toc_ehname = '', $toc_ofname = '', $toc_efname = '', $toc_ohvalue = 0, $toc_ehvalue = 0, $toc_ofvalue = 0, $toc_efvalue = 0, $toc_preHTML = '', $toc_postHTML = '', $toc_bookmarkText = '', $resetpagenum = '', $pagenumstyle = '', $suppress = '', $orientation = '', $mgl = '', $mgr = '', $mgt = '', $mgb = '', $mgh = '', $mgf = '', $ohname = '', $ehname = '', $ofname = '', $efname = '', $ohvalue = 0, $ehvalue = 0, $ofvalue = 0, $efvalue = 0, $toc_id = 0, $pagesel = '', $toc_pagesel = '', $sheetsize = '', $toc_sheetsize = '', $tocoutdent = '') + { + // Start a new page + if ($this->state == 0) { + $this->AddPage(); + } + if ($this->y == $this->tMargin && (!$this->mirrorMargins || ($this->mirrorMargins && $this->page % 2 == 1))) { + // Don't add a page + if ($this->page == 1 && count($this->PageNumSubstitutions) == 0) { + if (!$suppress) { + $suppress = 'off'; + } + // $this->PageNumSubstitutions[] = array('from'=>1, 'reset'=> $resetpagenum, 'type'=>$pagenumstyle, 'suppress'=> $suppress); + } + $this->PageNumSubstitutions[] = ['from' => $this->page, 'reset' => $resetpagenum, 'type' => $pagenumstyle, 'suppress' => $suppress]; + } else { + $this->AddPage($orientation, 'NEXT-ODD', $resetpagenum, $pagenumstyle, $suppress, $mgl, $mgr, $mgt, $mgb, $mgh, $mgf, $ohname, $ehname, $ofname, $efname, $ohvalue, $ehvalue, $ofvalue, $efvalue, $pagesel, $sheetsize); + } + $this->tableOfContents->TOCpagebreak($tocfont, $tocfontsize, $tocindent, $TOCusePaging, $TOCuseLinking, $toc_orientation, $toc_mgl, $toc_mgr, $toc_mgt, $toc_mgb, $toc_mgh, $toc_mgf, $toc_ohname, $toc_ehname, $toc_ofname, $toc_efname, $toc_ohvalue, $toc_ehvalue, $toc_ofvalue, $toc_efvalue, $toc_preHTML, $toc_postHTML, $toc_bookmarkText, $resetpagenum, $pagenumstyle, $suppress, $orientation, $mgl, $mgr, $mgt, $mgb, $mgh, $mgf, $ohname, $ehname, $ofname, $efname, $ohvalue, $ehvalue, $ofvalue, $efvalue, $toc_id, $pagesel, $toc_pagesel, $sheetsize, $toc_sheetsize, $tocoutdent); + } + + function TOC_Entry($txt, $level = 0, $toc_id = 0) + { + if ($this->ColActive) { + $ily = $this->y0; + } else { + $ily = $this->y; + } // use top of columns + + $linkn = $this->AddLink(); + $uid = '__mpdfinternallink_' . $linkn; + if ($this->table_rotate) { + $this->internallink[$uid] = ["Y" => $ily, "PAGE" => $this->page, "tbrot" => true]; + } elseif ($this->kwt) { + $this->internallink[$uid] = ["Y" => $ily, "PAGE" => $this->page, "kwt" => true]; + } elseif ($this->ColActive) { + $this->internallink[$uid] = ["Y" => $ily, "PAGE" => $this->page, "col" => $this->CurrCol]; + } elseif (!$this->keep_block_together) { + $this->internallink[$uid] = ["Y" => $ily, "PAGE" => $this->page]; + } + $this->internallink['#' . $uid] = $linkn; + $this->SetLink($linkn, $ily, $this->page); + + if (strtoupper($toc_id) == 'ALL') { + $toc_id = '_mpdf_all'; + } elseif (!$toc_id) { + $toc_id = 0; + } else { + $toc_id = strtolower($toc_id); + } + $btoc = ['t' => $txt, 'l' => $level, 'p' => $this->page, 'link' => $linkn, 'toc_id' => $toc_id]; + if ($this->keep_block_together) { + // do nothing + } /* -- TABLES -- */ elseif ($this->table_rotate) { + $this->tbrot_toc[] = $btoc; + } elseif ($this->kwt) { + $this->kwt_toc[] = $btoc; + } /* -- END TABLES -- */ elseif ($this->ColActive) { // *COLUMNS* + $this->col_toc[] = $btoc; // *COLUMNS* + } // *COLUMNS* + else { + $this->tableOfContents->_toc[] = $btoc; + } + } + + /* -- END TOC -- */ + + // ====================================================== + function MovePages($target_page, $start_page, $end_page = -1) + { + // move a page/pages EARLIER in the document + if ($end_page < 1) { + $end_page = $start_page; + } + $n_toc = $end_page - $start_page + 1; + + // Set/Update PageNumSubstitutions changes before moving anything + if (count($this->PageNumSubstitutions)) { + $tp_present = false; + $sp_present = false; + $ep_present = false; + foreach ($this->PageNumSubstitutions as $k => $v) { + if ($this->PageNumSubstitutions[$k]['from'] == $target_page) { + $tp_present = true; + if ($this->PageNumSubstitutions[$k]['suppress'] != 'on' && $this->PageNumSubstitutions[$k]['suppress'] != 1) { + $this->PageNumSubstitutions[$k]['suppress'] = 'off'; + } + } + if ($this->PageNumSubstitutions[$k]['from'] == $start_page) { + $sp_present = true; + if ($this->PageNumSubstitutions[$k]['suppress'] != 'on' && $this->PageNumSubstitutions[$k]['suppress'] != 1) { + $this->PageNumSubstitutions[$k]['suppress'] = 'off'; + } + } + if ($this->PageNumSubstitutions[$k]['from'] == ($end_page + 1)) { + $ep_present = true; + if ($this->PageNumSubstitutions[$k]['suppress'] != 'on' && $this->PageNumSubstitutions[$k]['suppress'] != 1) { + $this->PageNumSubstitutions[$k]['suppress'] = 'off'; + } + } + } + + if (!$tp_present) { + list($tp_type, $tp_suppress, $tp_reset) = $this->docPageSettings($target_page); + } + if (!$sp_present) { + list($sp_type, $sp_suppress, $sp_reset) = $this->docPageSettings($start_page); + } + if (!$ep_present) { + list($ep_type, $ep_suppress, $ep_reset) = $this->docPageSettings($start_page - 1); + } + } + + $last = []; + // store pages + for ($i = $start_page; $i <= $end_page; $i++) { + $last[] = $this->pages[$i]; + } + // move pages + for ($i = $start_page - 1; $i >= ($target_page); $i--) { + $this->pages[$i + $n_toc] = $this->pages[$i]; + } + // Put toc pages at insert point + for ($i = 0; $i < $n_toc; $i++) { + $this->pages[$target_page + $i] = $last[$i]; + } + + /* -- BOOKMARKS -- */ + // Update Bookmarks + foreach ($this->BMoutlines as $i => $o) { + if ($o['p'] >= $target_page) { + $this->BMoutlines[$i]['p'] += $n_toc; + } + } + /* -- END BOOKMARKS -- */ + + // Update Page Links + if (count($this->PageLinks)) { + $newarr = []; + foreach ($this->PageLinks as $i => $o) { + foreach ($this->PageLinks[$i] as $key => $pl) { + if (strpos($pl[4], '@') === 0) { + $p = substr($pl[4], 1); + if ($p >= $start_page && $p <= $end_page) { + $this->PageLinks[$i][$key][4] = '@' . ($p + ($target_page - $start_page)); + } elseif ($p >= $target_page && $p < $start_page) { + $this->PageLinks[$i][$key][4] = '@' . ($p + $n_toc); + } + } + } + if ($i >= $start_page && $i <= $end_page) { + $newarr[($i + ($target_page - $start_page))] = $this->PageLinks[$i]; + } elseif ($i >= $target_page && $i < $start_page) { + $newarr[($i + $n_toc)] = $this->PageLinks[$i]; + } else { + $newarr[$i] = $this->PageLinks[$i]; + } + } + $this->PageLinks = $newarr; + } + + // OrientationChanges + if (count($this->OrientationChanges)) { + $newarr = []; + foreach ($this->OrientationChanges as $p => $v) { + if ($p >= $start_page && $p <= $end_page) { + $newarr[($p + ($target_page - $start_page))] = $this->OrientationChanges[$p]; + } elseif ($p >= $target_page && $p < $start_page) { + $newarr[$p + $n_toc] = $this->OrientationChanges[$p]; + } else { + $newarr[$p] = $this->OrientationChanges[$p]; + } + } + ksort($newarr); + $this->OrientationChanges = $newarr; + } + + // Page Dimensions + if (count($this->pageDim)) { + $newarr = []; + foreach ($this->pageDim as $p => $v) { + if ($p >= $start_page && $p <= $end_page) { + $newarr[($p + ($target_page - $start_page))] = $this->pageDim[$p]; + } elseif ($p >= $target_page && $p < $start_page) { + $newarr[$p + $n_toc] = $this->pageDim[$p]; + } else { + $newarr[$p] = $this->pageDim[$p]; + } + } + ksort($newarr); + $this->pageDim = $newarr; + } + + // HTML Headers & Footers + if (count($this->saveHTMLHeader)) { + $newarr = []; + foreach ($this->saveHTMLHeader as $p => $v) { + if ($p >= $start_page && $p <= $end_page) { + $newarr[($p + ($target_page - $start_page))] = $this->saveHTMLHeader[$p]; + } elseif ($p >= $target_page && $p < $start_page) { + $newarr[$p + $n_toc] = $this->saveHTMLHeader[$p]; + } else { + $newarr[$p] = $this->saveHTMLHeader[$p]; + } + } + ksort($newarr); + $this->saveHTMLHeader = $newarr; + } + if (count($this->saveHTMLFooter)) { + $newarr = []; + foreach ($this->saveHTMLFooter as $p => $v) { + if ($p >= $start_page && $p <= $end_page) { + $newarr[($p + ($target_page - $start_page))] = $this->saveHTMLFooter[$p]; + } elseif ($p >= $target_page && $p < $start_page) { + $newarr[$p + $n_toc] = $this->saveHTMLFooter[$p]; + } else { + $newarr[$p] = $this->saveHTMLFooter[$p]; + } + } + ksort($newarr); + $this->saveHTMLFooter = $newarr; + } + + // Update Internal Links + if (count($this->internallink)) { + foreach ($this->internallink as $key => $o) { + if (is_array($o) && $o['PAGE'] >= $start_page && $o['PAGE'] <= $end_page) { + $this->internallink[$key]['PAGE'] += ($target_page - $start_page); + } elseif (is_array($o) && $o['PAGE'] >= $target_page && $o['PAGE'] < $start_page) { + $this->internallink[$key]['PAGE'] += $n_toc; + } + } + } + + // Update Links + if (count($this->links)) { + foreach ($this->links as $key => $o) { + if ($o[0] >= $start_page && $o[0] <= $end_page) { + $this->links[$key][0] += ($target_page - $start_page); + } + if ($o[0] >= $target_page && $o[0] < $start_page) { + $this->links[$key][0] += $n_toc; + } + } + } + + // Update Form fields + if (count($this->form->forms)) { + foreach ($this->form->forms as $key => $f) { + if ($f['page'] >= $start_page && $f['page'] <= $end_page) { + $this->form->forms[$key]['page'] += ($target_page - $start_page); + } + if ($f['page'] >= $target_page && $f['page'] < $start_page) { + $this->form->forms[$key]['page'] += $n_toc; + } + } + } + + /* -- ANNOTATIONS -- */ + // Update Annotations + if (count($this->PageAnnots)) { + $newarr = []; + foreach ($this->PageAnnots as $p => $anno) { + if ($p >= $start_page && $p <= $end_page) { + $np = $p + ($target_page - $start_page); + foreach ($anno as $o) { + $newarr[$np][] = $o; + } + } elseif ($p >= $target_page && $p < $start_page) { + $np = $p + $n_toc; + foreach ($anno as $o) { + $newarr[$np][] = $o; + } + } else { + $newarr[$p] = $this->PageAnnots[$p]; + } + } + $this->PageAnnots = $newarr; + unset($newarr); + } + /* -- END ANNOTATIONS -- */ + + // Update TOC pages + if (count($this->tableOfContents->_toc)) { + foreach ($this->tableOfContents->_toc as $key => $t) { + if ($t['p'] >= $start_page && $t['p'] <= $end_page) { + $this->tableOfContents->_toc[$key]['p'] += ($target_page - $start_page); + } + if ($t['p'] >= $target_page && $t['p'] < $start_page) { + $this->tableOfContents->_toc[$key]['p'] += $n_toc; + } + } + } + + // Update PageNumSubstitutions + if (count($this->PageNumSubstitutions)) { + $newarr = []; + foreach ($this->PageNumSubstitutions as $k => $v) { + if ($this->PageNumSubstitutions[$k]['from'] >= $start_page && $this->PageNumSubstitutions[$k]['from'] <= $end_page) { + $this->PageNumSubstitutions[$k]['from'] += ($target_page - $start_page); + $newarr[$this->PageNumSubstitutions[$k]['from']] = $this->PageNumSubstitutions[$k]; + } elseif ($this->PageNumSubstitutions[$k]['from'] >= $target_page && $this->PageNumSubstitutions[$k]['from'] < $start_page) { + $this->PageNumSubstitutions[$k]['from'] += $n_toc; + $newarr[$this->PageNumSubstitutions[$k]['from']] = $this->PageNumSubstitutions[$k]; + } else { + $newarr[$this->PageNumSubstitutions[$k]['from']] = $this->PageNumSubstitutions[$k]; + } + } + + if (!$sp_present) { + $newarr[$target_page] = ['from' => $target_page, 'suppress' => $sp_suppress, 'reset' => $sp_reset, 'type' => $sp_type]; + } + if (!$tp_present) { + $newarr[($target_page + $n_toc)] = ['from' => ($target_page + $n_toc), 'suppress' => $tp_suppress, 'reset' => $tp_reset, 'type' => $tp_type]; + } + if (!$ep_present && $end_page > count($this->pages)) { + $newarr[($end_page + 1)] = ['from' => ($end_page + 1), 'suppress' => $ep_suppress, 'reset' => $ep_reset, 'type' => $ep_type]; + } + ksort($newarr); + $this->PageNumSubstitutions = []; + foreach ($newarr as $v) { + $this->PageNumSubstitutions[] = $v; + } + } + } + + function DeletePages($start_page, $end_page = -1) + { + // move a page/pages EARLIER in the document + if ($end_page < 1) { + $end_page = $start_page; + } + $n_tod = $end_page - $start_page + 1; + $last_page = count($this->pages); + $n_atend = $last_page - $end_page + 1; + + // move pages + for ($i = 0; $i < $n_atend; $i++) { + $this->pages[$start_page + $i] = $this->pages[$end_page + 1 + $i]; + } + // delete pages + for ($i = 0; $i < $n_tod; $i++) { + unset($this->pages[$last_page - $i]); + } + + + /* -- BOOKMARKS -- */ + // Update Bookmarks + foreach ($this->BMoutlines as $i => $o) { + if ($o['p'] >= $end_page) { + $this->BMoutlines[$i]['p'] -= $n_tod; + } elseif ($p < $start_page) { + unset($this->BMoutlines[$i]); + } + } + /* -- END BOOKMARKS -- */ + + // Update Page Links + if (count($this->PageLinks)) { + $newarr = []; + foreach ($this->PageLinks as $i => $o) { + foreach ($this->PageLinks[$i] as $key => $pl) { + if (strpos($pl[4], '@') === 0) { + $p = substr($pl[4], 1); + if ($p > $end_page) { + $this->PageLinks[$i][$key][4] = '@' . ($p - $n_tod); + } elseif ($p < $start_page) { + unset($this->PageLinks[$i][$key]); + } + } + } + if ($i > $end_page) { + $newarr[($i - $n_tod)] = $this->PageLinks[$i]; + } elseif ($p < $start_page) { + $newarr[$i] = $this->PageLinks[$i]; + } + } + $this->PageLinks = $newarr; + } + + // OrientationChanges + if (count($this->OrientationChanges)) { + $newarr = []; + foreach ($this->OrientationChanges as $p => $v) { + if ($p > $end_page) { + $newarr[($p - $t_tod)] = $this->OrientationChanges[$p]; + } elseif ($p < $start_page) { + $newarr[$p] = $this->OrientationChanges[$p]; + } + } + ksort($newarr); + $this->OrientationChanges = $newarr; + } + + // Page Dimensions + if (count($this->pageDim)) { + $newarr = []; + foreach ($this->pageDim as $p => $v) { + if ($p > $end_page) { + $newarr[($p - $n_tod)] = $this->pageDim[$p]; + } elseif ($p < $start_page) { + $newarr[$p] = $this->pageDim[$p]; + } + } + ksort($newarr); + $this->pageDim = $newarr; + } + + // HTML Headers & Footers + if (count($this->saveHTMLHeader)) { + foreach ($this->saveHTMLHeader as $p => $v) { + if ($p > $end_page) { + $newarr[($p - $n_tod)] = $this->saveHTMLHeader[$p]; + } // mPDF 5.7.3 + elseif ($p < $start_page) { + $newarr[$p] = $this->saveHTMLHeader[$p]; + } + } + ksort($newarr); + $this->saveHTMLHeader = $newarr; + } + if (count($this->saveHTMLFooter)) { + $newarr = []; + foreach ($this->saveHTMLFooter as $p => $v) { + if ($p > $end_page) { + $newarr[($p - $n_tod)] = $this->saveHTMLFooter[$p]; + } elseif ($p < $start_page) { + $newarr[$p] = $this->saveHTMLFooter[$p]; + } + } + ksort($newarr); + $this->saveHTMLFooter = $newarr; + } + + // Update Internal Links + foreach ($this->internallink as $key => $o) { + if ($o['PAGE'] > $end_page) { + $this->internallink[$key]['PAGE'] -= $n_tod; + } elseif ($o['PAGE'] < $start_page) { + unset($this->internallink[$key]); + } + } + + // Update Links + foreach ($this->links as $key => $o) { + if ($o[0] > $end_page) { + $this->links[$key][0] -= $n_tod; + } elseif ($o[0] < $start_page) { + unset($this->links[$key]); + } + } + + // Update Form fields + foreach ($this->form->forms as $key => $f) { + if ($f['page'] > $end_page) { + $this->form->forms[$key]['page'] -= $n_tod; + } elseif ($f['page'] < $start_page) { + unset($this->form->forms[$key]); + } + } + + /* -- ANNOTATIONS -- */ + // Update Annotations + if (count($this->PageAnnots)) { + $newarr = []; + foreach ($this->PageAnnots as $p => $anno) { + if ($p > $end_page) { + foreach ($anno as $o) { + $newarr[($p - $n_tod)][] = $o; + } + } elseif ($p < $start_page) { + $newarr[$p] = $this->PageAnnots[$p]; + } + } + ksort($newarr); + $this->PageAnnots = $newarr; + } + /* -- END ANNOTATIONS -- */ + + // Update PageNumSubstitutions + foreach ($this->PageNumSubstitutions as $k => $v) { + if ($this->PageNumSubstitutions[$k]['from'] > $end_page) { + $this->PageNumSubstitutions[$k]['from'] -= $n_tod; + } elseif ($this->PageNumSubstitutions[$k]['from'] < $start_page) { + unset($this->PageNumSubstitutions[$k]); + } + } + + unset($newarr); + $this->page = count($this->pages); + } + + // ====================================================== + /* -- INDEX -- */ + // FROM class PDF_Ref == INDEX + + function IndexEntry($txt, $xref = '') + { + if ($xref) { + $this->IndexEntrySee($txt, $xref); + return; + } + + // Search the reference (AND Ref/PageNo) in the array + $Present = false; + if ($this->keep_block_together) { + // do nothing + } /* -- TABLES -- */ elseif ($this->kwt) { + $size = count($this->kwt_Reference); + for ($i = 0; $i < $size; $i++) { + if (isset($this->kwt_Reference[$i]['t']) && $this->kwt_Reference[$i]['t'] == $txt) { + $Present = true; + if ($this->page != $this->kwt_Reference[$i]['op']) { + $this->kwt_Reference[$i]['op'] = $this->page; + } + } + } + if (!$Present) { // If not found, add it + $this->kwt_Reference[] = ['t' => $txt, 'op' => $this->page]; + } + } /* -- END TABLES -- */ else { + $size = count($this->Reference); + for ($i = 0; $i < $size; $i++) { + if (isset($this->Reference[$i]['t']) && $this->Reference[$i]['t'] == $txt) { + $Present = true; + if (!in_array($this->page, $this->Reference[$i]['p'])) { + $this->Reference[$i]['p'][] = $this->page; + } + } + } + if (!$Present) { // If not found, add it + $this->Reference[] = ['t' => $txt, 'p' => [$this->page]]; + } + } + } + + // Added function to add a reference "Elephants. See Chickens" + function IndexEntrySee($txta, $txtb) + { + if ($this->directionality == 'rtl') { // *OTL* + // ONLY DO THIS IF NOT IN TAGS + if ($txta == strip_tags($txta)) { + $txta = str_replace(':', ' - ', $txta); // *OTL* + } + if ($txtb == strip_tags($txtb)) { + $txtb = str_replace(':', ' - ', $txtb); // *OTL* + } + } // *OTL* + else { // *OTL* + if ($txta == strip_tags($txta)) { + $txta = str_replace(':', ', ', $txta); + } + if ($txtb == strip_tags($txtb)) { + $txtb = str_replace(':', ', ', $txtb); + } + } // *OTL* + $this->Reference[] = ['t' => $txta . ' - see ' . $txtb, 'p' => []]; + } + + private function filesInDir($directory) + { + $files = []; + foreach ((new \DirectoryIterator($directory)) as $v) { + if ($v->isDir() || $v->isDot()) { + continue; + } + + $files[] = $v->getPathname(); + } + + return $files; + } + + function InsertIndex($usedivletters = 1, $useLinking = false, $indexCollationLocale = '', $indexCollationGroup = '') + { + $size = count($this->Reference); + if ($size == 0) { + return false; + } + + // $spacer used after named entry + // $sep separates number [groups], $joiner joins numbers in range + // e.g. "elephant 73, 97-99" = elephant[$spacer]73[$sep]97[$joiner]99 + // $subEntrySeparator separates main and subentry (if $this->indexUseSubentries == false;) e.g. + // Mammal:elephant => Mammal[$subEntrySeparator]elephant + // $subEntryInset specifies what precedes a subentry (if $this->indexUseSubentries == true;) e.g. + // Mammal:elephant => [$subEntryInset]elephant + $spacer = "\xc2\xa0 "; + if ($this->directionality == 'rtl') { + $sep = '، '; + $joiner = '-'; + $subEntrySeparator = '، '; + $subEntryInset = ' - '; + } else { + $sep = ', '; + $joiner = '-'; + $subEntrySeparator = ', '; + $subEntryInset = ' - '; + } + + for ($i = 0; $i < $size; $i++) { + $txt = $this->Reference[$i]['t']; + $txt = strip_tags($txt); // mPDF 6 + $txt = $this->purify_utf8($txt); + $this->Reference[$i]['uf'] = $txt; // Unformatted e.g. pure utf-8 encoded characters, no mark-up/tags + // Used for ordering and collation + } + + if ($usedivletters) { + if ($indexCollationGroup && \in_array(strtolower($indexCollationGroup), array_map(function ($v) { + return strtolower(basename($v, '.php')); + }, $this->filesInDir(__DIR__ . '/../data/collations/')))) { + $collation = require __DIR__ . '/../data/collations/' . $indexCollationGroup . '.php'; + } else { + $collation = []; + } + for ($i = 0; $i < $size; $i++) { + if ($this->Reference[$i]['uf']) { + $l = mb_substr($this->Reference[$i]['uf'], 0, 1, 'UTF-8'); + if (isset($indexCollationGroup) && $indexCollationGroup) { + $uni = $this->UTF8StringToArray($l); + $ucode = $uni[0]; + if (isset($collation[$ucode])) { + $this->Reference[$i]['d'] = UtfString::code2utf($collation[$ucode]); + } else { + $this->Reference[$i]['d'] = mb_strtolower($l, 'UTF-8'); + } + } else { + $this->Reference[$i]['d'] = mb_strtolower($l, 'UTF-8'); + } + } + } + } + + // Alphabetic sort of the references + $originalLocale = setlocale(LC_COLLATE, 0); + if ($indexCollationLocale) { + setlocale(LC_COLLATE, $indexCollationLocale); + } + + usort($this->Reference, function ($a, $b) { + return strcoll(strtolower($a['uf']), strtolower($b['uf'])); + }); + + if ($indexCollationLocale) { + setlocale(LC_COLLATE, $originalLocale); + } + + $html = '<div class="mpdf_index_main">'; + + $lett = ''; + $last_lett = ''; + $mainentry = ''; + for ($i = 0; $i < $size; $i++) { + if ($this->Reference[$i]['t']) { + if ($usedivletters) { + $lett = $this->Reference[$i]['d']; + if ($lett != $last_lett) { + $html .= '<div class="mpdf_index_letter">' . $lett . '</div>'; + } + } + $txt = $this->Reference[$i]['t']; + + // Sub-entries e.g. Mammals:elephant + // But allow for tags e.g. <b>Mammal</b>:elephants + $a = preg_split('/(<.*?>)/', $txt, -1, PREG_SPLIT_DELIM_CAPTURE); + $txt = ''; + $marker = false; + foreach ($a as $k => $e) { + if ($k % 2 == 0 && !$marker) { + if (strpos($e, ':') !== false) { // == SubEntry + if ($this->indexUseSubentries) { + // If the Main entry does not have any page numbers associated with it + // create and insert an entry + list($txtmain, $sub) = preg_split('/[:]/', $e, 2); + if (strip_tags($txt . $txtmain) != $mainentry) { + $html .= '<div class="mpdf_index_entry">' . $txt . $txtmain . '</div>'; + $mainentry = strip_tags($txt . $txtmain); + } + + $txt = $subEntryInset; + $e = $sub; // Only replace first one + } else { + $e = preg_replace('/[:]/', $subEntrySeparator, $e, 1); // Only replace first one + } + $marker = true; // Don't replace any more once the subentry marker has been found + } + } + $txt .= $e; + } + + if (!$marker) { + $mainentry = strip_tags($txt); + } + + $html .= '<div class="mpdf_index_entry">'; + $html .= $txt; + $ppp = $this->Reference[$i]['p']; // = array of page numbers to point to + if (count($ppp)) { + sort($ppp); + $newarr = []; + $range_start = $ppp[0]; + $range_end = 0; + + $html .= $spacer; + + for ($zi = 1; $zi < count($ppp); $zi++) { + if ($ppp[$zi] == ($ppp[($zi - 1)] + 1)) { + $range_end = $ppp[$zi]; + } else { + if ($range_end) { + if ($range_end == $range_start + 1) { + if ($useLinking) { + $html .= '<a class="mpdf_index_link" href="@' . $range_start . '">'; + } + $html .= $this->docPageNum($range_start); + if ($useLinking) { + $html .= '</a>'; + } + $html .= $sep; + + if ($useLinking) { + $html .= '<a class="mpdf_index_link" href="@' . $ppp[$zi - 1] . '">'; + } + $html .= $this->docPageNum($ppp[$zi - 1]); + if ($useLinking) { + $html .= '</a>'; + } + $html .= $sep; + } + } else { + if ($useLinking) { + $html .= '<a class="mpdf_index_link" href="@' . $ppp[$zi - 1] . '">'; + } + $html .= $this->docPageNum($ppp[$zi - 1]); + if ($useLinking) { + $html .= '</a>'; + } + $html .= $sep; + } + $range_start = $ppp[$zi]; + $range_end = 0; + } + } + + if ($range_end) { + if ($useLinking) { + $html .= '<a class="mpdf_index_link" href="@' . $range_start . '">'; + } + $html .= $this->docPageNum($range_start); + if ($range_end == $range_start + 1) { + if ($useLinking) { + $html .= '</a>'; + } + $html .= $sep; + if ($useLinking) { + $html .= '<a class="mpdf_index_link" href="@' . $range_end . '">'; + } + $html .= $this->docPageNum($range_end); + if ($useLinking) { + $html .= '</a>'; + } + } else { + $html .= $joiner; + $html .= $this->docPageNum($range_end); + if ($useLinking) { + $html .= '</a>'; + } + } + } else { + if ($useLinking) { + $html .= '<a class="mpdf_index_link" href="@' . $ppp[(count($ppp) - 1)] . '">'; + } + $html .= $this->docPageNum($ppp[(count($ppp) - 1)]); + if ($useLinking) { + $html .= '</a>'; + } + } + } + } + $html .= '</div>'; + $last_lett = $lett; + } + $html .= '</div>'; + $save_fpb = $this->fixedPosBlockSave; + $this->WriteHTML($html); + $this->fixedPosBlockSave = $save_fpb; + + $this->breakpoints[$this->CurrCol][] = $this->y; // *COLUMNS* + } + + /* -- END INDEX -- */ + + function AcceptPageBreak() + { + if (count($this->cellBorderBuffer)) { + $this->printcellbuffer(); + } // *TABLES* + /* -- COLUMNS -- */ + if ($this->ColActive == 1) { + if ($this->CurrCol < $this->NbCol - 1) { + // Go to the next column + $this->CurrCol++; + $this->SetCol($this->CurrCol); + $this->y = $this->y0; + $this->ChangeColumn = 1; // Number (and direction) of columns changed +1, +2, -2 etc. + // DIRECTIONALITY RTL + if ($this->directionality == 'rtl') { + $this->ChangeColumn = -($this->ChangeColumn); + } // *OTL* + // Stay on the page + return false; + } else { + // Go back to the first column - NEW PAGE + if (count($this->columnbuffer)) { + $this->printcolumnbuffer(); + } + $this->SetCol(0); + $this->y0 = $this->tMargin; + $this->ChangeColumn = -($this->NbCol - 1); + // DIRECTIONALITY RTL + if ($this->directionality == 'rtl') { + $this->ChangeColumn = -($this->ChangeColumn); + } // *OTL* + // Page break + return true; + } + } /* -- END COLUMNS -- */ + /* -- TABLES -- */ elseif ($this->table_rotate) { + if ($this->tablebuffer) { + $this->printtablebuffer(); + } + return true; + } /* -- END TABLES -- */ else { // *COLUMNS* + $this->ChangeColumn = 0; + return $this->autoPageBreak; + } // *COLUMNS* + return $this->autoPageBreak; + } + + // ----------- COLUMNS --------------------- + /* -- COLUMNS -- */ + + function SetColumns($NbCol, $vAlign = '', $gap = 5) + { + // NbCol = number of columns + // Anything less than 2 turns columns off + if ($NbCol < 2) { // SET COLUMNS OFF + if ($this->ColActive) { + $this->ColActive = 0; + if (count($this->columnbuffer)) { + $this->printcolumnbuffer(); + } + $this->NbCol = 1; + $this->ResetMargins(); + $this->pgwidth = $this->w - $this->lMargin - $this->rMargin; + $this->divwidth = 0; + $this->Ln(); + } + $this->ColActive = 0; + $this->columnbuffer = []; + $this->ColDetails = []; + $this->columnLinks = []; + $this->columnAnnots = []; + $this->columnForms = []; + $this->col_BMoutlines = []; + $this->col_toc = []; + $this->breakpoints = []; + } else { // SET COLUMNS ON + if ($this->ColActive) { + $this->ColActive = 0; + if (count($this->columnbuffer)) { + $this->printcolumnbuffer(); + } + $this->ResetMargins(); + } + if (isset($this->y) && $this->y > $this->tMargin) { + $this->Ln(); + } + $this->NbCol = $NbCol; + $this->ColGap = $gap; + $this->divwidth = 0; + $this->ColActive = 1; + $this->ColumnAdjust = true; // enables column height adjustment for the page + $this->columnbuffer = []; + $this->ColDetails = []; + $this->columnLinks = []; + $this->columnAnnots = []; + $this->columnForms = []; + $this->col_BMoutlines = []; + $this->col_toc = []; + $this->breakpoints = []; + if ((strtoupper($vAlign) == 'J') || (strtoupper($vAlign) == 'JUSTIFY')) { + $vAlign = 'J'; + } else { + $vAlign = ''; + } + $this->colvAlign = $vAlign; + // Save the ordinate + $absL = $this->DeflMargin - ($gap / 2); + $absR = $this->DefrMargin - ($gap / 2); + $PageWidth = $this->w - $absL - $absR; // virtual pagewidth for calculation only + $ColWidth = (($PageWidth - ($gap * ($NbCol))) / $NbCol); + $this->ColWidth = $ColWidth; + /* -- OTL -- */ + + if ($this->directionality == 'rtl') { + for ($i = 0; $i < $this->NbCol; $i++) { + $this->ColL[$i] = $absL + ($gap / 2) + (($NbCol - ($i + 1)) * ($PageWidth / $NbCol)); + $this->ColR[$i] = $this->ColL[$i] + $ColWidth; // NB This is not R margin -> R pos + } + } else { + /* -- END OTL -- */ + for ($i = 0; $i < $this->NbCol; $i++) { + $this->ColL[$i] = $absL + ($gap / 2) + ($i * ($PageWidth / $NbCol) ); + $this->ColR[$i] = $this->ColL[$i] + $ColWidth; // NB This is not R margin -> R pos + } + } // *OTL* + $this->pgwidth = $ColWidth; + $this->SetCol(0); + $this->y0 = $this->y; + } + $this->x = $this->lMargin; + } + + function SetCol($CurrCol) + { + // Used internally to set column by number: 0 is 1st column + // Set position on a column + $this->CurrCol = $CurrCol; + $x = $this->ColL[$CurrCol]; + $xR = $this->ColR[$CurrCol]; // NB This is not R margin -> R pos + if (($this->mirrorMargins) && (($this->page) % 2 == 0)) { // EVEN + $x += $this->MarginCorrection; + $xR += $this->MarginCorrection; + } + $this->SetMargins($x, ($this->w - $xR), $this->tMargin); + } + + function AddColumn() + { + $this->NewColumn(); + $this->ColumnAdjust = false; // disables all column height adjustment for the page. + } + + function NewColumn() + { + if ($this->ColActive == 1) { + if ($this->CurrCol < $this->NbCol - 1) { + // Go to the next column + $this->CurrCol++; + $this->SetCol($this->CurrCol); + $this->y = $this->y0; + $this->ChangeColumn = 1; + // DIRECTIONALITY RTL + if ($this->directionality == 'rtl') { + $this->ChangeColumn = -($this->ChangeColumn); + } // *OTL* + // Stay on the page + } else { + // Go back to the first column + // Page break + if (count($this->columnbuffer)) { + $this->printcolumnbuffer(); + } + $this->AddPage($this->CurOrientation); + $this->SetCol(0); + $this->y0 = $this->tMargin; + $this->ChangeColumn = -($this->NbCol - 1); + // DIRECTIONALITY RTL + if ($this->directionality == 'rtl') { + $this->ChangeColumn = -($this->ChangeColumn); + } // *OTL* + } + $this->x = $this->lMargin; + } else { + $this->AddPage($this->CurOrientation); + } + } + + function printcolumnbuffer() + { + // Columns ended (but page not ended) -> try to match all columns - unless disabled by using a custom column-break + if (!$this->ColActive && $this->ColumnAdjust && !$this->keepColumns) { + // Calculate adjustment to add to each column to calculate rel_y value + $this->ColDetails[0]['add_y'] = 0; + $last_col = 0; + // Recursively add previous column's height + for ($i = 1; $i < $this->NbCol; $i++) { + if (isset($this->ColDetails[$i]['bottom_margin']) && $this->ColDetails[$i]['bottom_margin']) { // If any entries in the column + $this->ColDetails[$i]['add_y'] = ($this->ColDetails[$i - 1]['bottom_margin'] - $this->y0) + $this->ColDetails[$i - 1]['add_y']; + $last_col = $i; // Last column actually printed + } + } + + // Calculate value for each position sensitive entry as though for one column + foreach ($this->columnbuffer as $key => $s) { + $t = $s['s']; + if ($t == 'ACROFORM') { + $this->columnbuffer[$key]['rel_y'] = $s['y'] + $this->ColDetails[$s['col']]['add_y'] - $this->y0; + $this->columnbuffer[$key]['s'] = ''; + } elseif (preg_match('/BT \d+\.\d\d+ (\d+\.\d\d+) Td/', $t)) { + $this->columnbuffer[$key]['rel_y'] = $s['y'] + $this->ColDetails[$s['col']]['add_y'] - $this->y0; + } elseif (preg_match('/\d+\.\d\d+ (\d+\.\d\d+) \d+\.\d\d+ [\-]{0,1}\d+\.\d\d+ re/', $t)) { + $this->columnbuffer[$key]['rel_y'] = $s['y'] + $this->ColDetails[$s['col']]['add_y'] - $this->y0; + } elseif (preg_match('/\d+\.\d\d+ (\d+\.\d\d+) m/', $t)) { + $this->columnbuffer[$key]['rel_y'] = $s['y'] + $this->ColDetails[$s['col']]['add_y'] - $this->y0; + } elseif (preg_match('/\d+\.\d\d+ (\d+\.\d\d+) l/', $t)) { + $this->columnbuffer[$key]['rel_y'] = $s['y'] + $this->ColDetails[$s['col']]['add_y'] - $this->y0; + } elseif (preg_match('/q \d+\.\d\d+ 0 0 \d+\.\d\d+ \d+\.\d\d+ (\d+\.\d\d+) cm \/(I|FO)\d+ Do Q/', $t)) { + $this->columnbuffer[$key]['rel_y'] = $s['y'] + $this->ColDetails[$s['col']]['add_y'] - $this->y0; + } elseif (preg_match('/\d+\.\d\d+ (\d+\.\d\d+) \d+\.\d\d+ \d+\.\d\d+ \d+\.\d\d+ \d+\.\d\d+ c/', $t)) { + $this->columnbuffer[$key]['rel_y'] = $s['y'] + $this->ColDetails[$s['col']]['add_y'] - $this->y0; + } + } + foreach ($this->internallink as $key => $f) { + if (is_array($f) && isset($f['col'])) { + $this->internallink[$key]['rel_y'] = $f['Y'] + $this->ColDetails[$f['col']]['add_y'] - $this->y0; + } + } + + $breaks = []; + foreach ($this->breakpoints as $c => $bpa) { + foreach ($bpa as $rely) { + $breaks[] = $rely + $this->ColDetails[$c]['add_y'] - $this->y0; + } + } + + + if (isset($this->ColDetails[$last_col]['bottom_margin'])) { + $lcbm = $this->ColDetails[$last_col]['bottom_margin']; + } else { + $lcbm = 0; + } + $sum_h = $this->ColDetails[$last_col]['add_y'] + $lcbm - $this->y0; + // $sum_h = max($this->ColDetails[$last_col]['add_y'] + $this->ColDetails[$last_col]['bottom_margin'] - $this->y0, end($breaks)); + $target_h = ($sum_h / $this->NbCol); + + $cbr = []; + for ($i = 1; $i < $this->NbCol; $i++) { + $th = ($sum_h * $i / $this->NbCol); + foreach ($breaks as $bk => $val) { + if ($val > $th) { + if (($val - $th) < ($th - $breaks[$bk - 1])) { + $cbr[$i - 1] = $val; + } else { + $cbr[$i - 1] = $breaks[$bk - 1]; + } + break; + } + } + } + $cbr[($this->NbCol - 1)] = $sum_h; + + // mPDF 6 + // Avoid outputing with 1st column empty + if (isset($cbr[0]) && $cbr[0] == 0) { + for ($i = 0; $i < $this->NbCol - 1; $i++) { + $cbr[$i] = $cbr[$i + 1]; + } + } + + // Now update the columns - divide into columns of approximately equal value + $last_new_col = 0; + $yadj = 0; // mm + $xadj = 0; + $last_col_bottom = 0; + $lowest_bottom_y = 0; + $block_bottom = 0; + $newcolumn = 0; + foreach ($this->columnbuffer as $key => $s) { + if (isset($s['rel_y'])) { // only process position sensitive data + if ($s['rel_y'] >= $cbr[$newcolumn]) { + $newcolumn++; + } else { + $newcolumn = $last_new_col; + } + + + $block_bottom = max($block_bottom, ($s['rel_y'] + $s['h'])); + + if ($this->directionality == 'rtl') { // *OTL* + $xadj = -(($newcolumn - $s['col']) * ($this->ColWidth + $this->ColGap)); // *OTL* + } // *OTL* + else { // *OTL* + $xadj = ($newcolumn - $s['col']) * ($this->ColWidth + $this->ColGap); + } // *OTL* + + if ($last_new_col != $newcolumn) { // Added new column + $last_col_bottom = $this->columnbuffer[$key]['rel_y']; + $block_bottom = 0; + } + $yadj = ($s['rel_y'] - $s['y']) - ($last_col_bottom) + $this->y0; + // callback function + $t = $s['s']; + + // mPDF 5.7+ + $t = $this->columnAdjustPregReplace('Td', $xadj, $yadj, '/BT (\d+\.\d\d+) (\d+\.\d\d+) Td/', $t); + $t = $this->columnAdjustPregReplace('re', $xadj, $yadj, '/(\d+\.\d\d+) (\d+\.\d\d+) (\d+\.\d\d+) ([\-]{0,1}\d+\.\d\d+) re/', $t); + $t = $this->columnAdjustPregReplace('l', $xadj, $yadj, '/(\d+\.\d\d+) (\d+\.\d\d+) l/', $t); + $t = $this->columnAdjustPregReplace('img', $xadj, $yadj, '/q (\d+\.\d\d+) 0 0 (\d+\.\d\d+) (\d+\.\d\d+) (\d+\.\d\d+) cm \/(I|FO)/', $t); + $t = $this->columnAdjustPregReplace('draw', $xadj, $yadj, '/(\d+\.\d\d+) (\d+\.\d\d+) m/', $t); + $t = $this->columnAdjustPregReplace('bezier', $xadj, $yadj, '/(\d+\.\d\d+) (\d+\.\d\d+) (\d+\.\d\d+) (\d+\.\d\d+) (\d+\.\d\d+) (\d+\.\d\d+) c/', $t); + + $this->columnbuffer[$key]['s'] = $t; + $this->columnbuffer[$key]['newcol'] = $newcolumn; + $this->columnbuffer[$key]['newy'] = $s['y'] + $yadj; + $last_new_col = $newcolumn; + $clb = $s['y'] + $yadj + $s['h']; // bottom_margin of current + if ((isset($this->ColDetails[$newcolumn]['max_bottom']) && $clb > $this->ColDetails[$newcolumn]['max_bottom']) || (!isset($this->ColDetails[$newcolumn]['max_bottom']) && $clb)) { + $this->ColDetails[$newcolumn]['max_bottom'] = $clb; + } + if ($clb > $lowest_bottom_y) { + $lowest_bottom_y = $clb; + } + // Adjust LINKS + if (isset($this->columnLinks[$s['col']][intval($s['x'])][intval($s['y'])])) { + $ref = $this->columnLinks[$s['col']][intval($s['x'])][intval($s['y'])]; + $this->PageLinks[$this->page][$ref][0] += ($xadj * Mpdf::SCALE); + $this->PageLinks[$this->page][$ref][1] -= ($yadj * Mpdf::SCALE); + unset($this->columnLinks[$s['col']][intval($s['x'])][intval($s['y'])]); + } + // Adjust FORM FIELDS + if (isset($this->columnForms[$s['col']][intval($s['x'])][intval($s['y'])])) { + $ref = $this->columnForms[$s['col']][intval($s['x'])][intval($s['y'])]; + $this->form->forms[$ref]['x'] += ($xadj); + $this->form->forms[$ref]['y'] += ($yadj); + unset($this->columnForms[$s['col']][intval($s['x'])][intval($s['y'])]); + } + /* -- ANNOTATIONS -- */ + if (isset($this->columnAnnots[$s['col']][intval($s['x'])][intval($s['y'])])) { + $ref = $this->columnAnnots[$s['col']][intval($s['x'])][intval($s['y'])]; + if ($this->PageAnnots[$this->page][$ref]['x'] < 0) { + $this->PageAnnots[$this->page][$ref]['x'] -= ($xadj); + } else { + $this->PageAnnots[$this->page][$ref]['x'] += ($xadj); + } + $this->PageAnnots[$this->page][$ref]['y'] += ($yadj); // unlike PageLinks, Page annots has y values from top in mm + unset($this->columnAnnots[$s['col']][intval($s['x'])][intval($s['y'])]); + } + /* -- END ANNOTATIONS -- */ + } + } + + /* -- BOOKMARKS -- */ + // Adjust Bookmarks + foreach ($this->col_BMoutlines as $v) { + $this->BMoutlines[] = ['t' => $v['t'], 'l' => $v['l'], 'y' => $this->y0, 'p' => $v['p']]; + } + /* -- END BOOKMARKS -- */ + + /* -- TOC -- */ + + // Adjust ToC + foreach ($this->col_toc as $v) { + $this->tableOfContents->_toc[] = ['t' => $v['t'], 'l' => $v['l'], 'p' => $v['p'], 'link' => $v['link'], 'toc_id' => $v['toc_id']]; + $this->links[$v['link']][1] = $this->y0; + } + /* -- END TOC -- */ + + // Adjust column length to be equal + if ($this->colvAlign == 'J') { + foreach ($this->columnbuffer as $key => $s) { + if (isset($s['rel_y'])) { // only process position sensitive data + // Set ratio to expand y values or heights + if (isset($this->ColDetails[$s['newcol']]['max_bottom']) && $this->ColDetails[$s['newcol']]['max_bottom'] && $this->ColDetails[$s['newcol']]['max_bottom'] != $this->y0) { + $ratio = ($lowest_bottom_y - ($this->y0)) / ($this->ColDetails[$s['newcol']]['max_bottom'] - ($this->y0)); + } else { + $ratio = 1; + } + if (($ratio > 1) && ($ratio <= $this->max_colH_correction)) { + $yadj = ($s['newy'] - $this->y0) * ($ratio - 1); + + // Adjust LINKS + if (isset($this->columnLinks[$s['col']][intval($s['x'])][intval($s['y'])])) { + $ref = $this->columnLinks[$s['col']][intval($s['x'])][intval($s['y'])]; + $this->PageLinks[$this->page][$ref][1] -= ($yadj * Mpdf::SCALE); // y value + $this->PageLinks[$this->page][$ref][3] *= $ratio; // height + unset($this->columnLinks[$s['col']][intval($s['x'])][intval($s['y'])]); + } + // Adjust FORM FIELDS + if (isset($this->columnForms[$s['col']][intval($s['x'])][intval($s['y'])])) { + $ref = $this->columnForms[$s['col']][intval($s['x'])][intval($s['y'])]; + $this->form->forms[$ref]['x'] += ($xadj); + $this->form->forms[$ref]['y'] += ($yadj); + unset($this->columnForms[$s['col']][intval($s['x'])][intval($s['y'])]); + } + /* -- ANNOTATIONS -- */ + if (isset($this->columnAnnots[$s['col']][intval($s['x'])][intval($s['y'])])) { + $ref = $this->columnAnnots[$s['col']][intval($s['x'])][intval($s['y'])]; + $this->PageAnnots[$this->page][$ref]['y'] += ($yadj); + unset($this->columnAnnots[$s['col']][intval($s['x'])][intval($s['y'])]); + } + /* -- END ANNOTATIONS -- */ + } + } + } + foreach ($this->internallink as $key => $f) { + if (is_array($f) && isset($f['col'])) { + $last_col_bottom = 0; + for ($nbc = 0; $nbc < $this->NbCol; $nbc++) { + if ($f['rel_y'] >= $cbr[$nbc]) { + $last_col_bottom = $cbr[$nbc]; + } + } + $yadj = ($f['rel_y'] - $f['Y']) - $last_col_bottom + $this->y0; + $f['Y'] += $yadj; + unset($f['col']); + unset($f['rel_y']); + $this->internallink[$key] = $f; + } + } + + $last_col = -1; + $trans_on = false; + foreach ($this->columnbuffer as $key => $s) { + if (isset($s['rel_y'])) { // only process position sensitive data + // Set ratio to expand y values or heights + if (isset($this->ColDetails[$s['newcol']]['max_bottom']) && $this->ColDetails[$s['newcol']]['max_bottom'] && $this->ColDetails[$s['newcol']]['max_bottom'] != $this->y0) { + $ratio = ($lowest_bottom_y - ($this->y0)) / ($this->ColDetails[$s['newcol']]['max_bottom'] - ($this->y0)); + } else { + $ratio = 1; + } + if (($ratio > 1) && ($ratio <= $this->max_colH_correction)) { + // Start Transformation + $this->pages[$this->page] .= $this->StartTransform(true) . "\n"; + $this->pages[$this->page] .= $this->transformScale(100, $ratio * 100, $x = '', $this->y0, true) . "\n"; + $trans_on = true; + } + } + // Now output the adjusted values + $this->pages[$this->page] .= $s['s'] . "\n"; + if (isset($s['rel_y']) && ($ratio > 1) && ($ratio <= $this->max_colH_correction)) { // only process position sensitive data + // Stop Transformation + $this->pages[$this->page] .= $this->StopTransform(true) . "\n"; + $trans_on = false; + } + } + if ($trans_on) { + $this->pages[$this->page] .= $this->StopTransform(true) . "\n"; + } + } else { // if NOT $this->colvAlign == 'J' + // Now output the adjusted values + foreach ($this->columnbuffer as $s) { + $this->pages[$this->page] .= $s['s'] . "\n"; + } + } + if ($lowest_bottom_y > 0) { + $this->y = $lowest_bottom_y; + } + } // Columns not ended but new page -> align columns (can leave the columns alone - just tidy up the height) + elseif ($this->colvAlign == 'J' && $this->ColumnAdjust && !$this->keepColumns) { + // calculate the lowest bottom margin + $lowest_bottom_y = 0; + foreach ($this->columnbuffer as $key => $s) { + // Only process output data + $t = $s['s']; + if ($t == 'ACROFORM' || (preg_match('/BT \d+\.\d\d+ (\d+\.\d\d+) Td/', $t)) || (preg_match('/\d+\.\d\d+ (\d+\.\d\d+) \d+\.\d\d+ [\-]{0,1}\d+\.\d\d+ re/', $t)) || + (preg_match('/\d+\.\d\d+ (\d+\.\d\d+) l/', $t)) || + (preg_match('/q \d+\.\d\d+ 0 0 \d+\.\d\d+ \d+\.\d\d+ (\d+\.\d\d+) cm \/(I|FO)\d+ Do Q/', $t)) || + (preg_match('/\d+\.\d\d+ (\d+\.\d\d+) m/', $t)) || + (preg_match('/\d+\.\d\d+ (\d+\.\d\d+) \d+\.\d\d+ \d+\.\d\d+ \d+\.\d\d+ \d+\.\d\d+ c/', $t))) { + $clb = $s['y'] + $s['h']; + if ((isset($this->ColDetails[$s['col']]['max_bottom']) && $clb > $this->ColDetails[$s['col']]['max_bottom']) || !isset($this->ColDetails[$s['col']]['max_bottom'])) { + $this->ColDetails[$s['col']]['max_bottom'] = $clb; + } + if ($clb > $lowest_bottom_y) { + $lowest_bottom_y = $clb; + } + $this->columnbuffer[$key]['rel_y'] = $s['y']; // Marks position sensitive data to process later + if ($t == 'ACROFORM') { + $this->columnbuffer[$key]['s'] = ''; + } + } + } + // Adjust column length equal + foreach ($this->columnbuffer as $key => $s) { + // Set ratio to expand y values or heights + if (isset($this->ColDetails[$s['col']]['max_bottom']) && $this->ColDetails[$s['col']]['max_bottom']) { + $ratio = ($lowest_bottom_y - ($this->y0)) / ($this->ColDetails[$s['col']]['max_bottom'] - ($this->y0)); + } else { + $ratio = 1; + } + if (($ratio > 1) && ($ratio <= $this->max_colH_correction)) { + $yadj = ($s['y'] - $this->y0) * ($ratio - 1); + + // Adjust LINKS + if (isset($s['rel_y'])) { // only process position sensitive data + // otherwise triggers for all entries in column buffer (.e.g. formatting) and makes below adjustments more than once + if (isset($this->columnLinks[$s['col']][intval($s['x'])][intval($s['y'])])) { + $ref = $this->columnLinks[$s['col']][intval($s['x'])][intval($s['y'])]; + $this->PageLinks[$this->page][$ref][1] -= ($yadj * Mpdf::SCALE); // y value + $this->PageLinks[$this->page][$ref][3] *= $ratio; // height + unset($this->columnLinks[$s['col']][intval($s['x'])][intval($s['y'])]); + } + // Adjust FORM FIELDS + if (isset($this->columnForms[$s['col']][intval($s['x'])][intval($s['y'])])) { + $ref = $this->columnForms[$s['col']][intval($s['x'])][intval($s['y'])]; + $this->form->forms[$ref]['x'] += ($xadj); + $this->form->forms[$ref]['y'] += ($yadj); + unset($this->columnForms[$s['col']][intval($s['x'])][intval($s['y'])]); + } + /* -- ANNOTATIONS -- */ + if (isset($this->columnAnnots[$s['col']][intval($s['x'])][intval($s['y'])])) { + $ref = $this->columnAnnots[$s['col']][intval($s['x'])][intval($s['y'])]; + $this->PageAnnots[$this->page][$ref]['y'] += ($yadj); + unset($this->columnAnnots[$s['col']][intval($s['x'])][intval($s['y'])]); + } + /* -- END ANNOTATIONS -- */ + } + } + } + + /* -- BOOKMARKS -- */ + + // Adjust Bookmarks + foreach ($this->col_BMoutlines as $v) { + $this->BMoutlines[] = ['t' => $v['t'], 'l' => $v['l'], 'y' => $this->y0, 'p' => $v['p']]; + } + /* -- END BOOKMARKS -- */ + + /* -- TOC -- */ + + // Adjust ToC + foreach ($this->col_toc as $v) { + $this->tableOfContents->_toc[] = ['t' => $v['t'], 'l' => $v['l'], 'p' => $v['p'], 'link' => $v['link'], 'toc_id' => $v['toc_id']]; + $this->links[$v['link']][1] = $this->y0; + } + /* -- END TOC -- */ + + $trans_on = false; + foreach ($this->columnbuffer as $key => $s) { + + if (isset($s['rel_y'])) { // only process position sensitive data + + // Set ratio to expand y values or heights + if (isset($this->ColDetails[$s['col']]['max_bottom']) && $this->ColDetails[$s['col']]['max_bottom']) { + $ratio = ($lowest_bottom_y - ($this->y0)) / ($this->ColDetails[$s['col']]['max_bottom'] - ($this->y0)); + } else { + $ratio = 1; + } + + if (($ratio > 1) && ($ratio <= $this->max_colH_correction)) { + // Start Transformation + $this->pages[$this->page] .= $this->StartTransform(true) . "\n"; + $this->pages[$this->page] .= $this->transformScale(100, $ratio * 100, $x = '', $this->y0, true) . "\n"; + $trans_on = true; + } + } + + // Now output the adjusted values + $this->pages[$this->page] .= $s['s'] . "\n"; + if (isset($s['rel_y']) && ($ratio > 1) && ($ratio <= $this->max_colH_correction)) { + // Stop Transformation + $this->pages[$this->page] .= $this->StopTransform(true) . "\n"; + $trans_on = false; + } + } + + if ($trans_on) { + $this->pages[$this->page] .= $this->StopTransform(true) . "\n"; + } + + if ($lowest_bottom_y > 0) { + $this->y = $lowest_bottom_y; + } + + } else { // Just reproduce the page as it was + + // If page has not ended but height adjustment was disabled by custom column-break - adjust y + $lowest_bottom_y = 0; + + if (!$this->ColActive && (!$this->ColumnAdjust || $this->keepColumns)) { + + // calculate the lowest bottom margin + foreach ($this->columnbuffer as $key => $s) { + + // Only process output data + $t = $s['s']; + if ($t === 'ACROFORM' + || (preg_match('/BT \d+\.\d\d+ (\d+\.\d\d+) Td/', $t)) + || (preg_match('/\d+\.\d\d+ (\d+\.\d\d+) \d+\.\d\d+ [\-]{0,1}\d+\.\d\d+ re/', $t)) + || (preg_match('/\d+\.\d\d+ (\d+\.\d\d+) l/', $t)) + || (preg_match('/q \d+\.\d\d+ 0 0 \d+\.\d\d+ \d+\.\d\d+ (\d+\.\d\d+) cm \/(I|FO)\d+ Do Q/', $t)) + || (preg_match('/\d+\.\d\d+ (\d+\.\d\d+) m/', $t)) + || (preg_match('/\d+\.\d\d+ (\d+\.\d\d+) \d+\.\d\d+ \d+\.\d\d+ \d+\.\d\d+ \d+\.\d\d+ c/', $t))) { + + $clb = $s['y'] + $s['h']; + + if (isset($this->ColDetails[$s['col']]['max_bottom']) && $clb > $this->ColDetails[$s['col']]['max_bottom'] || (!isset($this->ColDetails[$s['col']]['max_bottom']) && $clb)) { + $this->ColDetails[$s['col']]['max_bottom'] = $clb; + } + + if ($clb > $lowest_bottom_y) { + $lowest_bottom_y = $clb; + } + } + } + } + + foreach ($this->columnbuffer as $key => $s) { + if ($s['s'] != 'ACROFORM') { + $this->pages[$this->page] .= $s['s'] . "\n"; + } + } + + if ($lowest_bottom_y > 0) { + $this->y = $lowest_bottom_y; + } + + /* -- BOOKMARKS -- */ + // Output Bookmarks + foreach ($this->col_BMoutlines as $v) { + $this->BMoutlines[] = ['t' => $v['t'], 'l' => $v['l'], 'y' => $v['y'], 'p' => $v['p']]; + } + /* -- END BOOKMARKS -- */ + + /* -- TOC -- */ + // Output ToC + foreach ($this->col_toc as $v) { + $this->tableOfContents->_toc[] = ['t' => $v['t'], 'l' => $v['l'], 'p' => $v['p'], 'link' => $v['link'], 'toc_id' => $v['toc_id']]; + } + /* -- END TOC -- */ + } + + foreach ($this->internallink as $key => $f) { + + if (isset($this->internallink[$key]['col'])) { + unset($this->internallink[$key]['col']); + } + + if (isset($this->internallink[$key]['rel_y'])) { + unset($this->internallink[$key]['rel_y']); + } + } + + $this->columnbuffer = []; + $this->ColDetails = []; + $this->columnLinks = []; + $this->columnAnnots = []; + $this->columnForms = []; + + $this->col_BMoutlines = []; + $this->col_toc = []; + $this->breakpoints = []; + } + + // mPDF 5.7+ + function columnAdjustPregReplace($type, $xadj, $yadj, $pattern, $subject) + { + preg_match($pattern, $subject, $matches); + + if (!count($matches)) { + return $subject; + } + + if (!isset($matches[3])) { + $matches[3] = 0; + } + + if (!isset($matches[4])) { + $matches[4] = 0; + } + + if (!isset($matches[5])) { + $matches[5] = 0; + } + + if (!isset($matches[6])) { + $matches[6] = 0; + } + + return str_replace($matches[0], $this->columnAdjustAdd($type, Mpdf::SCALE, $xadj, $yadj, $matches[1], $matches[2], $matches[3], $matches[4], $matches[5], $matches[6]), $subject); + } + /* -- END COLUMNS -- */ + + // ================================================================== + /* -- TABLES -- */ + function printcellbuffer() + { + if (count($this->cellBorderBuffer)) { + + sort($this->cellBorderBuffer); + + foreach ($this->cellBorderBuffer as $cbb) { + + $cba = unpack("A16dom/nbord/A1side/ns/dbw/a6ca/A10style/dx/dy/dw/dh/dmbl/dmbr/dmrt/dmrb/dmtl/dmtr/dmlt/dmlb/dcpd/dover/", $cbb); + $side = $cba['side']; + $color = str_pad($cba['ca'], 6, "\x00"); + + $details = []; + + $details[$side]['dom'] = (float) $cba['dom']; + $details[$side]['s'] = $cba['s']; + $details[$side]['w'] = $cba['bw']; + $details[$side]['c'] = $color; + $details[$side]['style'] = trim($cba['style']); + + $details['mbw']['BL'] = $cba['mbl']; + $details['mbw']['BR'] = $cba['mbr']; + $details['mbw']['RT'] = $cba['mrt']; + $details['mbw']['RB'] = $cba['mrb']; + $details['mbw']['TL'] = $cba['mtl']; + $details['mbw']['TR'] = $cba['mtr']; + $details['mbw']['LT'] = $cba['mlt']; + $details['mbw']['LB'] = $cba['mlb']; + + $details['cellposdom'] = $cba['cpd']; + + $details['p'] = $side; + + if ($cba['over'] == 1) { + $details[$side]['overlay'] = true; + } else { + $details[$side]['overlay'] = false; + } + + $this->_tableRect($cba['x'], $cba['y'], $cba['w'], $cba['h'], $cba['bord'], $details, false, false); + } + + $this->cellBorderBuffer = []; + } + } + + // ================================================================== + function printtablebuffer() + { + + if (!$this->table_rotate) { + + $this->pages[$this->page] .= $this->tablebuffer; + + foreach ($this->tbrot_Links as $p => $l) { + foreach ($l as $v) { + $this->PageLinks[$p][] = $v; + } + } + $this->tbrot_Links = []; + + /* -- ANNOTATIONS -- */ + foreach ($this->tbrot_Annots as $p => $l) { + foreach ($l as $v) { + $this->PageAnnots[$p][] = $v; + } + } + $this->tbrot_Annots = []; + /* -- END ANNOTATIONS -- */ + + /* -- BOOKMARKS -- */ + // Output Bookmarks + foreach ($this->tbrot_BMoutlines as $v) { + $this->BMoutlines[] = ['t' => $v['t'], 'l' => $v['l'], 'y' => $v['y'], 'p' => $v['p']]; + } + $this->tbrot_BMoutlines = []; + /* -- END BOOKMARKS -- */ + + /* -- TOC -- */ + // Output ToC + foreach ($this->tbrot_toc as $v) { + $this->tableOfContents->_toc[] = ['t' => $v['t'], 'l' => $v['l'], 'p' => $v['p'], 'link' => $v['link'], 'toc_id' => $v['toc_id']]; + } + $this->tbrot_toc = []; + /* -- END TOC -- */ + + return; + } + + // elseif rotated + $lm = $this->lMargin + $this->blk[$this->blklvl]['outer_left_margin'] + $this->blk[$this->blklvl]['border_left']['w'] + $this->blk[$this->blklvl]['padding_left']; + $pw = $this->blk[$this->blklvl]['inner_width']; + + // Start Transformation + $this->pages[$this->page] .= $this->StartTransform(true) . "\n"; + + if ($this->table_rotate > 1) { // clockwise + + if ($this->tbrot_align == 'L') { + $xadj = $this->tbrot_h; // align L (as is) + } elseif ($this->tbrot_align == 'R') { + $xadj = $lm - $this->tbrot_x0 + ($pw); // align R + } else { + $xadj = $lm - $this->tbrot_x0 + (($pw + $this->tbrot_h) / 2); // align C + } + + $yadj = 0; + + } else { // anti-clockwise + + if ($this->tbrot_align == 'L') { + $xadj = 0; // align L (as is) + } elseif ($this->tbrot_align == 'R') { + $xadj = $lm - $this->tbrot_x0 + ($pw - $this->tbrot_h); // align R + } else { + $xadj = $lm - $this->tbrot_x0 + (($pw - $this->tbrot_h) / 2); // align C + } + + $yadj = $this->tbrot_w; + } + + + $this->pages[$this->page] .= $this->transformTranslate($xadj, $yadj, true) . "\n"; + $this->pages[$this->page] .= $this->transformRotate($this->table_rotate, $this->tbrot_x0, $this->tbrot_y0, true) . "\n"; + + // Now output the adjusted values + $this->pages[$this->page] .= $this->tablebuffer; + + foreach ($this->tbrot_Links as $p => $l) { + + foreach ($l as $v) { + + $w = $v[2] / Mpdf::SCALE; + $h = $v[3] / Mpdf::SCALE; + $ax = ($v[0] / Mpdf::SCALE) - $this->tbrot_x0; + $ay = (($this->hPt - $v[1]) / Mpdf::SCALE) - $this->tbrot_y0; + + if ($this->table_rotate > 1) { // clockwise + $bx = $this->tbrot_x0 + $xadj - $ay - $h; + $by = $this->tbrot_y0 + $yadj + $ax; + } else { + $bx = $this->tbrot_x0 + $xadj + $ay; + $by = $this->tbrot_y0 + $yadj - $ax - $w; + } + + $v[0] = $bx * Mpdf::SCALE; + $v[1] = ($this->h - $by) * Mpdf::SCALE; + $v[2] = $h * Mpdf::SCALE; // swap width and height + $v[3] = $w * Mpdf::SCALE; + + $this->PageLinks[$p][] = $v; + } + } + + $this->tbrot_Links = []; + foreach ($this->internallink as $key => $f) { + if (is_array($f) && isset($f['tbrot'])) { + $f['Y'] = $this->tbrot_y0; + $f['PAGE'] = $this->page; + unset($f['tbrot']); + $this->internallink[$key] = $f; + } + } + + /* -- ANNOTATIONS -- */ + foreach ($this->tbrot_Annots as $p => $l) { + foreach ($l as $v) { + $ax = abs($v['x']) - $this->tbrot_x0; // abs because -ve values are internally set and held for reference if annotMargin set + $ay = $v['y'] - $this->tbrot_y0; + + if ($this->table_rotate > 1) { // clockwise + $bx = $this->tbrot_x0 + $xadj - $ay; + $by = $this->tbrot_y0 + $yadj + $ax; + } else { + $bx = $this->tbrot_x0 + $xadj + $ay; + $by = $this->tbrot_y0 + $yadj - $ax; + } + + if ($v['x'] < 0) { + $v['x'] = -$bx; + } else { + $v['x'] = $bx; + } + + $v['y'] = ($by); + $this->PageAnnots[$p][] = $v; + } + } + + $this->tbrot_Annots = []; + /* -- END ANNOTATIONS -- */ + + /* -- BOOKMARKS -- */ + // Adjust Bookmarks + foreach ($this->tbrot_BMoutlines as $v) { + $v['y'] = $this->tbrot_y0; + $this->BMoutlines[] = ['t' => $v['t'], 'l' => $v['l'], 'y' => $v['y'], 'p' => $this->page]; + } + /* -- END BOOKMARKS -- */ + + /* -- TOC -- */ + // Adjust ToC - uses document page number + foreach ($this->tbrot_toc as $v) { + $this->tableOfContents->_toc[] = ['t' => $v['t'], 'l' => $v['l'], 'p' => $this->page, 'link' => $v['link'], 'toc_id' => $v['toc_id']]; + $this->links[$v['link']][1] = $this->tbrot_y0; + } + /* -- END TOC -- */ + + $this->tbrot_BMoutlines = []; + $this->tbrot_toc = []; + + // Stop Transformation + $this->pages[$this->page] .= $this->StopTransform(true) . "\n"; + + $this->y = $this->tbrot_y0 + $this->tbrot_w; + $this->x = $this->lMargin; + + $this->tablebuffer = ''; + } + + /** + * Keep-with-table This buffers contents of h1-6 to keep on page with table + */ + function printkwtbuffer() + { + if (!$this->kwt_moved) { + + foreach ($this->kwt_buffer as $s) { + $this->pages[$this->page] .= $s['s'] . "\n"; + } + + foreach ($this->kwt_Links as $p => $l) { + foreach ($l as $v) { + $this->PageLinks[$p][] = $v; + } + } + + $this->kwt_Links = []; + + /* -- ANNOTATIONS -- */ + foreach ($this->kwt_Annots as $p => $l) { + foreach ($l as $v) { + $this->PageAnnots[$p][] = $v; + } + } + $this->kwt_Annots = []; + /* -- END ANNOTATIONS -- */ + + /* -- INDEX -- */ + // Output Reference (index) + foreach ($this->kwt_Reference as $v) { + + $Present = 0; + + for ($i = 0; $i < count($this->Reference); $i++) { + if ($this->Reference[$i]['t'] == $v['t']) { + $Present = 1; + if (!in_array($v['op'], $this->Reference[$i]['p'])) { + $this->Reference[$i]['p'][] = $v['op']; + } + } + } + + if ($Present == 0) { + $this->Reference[] = ['t' => $v['t'], 'p' => [$v['op']]]; + } + } + $this->kwt_Reference = []; + /* -- END INDEX -- */ + + /* -- BOOKMARKS -- */ + // Output Bookmarks + foreach ($this->kwt_BMoutlines as $v) { + $this->BMoutlines[] = ['t' => $v['t'], 'l' => $v['l'], 'y' => $v['y'], 'p' => $v['p']]; + } + $this->kwt_BMoutlines = []; + /* -- END BOOKMARKS -- */ + + /* -- TOC -- */ + // Output ToC + foreach ($this->kwt_toc as $v) { + $this->tableOfContents->_toc[] = ['t' => $v['t'], 'l' => $v['l'], 'p' => $v['p'], 'link' => $v['link'], 'toc_id' => $v['toc_id']]; + } + $this->kwt_toc = []; + /* -- END TOC -- */ + + $this->pageoutput[$this->page] = []; // mPDF 6 + + return; + } + + // Start Transformation + $this->pages[$this->page] .= $this->StartTransform(true) . "\n"; + $xadj = $this->lMargin - $this->kwt_x0; + // $yadj = $this->y - $this->kwt_y0 ; + $yadj = $this->tMargin - $this->kwt_y0; + + $this->pages[$this->page] .= $this->transformTranslate($xadj, $yadj, true) . "\n"; + + // Now output the adjusted values + foreach ($this->kwt_buffer as $s) { + $this->pages[$this->page] .= $s['s'] . "\n"; + } + + // Adjust hyperLinks + foreach ($this->kwt_Links as $p => $l) { + foreach ($l as $v) { + $bx = $this->kwt_x0 + $xadj; + $by = $this->kwt_y0 + $yadj; + $v[0] = $bx * Mpdf::SCALE; + $v[1] = ($this->h - $by) * Mpdf::SCALE; + $this->PageLinks[$p][] = $v; + } + } + + foreach ($this->internallink as $key => $f) { + if (is_array($f) && isset($f['kwt'])) { + $f['Y'] += $yadj; + $f['PAGE'] = $this->page; + unset($f['kwt']); + $this->internallink[$key] = $f; + } + } + + /* -- ANNOTATIONS -- */ + foreach ($this->kwt_Annots as $p => $l) { + foreach ($l as $v) { + $bx = $this->kwt_x0 + $xadj; + $by = $this->kwt_y0 + $yadj; + if ($v['x'] < 0) { + $v['x'] = -$bx; + } else { + $v['x'] = $bx; + } + $v['y'] = $by; + $this->PageAnnots[$p][] = $v; + } + } + /* -- END ANNOTATIONS -- */ + + /* -- BOOKMARKS -- */ + + // Adjust Bookmarks + foreach ($this->kwt_BMoutlines as $v) { + if ($v['y'] != 0) { + $v['y'] += $yadj; + } + $this->BMoutlines[] = ['t' => $v['t'], 'l' => $v['l'], 'y' => $v['y'], 'p' => $this->page]; + } + /* -- END BOOKMARKS -- */ + + /* -- INDEX -- */ + // Adjust Reference (index) + foreach ($this->kwt_Reference as $v) { + + $Present = 0; + + // Search the reference (AND Ref/PageNo) in the array + for ($i = 0; $i < count($this->Reference); $i++) { + if ($this->Reference[$i]['t'] == $v['t']) { + $Present = 1; + if (!in_array($this->page, $this->Reference[$i]['p'])) { + $this->Reference[$i]['p'][] = $this->page; + } + } + } + + if ($Present == 0) { + $this->Reference[] = ['t' => $v['t'], 'p' => [$this->page]]; + } + } + /* -- END INDEX -- */ + + /* -- TOC -- */ + + // Adjust ToC + foreach ($this->kwt_toc as $v) { + $this->tableOfContents->_toc[] = ['t' => $v['t'], 'l' => $v['l'], 'p' => $this->page, 'link' => $v['link'], 'toc_id' => $v['toc_id']]; + $this->links[$v['link']][0] = $this->page; + $this->links[$v['link']][1] += $yadj; + } + /* -- END TOC -- */ + + + $this->kwt_Links = []; + $this->kwt_Annots = []; + + $this->kwt_Reference = []; + $this->kwt_BMoutlines = []; + $this->kwt_toc = []; + + // Stop Transformation + $this->pages[$this->page] .= $this->StopTransform(true) . "\n"; + + $this->kwt_buffer = []; + + $this->y += $this->kwt_height; + $this->pageoutput[$this->page] = []; // mPDF 6 + } + /* -- END TABLES -- */ + + function printfloatbuffer() + { + if (count($this->floatbuffer)) { + $this->objectbuffer = $this->floatbuffer; + $this->printobjectbuffer(false); + $this->objectbuffer = []; + $this->floatbuffer = []; + $this->floatmargins = []; + } + } + + function Circle($x, $y, $r, $style = 'S') + { + $this->Ellipse($x, $y, $r, $r, $style); + } + + function Ellipse($x, $y, $rx, $ry, $style = 'S') + { + if ($style === 'F') { + $op = 'f'; + } elseif ($style === 'FD' or $style === 'DF') { + $op = 'B'; + } else { + $op = 'S'; + } + + $lx = 4 / 3 * (M_SQRT2 - 1) * $rx; + $ly = 4 / 3 * (M_SQRT2 - 1) * $ry; + + $h = $this->h; + + $this->writer->write(sprintf('%.3F %.3F m %.3F %.3F %.3F %.3F %.3F %.3F c', ($x + $rx) * Mpdf::SCALE, ($h - $y) * Mpdf::SCALE, ($x + $rx) * Mpdf::SCALE, ($h - ($y - $ly)) * Mpdf::SCALE, ($x + $lx) * Mpdf::SCALE, ($h - ($y - $ry)) * Mpdf::SCALE, $x * Mpdf::SCALE, ($h - ($y - $ry)) * Mpdf::SCALE)); + $this->writer->write(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F c', ($x - $lx) * Mpdf::SCALE, ($h - ($y - $ry)) * Mpdf::SCALE, ($x - $rx) * Mpdf::SCALE, ($h - ($y - $ly)) * Mpdf::SCALE, ($x - $rx) * Mpdf::SCALE, ($h - $y) * Mpdf::SCALE)); + $this->writer->write(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F c', ($x - $rx) * Mpdf::SCALE, ($h - ($y + $ly)) * Mpdf::SCALE, ($x - $lx) * Mpdf::SCALE, ($h - ($y + $ry)) * Mpdf::SCALE, $x * Mpdf::SCALE, ($h - ($y + $ry)) * Mpdf::SCALE)); + $this->writer->write(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F c %s', ($x + $lx) * Mpdf::SCALE, ($h - ($y + $ry)) * Mpdf::SCALE, ($x + $rx) * Mpdf::SCALE, ($h - ($y + $ly)) * Mpdf::SCALE, ($x + $rx) * Mpdf::SCALE, ($h - $y) * Mpdf::SCALE, $op)); + } + + /* -- DIRECTW -- */ + function AutosizeText($text, $w, $font, $style, $szfont = 72) + { + + $text = ' ' . $text . ' '; + + $this->SetFont($font, $style, $szfont, false); + + $text = $this->purify_utf8_text($text); + if ($this->text_input_as_HTML) { + $text = $this->all_entities_to_utf8($text); + } + if ($this->usingCoreFont) { + $text = mb_convert_encoding($text, $this->mb_enc, 'UTF-8'); + } + + // DIRECTIONALITY + if (preg_match("/([" . $this->pregRTLchars . "])/u", $text)) { + $this->biDirectional = true; + } + + $textvar = 0; + $save_OTLtags = $this->OTLtags; + $this->OTLtags = []; + + if ($this->useKerning) { + if ($this->CurrentFont['haskernGPOS']) { + $this->OTLtags['Plus'] .= ' kern'; + } else { + $textvar = ($textvar | TextVars::FC_KERNING); + } + } + + /* -- OTL -- */ + // Use OTL OpenType Table Layout - GSUB & GPOS + if (isset($this->CurrentFont['useOTL']) && $this->CurrentFont['useOTL']) { + $text = $this->otl->applyOTL($text, $this->CurrentFont['useOTL']); + $OTLdata = $this->otl->OTLdata; + } + /* -- END OTL -- */ + + $this->OTLtags = $save_OTLtags; + + $this->magic_reverse_dir($text, $this->directionality, $OTLdata); + + $width = $this->sizeConverter->convert($w); + $loop = 0; + + while ($loop == 0) { + + $this->SetFont($font, $style, $szfont, false); + $sz = $this->GetStringWidth($text, true, $OTLdata, $textvar); + + if ($sz > $w) { + $szfont --; + } else { + $loop ++; + } + } + + $this->SetFont($font, $style, $szfont, true, true); + $this->Cell($w, 0, $text, 0, 0, "C", 0, '', 0, 0, 0, 'M', 0, false, $OTLdata, $textvar); + } + /* -- END DIRECTW -- */ + + // ==================================================== + // ==================================================== + + function magic_reverse_dir(&$chunk, $dir, &$chunkOTLdata) + { + /* -- OTL -- */ + if ($this->usingCoreFont) { + return 0; + } + + if ($chunk == '') { + return 0; + } + + if ($this->biDirectional || $dir == 'rtl') { + + // check if string contains RTL text + // including any added from OTL tables (in PUA) + $pregRTLchars = $this->pregRTLchars; + + if (isset($this->CurrentFont['rtlPUAstr']) && $this->CurrentFont['rtlPUAstr']) { + $pregRTLchars .= $this->CurrentFont['rtlPUAstr']; + } + + if (!preg_match("/[" . $pregRTLchars . "]/u", $chunk) && $dir != 'rtl') { + return 0; + } // Chunk doesn't contain RTL characters + + $unicode = $this->UTF8StringToArray($chunk, false); + + $isStrong = false; + if (empty($chunkOTLdata)) { + $this->getBasicOTLdata($chunkOTLdata, $unicode, $isStrong); + } + + $useGPOS = isset($this->CurrentFont['useOTL']) && ($this->CurrentFont['useOTL'] & 0x80); + + // NB Returned $chunk may be a shorter string (with adjusted $cOTLdata) by removal of LRE, RLE etc embedding codes. + list($chunk, $rtl_content) = $this->otl->bidiSort($unicode, $chunk, $dir, $chunkOTLdata, $useGPOS); + + return $rtl_content; + } + + /* -- END OTL -- */ + return 0; + } + + /* -- OTL -- */ + + function getBasicOTLdata(&$chunkOTLdata, $unicode, &$is_strong) + { + if (empty($this->otl)) { + $this->otl = new Otl($this, $this->fontCache); + } + + $chunkOTLdata['group'] = ''; + $chunkOTLdata['GPOSinfo'] = []; + $chunkOTLdata['char_data'] = []; + + foreach ($unicode as $char) { + + $ucd_record = Ucdn::get_ucd_record($char); + $chunkOTLdata['char_data'][] = ['bidi_class' => $ucd_record[2], 'uni' => $char]; + + if ($ucd_record[2] == 0 || $ucd_record[2] == 3 || $ucd_record[2] == 4) { + $is_strong = true; + } // contains strong character + + if ($ucd_record[0] == Ucdn::UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK) { + $chunkOTLdata['group'] .= 'M'; + } elseif ($char == 32 || $char == 12288) { + $chunkOTLdata['group'] .= 'S'; + } else { + $chunkOTLdata['group'] .= 'C'; + } + } + } + + function _setBidiCodes($mode = 'start', $bdf = '') + { + $s = ''; + + if ($mode == 'end') { + + // PDF comes before PDI to close isolate-override (e.g. "LRILROPDFPDI") + if (strpos($bdf, 'PDF') !== false) { + $s .= UtfString::code2utf(0x202C); + } // POP DIRECTIONAL FORMATTING + + if (strpos($bdf, 'PDI') !== false) { + $s .= UtfString::code2utf(0x2069); + } // POP DIRECTIONAL ISOLATE + + } elseif ($mode == 'start') { + + // LRI comes before LRO to open isolate-override (e.g. "LRILROPDFPDI") + if (strpos($bdf, 'LRI') !== false) { // U+2066 LRI + $s .= UtfString::code2utf(0x2066); + } elseif (strpos($bdf, 'RLI') !== false) { // U+2067 RLI + $s .= UtfString::code2utf(0x2067); + } elseif (strpos($bdf, 'FSI') !== false) { // U+2068 FSI + $s .= UtfString::code2utf(0x2068); + } + + if (strpos($bdf, 'LRO') !== false) { // U+202D LRO + $s .= UtfString::code2utf(0x202D); + } elseif (strpos($bdf, 'RLO') !== false) { // U+202E RLO + $s .= UtfString::code2utf(0x202E); + } elseif (strpos($bdf, 'LRE') !== false) { // U+202A LRE + $s .= UtfString::code2utf(0x202A); + } elseif (strpos($bdf, 'RLE') !== false) { // U+202B RLE + $s .= UtfString::code2utf(0x202B); + } + } + + return $s; + } + /* -- END OTL -- */ + + function SetSubstitutions() + { + $subsarray = []; + require __DIR__ . '/../data/subs_win-1252.php'; + $this->substitute = []; + foreach ($subsarray as $key => $val) { + $this->substitute[UtfString::code2utf($key)] = $val; + } + } + + function SubstituteChars($html) + { + // only substitute characters between tags + if (count($this->substitute)) { + $a = preg_split('/(<.*?>)/ms', $html, -1, PREG_SPLIT_DELIM_CAPTURE); + $html = ''; + foreach ($a as $i => $e) { + if ($i % 2 == 0) { + $e = strtr($e, $this->substitute); + } + $html .= $e; + } + } + + return $html; + } + + function SubstituteCharsSIP(&$writehtml_a, &$writehtml_i, &$writehtml_e) + { + if (preg_match("/^(.*?)([\x{20000}-\x{2FFFF}]+)(.*)/u", $writehtml_e, $m)) { + if (isset($this->CurrentFont['sipext']) && $this->CurrentFont['sipext']) { + $font = $this->CurrentFont['sipext']; + if (!in_array($font, $this->available_unifonts)) { + return 0; + } + $writehtml_a[$writehtml_i] = $writehtml_e = $m[1]; + array_splice($writehtml_a, $writehtml_i + 1, 0, ['span style="font-family: ' . $font . '"', $m[2], '/span', $m[3]]); + $this->subPos = $writehtml_i; + return 4; + } + } + + return 0; + } + + /** + * If core font is selected in document which is not onlyCoreFonts - substitute with non-core font + */ + function SubstituteCharsNonCore(&$writehtml_a, &$writehtml_i, &$writehtml_e) + { + // Ignore if in Textarea + if ($writehtml_i > 0 && strtolower(substr($writehtml_a[$writehtml_i - 1], 0, 8)) == 'textarea') { + return 0; + } + + if (mb_convert_encoding(mb_convert_encoding($writehtml_e, $this->mb_enc, "UTF-8"), "UTF-8", $this->mb_enc) == $writehtml_e) { + return 0; + } + + $cw = &$this->CurrentFont['cw']; + $unicode = $this->UTF8StringToArray($writehtml_e, false); + $start = -1; + $end = 0; + $flag = 0; + $ftype = ''; + $u = []; + + if (!$this->subArrMB) { + + require __DIR__ . '/../data/subs_core.php'; + + $this->subArrMB['a'] = $aarr; + $this->subArrMB['s'] = $sarr; + $this->subArrMB['z'] = $zarr; + } + + foreach ($unicode as $c => $char) { + + if (($char > 127 || ($flag == 1 && $char == 32)) && $char != 173 && (!isset($this->subArrMB['a'][$char]) || ($flag == 1 && $char == 32)) && ($char < 1536 || ($char > 1791 && $char < 2304) || $char > 3455)) { + if ($flag == 0) { + $start = $c; + } + $flag = 1; + $u[] = $char; + } elseif ($flag > 0) { + $end = $c - 1; + break; + } + } + + if ($flag > 0 && !$end) { + $end = count($unicode) - 1; + } + + if ($start == -1) { + return 0; + } + + // Try in backup subs font + if (!is_array($this->backupSubsFont)) { + $this->backupSubsFont = ["$this->backupSubsFont"]; + } + + foreach ($this->backupSubsFont as $bsfctr => $bsf) { + + if ($this->fonttrans[$bsf] == 'chelvetica' || $this->fonttrans[$bsf] == 'ctimes' || $this->fonttrans[$bsf] == 'ccourier') { + continue; + } + + $font = $bsf; + unset($cw); + $cw = ''; + + if (isset($this->fonts[$font])) { + $cw = &$this->fonts[$font]['cw']; + } elseif ($this->fontCache->has($font . '.cw.dat')) { + $cw = $this->fontCache->load($font . '.cw.dat'); + } else { + $prevFontFamily = $this->FontFamily; + $prevFontStyle = $this->currentfontstyle; + $prevFontSizePt = $this->FontSizePt; + $this->SetFont($bsf, '', '', false); + $this->SetFont($prevFontFamily, $prevFontStyle, $prevFontSizePt, false); + } + + if (!$cw) { + continue; + } + + $l = 0; + foreach ($u as $char) { + if ($char == 173 || $this->_charDefined($cw, $char) || ($char > 1536 && $char < 1791) || ($char > 2304 && $char < 3455 )) { + $l++; + } else { + if ($l == 0 && $bsfctr == (count($this->backupSubsFont) - 1)) { // Not found even in last backup font + $cont = mb_substr($writehtml_e, $start + 1); + $writehtml_e = mb_substr($writehtml_e, 0, $start + 1, 'UTF-8'); + array_splice($writehtml_a, $writehtml_i + 1, 0, ['', $cont]); + $this->subPos = $writehtml_i + 1; + + return 2; + } else { + break; + } + } + } + + if ($l > 0) { + $patt = mb_substr($writehtml_e, $start, $l, 'UTF-8'); + if (preg_match("/(.*?)(" . preg_quote($patt, '/') . ")(.*)/u", $writehtml_e, $m)) { + $writehtml_e = $m[1]; + array_splice($writehtml_a, $writehtml_i + 1, 0, ['span style="font-family: ' . $font . '"', $m[2], '/span', $m[3]]); + $this->subPos = $writehtml_i + 3; + + return 4; + } + } + } + + unset($cw); + + return 0; + } + + function SubstituteCharsMB(&$writehtml_a, &$writehtml_i, &$writehtml_e) + { + // Ignore if in Textarea + if ($writehtml_i > 0 && strtolower(substr($writehtml_a[$writehtml_i - 1], 0, 8)) == 'textarea') { + return 0; + } + + $cw = &$this->CurrentFont['cw']; + $unicode = $this->UTF8StringToArray($writehtml_e, false); + $start = -1; + $end = 0; + $flag = 0; + $ftype = ''; + $u = []; + + foreach ($unicode as $c => $char) { + + if (($flag == 0 || $flag == 2) && (!$this->_charDefined($cw, $char) || ($flag == 2 && $char == 32)) && $this->checkSIP && $char > 131071) { // Unicode Plane 2 (SIP) + + if (in_array($this->FontFamily, $this->available_CJK_fonts)) { + return 0; + } + + if ($flag == 0) { + $start = $c; + } + + $flag = 2; + $u[] = $char; + + // elseif (($flag == 0 || $flag==1) && $char != 173 && !$this->_charDefined($cw,$char) && ($char<1423 || ($char>3583 && $char < 11263))) { + + } elseif (($flag == 0 || $flag == 1) && $char != 173 && (!$this->_charDefined($cw, $char) || ($flag == 1 && $char == 32)) && ($char < 1536 || ($char > 1791 && $char < 2304) || $char > 3455)) { + + if ($flag == 0) { + $start = $c; + } + + $flag = 1; + $u[] = $char; + + } elseif ($flag > 0) { + + $end = $c - 1; + break; + + } + } + + if ($flag > 0 && !$end) { + $end = count($unicode) - 1; + } + + if ($start == -1) { + return 0; + } + + if ($flag == 2) { // SIP + + // Check if current CJK font has a ext-B related font + if (isset($this->CurrentFont['sipext']) && $this->CurrentFont['sipext']) { + $font = $this->CurrentFont['sipext']; + unset($cw); + $cw = ''; + + if (isset($this->fonts[$font])) { + $cw = &$this->fonts[$font]['cw']; + } elseif ($this->fontCache->has($font . '.cw.dat')) { + $cw = $this->fontCache->load($font . '.cw.dat'); + } else { + $prevFontFamily = $this->FontFamily; + $prevFontStyle = $this->currentfontstyle; + $prevFontSizePt = $this->FontSizePt; + $this->SetFont($font, '', '', false); + $this->SetFont($prevFontFamily, $prevFontStyle, $prevFontSizePt, false); + } + + if (!$cw) { + return 0; + } + + $l = 0; + foreach ($u as $char) { + if ($this->_charDefined($cw, $char) || $char > 131071) { + $l++; + } else { + break; + } + } + + if ($l > 0) { + $patt = mb_substr($writehtml_e, $start, $l); + if (preg_match("/(.*?)(" . preg_quote($patt, '/') . ")(.*)/u", $writehtml_e, $m)) { + $writehtml_e = $m[1]; + array_splice($writehtml_a, $writehtml_i + 1, 0, ['span style="font-family: ' . $font . '"', $m[2], '/span', $m[3]]); + $this->subPos = $writehtml_i + 3; + return 4; + } + } + } + + // Check Backup SIP font (defined in Config\FontVariables) + if (isset($this->backupSIPFont) && $this->backupSIPFont) { + + if ($this->currentfontfamily != $this->backupSIPFont) { + $font = $this->backupSIPFont; + } else { + unset($cw); + return 0; + } + + unset($cw); + $cw = ''; + + if (isset($this->fonts[$font])) { + $cw = &$this->fonts[$font]['cw']; + } elseif ($this->fontCache->has($font . '.cw.dat')) { + $cw = $this->fontCache->load($font . '.cw.dat'); + } else { + $prevFontFamily = $this->FontFamily; + $prevFontStyle = $this->currentfontstyle; + $prevFontSizePt = $this->FontSizePt; + $this->SetFont($this->backupSIPFont, '', '', false); + $this->SetFont($prevFontFamily, $prevFontStyle, $prevFontSizePt, false); + } + + if (!$cw) { + return 0; + } + + $l = 0; + foreach ($u as $char) { + if ($this->_charDefined($cw, $char) || $char > 131071) { + $l++; + } else { + break; + } + } + + if ($l > 0) { + $patt = mb_substr($writehtml_e, $start, $l); + if (preg_match("/(.*?)(" . preg_quote($patt, '/') . ")(.*)/u", $writehtml_e, $m)) { + $writehtml_e = $m[1]; + array_splice($writehtml_a, $writehtml_i + 1, 0, ['span style="font-family: ' . $font . '"', $m[2], '/span', $m[3]]); + $this->subPos = $writehtml_i + 3; + return 4; + } + } + } + + return 0; + } + + // FIRST TRY CORE FONTS (when appropriate) + if (!$this->PDFA && !$this->PDFX && !$this->biDirectional) { // mPDF 6 + $repl = []; + if (!$this->subArrMB) { + require __DIR__ . '/../data/subs_core.php'; + $this->subArrMB['a'] = $aarr; + $this->subArrMB['s'] = $sarr; + $this->subArrMB['z'] = $zarr; + } + if (isset($this->subArrMB['a'][$u[0]])) { + $font = 'tta'; + $ftype = 'C'; + foreach ($u as $char) { + if (isset($this->subArrMB['a'][$char])) { + $repl[] = $this->subArrMB['a'][$char]; + } else { + break; + } + } + } elseif (isset($this->subArrMB['z'][$u[0]])) { + $font = 'ttz'; + $ftype = 'C'; + foreach ($u as $char) { + if (isset($this->subArrMB['z'][$char])) { + $repl[] = $this->subArrMB['z'][$char]; + } else { + break; + } + } + } elseif (isset($this->subArrMB['s'][$u[0]])) { + $font = 'tts'; + $ftype = 'C'; + foreach ($u as $char) { + if (isset($this->subArrMB['s'][$char])) { + $repl[] = $this->subArrMB['s'][$char]; + } else { + break; + } + } + } + if ($ftype == 'C') { + $patt = mb_substr($writehtml_e, $start, count($repl)); + if (preg_match("/(.*?)(" . preg_quote($patt, '/') . ")(.*)/u", $writehtml_e, $m)) { + $writehtml_e = $m[1]; + array_splice($writehtml_a, $writehtml_i + 1, 0, [$font, implode('|', $repl), '/' . $font, $m[3]]); // e.g. <tts> + $this->subPos = $writehtml_i + 3; + return 4; + } + return 0; + } + } + + // LASTLY TRY IN BACKUP SUBS FONT + if (!is_array($this->backupSubsFont)) { + $this->backupSubsFont = ["$this->backupSubsFont"]; + } + + foreach ($this->backupSubsFont as $bsfctr => $bsf) { + if ($this->currentfontfamily != $bsf) { + $font = $bsf; + } else { + continue; + } + + unset($cw); + $cw = ''; + + if (isset($this->fonts[$font])) { + $cw = &$this->fonts[$font]['cw']; + } elseif ($this->fontCache->has($font . '.cw.dat')) { + $cw = $this->fontCache->load($font . '.cw.dat'); + } else { + $prevFontFamily = $this->FontFamily; + $prevFontStyle = $this->currentfontstyle; + $prevFontSizePt = $this->FontSizePt; + $this->SetFont($bsf, '', '', false); + $this->SetFont($prevFontFamily, $prevFontStyle, $prevFontSizePt, false); + if ($this->fontCache->has($font . '.cw.dat')) { + $cw = $this->fontCache->load($font . '.cw.dat'); + } + } + + if (!$cw) { + continue; + } + + $l = 0; + foreach ($u as $char) { + if ($char == 173 || $this->_charDefined($cw, $char) || ($char > 1536 && $char < 1791) || ($char > 2304 && $char < 3455 )) { // Arabic and Indic + $l++; + } else { + if ($l == 0 && $bsfctr == (count($this->backupSubsFont) - 1)) { // Not found even in last backup font + $cont = mb_substr($writehtml_e, $start + 1); + $writehtml_e = mb_substr($writehtml_e, 0, $start + 1); + array_splice($writehtml_a, $writehtml_i + 1, 0, ['', $cont]); + $this->subPos = $writehtml_i + 1; + return 2; + } else { + break; + } + } + } + + if ($l > 0) { + $patt = mb_substr($writehtml_e, $start, $l); + if (preg_match("/(.*?)(" . preg_quote($patt, '/') . ")(.*)/u", $writehtml_e, $m)) { + $writehtml_e = $m[1]; + array_splice($writehtml_a, $writehtml_i + 1, 0, ['span style="font-family: ' . $font . '"', $m[2], '/span', $m[3]]); + $this->subPos = $writehtml_i + 3; + return 4; + } + } + } + + unset($cw); + + return 0; + } + + function setHiEntitySubstitutions() + { + $entarr = include __DIR__ . '/../data/entity_substitutions.php'; + + foreach ($entarr as $key => $val) { + $this->entsearch[] = '&' . $key . ';'; + $this->entsubstitute[] = UtfString::code2utf($val); + } + } + + function SubstituteHiEntities($html) + { + // converts html_entities > ASCII 127 to unicode + // Leaves in particular < to distinguish from tag marker + if (count($this->entsearch)) { + $html = str_replace($this->entsearch, $this->entsubstitute, $html); + } + + return $html; + } + + /** + * Edited v1.2 Pass by reference; option to continue if invalid UTF-8 chars + */ + function is_utf8(&$string) + { + if ($string === mb_convert_encoding(mb_convert_encoding($string, "UTF-32", "UTF-8"), "UTF-8", "UTF-32")) { + return true; + } + + if ($this->ignore_invalid_utf8) { + $string = mb_convert_encoding(mb_convert_encoding($string, "UTF-32", "UTF-8"), "UTF-8", "UTF-32"); + return true; + } + + return false; + } + + /** + * For HTML + * + * Checks string is valid UTF-8 encoded + * converts html_entities > ASCII 127 to UTF-8 + * Only exception - leaves low ASCII entities e.g. < & etc. + * Leaves in particular < to distinguish from tag marker + */ + function purify_utf8($html, $lo = true) + { + if (!$this->is_utf8($html)) { + + while (mb_convert_encoding(mb_convert_encoding($html, "UTF-32", "UTF-8"), "UTF-8", "UTF-32") != $html) { + + $a = @iconv('UTF-8', 'UTF-8', $html); + $error = error_get_last(); + if ($error && $error['message'] === 'iconv(): Detected an illegal character in input string') { + throw new \Mpdf\MpdfException('Invalid input characters. Did you set $mpdf->in_charset properly?'); + } + + $pos = $start = strlen($a); + $err = ''; + while (ord(substr($html, $pos, 1)) > 128) { + $err .= '[[#' . ord(substr($html, $pos, 1)) . ']]'; + $pos++; + } + + $this->logger->error($err, ['context' => LogContext::UTF8]); + $html = substr($html, $pos); + } + + throw new \Mpdf\MpdfException("HTML contains invalid UTF-8 character(s). See log for further details"); + } + + $html = preg_replace("/\r/", "", $html); + + // converts html_entities > ASCII 127 to UTF-8 + // Leaves in particular < to distinguish from tag marker + $html = $this->SubstituteHiEntities($html); + + // converts all &#nnn; or &#xHHH; to UTF-8 multibyte + // If $lo==true then includes ASCII < 128 + $html = UtfString::strcode2utf($html, $lo); + + return $html; + } + + /** + * For TEXT + */ + function purify_utf8_text($txt) + { + // Make sure UTF-8 string of characters + if (!$this->is_utf8($txt)) { + throw new \Mpdf\MpdfException("Text contains invalid UTF-8 character(s)"); + } + + $txt = preg_replace("/\r/", "", $txt); + + return ($txt); + } + + function all_entities_to_utf8($txt) + { + // converts txt_entities > ASCII 127 to UTF-8 + // Leaves in particular < to distinguish from tag marker + $txt = $this->SubstituteHiEntities($txt); + + // converts all &#nnn; or &#xHHH; to UTF-8 multibyte + $txt = UtfString::strcode2utf($txt); + + $txt = $this->lesser_entity_decode($txt); + return ($txt); + } + + /* -- BARCODES -- */ + /** + * UPC/EAN barcode + * + * EAN13, EAN8, UPCA, UPCE, ISBN, ISSN + * Accepts 12 or 13 digits with or without - hyphens + */ + function WriteBarcode($code, $showtext = 1, $x = '', $y = '', $size = 1, $border = 0, $paddingL = 1, $paddingR = 1, $paddingT = 2, $paddingB = 2, $height = 1, $bgcol = false, $col = false, $btype = 'ISBN', $supplement = '0', $supplement_code = '', $k = 1) + { + if (empty($code)) { + return; + } + + $codestr = $code; + $code = preg_replace('/\-/', '', $code); + + $this->barcode = new Barcode(); + if ($btype == 'ISSN' || $btype == 'ISBN') { + $arrcode = $this->barcode->getBarcodeArray($code, 'EAN13'); + } else { + $arrcode = $this->barcode->getBarcodeArray($code, $btype); + } + + if ($arrcode === false) { + throw new \Mpdf\MpdfException('Error in barcode string: ' . $codestr); + } + + if ((($btype === 'EAN13' || $btype === 'ISBN' || $btype === 'ISSN') && strlen($code) === 12) + || ($btype == 'UPCA' && strlen($code) === 11) + || ($btype == 'UPCE' && strlen($code) === 11) + || ($btype == 'EAN8' && strlen($code) === 7)) { + + $code .= $arrcode['checkdigit']; + + if (stristr($codestr, '-')) { + $codestr .= '-' . $arrcode['checkdigit']; + } else { + $codestr .= $arrcode['checkdigit']; + } + } + + if ($btype === 'ISBN') { + $codestr = 'ISBN ' . $codestr; + } + + if ($btype === 'ISSN') { + $codestr = 'ISSN ' . $codestr; + } + + if (empty($x)) { + $x = $this->x; + } + + if (empty($y)) { + $y = $this->y; + } + + // set foreground color + $prevDrawColor = $this->DrawColor; + $prevTextColor = $this->TextColor; + $prevFillColor = $this->FillColor; + + $lw = $this->LineWidth; + $this->SetLineWidth(0.01); + + $size /= $k; // in case resized in a table + + $xres = $arrcode['nom-X'] * $size; + $llm = $arrcode['lightmL'] * $arrcode['nom-X'] * $size; // Left Light margin + $rlm = $arrcode['lightmR'] * $arrcode['nom-X'] * $size; // Right Light margin + + $bcw = ($arrcode["maxw"] * $xres); // Barcode width = Should always be 31.35mm * $size + + $fbw = $bcw + $llm + $rlm; // Full barcode width incl. light margins + $ow = $fbw + $paddingL + $paddingR; // Full overall width incl. user-defined padding + + $fbwi = $fbw - 2; // Full barcode width incl. light margins - 2mm - for isbn string + // cf. http://www.gs1uk.org/downloads/bar_code/Bar coding getting it right.pdf + $num_height = 3 * $size; // Height of numerals + $fbh = $arrcode['nom-H'] * $size * $height; // Full barcode height incl. numerals + $bch = $fbh - (1.5 * $size); // Barcode height of bars (3mm for numerals) + + if (($btype == 'EAN13' && $showtext) || $btype == 'ISSN' || $btype == 'ISBN') { // Add height for ISBN string + margin from top of bars + $tisbnm = 1.5 * $size; // Top margin between isbn (if shown) & bars + $codestr_fontsize = 2.1 * $size; + $paddingT += $codestr_fontsize + $tisbnm; + } + + $oh = $fbh + $paddingT + $paddingB; // Full overall height incl. user-defined padding + + // PRINT border background color + $xpos = $x; + $ypos = $y; + + if ($col) { + $this->SetDColor($col); + $this->SetTColor($col); + } else { + $this->SetDColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + $this->SetTColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + } + + if ($bgcol) { + $this->SetFColor($bgcol); + } else { + $this->SetFColor($this->colorConverter->convert(255, $this->PDFAXwarnings)); + } + + if (!$bgcol && !$col) { // fn. called directly - not via HTML + + if ($border) { + $fillb = 'DF'; + } else { + $fillb = 'F'; + } + + $this->Rect($xpos, $ypos, $ow, $oh, $fillb); + } + + + // PRINT BARS + $xpos = $x + $paddingL + $llm; + $ypos = $y + $paddingT; + + if ($col) { + $this->SetFColor($col); + } else { + $this->SetFColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + } + + if ($arrcode !== false) { + foreach ($arrcode["bcode"] as $v) { + $bw = ($v["w"] * $xres); + if ($v["t"]) { + // draw a vertical bar + $this->Rect($xpos, $ypos, $bw, $bch, 'F'); + } + $xpos += $bw; + } + } + + // print text + $prevFontFamily = $this->FontFamily; + $prevFontStyle = $this->FontStyle; + $prevFontSizePt = $this->FontSizePt; + + // ISBN string + if (($btype === 'EAN13' && $showtext) || $btype === 'ISBN' || $btype === 'ISSN') { + + if ($this->onlyCoreFonts) { + $this->SetFont('chelvetica'); + } else { + $this->SetFont('sans'); + } + + if ($bgcol) { + $this->SetFColor($bgcol); + } else { + $this->SetFColor($this->colorConverter->convert(255, $this->PDFAXwarnings)); + } + + $this->x = $x + $paddingL + 1; // 1mm left margin (cf. $fbwi above) + + // max width is $fbwi + $loop = 0; + while ($loop == 0) { + $this->SetFontSize($codestr_fontsize * 1.4 * Mpdf::SCALE, false); // don't write + $sz = $this->GetStringWidth($codestr); + + if ($sz > $fbwi) { + $codestr_fontsize -= 0.1; + } else { + $loop ++; + } + } + + $this->SetFont('', '', $codestr_fontsize * 1.4 * Mpdf::SCALE, true, true); // * 1.4 because font height is only 7/10 of given mm + // WORD SPACING + if ($fbwi > $sz) { + $xtra = $fbwi - $sz; + $charspacing = $xtra / (strlen($codestr) - 1); + if ($charspacing) { + $this->writer->write(sprintf('BT %.3F Tc ET', $charspacing * Mpdf::SCALE)); + } + } + + $this->y = $y + $paddingT - ($codestr_fontsize ) - $tisbnm; + $this->Cell($fbw, $codestr_fontsize, $codestr); + + if ($charspacing) { + $this->writer->write('BT 0 Tc ET'); + } + } + + + // Bottom NUMERALS + // mPDF 5.7.4 + if ($this->onlyCoreFonts) { + $this->SetFont('ccourier'); + $fh = 1.3; + } else { + $this->SetFont('ocrb'); + $fh = 1.06; + } + + $charRO = ''; + + if ($btype === 'EAN13' || $btype === 'ISBN' || $btype === 'ISSN') { + + $outerfontsize = 3; // Inner fontsize = 3 + $outerp = $xres * 4; + $innerp = $xres * 2.5; + $textw = ($bcw * 0.5) - $outerp - $innerp; + $chars = 6; // number of numerals in each half + $charLO = substr($code, 0, 1); // Left Outer + $charLI = substr($code, 1, 6); // Left Inner + $charRI = substr($code, 7, 6); // Right Inner + + if (!$supplement) { + $charRO = '>'; // Right Outer + } + + } elseif ($btype === 'UPCA') { + + $outerfontsize = 2.3; // Inner fontsize = 3 + $outerp = $xres * 10; + $innerp = $xres * 2.5; + $textw = ($bcw * 0.5) - $outerp - $innerp; + $chars = 5; + $charLO = substr($code, 0, 1); // Left Outer + $charLI = substr($code, 1, 5); // Left Inner + $charRI = substr($code, 6, 5); // Right Inner + $charRO = substr($code, 11, 1); // Right Outer + + } elseif ($btype === 'UPCE') { + + $outerfontsize = 2.3; // Inner fontsize = 3 + $outerp = $xres * 4; + $innerp = 0; + $textw = ($bcw * 0.5) - $outerp - $innerp; + $chars = 3; + $upce_code = $arrcode['code']; + $charLO = substr($code, 0, 1); // Left Outer + $charLI = substr($upce_code, 0, 3); // Left Inner + $charRI = substr($upce_code, 3, 3); // Right Inner + $charRO = substr($code, 11, 1); // Right Outer + + } elseif ($btype === 'EAN8') { + + $outerfontsize = 3; // Inner fontsize = 3 + $outerp = $xres * 4; + $innerp = $xres * 2.5; + $textw = ($bcw * 0.5) - $outerp - $innerp; + $chars = 4; + $charLO = '<'; // Left Outer + $charLI = substr($code, 0, 4); // Left Inner + $charRI = substr($code, 4, 4); // Right Inner + + if (!$supplement) { + $charRO = '>'; // Right Outer + } + } + + $this->SetFontSize(($outerfontsize / 3) * 3 * $fh * $size * Mpdf::SCALE); // 3mm numerals (FontSize is larger to account for space above/below characters) + + if (!$this->usingCoreFont) { // character width at 3mm + $cw = $this->_getCharWidth($this->CurrentFont['cw'], 32) * 3 * $fh * $size / 1000; + } else { + $cw = 600 * 3 * $fh * $size / 1000; + } + + // Outer left character + $y_text = $y + $paddingT + $bch - ($num_height / 2); + $y_text_outer = $y + $paddingT + $bch - ($num_height * ($outerfontsize / 3) / 2); + + $this->x = $x + $paddingL - ($cw * ($outerfontsize / 3) * 0.1); // 0.1 is correction as char does not fill full width; + $this->y = $y_text_outer; + $this->Cell($cw, $num_height, $charLO); + + // WORD SPACING for inner chars + $xtra = $textw - ($cw * $chars); + $charspacing = $xtra / ($chars - 1); + if ($charspacing) { + $this->writer->write(sprintf('BT %.3F Tc ET', $charspacing * Mpdf::SCALE)); + } + + if ($bgcol) { + $this->SetFColor($bgcol); + } else { + $this->SetFColor($this->colorConverter->convert(255, $this->PDFAXwarnings)); + } + + $this->SetFontSize(3 * $fh * $size * Mpdf::SCALE); // 3mm numerals (FontSize is larger to account for space above/below characters) + + // Inner left half characters + $this->x = $x + $paddingL + $llm + $outerp; + $this->y = $y_text; + $this->Cell($textw, $num_height, $charLI, 0, 0, '', 1); + + // Inner right half characters + $this->x = $x + $paddingL + $llm + ($bcw * 0.5) + $innerp; + $this->y = $y_text; + $this->Cell($textw, $num_height, $charRI, 0, 0, '', 1); + + if ($charspacing) { + $this->writer->write('BT 0 Tc ET'); + } + + // Outer Right character + $this->SetFontSize(($outerfontsize / 3) * 3 * $fh * $size * Mpdf::SCALE); // 3mm numerals (FontSize is larger to account for space above/below characters) + + $this->x = $x + $paddingL + $llm + $bcw + $rlm - ($cw * ($outerfontsize / 3) * 0.9); // 0.9 is correction as char does not fill full width + $this->y = $y_text_outer; + $this->Cell($cw * ($outerfontsize / 3), $num_height, $charRO, 0, 0, 'R'); + + if ($supplement) { // EAN-2 or -5 Supplement + // PRINT BARS + $supparrcode = $this->barcode->getBarcodeArray($supplement_code, 'EAN' . $supplement); + + if ($supparrcode === false) { + throw new \Mpdf\MpdfException('Error in barcode string (supplement): ' . $codestr . ' ' . $supplement_code); + } + + if (strlen($supplement_code) != $supplement) { + throw new \Mpdf\MpdfException('Barcode supplement incorrect: ' . $supplement_code); + } + + $llm = $fbw - (($arrcode['lightmR'] - $supparrcode['sepM']) * $arrcode['nom-X'] * $size); // Left Light margin + $rlm = $arrcode['lightmR'] * $arrcode['nom-X'] * $size; // Right Light margin + + $bcw = ($supparrcode["maxw"] * $xres); // Barcode width = Should always be 31.35mm * $size + + $fbw = $bcw + $llm + $rlm; // Full barcode width incl. light margins + $ow = $fbw + $paddingL + $paddingR; // Full overall width incl. user-defined padding + $bch = $fbh - (1.5 * $size) - ($num_height + 0.5); // Barcode height of bars (3mm for numerals) + + $xpos = $x + $paddingL + $llm; + $ypos = $y + $paddingT + $num_height + 0.5; + + if ($col) { + $this->SetFColor($col); + } else { + $this->SetFColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + } + + if ($supparrcode !== false) { + foreach ($supparrcode["bcode"] as $v) { + $bw = ($v["w"] * $xres); + if ($v["t"]) { + // draw a vertical bar + $this->Rect($xpos, $ypos, $bw, $bch, 'F'); + } + $xpos += $bw; + } + } + + // Characters + if ($bgcol) { + $this->SetFColor($bgcol); + } else { + $this->SetFColor($this->colorConverter->convert(255, $this->PDFAXwarnings)); + } + + $this->SetFontSize(3 * $fh * $size * Mpdf::SCALE); // 3mm numerals (FontSize is larger to account for space above/below characters) + $this->x = $x + $paddingL + $llm; + $this->y = $y + $paddingT; + $this->Cell($bcw, $num_height, $supplement_code, 0, 0, 'C'); + + // Outer Right character (light margin) + $this->SetFontSize(($outerfontsize / 3) * 3 * $fh * $size * Mpdf::SCALE); // 3mm numerals (FontSize is larger to account for space above/below characters) + $this->x = $x + $paddingL + $llm + $bcw + $rlm - ($cw * 0.9); // 0.9 is correction as char does not fill full width + $this->y = $y + $paddingT; + $this->Cell($cw * ($outerfontsize / 3), $num_height, '>', 0, 0, 'R'); + } + + // Restore ************** + $this->SetFont($prevFontFamily, $prevFontStyle, $prevFontSizePt); + $this->DrawColor = $prevDrawColor; + $this->TextColor = $prevTextColor; + $this->FillColor = $prevFillColor; + $this->SetLineWidth($lw); + $this->SetY($y); + } + + /** + * POSTAL and OTHER barcodes + */ + function WriteBarcode2($code, $x = '', $y = '', $size = 1, $height = 1, $bgcol = false, $col = false, $btype = 'IMB', $print_ratio = '', $k = 1) + { + if (empty($code)) { + return; + } + + $this->barcode = new Barcode(); + $arrcode = $this->barcode->getBarcodeArray($code, $btype, $print_ratio); + + if (empty($x)) { + $x = $this->x; + } + + if (empty($y)) { + $y = $this->y; + } + + $prevDrawColor = $this->DrawColor; + $prevTextColor = $this->TextColor; + $prevFillColor = $this->FillColor; + $lw = $this->LineWidth; + $this->SetLineWidth(0.01); + $size /= $k; // in case resized in a table + $xres = $arrcode['nom-X'] * $size; + + if ($btype === 'IMB' || $btype === 'RM4SCC' || $btype === 'KIX' || $btype === 'POSTNET' || $btype === 'PLANET') { + $llm = $arrcode['quietL'] / $k; // Left Quiet margin + $rlm = $arrcode['quietR'] / $k; // Right Quiet margin + $tlm = $blm = $arrcode['quietTB'] / $k; + $height = 1; // Overrides + } elseif (in_array($btype, ['C128A', 'C128B', 'C128C', 'C128RAW', 'EAN128A', 'EAN128B', 'EAN128C', 'C39', 'C39+', 'C39E', 'C39E+', 'S25', 'S25+', 'I25', 'I25+', 'I25B', 'I25B+', 'C93', 'MSI', 'MSI+', 'CODABAR', 'CODE11'])) { + $llm = $arrcode['lightmL'] * $xres; // Left Quiet margin + $rlm = $arrcode['lightmR'] * $xres; // Right Quiet margin + $tlm = $blm = $arrcode['lightTB'] * $xres * $height; + } + + $bcw = ($arrcode["maxw"] * $xres); + $fbw = $bcw + $llm + $rlm; // Full barcode width incl. light margins + + $bch = ($arrcode["nom-H"] * $size * $height); + $fbh = $bch + $tlm + $blm; // Full barcode height + + // PRINT border background color + $xpos = $x; + $ypos = $y; + + if ($col) { + $this->SetDColor($col); + $this->SetTColor($col); + } else { + $this->SetDColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + $this->SetTColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + } + + if ($bgcol) { + $this->SetFColor($bgcol); + } else { + $this->SetFColor($this->colorConverter->convert(255, $this->PDFAXwarnings)); + } + + // PRINT BARS + if ($col) { + $this->SetFColor($col); + } else { + $this->SetFColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + } + $xpos = $x + $llm; + + if ($arrcode !== false) { + foreach ($arrcode["bcode"] as $v) { + $bw = ($v["w"] * $xres); + if ($v["t"]) { + $ypos = $y + $tlm + ($bch * $v['p'] / $arrcode['maxh']); + $this->Rect($xpos, $ypos, $bw, ($v['h'] * $bch / $arrcode['maxh']), 'F'); + } + $xpos += $bw; + } + } + + // PRINT BEARER BARS + if ($btype == 'I25B' || $btype == 'I25B+') { + $this->Rect($x, $y, $fbw, ($arrcode['lightTB'] * $xres * $height), 'F'); + $this->Rect($x, $y + $tlm + $bch, $fbw, ($arrcode['lightTB'] * $xres * $height), 'F'); + } + + // Restore ************** + $this->DrawColor = $prevDrawColor; + $this->TextColor = $prevTextColor; + $this->FillColor = $prevFillColor; + $this->SetLineWidth($lw); + $this->SetY($y); + } + /* -- END BARCODES -- */ + + function StartTransform($returnstring = false) + { + if ($returnstring) { + return('q'); + } else { + $this->writer->write('q'); + } + } + + function StopTransform($returnstring = false) + { + if ($returnstring) { + return('Q'); + } else { + $this->writer->write('Q'); + } + } + + function transformScale($s_x, $s_y, $x = '', $y = '', $returnstring = false) + { + if ($x === '') { + $x = $this->x; + } + + if ($y === '') { + $y = $this->y; + } + + if (($s_x == 0) or ( $s_y == 0)) { + throw new \Mpdf\MpdfException('Please do not use values equal to zero for scaling'); + } + + $y = ($this->h - $y) * Mpdf::SCALE; + $x *= Mpdf::SCALE; + + // calculate elements of transformation matrix + $s_x /= 100; + $s_y /= 100; + $tm = []; + $tm[0] = $s_x; + $tm[1] = 0; + $tm[2] = 0; + $tm[3] = $s_y; + $tm[4] = $x * (1 - $s_x); + $tm[5] = $y * (1 - $s_y); + + // scale the coordinate system + if ($returnstring) { + return($this->_transform($tm, true)); + } else { + $this->_transform($tm); + } + } + + function transformTranslate($t_x, $t_y, $returnstring = false) + { + // calculate elements of transformation matrix + $tm = []; + $tm[0] = 1; + $tm[1] = 0; + $tm[2] = 0; + $tm[3] = 1; + $tm[4] = $t_x * Mpdf::SCALE; + $tm[5] = -$t_y * Mpdf::SCALE; + + // translate the coordinate system + if ($returnstring) { + return($this->_transform($tm, true)); + } else { + $this->_transform($tm); + } + } + + function transformRotate($angle, $x = '', $y = '', $returnstring = false) + { + if ($x === '') { + $x = $this->x; + } + + if ($y === '') { + $y = $this->y; + } + + $angle = -$angle; + $y = ($this->h - $y) * Mpdf::SCALE; + $x *= Mpdf::SCALE; + + // calculate elements of transformation matrix + $tm = []; + $tm[0] = cos(deg2rad($angle)); + $tm[1] = sin(deg2rad($angle)); + $tm[2] = -$tm[1]; + $tm[3] = $tm[0]; + $tm[4] = $x + $tm[1] * $y - $tm[0] * $x; + $tm[5] = $y - $tm[0] * $y - $tm[1] * $x; + + // rotate the coordinate system around ($x,$y) + if ($returnstring) { + return $this->_transform($tm, true); + } else { + $this->_transform($tm); + } + } + + /** + * mPDF 5.7.3 TRANSFORMS + */ + function transformSkew($angle_x, $angle_y, $x = '', $y = '', $returnstring = false) + { + if ($x === '') { + $x = $this->x; + } + + if ($y === '') { + $y = $this->y; + } + + $angle_x = -$angle_x; + $angle_y = -$angle_y; + + $x *= Mpdf::SCALE; + $y = ($this->h - $y) * Mpdf::SCALE; + + // calculate elements of transformation matrix + $tm = []; + $tm[0] = 1; + $tm[1] = tan(deg2rad($angle_y)); + $tm[2] = tan(deg2rad($angle_x)); + $tm[3] = 1; + $tm[4] = -$tm[2] * $y; + $tm[5] = -$tm[1] * $x; + + // skew the coordinate system + if ($returnstring) { + return $this->_transform($tm, true); + } else { + $this->_transform($tm); + } + } + + function _transform($tm, $returnstring = false) + { + if ($returnstring) { + return(sprintf('%.4F %.4F %.4F %.4F %.4F %.4F cm', $tm[0], $tm[1], $tm[2], $tm[3], $tm[4], $tm[5])); + } else { + $this->writer->write(sprintf('%.4F %.4F %.4F %.4F %.4F %.4F cm', $tm[0], $tm[1], $tm[2], $tm[3], $tm[4], $tm[5])); + } + } + + // AUTOFONT ========================= + function markScriptToLang($html) + { + if ($this->onlyCoreFonts) { + return $html; + } + + $n = ''; + $a = preg_split('/<(.*?)>/ms', $html, -1, PREG_SPLIT_DELIM_CAPTURE); + foreach ($a as $i => $e) { + if ($i % 2 == 0) { + + // ignore if in Textarea + if ($i > 0 && strtolower(substr($a[$i - 1], 1, 8)) == 'textarea') { + $a[$i] = $e; + continue; + } + + $e = UtfString::strcode2utf($e); + $e = $this->lesser_entity_decode($e); + + $earr = $this->UTF8StringToArray($e, false); + + $scriptblock = 0; + $scriptblocks = []; + $scriptblocks[0] = 0; + $chardata = []; + $subchunk = 0; + $charctr = 0; + + foreach ($earr as $char) { + + $ucd_record = Ucdn::get_ucd_record($char); + $sbl = $ucd_record[6]; + + if ($sbl && $sbl != 40 && $sbl != 102) { + if ($scriptblock == 0) { + $scriptblock = $sbl; + $scriptblocks[$subchunk] = $scriptblock; + } elseif ($scriptblock > 0 && $scriptblock != $sbl) { + // NEW (non-common) Script encountered in this chunk. + // Start a new subchunk + $subchunk++; + $scriptblock = $sbl; + $charctr = 0; + $scriptblocks[$subchunk] = $scriptblock; + } + } + + $chardata[$subchunk][$charctr]['script'] = $sbl; + $chardata[$subchunk][$charctr]['uni'] = $char; + $charctr++; + } + + // If scriptblock[x] = common & non-baseScript + // and scriptblock[x+1] = baseScript + // Move common script from end of x to start of x+1 + for ($sch = 0; $sch < $subchunk; $sch++) { + if ($scriptblocks[$sch] > 0 && $scriptblocks[$sch] != $this->baseScript && $scriptblocks[$sch + 1] == $this->baseScript) { + $end = count($chardata[$sch]) - 1; + while ($chardata[$sch][$end]['script'] == 0 && $end > 1) { // common script + $tmp = array_pop($chardata[$sch]); + array_unshift($chardata[$sch + 1], $tmp); + $end--; + } + } + } + + $o = ''; + for ($sch = 0; $sch <= $subchunk; $sch++) { + + if (isset($chardata[$sch])) { + $s = ''; + for ($j = 0; $j < count($chardata[$sch]); $j++) { + $s .= UtfString::code2utf($chardata[$sch][$j]['uni']); + } + + // ZZZ99 Undo lesser_entity_decode as above - but only for <>& + $s = str_replace("&", "&", $s); + $s = str_replace("<", "<", $s); + $s = str_replace(">", ">", $s); + + // Check Vietnamese if Latin script - even if Basescript + if ($scriptblocks[$sch] == Ucdn::SCRIPT_LATIN && $this->autoVietnamese && preg_match("/([" . $this->scriptToLanguage->getLanguageDelimiters('viet') . "])/u", $s)) { + $o .= '<span lang="vi" class="lang_vi">' . $s . '</span>'; + } elseif ($scriptblocks[$sch] == Ucdn::SCRIPT_ARABIC && $this->autoArabic) { // Check Arabic for different languages if Arabic script - even if Basescript + if (preg_match("/[" . $this->scriptToLanguage->getLanguageDelimiters('sindhi') . "]/u", $s)) { + $o .= '<span lang="sd" class="lang_sd">' . $s . '</span>'; + } elseif (preg_match("/[" . $this->scriptToLanguage->getLanguageDelimiters('urdu') . "]/u", $s)) { + $o .= '<span lang="ur" class="lang_ur">' . $s . '</span>'; + } elseif (preg_match("/[" . $this->scriptToLanguage->getLanguageDelimiters('pashto') . "]/u", $s)) { + $o .= '<span lang="ps" class="lang_ps">' . $s . '</span>'; + } elseif (preg_match("/[" . $this->scriptToLanguage->getLanguageDelimiters('persian') . "]/u", $s)) { + $o .= '<span lang="fa" class="lang_fa">' . $s . '</span>'; + } elseif ($this->baseScript != Ucdn::SCRIPT_ARABIC && $this->scriptToLanguage->getLanguageByScript($scriptblocks[$sch])) { + $o .= '<span lang="' . $this->scriptToLanguage->getLanguageByScript($scriptblocks[$sch]) . '" class="lang_' . $this->scriptToLanguage->getLanguageByScript($scriptblocks[$sch]) . '">' . $s . '</span>'; + } else { + // Just output chars + $o .= $s; + } + } elseif ($scriptblocks[$sch] > 0 && $scriptblocks[$sch] != $this->baseScript && $this->scriptToLanguage->getLanguageByScript($scriptblocks[$sch])) { // Identify Script block if not Basescript, and mark up as language + // Encase in <span> + $o .= '<span lang="' . $this->scriptToLanguage->getLanguageByScript($scriptblocks[$sch]) . '" class="lang_' . $this->scriptToLanguage->getLanguageByScript($scriptblocks[$sch]) . '">'; + $o .= $s; + $o .= '</span>'; + } else { + // Just output chars + $o .= $s; + } + } + } + + $a[$i] = $o; + } else { + $a[$i] = '<' . $e . '>'; + } + } + + $n = implode('', $a); + + return $n; + } + + /* -- COLUMNS -- */ + /** + * Callback function from function printcolumnbuffer in mpdf + */ + function columnAdjustAdd($type, $k, $xadj, $yadj, $a, $b, $c = 0, $d = 0, $e = 0, $f = 0) + { + if ($type === 'Td') { // xpos,ypos + + $a += ($xadj * $k); + $b -= ($yadj * $k); + + return 'BT ' . sprintf('%.3F %.3F', $a, $b) . ' Td'; + + } elseif ($type === 're') { // xpos,ypos,width,height + + $a += ($xadj * $k); + $b -= ($yadj * $k); + + return sprintf('%.3F %.3F %.3F %.3F', $a, $b, $c, $d) . ' re'; + + } elseif ($type === 'l') { // xpos,ypos,x2pos,y2pos + + $a += ($xadj * $k); + $b -= ($yadj * $k); + + return sprintf('%.3F %.3F l', $a, $b); + + } elseif ($type === 'img') { // width,height,xpos,ypos + + $c += ($xadj * $k); + $d -= ($yadj * $k); + + return sprintf('q %.3F 0 0 %.3F %.3F %.3F', $a, $b, $c, $d) . ' cm /' . $e; + + } elseif ($type === 'draw') { // xpos,ypos + + $a += ($xadj * $k); + $b -= ($yadj * $k); + + return sprintf('%.3F %.3F m', $a, $b); + + } elseif ($type === 'bezier') { // xpos,ypos,x2pos,y2pos,x3pos,y3pos + + $a += ($xadj * $k); + $b -= ($yadj * $k); + $c += ($xadj * $k); + $d -= ($yadj * $k); + $e += ($xadj * $k); + $f -= ($yadj * $k); + + return sprintf('%.3F %.3F %.3F %.3F %.3F %.3F', $a, $b, $c, $d, $e, $f) . ' c'; + } + } + + /* -- END COLUMNS -- */ + + // mPDF 5.7.3 TRANSFORMS + function ConvertAngle($s, $makepositive = true) + { + if (preg_match('/([\-]*[0-9\.]+)(deg|grad|rad)/i', $s, $m)) { + + $angle = $m[1] + 0; + + if (strtolower($m[2]) == 'deg') { + $angle = $angle; + } elseif (strtolower($m[2]) == 'grad') { + $angle *= (360 / 400); + } elseif (strtolower($m[2]) == 'rad') { + $angle = rad2deg($angle); + } + + while ($angle >= 360) { + $angle -= 360; + } + + while ($angle <= -360) { + $angle += 360; + } + + if ($makepositive) { // always returns an angle between 0 and 360deg + if ($angle < 0) { + $angle += 360; + } + } + + } else { + $angle = $s + 0; + } + + return $angle; + } + + function lesser_entity_decode($html) + { + // supports the most used entity codes (only does ascii safe characters) + $html = str_replace("<", "<", $html); + $html = str_replace(">", ">", $html); + + $html = str_replace("'", "'", $html); + $html = str_replace(""", '"', $html); + $html = str_replace("&", "&", $html); + + return $html; + } + + function AdjustHTML($html, $tabSpaces = 8) + { + $limit = ini_get('pcre.backtrack_limit'); + if (strlen($html) > $limit) { + throw new \Mpdf\MpdfException(sprintf( + 'The HTML code size is larger than pcre.backtrack_limit %d. You should use WriteHTML() with smaller string lengths.', + $limit + )); + } + + preg_match_all("/(<annotation.*?>)/si", $html, $m); + if (count($m[1])) { + for ($i = 0; $i < count($m[1]); $i++) { + $sub = preg_replace("/\n/si", "\xbb\xa4\xac", $m[1][$i]); + $html = preg_replace('/' . preg_quote($m[1][$i], '/') . '/si', $sub, $html); + } + } + + preg_match_all("/(<svg.*?<\/svg>)/si", $html, $svgi); + if (count($svgi[0])) { + for ($i = 0; $i < count($svgi[0]); $i++) { + $file = $this->cache->write('/_tempSVG' . uniqid(random_int(1, 100000), true) . '_' . $i . '.svg', $svgi[0][$i]); + $html = str_replace($svgi[0][$i], '<img src="' . $file . '" />', $html); + } + } + + // Remove javascript code from HTML (should not appear in the PDF file) + $html = preg_replace('/<script.*?<\/script>/is', '', $html); + + // Remove special comments + $html = preg_replace('/<!--mpdf/i', '', $html); + $html = preg_replace('/mpdf-->/i', '', $html); + + // Remove comments from HTML (should not appear in the PDF file) + $html = preg_replace('/<!--.*?-->/s', '', $html); + + $html = preg_replace('/\f/', '', $html); // replace formfeed by nothing + $html = preg_replace('/\r/', '', $html); // replace carriage return by nothing + + // Well formed XHTML end tags + $html = preg_replace('/<(br|hr)>/i', "<\\1 />", $html); // mPDF 6 + $html = preg_replace('/<(br|hr)\/>/i', "<\\1 />", $html); + + // Get rid of empty <thead></thead> etc + $html = preg_replace('/<tr>\s*<\/tr>/i', '', $html); + $html = preg_replace('/<thead>\s*<\/thead>/i', '', $html); + $html = preg_replace('/<tfoot>\s*<\/tfoot>/i', '', $html); + $html = preg_replace('/<table[^>]*>\s*<\/table>/i', '', $html); + + // Remove spaces at end of table cells + $html = preg_replace("/[ \n\r]+<\/t(d|h)/", '</t\\1', $html); + + $html = preg_replace("/[ ]*<dottab\s*[\/]*>[ ]*/", '<dottab />', $html); + + // Concatenates any Substitute characters from symbols/dingbats + $html = str_replace('</tts><tts>', '|', $html); + $html = str_replace('</ttz><ttz>', '|', $html); + $html = str_replace('</tta><tta>', '|', $html); + + $html = preg_replace('/<br \/>\s*/is', "<br />", $html); + + $html = preg_replace('/<wbr[ \/]*>\s*/is', "­", $html); + + // Preserve '\n's in content between the tags <pre> and </pre> + if (preg_match('/<pre/', $html)) { + + $html_a = preg_split('/(\<\/?pre[^\>]*\>)/', $html, -1, 2); + $h = []; + $c = 0; + + foreach ($html_a as $s) { + if ($c > 1 && preg_match('/^<\/pre/i', $s)) { + $c--; + $s = preg_replace('/<\/pre/i', '</innerpre', $s); + } elseif ($c > 0 && preg_match('/^<pre/i', $s)) { + $c++; + $s = preg_replace('/<pre/i', '<innerpre', $s); + } elseif (preg_match('/^<pre/i', $s)) { + $c++; + } elseif (preg_match('/^<\/pre/i', $s)) { + $c--; + } + array_push($h, $s); + } + + $html = implode('', $h); + } + + $thereispre = preg_match_all('#<pre(.*?)>(.*?)</pre>#si', $html, $temp); + + // Preserve '\n's in content between the tags <textarea> and </textarea> + $thereistextarea = preg_match_all('#<textarea(.*?)>(.*?)</textarea>#si', $html, $temp2); + $html = preg_replace('/[\n]/', ' ', $html); // replace linefeed by spaces + $html = preg_replace('/[\t]/', ' ', $html); // replace tabs by spaces + + // Converts < to < when not a tag + $html = preg_replace('/<([^!\/a-zA-Z_:])/i', '<\\1', $html); // mPDF 5.7.3 + $html = preg_replace("/[ ]+/", ' ', $html); + + $html = preg_replace('/\/li>\s+<\/(u|o)l/i', '/li></\\1l', $html); + $html = preg_replace('/\/(u|o)l>\s+<\/li/i', '/\\1l></li', $html); + $html = preg_replace('/\/li>\s+<\/(u|o)l/i', '/li></\\1l', $html); + $html = preg_replace('/\/li>\s+<li/i', '/li><li', $html); + $html = preg_replace('/<(u|o)l([^>]*)>[ ]+/i', '<\\1l\\2>', $html); + $html = preg_replace('/[ ]+<(u|o)l/i', '<\\1l', $html); + + // Make self closing tabs valid XHTML + // Tags which are self-closing: 1) Replaceable and 2) Non-replaced items + $selftabs = 'input|hr|img|br|barcode|dottab'; + $selftabs2 = 'indexentry|indexinsert|bookmark|watermarktext|watermarkimage|column_break|columnbreak|newcolumn|newpage|page_break|pagebreak|formfeed|columns|toc|tocpagebreak|setpageheader|setpagefooter|sethtmlpageheader|sethtmlpagefooter|annotation'; + + // Fix self-closing tags which don't close themselves + $html = preg_replace('/(<(' . $selftabs . '|' . $selftabs2 . ')[^>\/]*)>/i', '\\1 />', $html); + + // Fix self-closing tags that don't include a space between the tag name and the closing slash + $html = preg_replace('/(<(' . $selftabs . '|' . $selftabs2 . '))\/>/i', '\\1 />', $html); + + $iterator = 0; + while ($thereispre) { // Recover <pre attributes>content</pre> + $temp[2][$iterator] = preg_replace('/<([^!\/a-zA-Z_:])/', '<\\1', $temp[2][$iterator]); // mPDF 5.7.2 // mPDF 5.7.3 + + $temp[2][$iterator] = preg_replace_callback("/^([^\n\t]*?)\t/m", [$this, 'tabs2spaces_callback'], $temp[2][$iterator]); // mPDF 5.7+ + $temp[2][$iterator] = preg_replace('/\t/', str_repeat(" ", $tabSpaces), $temp[2][$iterator]); + + $temp[2][$iterator] = preg_replace('/\n/', "<br />", $temp[2][$iterator]); + $temp[2][$iterator] = str_replace('\\', "\\\\", $temp[2][$iterator]); + // $html = preg_replace('#<pre(.*?)>(.*?)</pre>#si','<erp'.$temp[1][$iterator].'>'.$temp[2][$iterator].'</erp>',$html,1); + $html = preg_replace('#<pre(.*?)>(.*?)</pre>#si', '<erp' . $temp[1][$iterator] . '>' . str_replace('$', '\$', $temp[2][$iterator]) . '</erp>', $html, 1); // mPDF 5.7+ + $thereispre--; + $iterator++; + } + + $iterator = 0; + while ($thereistextarea) { // Recover <textarea attributes>content</textarea> + $temp2[2][$iterator] = preg_replace('/\t/', str_repeat(" ", $tabSpaces), $temp2[2][$iterator]); + $temp2[2][$iterator] = str_replace('\\', "\\\\", $temp2[2][$iterator]); + $html = preg_replace('#<textarea(.*?)>(.*?)</textarea>#si', '<aeratxet' . $temp2[1][$iterator] . '>' . trim($temp2[2][$iterator]) . '</aeratxet>', $html, 1); + $thereistextarea--; + $iterator++; + } + + // Restore original tag names + $html = str_replace("<erp", "<pre", $html); + $html = str_replace("</erp>", "</pre>", $html); + $html = str_replace("<aeratxet", "<textarea", $html); + $html = str_replace("</aeratxet>", "</textarea>", $html); + $html = str_replace("</innerpre", "</pre", $html); + $html = str_replace("<innerpre", "<pre", $html); + + $html = preg_replace('/<textarea([^>]*)><\/textarea>/si', '<textarea\\1> </textarea>', $html); + $html = preg_replace('/(<table[^>]*>)\s*(<caption)(.*?<\/caption>)(.*?<\/table>)/si', '\\2 position="top"\\3\\1\\4\\2 position="bottom"\\3', $html); // *TABLES* + $html = preg_replace('/<(h[1-6])([^>]*)(>(?:(?!h[1-6]).)*?<\/\\1>\s*<table)/si', '<\\1\\2 keep-with-table="1"\\3', $html); // *TABLES* + $html = preg_replace("/\xbb\xa4\xac/", "\n", $html); + + // Fixes <p>₹</p> which browser copes with even though it is wrong! + $html = preg_replace("/(&#[x]{0,1}[0-9a-f]{1,5})</i", "\\1;<", $html); + + return $html; + } + + // mPDF 5.7+ + function tabs2spaces_callback($matches) + { + return (stripslashes($matches[1]) . str_repeat(' ', $this->tabSpaces - (mb_strlen(stripslashes($matches[1])) % $this->tabSpaces))); + } + + // mPDF 5.7+ + function date_callback($matches) + { + return date($matches[1]); + } + + // ========== OVERWRITE SEARCH STRING IN A PDF FILE ================ + function OverWrite($file_in, $search, $replacement, $dest = Destination::DOWNLOAD, $file_out = "mpdf") + { + $pdf = file_get_contents($file_in); + + if (!is_array($search)) { + $x = $search; + $search = [$x]; + } + if (!is_array($replacement)) { + $x = $replacement; + $replacement = [$x]; // mPDF 5.7.4 + } + + if (!$this->onlyCoreFonts && !$this->usingCoreFont) { + foreach ($search as $k => $val) { + $search[$k] = $this->writer->utf8ToUtf16BigEndian($search[$k], false); + $search[$k] = $this->writer->escape($search[$k]); + $replacement[$k] = $this->writer->utf8ToUtf16BigEndian($replacement[$k], false); + $replacement[$k] = $this->writer->escape($replacement[$k]); + } + } else { + foreach ($replacement as $k => $val) { + $replacement[$k] = mb_convert_encoding($replacement[$k], $this->mb_enc, 'utf-8'); + $replacement[$k] = $this->writer->escape($replacement[$k]); + } + } + + // Get xref into array + $xref = []; + preg_match("/xref\n0 (\d+)\n(.*?)\ntrailer/s", $pdf, $m); + $xref_objid = $m[1]; + preg_match_all('/(\d{10}) (\d{5}) (f|n)/', $m[2], $x); + for ($i = 0; $i < count($x[0]); $i++) { + $xref[] = [intval($x[1][$i]), $x[2][$i], $x[3][$i]]; + } + + $changes = []; + preg_match("/<<\s*\/Type\s*\/Pages\s*\/Kids\s*\[(.*?)\]\s*\/Count/s", $pdf, $m); + preg_match_all("/(\d+) 0 R /s", $m[1], $o); + $objlist = $o[1]; + + foreach ($objlist as $obj) { + if ($this->compress) { + preg_match("/" . ($obj + 1) . " 0 obj\n<<\s*\/Filter\s*\/FlateDecode\s*\/Length (\d+)>>\nstream\n(.*?)\nendstream\n/s", $pdf, $m); + } else { + preg_match("/" . ($obj + 1) . " 0 obj\n<<\s*\/Length (\d+)>>\nstream\n(.*?)\nendstream\n/s", $pdf, $m); + } + + $s = $m[2]; + if (!$s) { + continue; + } + + $oldlen = $m[1]; + + if ($this->encrypted) { + $s = $this->protection->rc4($this->protection->objectKey($obj + 1), $s); + } + + if ($this->compress) { + $s = gzuncompress($s); + } + + foreach ($search as $k => $val) { + $s = str_replace($search[$k], $replacement[$k], $s); + } + + if ($this->compress) { + $s = gzcompress($s); + } + + if ($this->encrypted) { + $s = $this->protection->rc4($this->protection->objectKey($obj + 1), $s); + } + + $newlen = strlen($s); + + $changes[($xref[$obj + 1][0])] = ($newlen - $oldlen) + (strlen($newlen) - strlen($oldlen)); + + if ($this->compress) { + $newstr = ($obj + 1) . " 0 obj\n<</Filter /FlateDecode /Length " . $newlen . ">>\nstream\n" . $s . "\nendstream\n"; + } else { + $newstr = ($obj + 1) . " 0 obj\n<</Length " . $newlen . ">>\nstream\n" . $s . "\nendstream\n"; + } + + $pdf = str_replace($m[0], $newstr, $pdf); + } + + // Update xref in PDF + krsort($changes); + $newxref = "xref\n0 " . $xref_objid . "\n"; + foreach ($xref as $v) { + foreach ($changes as $ck => $cv) { + if ($v[0] > $ck) { + $v[0] += $cv; + } + } + $newxref .= sprintf('%010d', $v[0]) . ' ' . $v[1] . ' ' . $v[2] . " \n"; + } + $newxref .= "trailer"; + $pdf = preg_replace("/xref\n0 \d+\n.*?\ntrailer/s", $newxref, $pdf); + + // Update startxref in PDF + preg_match("/startxref\n(\d+)\n%%EOF/s", $pdf, $m); + $startxref = $m[1]; + $startxref += array_sum($changes); + $pdf = preg_replace("/startxref\n(\d+)\n%%EOF/s", "startxref\n" . $startxref . "\n%%EOF", $pdf); + + // OUTPUT + switch ($dest) { + case Destination::INLINE: + if (isset($_SERVER['SERVER_NAME'])) { + // We send to a browser + header('Content-Type: application/pdf'); + header('Content-Length: ' . strlen($pdf)); + header('Content-disposition: inline; filename=' . $file_out); + } + + echo $pdf; + + break; + + case Destination::FILE: + if (!$file_out) { + $file_out = 'mpdf.pdf'; + } + + $f = fopen($file_out, 'wb'); + + if (!$f) { + throw new \Mpdf\MpdfException('Unable to create output file: ' . $file_out); + } + + fwrite($f, $pdf, strlen($pdf)); + + fclose($f); + + break; + + case Destination::STRING_RETURN: + return $pdf; + + case Destination::DOWNLOAD: // Download file + default: + if (isset($_SERVER['HTTP_USER_AGENT']) and strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) { + header('Content-Type: application/force-download'); + } else { + header('Content-Type: application/octet-stream'); + } + + header('Content-Length: ' . strlen($pdf)); + header('Content-disposition: attachment; filename=' . $file_out); + + echo $pdf; + + break; + } + } + + + function Thumbnail($file, $npr = 3, $spacing = 10) + { + // $npr = number per row + $w = (($this->pgwidth + $spacing) / $npr) - $spacing; + $oldlinewidth = $this->LineWidth; + $this->SetLineWidth(0.02); + $this->SetDColor($this->colorConverter->convert(0, $this->PDFAXwarnings)); + $h = 0; + $maxh = 0; + $x = $_x = $this->lMargin; + $_y = $this->tMargin; + + if ($this->y == 0) { + $y = $_y; + } else { + $y = $this->y; + } + + $pagecount = $this->setSourceFile($file); + + for ($n = 1; $n <= $pagecount; $n++) { + $tplidx = $this->importPage($n); + $size = $this->useTemplate($tplidx, $x, $y, $w); + $this->Rect($x, $y, $size['width'], $size['height']); + $h = max($h, $size['height']); + $maxh = max($h, $maxh); + + if ($n % $npr == 0) { + if (($y + $h + $spacing + $maxh) > $this->PageBreakTrigger && $n != $pagecount) { + $this->AddPage(); + $x = $_x; + $y = $_y; + } else { + $y += $h + $spacing; + $x = $_x; + $h = 0; + } + } else { + $x += $w + $spacing; + } + } + $this->SetLineWidth($oldlinewidth); + } + + function SetPageTemplate($tplidx = '') + { + if (!isset($this->importedPages[$tplidx])) { + $this->pageTemplate = ''; + return false; + } + $this->pageTemplate = $tplidx; + } + + function SetDocTemplate($file = '', $continue = 0) + { + $this->docTemplate = $file; + $this->docTemplateContinue = $continue; + } + + /* -- END IMPORTS -- */ + + // JAVASCRIPT + function _set_object_javascript($string) + { + $this->writer->object(); + $this->writer->write('<<'); + $this->writer->write('/S /JavaScript '); + $this->writer->write('/JS ' . $this->writer->string($string)); + $this->writer->write('>>'); + $this->writer->write('endobj'); + } + + function SetJS($script) + { + $this->js = $script; + } + + /** + * This function takes the last comma or dot (if any) to make a clean float, ignoring thousand separator, currency or any other letter + * + * @param string $num + * @see http://php.net/manual/de/function.floatval.php#114486 + * @return float + */ + public function toFloat($num) + { + $dotPos = strrpos($num, '.'); + $commaPos = strrpos($num, ','); + $sep = (($dotPos > $commaPos) && $dotPos) ? $dotPos : ((($commaPos > $dotPos) && $commaPos) ? $commaPos : false); + + if (!$sep) { + return floatval(preg_replace('/[^0-9]/', '', $num)); + } + + return floatval( + preg_replace('/[^0-9]/', '', substr($num, 0, $sep)) . '.' . + preg_replace('/[^0-9]/', '', substr($num, $sep+1, strlen($num))) + ); + } + + public function getFontDescriptor() + { + return $this->fontDescriptor; + } + + /** + * Temporarily return the method to preserve example 44 yearbook + */ + public function _out($s) + { + $this->writer->write($s); + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/MpdfException.php b/src/bb-vendor/mpdf/mpdf/src/MpdfException.php new file mode 100644 index 000000000..f84535490 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/MpdfException.php @@ -0,0 +1,8 @@ +<?php + +namespace Mpdf; + +class MpdfException extends \ErrorException +{ + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/MpdfImageException.php b/src/bb-vendor/mpdf/mpdf/src/MpdfImageException.php new file mode 100644 index 000000000..c8f4ca094 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/MpdfImageException.php @@ -0,0 +1,8 @@ +<?php + +namespace Mpdf; + +class MpdfImageException extends \Mpdf\MpdfException +{ + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Otl.php b/src/bb-vendor/mpdf/mpdf/src/Otl.php new file mode 100644 index 000000000..46039963c --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Otl.php @@ -0,0 +1,6211 @@ +<?php + +namespace Mpdf; + +use Mpdf\Strict; + +use Mpdf\Css\TextVars; +use Mpdf\Fonts\FontCache; + +use Mpdf\Shaper\Indic; +use Mpdf\Shaper\Myanmar; +use Mpdf\Shaper\Sea; + +use Mpdf\Utils\UtfString; + +class Otl +{ + + use Strict; + + const _OTL_OLD_SPEC_COMPAT_1 = true; + const _DICT_NODE_TYPE_SPLIT = 0x01; + const _DICT_NODE_TYPE_LINEAR = 0x02; + const _DICT_INTERMEDIATE_MATCH = 0x03; + const _DICT_FINAL_MATCH = 0x04; + + private $mpdf; + + private $fontCache; + + var $arabLeftJoining; + + var $arabRightJoining; + + var $arabTransparentJoin; + + var $arabTransparent; + + var $GSUBdata; + + var $GPOSdata; + + var $GSUBfont; + + var $fontkey; + + var $ttfOTLdata; + + var $glyphIDtoUni; + + var $_pos; + + var $GSUB_offset; + + var $GPOS_offset; + + var $MarkAttachmentType; + + var $MarkGlyphSets; + + var $GlyphClassMarks; + + var $GlyphClassLigatures; + + var $GlyphClassBases; + + var $GlyphClassComponents; + + var $Ignores; + + var $LuCoverage; + + var $OTLdata; + + var $assocLigs; + + var $assocMarks; + + var $shaper; + + var $restrictToSyllable; + + var $lbdicts; // Line-breaking dictionaries + + var $LuDataCache; + + var $arabGlyphs; + + var $current_fh; + + var $Entry; + + var $Exit; + + var $GDEFdata; + + var $GPOSLookups; + + var $GSLuCoverage; + + var $GSUB_length; + + var $GSUBLookups; + + var $schOTLdata; + + var $lastBidiStrongType; + + var $debugOTL = false; + + public function __construct(Mpdf $mpdf, FontCache $fontCache) + { + $this->mpdf = $mpdf; + $this->fontCache = $fontCache; + + $this->current_fh = ''; + + $this->lbdicts = []; + $this->LuDataCache = []; + } + + function applyOTL($str, $useOTL) + { + if (!$this->arabLeftJoining) { + $this->arabic_initialise(); + } + + $this->OTLdata = []; + if (trim($str) == '') { + return $str; + } + if (!$useOTL) { + return $str; + } + + // 1. Load GDEF data + //============================== + $this->fontkey = $this->mpdf->CurrentFont['fontkey']; + $this->glyphIDtoUni = $this->mpdf->CurrentFont['glyphIDtoUni']; + $fontCacheFilename = $this->fontkey . '.GDEFdata.json'; + if (!isset($this->GDEFdata[$this->fontkey]) && $this->fontCache->jsonHas($fontCacheFilename)) { + $font = $this->fontCache->jsonLoad($fontCacheFilename); + + $this->GSUB_offset = $this->GDEFdata[$this->fontkey]['GSUB_offset'] = $font['GSUB_offset']; + $this->GPOS_offset = $this->GDEFdata[$this->fontkey]['GPOS_offset'] = $font['GPOS_offset']; + $this->GSUB_length = $this->GDEFdata[$this->fontkey]['GSUB_length'] = $font['GSUB_length']; + $this->MarkAttachmentType = $this->GDEFdata[$this->fontkey]['MarkAttachmentType'] = $font['MarkAttachmentType']; + $this->MarkGlyphSets = $this->GDEFdata[$this->fontkey]['MarkGlyphSets'] = $font['MarkGlyphSets']; + $this->GlyphClassMarks = $this->GDEFdata[$this->fontkey]['GlyphClassMarks'] = $font['GlyphClassMarks']; + $this->GlyphClassLigatures = $this->GDEFdata[$this->fontkey]['GlyphClassLigatures'] = $font['GlyphClassLigatures']; + $this->GlyphClassComponents = $this->GDEFdata[$this->fontkey]['GlyphClassComponents'] = $font['GlyphClassComponents']; + $this->GlyphClassBases = $this->GDEFdata[$this->fontkey]['GlyphClassBases'] = $font['GlyphClassBases']; + } else { + $this->GSUB_offset = $this->GDEFdata[$this->fontkey]['GSUB_offset']; + $this->GPOS_offset = $this->GDEFdata[$this->fontkey]['GPOS_offset']; + $this->GSUB_length = $this->GDEFdata[$this->fontkey]['GSUB_length']; + $this->MarkAttachmentType = $this->GDEFdata[$this->fontkey]['MarkAttachmentType']; + $this->MarkGlyphSets = $this->GDEFdata[$this->fontkey]['MarkGlyphSets']; + $this->GlyphClassMarks = $this->GDEFdata[$this->fontkey]['GlyphClassMarks']; + $this->GlyphClassLigatures = $this->GDEFdata[$this->fontkey]['GlyphClassLigatures']; + $this->GlyphClassComponents = $this->GDEFdata[$this->fontkey]['GlyphClassComponents']; + $this->GlyphClassBases = $this->GDEFdata[$this->fontkey]['GlyphClassBases']; + } + + // 2. Prepare string as HEX string and Analyse character properties + //================================================================= + $earr = $this->mpdf->UTF8StringToArray($str, false); + + $scriptblock = 0; + $scriptblocks = []; + $scriptblocks[0] = 0; + $vstr = ''; + $OTLdata = []; + $subchunk = 0; + $charctr = 0; + foreach ($earr as $char) { + $ucd_record = Ucdn::get_ucd_record($char); + $sbl = $ucd_record[6]; + + // Special case - Arabic End of Ayah + if ($char == 1757) { + $sbl = Ucdn::SCRIPT_ARABIC; + } + + if ($sbl && $sbl != 40 && $sbl != 102) { + if ($scriptblock == 0) { + $scriptblock = $sbl; + $scriptblocks[$subchunk] = $scriptblock; + } elseif ($scriptblock > 0 && $scriptblock != $sbl) { + // ************************************************* + // NEW (non-common) Script encountered in this chunk. Start a new subchunk + $subchunk++; + $scriptblock = $sbl; + $charctr = 0; + $scriptblocks[$subchunk] = $scriptblock; + } + } + + $OTLdata[$subchunk][$charctr]['general_category'] = $ucd_record[0]; + $OTLdata[$subchunk][$charctr]['bidi_type'] = $ucd_record[2]; + + //$OTLdata[$subchunk][$charctr]['combining_class'] = $ucd_record[1]; + //$OTLdata[$subchunk][$charctr]['bidi_type'] = $ucd_record[2]; + //$OTLdata[$subchunk][$charctr]['mirrored'] = $ucd_record[3]; + //$OTLdata[$subchunk][$charctr]['east_asian_width'] = $ucd_record[4]; + //$OTLdata[$subchunk][$charctr]['normalization_check'] = $ucd_record[5]; + //$OTLdata[$subchunk][$charctr]['script'] = $ucd_record[6]; + + $charasstr = $this->unicode_hex($char); + + if (strpos($this->GlyphClassMarks, $charasstr) !== false) { + $OTLdata[$subchunk][$charctr]['group'] = 'M'; + } elseif ($char == 32 || $char == 12288) { + $OTLdata[$subchunk][$charctr]['group'] = 'S'; + } // 12288 = 0x3000 = CJK space + else { + $OTLdata[$subchunk][$charctr]['group'] = 'C'; + } + + $OTLdata[$subchunk][$charctr]['uni'] = $char; + $OTLdata[$subchunk][$charctr]['hex'] = $charasstr; + $charctr++; + } + + /* PROCESS EACH SUBCHUNK WITH DIFFERENT SCRIPTS */ + for ($sch = 0; $sch <= $subchunk; $sch++) { + $this->OTLdata = $OTLdata[$sch]; + $scriptblock = $scriptblocks[$sch]; + + // 3. Get Appropriate Scripts, and Shaper engine from analysing text and list of available scripts/langsys in font + //============================== + // Based on actual script block of text, select shaper (and line-breaking dictionaries) + if (Ucdn::SCRIPT_DEVANAGARI <= $scriptblock && $scriptblock <= Ucdn::SCRIPT_MALAYALAM) { + $this->shaper = "I"; + } // INDIC shaper + elseif ($scriptblock == Ucdn::SCRIPT_ARABIC || $scriptblock == Ucdn::SCRIPT_SYRIAC) { + $this->shaper = "A"; + } // ARABIC shaper + elseif ($scriptblock == Ucdn::SCRIPT_NKO || $scriptblock == Ucdn::SCRIPT_MANDAIC) { + $this->shaper = "A"; + } // ARABIC shaper + elseif ($scriptblock == Ucdn::SCRIPT_KHMER) { + $this->shaper = "K"; + } // KHMER shaper + elseif ($scriptblock == Ucdn::SCRIPT_THAI) { + $this->shaper = "T"; + } // THAI shaper + elseif ($scriptblock == Ucdn::SCRIPT_LAO) { + $this->shaper = "L"; + } // LAO shaper + elseif ($scriptblock == Ucdn::SCRIPT_SINHALA) { + $this->shaper = "S"; + } // SINHALA shaper + elseif ($scriptblock == Ucdn::SCRIPT_MYANMAR) { + $this->shaper = "M"; + } // MYANMAR shaper + elseif ($scriptblock == Ucdn::SCRIPT_NEW_TAI_LUE) { + $this->shaper = "E"; + } // SEA South East Asian shaper + elseif ($scriptblock == Ucdn::SCRIPT_CHAM) { + $this->shaper = "E"; + } // SEA South East Asian shaper + elseif ($scriptblock == Ucdn::SCRIPT_TAI_THAM) { + $this->shaper = "E"; + } // SEA South East Asian shaper + else { + $this->shaper = ""; + } + // Get scripttag based on actual text script + $scripttag = Ucdn::$uni_scriptblock[$scriptblock]; + + $GSUBscriptTag = ''; + $GSUBlangsys = ''; + $GPOSscriptTag = ''; + $GPOSlangsys = ''; + $is_old_spec = false; + + $ScriptLang = $this->mpdf->CurrentFont['GSUBScriptLang']; + if (count($ScriptLang)) { + list($GSUBscriptTag, $is_old_spec) = $this->_getOTLscriptTag($ScriptLang, $scripttag, $scriptblock, $this->shaper, $useOTL, 'GSUB'); + if ($this->mpdf->fontLanguageOverride && strpos($ScriptLang[$GSUBscriptTag], $this->mpdf->fontLanguageOverride) !== false) { + $GSUBlangsys = str_pad($this->mpdf->fontLanguageOverride, 4); + } elseif ($GSUBscriptTag && isset($ScriptLang[$GSUBscriptTag]) && $ScriptLang[$GSUBscriptTag] != '') { + $GSUBlangsys = $this->_getOTLLangTag($this->mpdf->currentLang, $ScriptLang[$GSUBscriptTag]); + } + } + $ScriptLang = $this->mpdf->CurrentFont['GPOSScriptLang']; + + // NB If after GSUB, the same script/lang exist for GPOS, just use these... + if ($GSUBscriptTag && $GSUBlangsys && isset($ScriptLang[$GSUBscriptTag]) && strpos($ScriptLang[$GSUBscriptTag], $GSUBlangsys) !== false) { + $GPOSlangsys = $GSUBlangsys; + $GPOSscriptTag = $GSUBscriptTag; + } // else repeat for GPOS + // [Font XBRiyaz has GSUB tables for latn, but not GPOS for latn] + elseif (count($ScriptLang)) { + list($GPOSscriptTag, $dummy) = $this->_getOTLscriptTag($ScriptLang, $scripttag, $scriptblock, $this->shaper, $useOTL, 'GPOS'); + if ($GPOSscriptTag && $this->mpdf->fontLanguageOverride && strpos($ScriptLang[$GPOSscriptTag], $this->mpdf->fontLanguageOverride) !== false) { + $GPOSlangsys = str_pad($this->mpdf->fontLanguageOverride, 4); + } elseif ($GPOSscriptTag && isset($ScriptLang[$GPOSscriptTag]) && $ScriptLang[$GPOSscriptTag] != '') { + $GPOSlangsys = $this->_getOTLLangTag($this->mpdf->currentLang, $ScriptLang[$GPOSscriptTag]); + } + } + + // This is just for the font_dump_OTL utility to set script and langsys override + // $mpdf->overrideOTLsettings does not exist, this is never called + /*if (isset($this->mpdf->overrideOTLsettings) && isset($this->mpdf->overrideOTLsettings[$this->fontkey])) { + $GSUBscriptTag = $GPOSscriptTag = $this->mpdf->overrideOTLsettings[$this->fontkey]['script']; + $GSUBlangsys = $GPOSlangsys = $this->mpdf->overrideOTLsettings[$this->fontkey]['lang']; + }*/ + + if (!$GSUBscriptTag && !$GSUBlangsys && !$GPOSscriptTag && !$GPOSlangsys) { + // Remove ZWJ and ZWNJ + for ($i = 0; $i < count($this->OTLdata); $i++) { + if ($this->OTLdata[$i]['uni'] == 8204 || $this->OTLdata[$i]['uni'] == 8205) { + array_splice($this->OTLdata, $i, 1); + } + } + $this->schOTLdata[$sch] = $this->OTLdata; + $this->OTLdata = []; + continue; + } + + // Don't use MYANMAR shaper unless using v2 scripttag + if ($this->shaper == 'M' && $GSUBscriptTag != 'mym2') { + $this->shaper = ''; + } + + $GSUBFeatures = (isset($this->mpdf->CurrentFont['GSUBFeatures'][$GSUBscriptTag][$GSUBlangsys]) ? $this->mpdf->CurrentFont['GSUBFeatures'][$GSUBscriptTag][$GSUBlangsys] : false); + $GPOSFeatures = (isset($this->mpdf->CurrentFont['GPOSFeatures'][$GPOSscriptTag][$GPOSlangsys]) ? $this->mpdf->CurrentFont['GPOSFeatures'][$GPOSscriptTag][$GPOSlangsys] : false); + + $this->assocLigs = []; // Ligatures[$posarr lpos] => nc + $this->assocMarks = []; // assocMarks[$posarr mpos] => array(compID, ligPos) + + if (!isset($this->GDEFdata[$this->fontkey]['GSUBGPOStables'])) { + $this->ttfOTLdata = $this->GDEFdata[$this->fontkey]['GSUBGPOStables'] = $this->fontCache->load($this->fontkey . '.GSUBGPOStables.dat', 'rb'); + if (!$this->ttfOTLdata) { + throw new \Mpdf\MpdfException('Can\'t open file ' . $this->fontCache->tempFilename($this->fontkey . '.GSUBGPOStables.dat')); + } + } else { + $this->ttfOTLdata = $this->GDEFdata[$this->fontkey]['GSUBGPOStables']; + } + + if ($this->debugOTL) { + $this->_dumpproc('BEGIN', '-', '-', '-', '-', -1, '-', 0); + } + + //////////////////////////////////////////////////////////////// + ///////// LINE BREAKING FOR KHMER, THAI + LAO ///////////////// + //////////////////////////////////////////////////////////////// + // Insert U+200B at word boundaries using dictionaries + if ($this->mpdf->useDictionaryLBR && ($this->shaper == "K" || $this->shaper == "T" || $this->shaper == "L")) { + // Sets $this->OTLdata[$i]['wordend']=true at possible end of word boundaries + $this->seaLineBreaking(); + } // Insert U+200B at word boundaries for Tibetan + elseif ($this->mpdf->useTibetanLBR && $scriptblock == Ucdn::SCRIPT_TIBETAN) { + // Sets $this->OTLdata[$i]['wordend']=true at possible end of word boundaries + $this->tibetanLineBreaking(); + } + + + //////////////////////////////////////////////////////////////// + ////////// GSUB ///////////////////////////////// + //////////////////////////////////////////////////////////////// + if (($useOTL & 0xFF) && $GSUBscriptTag && $GSUBlangsys && $GSUBFeatures) { + // 4. Load GSUB data, Coverage & Lookups + //================================================================= + + $this->GSUBfont = $this->fontkey . '.GSUB.' . $GSUBscriptTag . '.' . $GSUBlangsys; + + if (!isset($this->GSUBdata[$this->GSUBfont])) { + $fontCacheFilename = $this->GSUBfont . '.json'; + if ($this->fontCache->jsonHas($fontCacheFilename)) { + $font = $this->fontCache->jsonLoad($fontCacheFilename); + + $this->GSUBdata[$this->GSUBfont]['rtlSUB'] = $font['rtlSUB']; + $this->GSUBdata[$this->GSUBfont]['finals'] = $font['finals']; + if ($this->shaper == 'I') { + $this->GSUBdata[$this->GSUBfont]['rphf'] = $font['rphf']; + $this->GSUBdata[$this->GSUBfont]['half'] = $font['half']; + $this->GSUBdata[$this->GSUBfont]['pref'] = $font['pref']; + $this->GSUBdata[$this->GSUBfont]['blwf'] = $font['blwf']; + $this->GSUBdata[$this->GSUBfont]['pstf'] = $font['pstf']; + } + } else { + $this->GSUBdata[$this->GSUBfont] = ['rtlSUB' => [], 'rphf' => [], 'rphf' => [], + 'pref' => [], 'blwf' => [], 'pstf' => [], 'finals' => '' + ]; + } + } + + $fontCacheFilename = $this->fontkey . '.GSUBdata.json'; + if (!isset($this->GSUBdata[$this->fontkey]) && $this->fontCache->jsonHas($fontCacheFilename)) { + $this->GSLuCoverage = $this->GSUBdata[$this->fontkey]['GSLuCoverage'] = $this->fontCache->jsonLoad($fontCacheFilename); + } else { + $this->GSLuCoverage = $this->GSUBdata[$this->fontkey]['GSLuCoverage']; + } + + $this->GSUBLookups = $this->mpdf->CurrentFont['GSUBLookups']; + + + // 5(A). GSUB - Shaper - ARABIC + //============================== + if ($this->shaper == 'A') { + //----------------------------------------------------------------------------------- + // a. Apply initial GSUB Lookups (in order specified in lookup list but only selecting from certain tags) + //----------------------------------------------------------------------------------- + $tags = 'locl ccmp'; + $omittags = ''; + $usetags = $tags; + if (!empty($this->mpdf->OTLtags)) { + $usetags = $this->_applyTagSettings($tags, $GSUBFeatures, $omittags, true); + } + $this->_applyGSUBrules($usetags, $GSUBscriptTag, $GSUBlangsys); + + //----------------------------------------------------------------------------------- + // b. Apply context-specific forms GSUB Lookups (initial, isolated, medial, final) + //----------------------------------------------------------------------------------- + // Arab and Syriac are the only scripts requiring the special joining - which takes the place of + // isol fina medi init rules in GSUB (+ fin2 fin3 med2 in Syriac syrc) + $tags = 'isol fina fin2 fin3 medi med2 init'; + $omittags = ''; + $usetags = $tags; + if (!empty($this->mpdf->OTLtags)) { + $usetags = $this->_applyTagSettings($tags, $GSUBFeatures, $omittags, true); + } + + $this->arabGlyphs = $this->GSUBdata[$this->GSUBfont]['rtlSUB']; + + $gcms = explode("| ", $this->GlyphClassMarks); + $gcm = []; + foreach ($gcms as $g) { + $gcm[hexdec($g)] = 1; + } + $this->arabTransparentJoin = $this->arabTransparent + $gcm; + $this->arabic_shaper($usetags, $GSUBscriptTag); + + //----------------------------------------------------------------------------------- + // c. Set Kashida points (after joining occurred - medi, fina, init) but before other substitutions + //----------------------------------------------------------------------------------- + //if ($scriptblock == Ucdn::SCRIPT_ARABIC ) { + for ($i = 0; $i < count($this->OTLdata); $i++) { + // Put the kashida marker on the character BEFORE which is inserted the kashida + // Kashida marker is inverse of priority i.e. Priority 1 => 7, Priority 7 => 1. + // Priority 1 User-inserted Kashida 0640 = Tatweel + // The user entered a Kashida in a position + // Position: Before the user-inserted kashida + if ($this->OTLdata[$i]['uni'] == 0x0640) { + $this->OTLdata[$i]['GPOSinfo']['kashida'] = 8; // Put before the next character + } // Priority 2 Seen (0633) FEB3, FEB4; Sad (0635) FEBB, FEBC + // Initial or medial form + // Connecting to the next character + // Position: After the character + elseif ($this->OTLdata[$i]['uni'] == 0xFEB3 || $this->OTLdata[$i]['uni'] == 0xFEB4 || $this->OTLdata[$i]['uni'] == 0xFEBB || $this->OTLdata[$i]['uni'] == 0xFEBC) { + $checkpos = $i + 1; + while (isset($this->OTLdata[$checkpos]) && strpos($this->GlyphClassMarks, $this->OTLdata[$checkpos]['hex']) !== false) { + $checkpos++; + } + if (isset($this->OTLdata[$checkpos])) { + $this->OTLdata[$checkpos]['GPOSinfo']['kashida'] = 7; // Put after marks on next character + } + } // Priority 3 Taa Marbutah (0629) FE94; Haa (062D) FEA2; Dal (062F) FEAA + // Final form + // Connecting to previous character + // Position: Before the character + elseif ($this->OTLdata[$i]['uni'] == 0xFE94 || $this->OTLdata[$i]['uni'] == 0xFEA2 || $this->OTLdata[$i]['uni'] == 0xFEAA) { + $this->OTLdata[$i]['GPOSinfo']['kashida'] = 6; + } // Priority 4 Alef (0627) FE8E; Tah (0637) FEC2; Lam (0644) FEDE; Kaf (0643) FEDA; Gaf (06AF) FB93 + // Final form + // Connecting to previous character + // Position: Before the character + elseif ($this->OTLdata[$i]['uni'] == 0xFE8E || $this->OTLdata[$i]['uni'] == 0xFEC2 || $this->OTLdata[$i]['uni'] == 0xFEDE || $this->OTLdata[$i]['uni'] == 0xFEDA || $this->OTLdata[$i]['uni'] == 0xFB93) { + $this->OTLdata[$i]['GPOSinfo']['kashida'] = 5; + } // Priority 5 RA (0631) FEAE; Ya (064A) FEF2 FEF4; Alef Maqsurah (0649) FEF0 FBE9 + // Final or Medial form + // Connected to preceding medial BAA (0628) = FE92 + // Position: Before preceding medial Baa + // Although not mentioned in spec, added Farsi Yeh (06CC) FBFD FBFF; equivalent to 064A or 0649 + elseif ($this->OTLdata[$i]['uni'] == 0xFEAE || $this->OTLdata[$i]['uni'] == 0xFEF2 || $this->OTLdata[$i]['uni'] == 0xFEF0 || $this->OTLdata[$i]['uni'] == 0xFEF4 || $this->OTLdata[$i]['uni'] == 0xFBE9 || $this->OTLdata[$i]['uni'] == 0xFBFD || $this->OTLdata[$i]['uni'] == 0xFBFF + ) { + $checkpos = $i - 1; + while (isset($this->OTLdata[$checkpos]) && strpos($this->GlyphClassMarks, $this->OTLdata[$checkpos]['hex']) !== false) { + $checkpos--; + } + if (isset($this->OTLdata[$checkpos]) && $this->OTLdata[$checkpos]['uni'] == 0xFE92) { + $this->OTLdata[$checkpos]['GPOSinfo']['kashida'] = 4; // ******* Before preceding BAA + } + } // Priority 6 WAW (0648) FEEE; Ain (0639) FECA; Qaf (0642) FED6; Fa (0641) FED2 + // Final form + // Connecting to previous character + // Position: Before the character + elseif ($this->OTLdata[$i]['uni'] == 0xFEEE || $this->OTLdata[$i]['uni'] == 0xFECA || $this->OTLdata[$i]['uni'] == 0xFED6 || $this->OTLdata[$i]['uni'] == 0xFED2) { + $this->OTLdata[$i]['GPOSinfo']['kashida'] = 3; + } + + // Priority 7 Other connecting characters + // Final form + // Connecting to previous character + // Position: Before the character + /* This isn't in the spec, but using MS WORD as a basis, give a lower priority to the 3 characters already checked + in (5) above. Test case: + خْرَىٰ + فَتُذَكِّر + */ + + if (!isset($this->OTLdata[$i]['GPOSinfo']['kashida'])) { + if (strpos($this->GSUBdata[$this->GSUBfont]['finals'], $this->OTLdata[$i]['hex']) !== false) { // ANY OTHER FINAL FORM + $this->OTLdata[$i]['GPOSinfo']['kashida'] = 2; + } elseif (strpos('0FEAE 0FEF0 0FEF2', $this->OTLdata[$i]['hex']) !== false) { // not already included in 5 above + $this->OTLdata[$i]['GPOSinfo']['kashida'] = 1; + } + } + } + + //----------------------------------------------------------------------------------- + // d. Apply Presentation Forms GSUB Lookups (+ any discretionary) - Apply one at a time in Feature order + //----------------------------------------------------------------------------------- + $tags = 'rlig calt liga clig mset'; + + $omittags = 'locl ccmp nukt akhn rphf rkrf pref blwf abvf half pstf cfar vatu cjct init medi fina isol med2 fin2 fin3 ljmo vjmo tjmo'; + $usetags = $tags; + if (!empty($this->mpdf->OTLtags)) { + $usetags = $this->_applyTagSettings($tags, $GSUBFeatures, $omittags, false); + } + + $ts = explode(' ', $usetags); + foreach ($ts as $ut) { // - Apply one at a time in Feature order + $this->_applyGSUBrules($ut, $GSUBscriptTag, $GSUBlangsys); + } + //----------------------------------------------------------------------------------- + // e. NOT IN SPEC + // If space precedes a mark -> substitute a   before the Mark, to prevent line breaking Test: + //----------------------------------------------------------------------------------- + for ($ptr = 1; $ptr < count($this->OTLdata); $ptr++) { + if ($this->OTLdata[$ptr]['general_category'] == Ucdn::UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK && $this->OTLdata[$ptr - 1]['uni'] == 32) { + $this->OTLdata[$ptr - 1]['uni'] = 0xa0; + $this->OTLdata[$ptr - 1]['hex'] = '000A0'; + } + } + } // 5(I). GSUB - Shaper - INDIC and SINHALA and KHMER + //=================================== + elseif ($this->shaper == 'I' || $this->shaper == 'K' || $this->shaper == 'S') { + $this->restrictToSyllable = true; + //----------------------------------------------------------------------------------- + // a. First decompose/compose split mattras + // (normalize) ??????? Nukta/Halant order etc ?????????????????????????????????????????????????????????????????????????? + //----------------------------------------------------------------------------------- + for ($ptr = 0; $ptr < count($this->OTLdata); $ptr++) { + $char = $this->OTLdata[$ptr]['uni']; + $sub = Indic::decompose_indic($char); + if ($sub) { + $newinfo = []; + for ($i = 0; $i < count($sub); $i++) { + $newinfo[$i] = []; + $ucd_record = Ucdn::get_ucd_record($sub[$i]); + $newinfo[$i]['general_category'] = $ucd_record[0]; + $newinfo[$i]['bidi_type'] = $ucd_record[2]; + $charasstr = $this->unicode_hex($sub[$i]); + if (strpos($this->GlyphClassMarks, $charasstr) !== false) { + $newinfo[$i]['group'] = 'M'; + } else { + $newinfo[$i]['group'] = 'C'; + } + $newinfo[$i]['uni'] = $sub[$i]; + $newinfo[$i]['hex'] = $charasstr; + } + array_splice($this->OTLdata, $ptr, 1, $newinfo); + $ptr += count($sub) - 1; + } + /* Only Composition-exclusion exceptions that we want to recompose. */ + if ($this->shaper == 'I') { + if ($char == 0x09AF && isset($this->OTLdata[$ptr + 1]) && $this->OTLdata[$ptr + 1]['uni'] == 0x09BC) { + $sub = 0x09DF; + $newinfo = []; + $newinfo[0] = []; + $ucd_record = Ucdn::get_ucd_record($sub); + $newinfo[0]['general_category'] = $ucd_record[0]; + $newinfo[0]['bidi_type'] = $ucd_record[2]; + $newinfo[0]['group'] = 'C'; + $newinfo[0]['uni'] = $sub; + $newinfo[0]['hex'] = $this->unicode_hex($sub); + array_splice($this->OTLdata, $ptr, 2, $newinfo); + } + } + } + //----------------------------------------------------------------------------------- + // b. Analyse characters - group as syllables/clusters (Indic); invalid diacritics; add dotted circle + //----------------------------------------------------------------------------------- + $indic_category_string = ''; + foreach ($this->OTLdata as $eid => $c) { + Indic::set_indic_properties($this->OTLdata[$eid], $scriptblock); // sets ['indic_category'] and ['indic_position'] + //$c['general_category'] + //$c['combining_class'] + //$c['uni'] = $char; + + $indic_category_string .= Indic::$indic_category_char[$this->OTLdata[$eid]['indic_category']]; + } + + $broken_syllables = false; + if ($this->shaper == 'I') { + Indic::set_syllables($this->OTLdata, $indic_category_string, $broken_syllables); + } elseif ($this->shaper == 'S') { + Indic::set_syllables_sinhala($this->OTLdata, $indic_category_string, $broken_syllables); + } elseif ($this->shaper == 'K') { + Indic::set_syllables_khmer($this->OTLdata, $indic_category_string, $broken_syllables); + } + $indic_category_string = ''; + + //----------------------------------------------------------------------------------- + // c. Initial Re-ordering (Indic / Khmer / Sinhala) + //----------------------------------------------------------------------------------- + // Find base consonant + // Decompose/compose and reorder Matras + // Reorder marks to canonical order + + $indic_config = Indic::$indic_configs[$scriptblock]; + $dottedcircle = false; + if ($broken_syllables) { + if ($this->mpdf->_charDefined($this->mpdf->fonts[$this->fontkey]['cw'], 0x25CC)) { + $dottedcircle = []; + $ucd_record = Ucdn::get_ucd_record(0x25CC); + $dottedcircle[0]['general_category'] = $ucd_record[0]; + $dottedcircle[0]['bidi_type'] = $ucd_record[2]; + $dottedcircle[0]['group'] = 'C'; + $dottedcircle[0]['uni'] = 0x25CC; + $dottedcircle[0]['indic_category'] = Indic::OT_DOTTEDCIRCLE; + $dottedcircle[0]['indic_position'] = Indic::POS_BASE_C; + + $dottedcircle[0]['hex'] = '025CC'; // TEMPORARY ***** + } + } + Indic::initial_reordering($this->OTLdata, $this->GSUBdata[$this->GSUBfont], $broken_syllables, $indic_config, $scriptblock, $is_old_spec, $dottedcircle); + + //----------------------------------------------------------------------------------- + // d. Apply initial and basic shaping forms GSUB Lookups (one at a time) + //----------------------------------------------------------------------------------- + if ($this->shaper == 'I' || $this->shaper == 'S') { + $tags = 'locl ccmp nukt akhn rphf rkrf pref blwf half pstf vatu cjct'; + } elseif ($this->shaper == 'K') { + $tags = 'locl ccmp pref blwf abvf pstf cfar'; + } + $this->_applyGSUBrulesIndic($tags, $GSUBscriptTag, $GSUBlangsys, $is_old_spec); + + //----------------------------------------------------------------------------------- + // e. Final Re-ordering (Indic / Khmer / Sinhala) + //----------------------------------------------------------------------------------- + // Reorder matras + // Reorder reph + // Reorder pre-base reordering consonants: + + Indic::final_reordering($this->OTLdata, $this->GSUBdata[$this->GSUBfont], $indic_config, $scriptblock, $is_old_spec); + + //----------------------------------------------------------------------------------- + // f. Apply 'init' feature to first syllable in word (indicated by ['mask']) Indic::FLAG(Indic::INIT); + //----------------------------------------------------------------------------------- + if ($this->shaper == 'I' || $this->shaper == 'S') { + $tags = 'init'; + $this->_applyGSUBrulesIndic($tags, $GSUBscriptTag, $GSUBlangsys, $is_old_spec); + } + + //----------------------------------------------------------------------------------- + // g. Apply Presentation Forms GSUB Lookups (+ any discretionary) + //----------------------------------------------------------------------------------- + $tags = 'pres abvs blws psts haln rlig calt liga clig mset'; + + $omittags = 'locl ccmp nukt akhn rphf rkrf pref blwf abvf half pstf cfar vatu cjct init medi fina isol med2 fin2 fin3 ljmo vjmo tjmo'; + $usetags = $tags; + if (!empty($this->mpdf->OTLtags)) { + $usetags = $this->_applyTagSettings($tags, $GSUBFeatures, $omittags, false); + } + if ($this->shaper == 'K') { // Features are applied one at a time, working through each codepoint + $this->_applyGSUBrulesSingly($usetags, $GSUBscriptTag, $GSUBlangsys); + } else { + $this->_applyGSUBrules($usetags, $GSUBscriptTag, $GSUBlangsys); + } + $this->restrictToSyllable = false; + } // 5(M). GSUB - Shaper - MYANMAR (ONLY mym2) + //============================== + // NB Old style 'mymr' is left to go through the default shaper + elseif ($this->shaper == 'M') { + $this->restrictToSyllable = true; + //----------------------------------------------------------------------------------- + // a. Analyse characters - group as syllables/clusters (Myanmar); invalid diacritics; add dotted circle + //----------------------------------------------------------------------------------- + $myanmar_category_string = ''; + foreach ($this->OTLdata as $eid => $c) { + Myanmar::set_myanmar_properties($this->OTLdata[$eid]); // sets ['myanmar_category'] and ['myanmar_position'] + $myanmar_category_string .= Myanmar::$myanmar_category_char[$this->OTLdata[$eid]['myanmar_category']]; + } + $broken_syllables = false; + Myanmar::set_syllables($this->OTLdata, $myanmar_category_string, $broken_syllables); + $myanmar_category_string = ''; + + //----------------------------------------------------------------------------------- + // b. Re-ordering (Myanmar mym2) + //----------------------------------------------------------------------------------- + $dottedcircle = false; + if ($broken_syllables) { + if ($this->mpdf->_charDefined($this->mpdf->fonts[$this->fontkey]['cw'], 0x25CC)) { + $dottedcircle = []; + $ucd_record = Ucdn::get_ucd_record(0x25CC); + $dottedcircle[0]['general_category'] = $ucd_record[0]; + $dottedcircle[0]['bidi_type'] = $ucd_record[2]; + $dottedcircle[0]['group'] = 'C'; + $dottedcircle[0]['uni'] = 0x25CC; + $dottedcircle[0]['myanmar_category'] = Myanmar::OT_DOTTEDCIRCLE; + $dottedcircle[0]['myanmar_position'] = Myanmar::POS_BASE_C; + $dottedcircle[0]['hex'] = '025CC'; + } + } + Myanmar::reordering($this->OTLdata, $this->GSUBdata[$this->GSUBfont], $broken_syllables, $dottedcircle); + + //----------------------------------------------------------------------------------- + // c. Apply initial and basic shaping forms GSUB Lookups (one at a time) + //----------------------------------------------------------------------------------- + + $tags = 'locl ccmp rphf pref blwf pstf'; + $this->_applyGSUBrulesMyanmar($tags, $GSUBscriptTag, $GSUBlangsys); + + //----------------------------------------------------------------------------------- + // d. Apply Presentation Forms GSUB Lookups (+ any discretionary) + //----------------------------------------------------------------------------------- + $tags = 'pres abvs blws psts haln rlig calt liga clig mset'; + $omittags = 'locl ccmp nukt akhn rphf rkrf pref blwf abvf half pstf cfar vatu cjct init medi fina isol med2 fin2 fin3 ljmo vjmo tjmo'; + $usetags = $tags; + if (!empty($this->mpdf->OTLtags)) { + $usetags = $this->_applyTagSettings($tags, $GSUBFeatures, $omittags, false); + } + $this->_applyGSUBrules($usetags, $GSUBscriptTag, $GSUBlangsys); + $this->restrictToSyllable = false; + } // 5(E). GSUB - Shaper - SEA South East Asian (New Tai Lue, Cham, Tai Tam) + //============================== + elseif ($this->shaper == 'E') { + /* HarfBuzz says: If the designer designed the font for the 'DFLT' script, + * use the default shaper. Otherwise, use the SEA shaper. + * Note that for some simple scripts, there may not be *any* + * GSUB/GPOS needed, so there may be no scripts found! */ + + $this->restrictToSyllable = true; + //----------------------------------------------------------------------------------- + // a. Analyse characters - group as syllables/clusters (Indic); invalid diacritics; add dotted circle + //----------------------------------------------------------------------------------- + $sea_category_string = ''; + foreach ($this->OTLdata as $eid => $c) { + Sea::set_sea_properties($this->OTLdata[$eid], $scriptblock); // sets ['sea_category'] and ['sea_position'] + //$c['general_category'] + //$c['combining_class'] + //$c['uni'] = $char; + + $sea_category_string .= Sea::$sea_category_char[$this->OTLdata[$eid]['sea_category']]; + } + + $broken_syllables = false; + Sea::set_syllables($this->OTLdata, $sea_category_string, $broken_syllables); + $sea_category_string = ''; + + //----------------------------------------------------------------------------------- + // b. Apply locl and ccmp shaping forms - before initial re-ordering; GSUB Lookups (one at a time) + //----------------------------------------------------------------------------------- + $tags = 'locl ccmp'; + $this->_applyGSUBrulesSingly($tags, $GSUBscriptTag, $GSUBlangsys); + + //----------------------------------------------------------------------------------- + // c. Initial Re-ordering + //----------------------------------------------------------------------------------- + // Find base consonant + // Decompose/compose and reorder Matras + // Reorder marks to canonical order + + $dottedcircle = false; + if ($broken_syllables) { + if ($this->mpdf->_charDefined($this->mpdf->fonts[$this->fontkey]['cw'], 0x25CC)) { + $dottedcircle = []; + $ucd_record = Ucdn::get_ucd_record(0x25CC); + $dottedcircle[0]['general_category'] = $ucd_record[0]; + $dottedcircle[0]['bidi_type'] = $ucd_record[2]; + $dottedcircle[0]['group'] = 'C'; + $dottedcircle[0]['uni'] = 0x25CC; + $dottedcircle[0]['sea_category'] = Sea::OT_GB; + $dottedcircle[0]['sea_position'] = Sea::POS_BASE_C; + + $dottedcircle[0]['hex'] = '025CC'; // TEMPORARY ***** + } + } + Sea::initial_reordering($this->OTLdata, $this->GSUBdata[$this->GSUBfont], $broken_syllables, $scriptblock, $dottedcircle); + + //----------------------------------------------------------------------------------- + // d. Apply basic shaping forms GSUB Lookups (one at a time) + //----------------------------------------------------------------------------------- + $tags = 'pref abvf blwf pstf'; + $this->_applyGSUBrulesSingly($tags, $GSUBscriptTag, $GSUBlangsys); + + //----------------------------------------------------------------------------------- + // e. Final Re-ordering + //----------------------------------------------------------------------------------- + + Sea::final_reordering($this->OTLdata, $this->GSUBdata[$this->GSUBfont], $scriptblock); + + //----------------------------------------------------------------------------------- + // f. Apply Presentation Forms GSUB Lookups (+ any discretionary) + //----------------------------------------------------------------------------------- + $tags = 'pres abvs blws psts'; + + $omittags = 'locl ccmp nukt akhn rphf rkrf pref blwf abvf half pstf cfar vatu cjct init medi fina isol med2 fin2 fin3 ljmo vjmo tjmo'; + $usetags = $tags; + if (!empty($this->mpdf->OTLtags)) { + $usetags = $this->_applyTagSettings($tags, $GSUBFeatures, $omittags, false); + } + $this->_applyGSUBrules($usetags, $GSUBscriptTag, $GSUBlangsys); + $this->restrictToSyllable = false; + } // 5(D). GSUB - Shaper - DEFAULT (including THAI and LAO and MYANMAR v1 [mymr] and TIBETAN) + //============================== + else { // DEFAULT + //----------------------------------------------------------------------------------- + // a. First decompose/compose in Thai / Lao - Tibetan + //----------------------------------------------------------------------------------- + // Decomposition for THAI or LAO + /* This function implements the shaping logic documented here: + * + * http://linux.thai.net/~thep/th-otf/shaping.html + * + * The first shaping rule listed there is needed even if the font has Thai + * OpenType tables. + * + * + * The following is NOT specified in the MS OT Thai spec, however, it seems + * to be what Uniscribe and other engines implement. According to Eric Muller: + * + * When you have a SARA AM, decompose it in NIKHAHIT + SARA AA, *and* move the + * NIKHAHIT backwards over any tone mark (0E48-0E4B). + * + * <0E14, 0E4B, 0E33> -> <0E14, 0E4D, 0E4B, 0E32> + * + * This reordering is legit only when the NIKHAHIT comes from a SARA AM, not + * when it's there to start with. The string <0E14, 0E4B, 0E4D> is probably + * not what a user wanted, but the rendering is nevertheless nikhahit above + * chattawa. + * + * Same for Lao. + * + * Thai Lao + * SARA AM: U+0E33 U+0EB3 + * SARA AA: U+0E32 U+0EB2 + * Nikhahit: U+0E4D U+0ECD + * + * Testing shows that Uniscribe reorder the following marks: + * Thai: <0E31,0E34..0E37,0E47..0E4E> + * Lao: <0EB1,0EB4..0EB7,0EC7..0ECE> + * + * Lao versions are the same as Thai + 0x80. + */ + if ($this->shaper == 'T' || $this->shaper == 'L') { + for ($ptr = 0; $ptr < count($this->OTLdata); $ptr++) { + $char = $this->OTLdata[$ptr]['uni']; + if (($char & ~0x0080) == 0x0E33) { // if SARA_AM (U+0E33 or U+0EB3) + $NIKHAHIT = $char + 0x1A; + $SARA_AA = $char - 1; + $sub = [$SARA_AA, $NIKHAHIT]; + + $newinfo = []; + $ucd_record = Ucdn::get_ucd_record($sub[0]); + $newinfo[0]['general_category'] = $ucd_record[0]; + $newinfo[0]['bidi_type'] = $ucd_record[2]; + $charasstr = $this->unicode_hex($sub[0]); + if (strpos($this->GlyphClassMarks, $charasstr) !== false) { + $newinfo[0]['group'] = 'M'; + } else { + $newinfo[0]['group'] = 'C'; + } + $newinfo[0]['uni'] = $sub[0]; + $newinfo[0]['hex'] = $charasstr; + $this->OTLdata[$ptr] = $newinfo[0]; // Substitute SARA_AM => SARA_AA + + $ntones = 0; // number of (preceding) tone marks + // IS_TONE_MARK ((x) & ~0x0080, 0x0E34 - 0x0E37, 0x0E47 - 0x0E4E, 0x0E31) + while (isset($this->OTLdata[$ptr - 1 - $ntones]) && ( + ($this->OTLdata[$ptr - 1 - $ntones]['uni'] & ~0x0080) == 0x0E31 || + (($this->OTLdata[$ptr - 1 - $ntones]['uni'] & ~0x0080) >= 0x0E34 && + ($this->OTLdata[$ptr - 1 - $ntones]['uni'] & ~0x0080) <= 0x0E37) || + (($this->OTLdata[$ptr - 1 - $ntones]['uni'] & ~0x0080) >= 0x0E47 && + ($this->OTLdata[$ptr - 1 - $ntones]['uni'] & ~0x0080) <= 0x0E4E) + ) + ) { + $ntones++; + } + + $newinfo = []; + $ucd_record = Ucdn::get_ucd_record($sub[1]); + $newinfo[0]['general_category'] = $ucd_record[0]; + $newinfo[0]['bidi_type'] = $ucd_record[2]; + $charasstr = $this->unicode_hex($sub[1]); + if (strpos($this->GlyphClassMarks, $charasstr) !== false) { + $newinfo[0]['group'] = 'M'; + } else { + $newinfo[0]['group'] = 'C'; + } + $newinfo[0]['uni'] = $sub[1]; + $newinfo[0]['hex'] = $charasstr; + // Insert NIKAHIT + array_splice($this->OTLdata, $ptr - $ntones, 0, $newinfo); + + $ptr++; + } + } + } + + if ($scriptblock == Ucdn::SCRIPT_TIBETAN) { + // ========================= + // Reordering TIBETAN + // ========================= + // Tibetan does not need to need a shaper generally, as long as characters are presented in the correct order + // so we will do one minor change here: + // From ICU: If the present character is a number, and the next character is a pre-number combining mark + // then the two characters are reordered + // From MS OTL spec the following are Digit modifiers (Md): 0F18–0F19, 0F3E–0F3F + // Digits: 0F20–0F33 + // On testing only 0x0F3F (pre-based mark) seems to need re-ordering + for ($ptr = 0; $ptr < count($this->OTLdata) - 1; $ptr++) { + if (Indic::in_range($this->OTLdata[$ptr]['uni'], 0x0F20, 0x0F33) && $this->OTLdata[$ptr + 1]['uni'] == 0x0F3F) { + $tmp = $this->OTLdata[$ptr + 1]; + $this->OTLdata[$ptr + 1] = $this->OTLdata[$ptr]; + $this->OTLdata[$ptr] = $tmp; + } + } + + + // ========================= + // Decomposition for TIBETAN + // ========================= + /* Recommended, but does not seem to change anything... + for($ptr=0; $ptr<count($this->OTLdata); $ptr++) { + $char = $this->OTLdata[$ptr]['uni']; + $sub = Indic::decompose_indic($char); + if ($sub) { + $newinfo = array(); + for($i=0;$i<count($sub);$i++) { + $newinfo[$i] = array(); + $ucd_record = Ucdn::get_ucd_record($sub[$i]); + $newinfo[$i]['general_category'] = $ucd_record[0]; + $newinfo[$i]['bidi_type'] = $ucd_record[2]; + $charasstr = $this->unicode_hex($sub[$i]); + if (strpos($this->GlyphClassMarks, $charasstr)!==false) { $newinfo[$i]['group'] = 'M'; } + else { $newinfo[$i]['group'] = 'C'; } + $newinfo[$i]['uni'] = $sub[$i]; + $newinfo[$i]['hex'] = $charasstr; + } + array_splice($this->OTLdata, $ptr, 1, $newinfo); + $ptr += count($sub)-1; + } + } + */ + } + + + //----------------------------------------------------------------------------------- + // b. Apply all GSUB Lookups (in order specified in lookup list) + //----------------------------------------------------------------------------------- + $tags = 'locl ccmp pref blwf abvf pstf pres abvs blws psts haln rlig calt liga clig mset RQD'; + // pref blwf abvf pstf required for Tibetan + // " RQD" is a non-standard tag in Garuda font - presumably intended to be used by default ? "ReQuireD" + // Being a 3 letter tag is non-standard, and does not allow it to be set by font-feature-settings + + + /* ?Add these until shapers witten? + Hangul: ljmo vjmo tjmo + */ + + $omittags = ''; + $useGSUBtags = $tags; + if (!empty($this->mpdf->OTLtags)) { + $useGSUBtags = $this->_applyTagSettings($tags, $GSUBFeatures, $omittags, false); + } + // APPLY GSUB rules (as long as not Latin + SmallCaps - but not OTL smcp) + if (!(($this->mpdf->textvar & TextVars::FC_SMALLCAPS) && $scriptblock == Ucdn::SCRIPT_LATIN && strpos($useGSUBtags, 'smcp') === false)) { + $this->_applyGSUBrules($useGSUBtags, $GSUBscriptTag, $GSUBlangsys); + } + } + } + + // Shapers - KHMER & THAI & LAO - Replace Word boundary marker with U+200B + // Also TIBETAN (no shaper) + //======================================================= + if (($this->shaper == "K" || $this->shaper == "T" || $this->shaper == "L") || $scriptblock == Ucdn::SCRIPT_TIBETAN) { + // Set up properties to insert a U+200B character + $newinfo = []; + //$newinfo[0] = array('general_category' => 1, 'bidi_type' => 14, 'group' => 'S', 'uni' => 0x200B, 'hex' => '0200B'); + $newinfo[0] = [ + 'general_category' => Ucdn::UNICODE_GENERAL_CATEGORY_FORMAT, + 'bidi_type' => Ucdn::BIDI_CLASS_BN, + 'group' => 'S', 'uni' => 0x200B, 'hex' => '0200B']; + // Then insert U+200B at (after) all word end boundaries + for ($i = count($this->OTLdata) - 1; $i > 0; $i--) { + // Make sure after GSUB that wordend has not been moved - check next char is not in the same syllable + if (isset($this->OTLdata[$i]['wordend']) && $this->OTLdata[$i]['wordend'] && + isset($this->OTLdata[$i + 1]['uni']) && (!isset($this->OTLdata[$i + 1]['syllable']) || !isset($this->OTLdata[$i + 1]['syllable']) || $this->OTLdata[$i + 1]['syllable'] != $this->OTLdata[$i]['syllable'])) { + array_splice($this->OTLdata, $i + 1, 0, $newinfo); + $this->_updateLigatureMarks($i, 1); + } elseif ($this->OTLdata[$i]['uni'] == 0x2e) { // Word end if Full-stop. + array_splice($this->OTLdata, $i + 1, 0, $newinfo); + $this->_updateLigatureMarks($i, 1); + } + } + } + + + // Shapers - INDIC & ARABIC & KHMER & SINHALA & MYANMAR - Remove ZWJ and ZWNJ + //======================================================= + if ($this->shaper == 'I' || $this->shaper == 'S' || $this->shaper == 'A' || $this->shaper == 'K' || $this->shaper == 'M') { + // Remove ZWJ and ZWNJ + for ($i = 0; $i < count($this->OTLdata); $i++) { + if ($this->OTLdata[$i]['uni'] == 8204 || $this->OTLdata[$i]['uni'] == 8205) { + array_splice($this->OTLdata, $i, 1); + $this->_updateLigatureMarks($i, -1); + } + } + } + + + //////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////// + ////////// GPOS ///////////////////////////////// + //////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////// + if (($useOTL & 0xFF) && $GPOSscriptTag && $GPOSlangsys && $GPOSFeatures) { + $this->Entry = []; + $this->Exit = []; + + // 6. Load GPOS data, Coverage & Lookups + //================================================================= + $fontCacheFilename = $this->mpdf->CurrentFont['fontkey'] . '.GPOSdata.json'; + if (!isset($this->GPOSdata[$this->fontkey]) && $this->fontCache->jsonHas($fontCacheFilename)) { + $this->LuCoverage = $this->GPOSdata[$this->fontkey]['LuCoverage'] = $this->fontCache->jsonLoad($fontCacheFilename); + } else { + $this->LuCoverage = $this->GPOSdata[$this->fontkey]['LuCoverage']; + } + + $this->GPOSLookups = $this->mpdf->CurrentFont['GPOSLookups']; + + + // 7. Select Feature tags to use (incl optional) + //============================== + $tags = 'abvm blwm mark mkmk curs cpsp dist requ'; // Default set + // 'requ' is not listed in the Microsoft registry of Feature tags + // Found in Arial Unicode MS, it repositions the baseline for punctuation in Kannada script + + // ZZZ96 + // Set kern to be included by default in non-Latin script (? just when shapers used) + // Kern is used in some fonts to reposition marks etc. and is essential for correct display + //if ($this->shaper) {$tags .= ' kern'; } + if ($scriptblock != Ucdn::SCRIPT_LATIN) { + $tags .= ' kern'; + } + + $omittags = ''; + $usetags = $tags; + if (!empty($this->mpdf->OTLtags)) { + $usetags = $this->_applyTagSettings($tags, $GPOSFeatures, $omittags, false); + } + + + + // 8. Get GPOS LookupList from Feature tags + //============================== + $LookupList = []; + foreach ($GPOSFeatures as $tag => $arr) { + if (strpos($usetags, $tag) !== false) { + foreach ($arr as $lu) { + $LookupList[$lu] = $tag; + } + } + } + ksort($LookupList); + + + // 9. Apply GPOS Lookups (in order specified in lookup list but selecting from specified tags) + //============================== + // APPLY THE GPOS RULES (as long as not Latin + SmallCaps - but not OTL smcp) + if (!(($this->mpdf->textvar & TextVars::FC_SMALLCAPS) && $scriptblock == Ucdn::SCRIPT_LATIN && strpos($useGSUBtags, 'smcp') === false)) { + $this->_applyGPOSrules($LookupList, $is_old_spec); + // (sets: $this->OTLdata[n]['GPOSinfo'] XPlacement YPlacement XAdvance Entry Exit ) + } + + // 10. Process cursive text + //============================== + if (count($this->Entry) || count($this->Exit)) { + // RTL + $incurs = false; + for ($i = (count($this->OTLdata) - 1); $i >= 0; $i--) { + if (isset($this->Entry[$i]) && isset($this->Entry[$i]['Y']) && $this->Entry[$i]['dir'] == 'RTL') { + $nextbase = $i - 1; // Set as next base ignoring marks (next base reading RTL in logical oder + while (isset($this->OTLdata[$nextbase]['hex']) && strpos($this->GlyphClassMarks, $this->OTLdata[$nextbase]['hex']) !== false) { + $nextbase--; + } + if (isset($this->Exit[$nextbase]) && isset($this->Exit[$nextbase]['Y'])) { + $diff = $this->Entry[$i]['Y'] - $this->Exit[$nextbase]['Y']; + if ($incurs === false) { + $incurs = $diff; + } else { + $incurs += $diff; + } + for ($j = ($i - 1); $j >= $nextbase; $j--) { + if (isset($this->OTLdata[$j]['GPOSinfo']['YPlacement'])) { + $this->OTLdata[$j]['GPOSinfo']['YPlacement'] += $incurs; + } else { + $this->OTLdata[$j]['GPOSinfo']['YPlacement'] = $incurs; + } + } + if (isset($this->Exit[$i]['X']) && isset($this->Entry[$nextbase]['X'])) { + $adj = -($this->Entry[$i]['X'] - $this->Exit[$nextbase]['X']); + // If XAdvance is aplied - in order for PDF to position the Advance correctly need to place it on: + // in RTL - the current glyph or the last of any associated marks + if (isset($this->OTLdata[$nextbase + 1]['GPOSinfo']['XAdvance'])) { + $this->OTLdata[$nextbase + 1]['GPOSinfo']['XAdvance'] += $adj; + } else { + $this->OTLdata[$nextbase + 1]['GPOSinfo']['XAdvance'] = $adj; + } + } + } else { + $incurs = false; + } + } elseif (strpos($this->GlyphClassMarks, $this->OTLdata[$i]['hex']) !== false) { + continue; + } // ignore Marks + else { + $incurs = false; + } + } + // LTR + $incurs = false; + for ($i = 0; $i < count($this->OTLdata); $i++) { + if (isset($this->Exit[$i]) && isset($this->Exit[$i]['Y']) && $this->Exit[$i]['dir'] == 'LTR') { + $nextbase = $i + 1; // Set as next base ignoring marks + while (strpos($this->GlyphClassMarks, $this->OTLdata[$nextbase]['hex']) !== false) { + $nextbase++; + } + if (isset($this->Entry[$nextbase]) && isset($this->Entry[$nextbase]['Y'])) { + $diff = $this->Exit[$i]['Y'] - $this->Entry[$nextbase]['Y']; + if ($incurs === false) { + $incurs = $diff; + } else { + $incurs += $diff; + } + for ($j = ($i + 1); $j <= $nextbase; $j++) { + if (isset($this->OTLdata[$j]['GPOSinfo']['YPlacement'])) { + $this->OTLdata[$j]['GPOSinfo']['YPlacement'] += $incurs; + } else { + $this->OTLdata[$j]['GPOSinfo']['YPlacement'] = $incurs; + } + } + if (isset($this->Exit[$i]['X']) && isset($this->Entry[$nextbase]['X'])) { + $adj = -($this->Exit[$i]['X'] - $this->Entry[$nextbase]['X']); + // If XAdvance is aplied - in order for PDF to position the Advance correctly need to place it on: + // in LTR - the next glyph, ignoring marks + if (isset($this->OTLdata[$nextbase]['GPOSinfo']['XAdvance'])) { + $this->OTLdata[$nextbase]['GPOSinfo']['XAdvance'] += $adj; + } else { + $this->OTLdata[$nextbase]['GPOSinfo']['XAdvance'] = $adj; + } + } + } else { + $incurs = false; + } + } elseif (strpos($this->GlyphClassMarks, $this->OTLdata[$i]['hex']) !== false) { + continue; + } // ignore Marks + else { + $incurs = false; + } + } + } + } // end GPOS + + if ($this->debugOTL) { + $this->_dumpproc('END', '-', '-', '-', '-', 0, '-', 0); + exit; + } + + $this->schOTLdata[$sch] = $this->OTLdata; + $this->OTLdata = []; + } // END foreach subchunk + // 11. Re-assemble and return text string + //============================== + $newGPOSinfo = []; + $newOTLdata = []; + $newchar_data = []; + $newgroup = ''; + $e = ''; + $ectr = 0; + + for ($sch = 0; $sch <= $subchunk; $sch++) { + for ($i = 0; $i < count($this->schOTLdata[$sch]); $i++) { + if (isset($this->schOTLdata[$sch][$i]['GPOSinfo'])) { + $newGPOSinfo[$ectr] = $this->schOTLdata[$sch][$i]['GPOSinfo']; + } + $newchar_data[$ectr] = ['bidi_class' => $this->schOTLdata[$sch][$i]['bidi_type'], 'uni' => $this->schOTLdata[$sch][$i]['uni']]; + $newgroup .= $this->schOTLdata[$sch][$i]['group']; + $e .= UtfString::code2utf($this->schOTLdata[$sch][$i]['uni']); + if (isset($this->mpdf->CurrentFont['subset'])) { + $this->mpdf->CurrentFont['subset'][$this->schOTLdata[$sch][$i]['uni']] = $this->schOTLdata[$sch][$i]['uni']; + } + $ectr++; + } + } + $this->OTLdata['GPOSinfo'] = $newGPOSinfo; + $this->OTLdata['char_data'] = $newchar_data; + $this->OTLdata['group'] = $newgroup; + + // This leaves OTLdata::GPOSinfo, ::bidi_type, & ::group + + return $e; + } + + function _applyTagSettings($tags, $Features, $omittags = '', $onlytags = false) + { + if (empty($this->mpdf->OTLtags['Plus']) && empty($this->mpdf->OTLtags['Minus']) && empty($this->mpdf->OTLtags['FFPlus']) && empty($this->mpdf->OTLtags['FFMinus'])) { + return $tags; + } + + // Use $tags as starting point + $usetags = $tags; + + // Only set / unset tags which are in the font + // Ignore tags which are in $omittags + // If $onlytags, then just unset tags which are already in the Tag list + + $fp = $fm = $ffp = $ffm = ''; + + // Font features to enable - set by font-variant-xx + if (isset($this->mpdf->OTLtags['Plus'])) { + $fp = $this->mpdf->OTLtags['Plus']; + } + preg_match_all('/([a-zA-Z0-9]{4})/', $fp, $m); + for ($i = 0; $i < count($m[0]); $i++) { + $t = $m[1][$i]; + // Is it a valid tag? + if (isset($Features[$t]) && strpos($omittags, $t) === false && (!$onlytags || strpos($tags, $t) !== false )) { + $usetags .= ' ' . $t; + } + } + + // Font features to disable - set by font-variant-xx + if (isset($this->mpdf->OTLtags['Minus'])) { + $fm = $this->mpdf->OTLtags['Minus']; + } + preg_match_all('/([a-zA-Z0-9]{4})/', $fm, $m); + for ($i = 0; $i < count($m[0]); $i++) { + $t = $m[1][$i]; + // Is it a valid tag? + if (isset($Features[$t]) && strpos($omittags, $t) === false && (!$onlytags || strpos($tags, $t) !== false )) { + $usetags = str_replace($t, '', $usetags); + } + } + + // Font features to enable - set by font-feature-settings + if (isset($this->mpdf->OTLtags['FFPlus'])) { + $ffp = $this->mpdf->OTLtags['FFPlus']; // Font Features - may include integer: salt4 + } + preg_match_all('/([a-zA-Z0-9]{4})([\d+]*)/', $ffp, $m); + for ($i = 0; $i < count($m[0]); $i++) { + $t = $m[1][$i]; + // Is it a valid tag? + if (isset($Features[$t]) && strpos($omittags, $t) === false && (!$onlytags || strpos($tags, $t) !== false )) { + $usetags .= ' ' . $m[0][$i]; // - may include integer: salt4 + } + } + + // Font features to disable - set by font-feature-settings + if (isset($this->mpdf->OTLtags['FFMinus'])) { + $ffm = $this->mpdf->OTLtags['FFMinus']; + } + preg_match_all('/([a-zA-Z0-9]{4})/', $ffm, $m); + for ($i = 0; $i < count($m[0]); $i++) { + $t = $m[1][$i]; + // Is it a valid tag? + if (isset($Features[$t]) && strpos($omittags, $t) === false && (!$onlytags || strpos($tags, $t) !== false )) { + $usetags = str_replace($t, '', $usetags); + } + } + return $usetags; + } + + function _applyGSUBrules($usetags, $scriptTag, $langsys) + { + // Features from all Tags are applied together, in Lookup List order. + // For Indic - should be applied one syllable at a time + // - Implemented in functions checkContextMatch and checkContextMatchMultiple by failing to match if outside scope of current 'syllable' + // if $this->restrictToSyllable is true + + $GSUBFeatures = $this->mpdf->CurrentFont['GSUBFeatures'][$scriptTag][$langsys]; + $LookupList = []; + foreach ($GSUBFeatures as $tag => $arr) { + if (strpos($usetags, $tag) !== false) { + foreach ($arr as $lu) { + $LookupList[$lu] = $tag; + } + } + } + ksort($LookupList); + + foreach ($LookupList as $lu => $tag) { + $Type = $this->GSUBLookups[$lu]['Type']; + $Flag = $this->GSUBLookups[$lu]['Flag']; + $MarkFilteringSet = $this->GSUBLookups[$lu]['MarkFilteringSet']; + $tagInt = 1; + if (preg_match('/' . $tag . '([0-9]{1,2})/', $usetags, $m)) { + $tagInt = $m[1]; + } + $ptr = 0; + // Test each glyph sequentially + while ($ptr < (count($this->OTLdata))) { // whilst there is another glyph ..0064 + $currGlyph = $this->OTLdata[$ptr]['hex']; + $currGID = $this->OTLdata[$ptr]['uni']; + $shift = 1; + foreach ($this->GSUBLookups[$lu]['Subtables'] as $c => $subtable_offset) { + // NB Coverage only looks at glyphs for position 1 (esp. 7.3 and 8.3) + if (isset($this->GSLuCoverage[$lu][$c][$currGID])) { + // Get rules from font GSUB subtable + $shift = $this->_applyGSUBsubtable($lu, $c, $ptr, $currGlyph, $currGID, ($subtable_offset - $this->GSUB_offset), $Type, $Flag, $MarkFilteringSet, $this->GSLuCoverage[$lu][$c], 0, $tag, 0, $tagInt); + + if ($shift) { + break; + } + } + } + if ($shift == 0) { + $shift = 1; + } + $ptr += $shift; + } + } + } + + function _applyGSUBrulesSingly($usetags, $scriptTag, $langsys) + { + // Features are applied one at a time, working through each codepoint + + $GSUBFeatures = $this->mpdf->CurrentFont['GSUBFeatures'][$scriptTag][$langsys]; + + $tags = explode(' ', $usetags); + foreach ($tags as $usetag) { + $LookupList = []; + foreach ($GSUBFeatures as $tag => $arr) { + if (strpos($usetags, $tag) !== false) { + foreach ($arr as $lu) { + $LookupList[$lu] = $tag; + } + } + } + ksort($LookupList); + + $ptr = 0; + // Test each glyph sequentially + while ($ptr < (count($this->OTLdata))) { // whilst there is another glyph ..0064 + $currGlyph = $this->OTLdata[$ptr]['hex']; + $currGID = $this->OTLdata[$ptr]['uni']; + $shift = 1; + + foreach ($LookupList as $lu => $tag) { + $Type = $this->GSUBLookups[$lu]['Type']; + $Flag = $this->GSUBLookups[$lu]['Flag']; + $MarkFilteringSet = $this->GSUBLookups[$lu]['MarkFilteringSet']; + $tagInt = 1; + if (preg_match('/' . $tag . '([0-9]{1,2})/', $usetags, $m)) { + $tagInt = $m[1]; + } + + foreach ($this->GSUBLookups[$lu]['Subtables'] as $c => $subtable_offset) { + // NB Coverage only looks at glyphs for position 1 (esp. 7.3 and 8.3) + if (isset($this->GSLuCoverage[$lu][$c][$currGID])) { + // Get rules from font GSUB subtable + $shift = $this->_applyGSUBsubtable($lu, $c, $ptr, $currGlyph, $currGID, ($subtable_offset - $this->GSUB_offset), $Type, $Flag, $MarkFilteringSet, $this->GSLuCoverage[$lu][$c], 0, $tag, 0, $tagInt); + + if ($shift) { + break 2; + } + } + } + } + if ($shift == 0) { + $shift = 1; + } + $ptr += $shift; + } + } + } + + function _applyGSUBrulesMyanmar($usetags, $scriptTag, $langsys) + { + // $usetags = locl ccmp rphf pref blwf pstf'; + // applied to all characters + + $GSUBFeatures = $this->mpdf->CurrentFont['GSUBFeatures'][$scriptTag][$langsys]; + + // ALL should be applied one syllable at a time + // Implemented in functions checkContextMatch and checkContextMatchMultiple by failing to match if outside scope of current 'syllable' + $tags = explode(' ', $usetags); + foreach ($tags as $usetag) { + $LookupList = []; + foreach ($GSUBFeatures as $tag => $arr) { + if ($tag == $usetag) { + foreach ($arr as $lu) { + $LookupList[$lu] = $tag; + } + } + } + ksort($LookupList); + + foreach ($LookupList as $lu => $tag) { + $Type = $this->GSUBLookups[$lu]['Type']; + $Flag = $this->GSUBLookups[$lu]['Flag']; + $MarkFilteringSet = $this->GSUBLookups[$lu]['MarkFilteringSet']; + $tagInt = 1; + if (preg_match('/' . $tag . '([0-9]{1,2})/', $usetags, $m)) { + $tagInt = $m[1]; + } + + $ptr = 0; + // Test each glyph sequentially + while ($ptr < (count($this->OTLdata))) { // whilst there is another glyph ..0064 + $currGlyph = $this->OTLdata[$ptr]['hex']; + $currGID = $this->OTLdata[$ptr]['uni']; + $shift = 1; + foreach ($this->GSUBLookups[$lu]['Subtables'] as $c => $subtable_offset) { + // NB Coverage only looks at glyphs for position 1 (esp. 7.3 and 8.3) + if (isset($this->GSLuCoverage[$lu][$c][$currGID])) { + // Get rules from font GSUB subtable + $shift = $this->_applyGSUBsubtable($lu, $c, $ptr, $currGlyph, $currGID, ($subtable_offset - $this->GSUB_offset), $Type, $Flag, $MarkFilteringSet, $this->GSLuCoverage[$lu][$c], 0, $usetag, 0, $tagInt); + + if ($shift) { + break; + } + } + } + if ($shift == 0) { + $shift = 1; + } + $ptr += $shift; + } + } + } + } + + function _applyGSUBrulesIndic($usetags, $scriptTag, $langsys, $is_old_spec) + { + // $usetags = 'locl ccmp nukt akhn rphf rkrf pref blwf half pstf vatu cjct'; then later - init + // rphf, pref, blwf, half, abvf, pstf, and init are only applied where ['mask'] indicates: Indic::FLAG(Indic::RPHF); + // The rest are applied to all characters + + $GSUBFeatures = $this->mpdf->CurrentFont['GSUBFeatures'][$scriptTag][$langsys]; + + // ALL should be applied one syllable at a time + // Implemented in functions checkContextMatch and checkContextMatchMultiple by failing to match if outside scope of current 'syllable' + $tags = explode(' ', $usetags); + foreach ($tags as $usetag) { + $LookupList = []; + foreach ($GSUBFeatures as $tag => $arr) { + if ($tag == $usetag) { + foreach ($arr as $lu) { + $LookupList[$lu] = $tag; + } + } + } + ksort($LookupList); + + foreach ($LookupList as $lu => $tag) { + $Type = $this->GSUBLookups[$lu]['Type']; + $Flag = $this->GSUBLookups[$lu]['Flag']; + $MarkFilteringSet = $this->GSUBLookups[$lu]['MarkFilteringSet']; + $tagInt = 1; + if (preg_match('/' . $tag . '([0-9]{1,2})/', $usetags, $m)) { + $tagInt = $m[1]; + } + + $ptr = 0; + // Test each glyph sequentially + while ($ptr < (count($this->OTLdata))) { // whilst there is another glyph ..0064 + $currGlyph = $this->OTLdata[$ptr]['hex']; + $currGID = $this->OTLdata[$ptr]['uni']; + $shift = 1; + foreach ($this->GSUBLookups[$lu]['Subtables'] as $c => $subtable_offset) { + // NB Coverage only looks at glyphs for position 1 (esp. 7.3 and 8.3) + if (isset($this->GSLuCoverage[$lu][$c][$currGID])) { + if (strpos('rphf pref blwf half pstf cfar init', $usetag) !== false) { // only apply when mask indicates + $mask = 0; + switch ($usetag) { + case 'rphf': + $mask = (1 << (Indic::RPHF)); + break; + case 'pref': + $mask = (1 << (Indic::PREF)); + break; + case 'blwf': + $mask = (1 << (Indic::BLWF)); + break; + case 'half': + $mask = (1 << (Indic::HALF)); + break; + case 'pstf': + $mask = (1 << (Indic::PSTF)); + break; + case 'cfar': + $mask = (1 << (Indic::CFAR)); + break; + case 'init': + $mask = (1 << (Indic::INIT)); + break; + } + if (!($this->OTLdata[$ptr]['mask'] & $mask)) { + continue; + } + } + // Get rules from font GSUB subtable + $shift = $this->_applyGSUBsubtable($lu, $c, $ptr, $currGlyph, $currGID, ($subtable_offset - $this->GSUB_offset), $Type, $Flag, $MarkFilteringSet, $this->GSLuCoverage[$lu][$c], 0, $usetag, $is_old_spec, $tagInt); + + if ($shift) { + break; + } + } // Special case for Indic ZZZ99S + // Check to substitute Halant-Consonant in PREF, BLWF or PSTF + // i.e. new spec but GSUB tables have Consonant-Halant in Lookups e.g. FreeSerif, which + // incorrectly just moved old spec tables to new spec. Uniscribe seems to cope with this + // See also ttffontsuni.php + // First check if current glyph is a Halant/Virama + elseif (static::_OTL_OLD_SPEC_COMPAT_1 && $Type == 4 && !$is_old_spec && strpos('0094D 009CD 00A4D 00ACD 00B4D 00BCD 00C4D 00CCD 00D4D', $currGlyph) !== false) { + // only apply when 'pref blwf pstf' tags, and when mask indicates + if (strpos('pref blwf pstf', $usetag) !== false) { + $mask = 0; + switch ($usetag) { + case 'pref': + $mask = (1 << (Indic::PREF)); + break; + case 'blwf': + $mask = (1 << (Indic::BLWF)); + break; + case 'pstf': + $mask = (1 << (Indic::PSTF)); + break; + } + if (!($this->OTLdata[$ptr]['mask'] & $mask)) { + continue; + } + + $nextGlyph = $this->OTLdata[$ptr + 1]['hex']; + $nextGID = $this->OTLdata[$ptr + 1]['uni']; + if (isset($this->GSLuCoverage[$lu][$c][$nextGID])) { + // Get rules from font GSUB subtable + $shift = $this->_applyGSUBsubtableSpecial($lu, $c, $ptr, $currGlyph, $currGID, $nextGlyph, $nextGID, ($subtable_offset - $this->GSUB_offset), $Type, $this->GSLuCoverage[$lu][$c]); + + if ($shift) { + break; + } + } + } + } + } + if ($shift == 0) { + $shift = 1; + } + $ptr += $shift; + } + } + } + } + + function _applyGSUBsubtableSpecial($lookupID, $subtable, $ptr, $currGlyph, $currGID, $nextGlyph, $nextGID, $subtable_offset, $Type, $LuCoverage) + { + + // Special case for Indic + // Check to substitute Halant-Consonant in PREF, BLWF or PSTF + // i.e. new spec but GSUB tables have Consonant-Halant in Lookups e.g. FreeSerif, which + // incorrectly just moved old spec tables to new spec. Uniscribe seems to cope with this + // See also ttffontsuni.php + + $this->seek($subtable_offset); + $SubstFormat = $this->read_ushort(); + + // Subtable contains Consonant - Halant + // Text string contains Halant ($CurrGlyph) - Consonant ($nextGlyph) + // Halant has already been matched, and already checked that $nextGID is in Coverage table + //////////////////////////////////////////////////////////////////////////////// + // Only does: LookupType 4: Ligature Substitution Subtable : n to 1 + //////////////////////////////////////////////////////////////////////////////// + $Coverage = $subtable_offset + $this->read_ushort(); + $NextGlyphPos = $LuCoverage[$nextGID]; + $LigSetCount = $this->read_short(); + + $this->skip($NextGlyphPos * 2); + $LigSet = $subtable_offset + $this->read_short(); + + $this->seek($LigSet); + $LigCount = $this->read_short(); + // LigatureSet i.e. all starting with the same Glyph $nextGlyph [Consonant] + $LigatureOffset = []; + for ($g = 0; $g < $LigCount; $g++) { + $LigatureOffset[$g] = $LigSet + $this->read_ushort(); + } + for ($g = 0; $g < $LigCount; $g++) { + // Ligature tables + $this->seek($LigatureOffset[$g]); + $LigGlyph = $this->read_ushort(); + $substitute = $this->glyphToChar($LigGlyph); + $CompCount = $this->read_ushort(); + + if ($CompCount != 2) { + return 0; + } // Only expecting to work with 2:1 (and no ignore characters in between) + + + $gid = $this->read_ushort(); + $checkGlyph = $this->glyphToChar($gid); // Other component/input Glyphs starting at position 2 (arrayindex 1) + + if ($currGID == $checkGlyph) { + $match = true; + } else { + $match = false; + break; + } + + $GlyphPos = []; + $GlyphPos[] = $ptr; + $GlyphPos[] = $ptr + 1; + + + if ($match) { + $shift = $this->GSUBsubstitute($ptr, $substitute, 4, $GlyphPos); // GlyphPos contains positions to set null + if ($shift) { + return 1; + } + } + } + return 0; + } + + function _applyGSUBsubtable($lookupID, $subtable, $ptr, $currGlyph, $currGID, $subtable_offset, $Type, $Flag, $MarkFilteringSet, $LuCoverage, $level, $currentTag, $is_old_spec, $tagInt) + { + $ignore = $this->_getGCOMignoreString($Flag, $MarkFilteringSet); + + // Lets start + $this->seek($subtable_offset); + $SubstFormat = $this->read_ushort(); + + //////////////////////////////////////////////////////////////////////////////// + // LookupType 1: Single Substitution Subtable : 1 to 1 + //////////////////////////////////////////////////////////////////////////////// + if ($Type == 1) { + // Flag = Ignore + if ($this->_checkGCOMignore($Flag, $currGlyph, $MarkFilteringSet)) { + return 0; + } + $CoverageOffset = $subtable_offset + $this->read_ushort(); + $GlyphPos = $LuCoverage[$currGID]; + //=========== + // Format 1: + //=========== + if ($SubstFormat == 1) { // Calculated output glyph indices + $DeltaGlyphID = $this->read_short(); + $this->seek($CoverageOffset); + $glyphs = $this->_getCoverageGID(); + $GlyphID = $glyphs[$GlyphPos] + $DeltaGlyphID; + } //=========== + // Format 2: + //=========== + elseif ($SubstFormat == 2) { // Specified output glyph indices + $GlyphCount = $this->read_ushort(); + $this->skip($GlyphPos * 2); + $GlyphID = $this->read_ushort(); + } + + $substitute = $this->glyphToChar($GlyphID); + $shift = $this->GSUBsubstitute($ptr, $substitute, $Type); + if ($this->debugOTL && $shift) { + $this->_dumpproc('GSUB', $lookupID, $subtable, $Type, $SubstFormat, $ptr, $currGlyph, $level); + } + if ($shift) { + return 1; + } + return 0; + } //////////////////////////////////////////////////////////////////////////////// + // LookupType 2: Multiple Substitution Subtable : 1 to n + //////////////////////////////////////////////////////////////////////////////// + elseif ($Type == 2) { + // Flag = Ignore + if ($this->_checkGCOMignore($Flag, $currGlyph, $MarkFilteringSet)) { + return 0; + } + $Coverage = $subtable_offset + $this->read_ushort(); + $GlyphPos = $LuCoverage[$currGID]; + $this->skip(2); + $this->skip($GlyphPos * 2); + $Sequences = $subtable_offset + $this->read_short(); + + $this->seek($Sequences); + $GlyphCount = $this->read_short(); + $SubstituteGlyphs = []; + for ($g = 0; $g < $GlyphCount; $g++) { + $sgid = $this->read_ushort(); + $SubstituteGlyphs[] = $this->glyphToChar($sgid); + } + + $shift = $this->GSUBsubstitute($ptr, $SubstituteGlyphs, $Type); + if ($this->debugOTL && $shift) { + $this->_dumpproc('GSUB', $lookupID, $subtable, $Type, $SubstFormat, $ptr, $currGlyph, $level); + } + if ($shift) { + return $shift; + } + return 0; + } //////////////////////////////////////////////////////////////////////////////// + // LookupType 3: Alternate Forms : 1 to 1(n) + //////////////////////////////////////////////////////////////////////////////// + elseif ($Type == 3) { + // Flag = Ignore + if ($this->_checkGCOMignore($Flag, $currGlyph, $MarkFilteringSet)) { + return 0; + } + $Coverage = $subtable_offset + $this->read_ushort(); + $AlternateSetCount = $this->read_short(); + ///////////////////////////////////////////////////////////////////////////////!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + // Need to set alternate IF set by CSS3 font-feature for a tag + // i.e. if this is 'salt' alternate may be set to 2 + // default value will be $alt=1 ( === index of 0 in list of alternates) + $alt = 1; // $alt=1 points to Alternative[0] + if ($tagInt > 1) { + $alt = $tagInt; + } + ///////////////////////////////////////////////////////////////////////////////!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + if ($alt == 0) { + return 0; + } // If specified alternate not present, cancel [ or could default $alt = 1 ?] + + $GlyphPos = $LuCoverage[$currGID]; + $this->skip($GlyphPos * 2); + + $AlternateSets = $subtable_offset + $this->read_short(); + $this->seek($AlternateSets); + + $AlternateGlyphCount = $this->read_short(); + if ($alt > $AlternateGlyphCount) { + return 0; + } // If specified alternate not present, cancel [ or could default $alt = 1 ?] + + $this->skip(($alt - 1) * 2); + $GlyphID = $this->read_ushort(); + + $substitute = $this->glyphToChar($GlyphID); + $shift = $this->GSUBsubstitute($ptr, $substitute, $Type); + if ($this->debugOTL && $shift) { + $this->_dumpproc('GSUB', $lookupID, $subtable, $Type, $SubstFormat, $ptr, $currGlyph, $level); + } + if ($shift) { + return 1; + } + return 0; + } //////////////////////////////////////////////////////////////////////////////// + // LookupType 4: Ligature Substitution Subtable : n to 1 + //////////////////////////////////////////////////////////////////////////////// + elseif ($Type == 4) { + // Flag = Ignore + if ($this->_checkGCOMignore($Flag, $currGlyph, $MarkFilteringSet)) { + return 0; + } + $Coverage = $subtable_offset + $this->read_ushort(); + $FirstGlyphPos = $LuCoverage[$currGID]; + + $LigSetCount = $this->read_short(); + + $this->skip($FirstGlyphPos * 2); + $LigSet = $subtable_offset + $this->read_short(); + + $this->seek($LigSet); + $LigCount = $this->read_short(); + // LigatureSet i.e. all starting with the same first Glyph $currGlyph + $LigatureOffset = []; + for ($g = 0; $g < $LigCount; $g++) { + $LigatureOffset[$g] = $LigSet + $this->read_ushort(); + } + for ($g = 0; $g < $LigCount; $g++) { + // Ligature tables + $this->seek($LigatureOffset[$g]); + $LigGlyph = $this->read_ushort(); // Output Ligature GlyphID + $substitute = $this->glyphToChar($LigGlyph); + $CompCount = $this->read_ushort(); + + $spos = $ptr; + $match = true; + $GlyphPos = []; + $GlyphPos[] = $spos; + for ($l = 1; $l < $CompCount; $l++) { + $gid = $this->read_ushort(); + $checkGlyph = $this->glyphToChar($gid); // Other component/input Glyphs starting at position 2 (arrayindex 1) + + $spos++; + //while $this->OTLdata[$spos]['uni'] is an "ignore" => spos++ + while (isset($this->OTLdata[$spos]) && strpos($ignore, $this->OTLdata[$spos]['hex']) !== false) { + $spos++; + } + + if (isset($this->OTLdata[$spos]) && $this->OTLdata[$spos]['uni'] == $checkGlyph) { + $GlyphPos[] = $spos; + } else { + $match = false; + break; + } + } + + + if ($match) { + $shift = $this->GSUBsubstitute($ptr, $substitute, $Type, $GlyphPos); // GlyphPos contains positions to set null + if ($this->debugOTL && $shift) { + $this->_dumpproc('GSUB', $lookupID, $subtable, $Type, $SubstFormat, $ptr, $currGlyph, $level); + } + if ($shift) { + return ($spos - $ptr + 1 - ($CompCount - 1)); + } + } + } + return 0; + } //////////////////////////////////////////////////////////////////////////////// + // LookupType 5: Contextual Substitution Subtable + //////////////////////////////////////////////////////////////////////////////// + elseif ($Type == 5) { + //=========== + // Format 1: Simple Context Glyph Substitution + //=========== + if ($SubstFormat == 1) { + $CoverageTableOffset = $subtable_offset + $this->read_ushort(); + $SubRuleSetCount = $this->read_ushort(); + $SubRuleSetOffset = []; + for ($b = 0; $b < $SubRuleSetCount; $b++) { + $offset = $this->read_ushort(); + if ($offset == 0x0000) { + $SubRuleSetOffset[] = $offset; + } else { + $SubRuleSetOffset[] = $subtable_offset + $offset; + } + } + + // SubRuleSet tables: All contexts beginning with the same glyph + // Select the SubRuleSet required using the position of the glyph in the coverage table + $GlyphPos = $LuCoverage[$currGID]; + if ($SubRuleSetOffset[$GlyphPos] > 0) { + $this->seek($SubRuleSetOffset[$GlyphPos]); + $SubRuleCnt = $this->read_ushort(); + $SubRule = []; + for ($b = 0; $b < $SubRuleCnt; $b++) { + $SubRule[$b] = $SubRuleSetOffset[$GlyphPos] + $this->read_ushort(); + } + for ($b = 0; $b < $SubRuleCnt; $b++) { // EACH RULE + $this->seek($SubRule[$b]); + $InputGlyphCount = $this->read_ushort(); + $SubstCount = $this->read_ushort(); + + $Backtrack = []; + $Lookahead = []; + $Input = []; + $Input[0] = $this->OTLdata[$ptr]['uni']; + for ($r = 1; $r < $InputGlyphCount; $r++) { + $gid = $this->read_ushort(); + $Input[$r] = $this->glyphToChar($gid); + } + $matched = $this->checkContextMatch($Input, $Backtrack, $Lookahead, $ignore, $ptr); + if ($matched) { + if ($this->debugOTL) { + $this->_dumpproc('GSUB', $lookupID, $subtable, $Type, $SubstFormat, $ptr, $currGlyph, $level); + } + for ($p = 0; $p < $SubstCount; $p++) { // EACH LOOKUP + $SequenceIndex[$p] = $this->read_ushort(); + $LookupListIndex[$p] = $this->read_ushort(); + } + + for ($p = 0; $p < $SubstCount; $p++) { + // Apply $LookupListIndex at $SequenceIndex + if ($SequenceIndex[$p] >= $InputGlyphCount) { + continue; + } + $lu = $LookupListIndex[$p]; + $luType = $this->GSUBLookups[$lu]['Type']; + $luFlag = $this->GSUBLookups[$lu]['Flag']; + $luMarkFilteringSet = $this->GSUBLookups[$lu]['MarkFilteringSet']; + + $luptr = $matched[$SequenceIndex[$p]]; + $lucurrGlyph = $this->OTLdata[$luptr]['hex']; + $lucurrGID = $this->OTLdata[$luptr]['uni']; + + foreach ($this->GSUBLookups[$lu]['Subtables'] as $luc => $lusubtable_offset) { + $shift = $this->_applyGSUBsubtable($lu, $luc, $luptr, $lucurrGlyph, $lucurrGID, ($lusubtable_offset - $this->GSUB_offset), $luType, $luFlag, $luMarkFilteringSet, $this->GSLuCoverage[$lu][$luc], 1, $currentTag, $is_old_spec, $tagInt); + if ($shift) { + break; + } + } + } + + if (!defined("OMIT_OTL_FIX_3") || OMIT_OTL_FIX_3 != 1) { + return $shift; + } /* OTL_FIX_3 */ + else { + return $InputGlyphCount; // should be + matched ignores in Input Sequence + } + } + } + } + return 0; + } //=========== + // Format 2: + //=========== + // Format 2: Class-based Context Glyph Substitution + elseif ($SubstFormat == 2) { + $CoverageTableOffset = $subtable_offset + $this->read_ushort(); + $InputClassDefOffset = $subtable_offset + $this->read_ushort(); + $SubClassSetCnt = $this->read_ushort(); + $SubClassSetOffset = []; + for ($b = 0; $b < $SubClassSetCnt; $b++) { + $offset = $this->read_ushort(); + if ($offset == 0x0000) { + $SubClassSetOffset[] = $offset; + } else { + $SubClassSetOffset[] = $subtable_offset + $offset; + } + } + + $InputClasses = $this->_getClasses($InputClassDefOffset); + + for ($s = 0; $s < $SubClassSetCnt; $s++) { // $SubClassSet is ordered by input class-may be NULL + // Select $SubClassSet if currGlyph is in First Input Class + if ($SubClassSetOffset[$s] > 0 && isset($InputClasses[$s][$currGID])) { + $this->seek($SubClassSetOffset[$s]); + $SubClassRuleCnt = $this->read_ushort(); + $SubClassRule = []; + for ($b = 0; $b < $SubClassRuleCnt; $b++) { + $SubClassRule[$b] = $SubClassSetOffset[$s] + $this->read_ushort(); + } + + for ($b = 0; $b < $SubClassRuleCnt; $b++) { // EACH RULE + $this->seek($SubClassRule[$b]); + $InputGlyphCount = $this->read_ushort(); + $SubstCount = $this->read_ushort(); + $Input = []; + for ($r = 1; $r < $InputGlyphCount; $r++) { + $Input[$r] = $this->read_ushort(); + } + + $inputClass = $s; + + $inputGlyphs = []; + $inputGlyphs[0] = $InputClasses[$inputClass]; + + if ($InputGlyphCount > 1) { + // NB starts at 1 + for ($gcl = 1; $gcl < $InputGlyphCount; $gcl++) { + $classindex = $Input[$gcl]; + if (isset($InputClasses[$classindex])) { + $inputGlyphs[$gcl] = $InputClasses[$classindex]; + } else { + $inputGlyphs[$gcl] = ''; + } + } + } + + // Class 0 contains all the glyphs NOT in the other classes + $class0excl = []; + for ($gc = 1; $gc <= count($InputClasses); $gc++) { + if (is_array($InputClasses[$gc])) { + $class0excl = $class0excl + $InputClasses[$gc]; + } + } + + $backtrackGlyphs = []; + $lookaheadGlyphs = []; + + $matched = $this->checkContextMatchMultipleUni($inputGlyphs, $backtrackGlyphs, $lookaheadGlyphs, $ignore, $ptr, $class0excl); + if ($matched) { + if ($this->debugOTL) { + $this->_dumpproc('GSUB', $lookupID, $subtable, $Type, $SubstFormat, $ptr, $currGlyph, $level); + } + for ($p = 0; $p < $SubstCount; $p++) { // EACH LOOKUP + $SequenceIndex[$p] = $this->read_ushort(); + $LookupListIndex[$p] = $this->read_ushort(); + } + + for ($p = 0; $p < $SubstCount; $p++) { + // Apply $LookupListIndex at $SequenceIndex + if ($SequenceIndex[$p] >= $InputGlyphCount) { + continue; + } + $lu = $LookupListIndex[$p]; + $luType = $this->GSUBLookups[$lu]['Type']; + $luFlag = $this->GSUBLookups[$lu]['Flag']; + $luMarkFilteringSet = $this->GSUBLookups[$lu]['MarkFilteringSet']; + + $luptr = $matched[$SequenceIndex[$p]]; + $lucurrGlyph = $this->OTLdata[$luptr]['hex']; + $lucurrGID = $this->OTLdata[$luptr]['uni']; + + foreach ($this->GSUBLookups[$lu]['Subtables'] as $luc => $lusubtable_offset) { + $shift = $this->_applyGSUBsubtable($lu, $luc, $luptr, $lucurrGlyph, $lucurrGID, ($lusubtable_offset - $this->GSUB_offset), $luType, $luFlag, $luMarkFilteringSet, $this->GSLuCoverage[$lu][$luc], 1, $currentTag, $is_old_spec, $tagInt); + if ($shift) { + break; + } + } + } + + if (!defined("OMIT_OTL_FIX_3") || OMIT_OTL_FIX_3 != 1) { + return $shift; + } /* OTL_FIX_3 */ + else { + return $InputGlyphCount; // should be + matched ignores in Input Sequence + } + } + } + } + } + + return 0; + } //=========== + // Format 3: + //=========== + // Format 3: Coverage-based Context Glyph Substitution + elseif ($SubstFormat == 3) { + throw new \Mpdf\MpdfException("GSUB Lookup Type " . $Type . " Format " . $SubstFormat . " not TESTED YET."); + } + } //////////////////////////////////////////////////////////////////////////////// + // LookupType 6: Chaining Contextual Substitution Subtable + //////////////////////////////////////////////////////////////////////////////// + elseif ($Type == 6) { + //=========== + // Format 1: + //=========== + // Format 1: Simple Chaining Context Glyph Substitution + if ($SubstFormat == 1) { + $Coverage = $subtable_offset + $this->read_ushort(); + $GlyphPos = $LuCoverage[$currGID]; + $ChainSubRuleSetCount = $this->read_ushort(); + // All of the ChainSubRule tables defining contexts that begin with the same first glyph are grouped together and defined in a ChainSubRuleSet table + $this->skip($GlyphPos * 2); + $ChainSubRuleSet = $subtable_offset + $this->read_ushort(); + $this->seek($ChainSubRuleSet); + $ChainSubRuleCount = $this->read_ushort(); + + for ($s = 0; $s < $ChainSubRuleCount; $s++) { + $ChainSubRule[$s] = $ChainSubRuleSet + $this->read_ushort(); + } + + for ($s = 0; $s < $ChainSubRuleCount; $s++) { + $this->seek($ChainSubRule[$s]); + + $BacktrackGlyphCount = $this->read_ushort(); + $Backtrack = []; + for ($b = 0; $b < $BacktrackGlyphCount; $b++) { + $gid = $this->read_ushort(); + $Backtrack[] = $this->glyphToChar($gid); + } + $Input = []; + $Input[0] = $this->OTLdata[$ptr]['uni']; + $InputGlyphCount = $this->read_ushort(); + for ($b = 1; $b < $InputGlyphCount; $b++) { + $gid = $this->read_ushort(); + $Input[$b] = $this->glyphToChar($gid); + } + $LookaheadGlyphCount = $this->read_ushort(); + $Lookahead = []; + for ($b = 0; $b < $LookaheadGlyphCount; $b++) { + $gid = $this->read_ushort(); + $Lookahead[] = $this->glyphToChar($gid); + } + + $matched = $this->checkContextMatch($Input, $Backtrack, $Lookahead, $ignore, $ptr); + if ($matched) { + if ($this->debugOTL) { + $this->_dumpproc('GSUB', $lookupID, $subtable, $Type, $SubstFormat, $ptr, $currGlyph, $level); + } + $SubstCount = $this->read_ushort(); + for ($p = 0; $p < $SubstCount; $p++) { + // SubstLookupRecord + $SubstLookupRecord[$p]['SequenceIndex'] = $this->read_ushort(); + $SubstLookupRecord[$p]['LookupListIndex'] = $this->read_ushort(); + } + for ($p = 0; $p < $SubstCount; $p++) { + // Apply $SubstLookupRecord[$p]['LookupListIndex'] at $SubstLookupRecord[$p]['SequenceIndex'] + if ($SubstLookupRecord[$p]['SequenceIndex'] >= $InputGlyphCount) { + continue; + } + $lu = $SubstLookupRecord[$p]['LookupListIndex']; + $luType = $this->GSUBLookups[$lu]['Type']; + $luFlag = $this->GSUBLookups[$lu]['Flag']; + $luMarkFilteringSet = $this->GSUBLookups[$lu]['MarkFilteringSet']; + + $luptr = $matched[$SubstLookupRecord[$p]['SequenceIndex']]; + $lucurrGlyph = $this->OTLdata[$luptr]['hex']; + $lucurrGID = $this->OTLdata[$luptr]['uni']; + + foreach ($this->GSUBLookups[$lu]['Subtables'] as $luc => $lusubtable_offset) { + $shift = $this->_applyGSUBsubtable($lu, $luc, $luptr, $lucurrGlyph, $lucurrGID, ($lusubtable_offset - $this->GSUB_offset), $luType, $luFlag, $luMarkFilteringSet, $this->GSLuCoverage[$lu][$luc], 1, $currentTag, $is_old_spec, $tagInt); + if ($shift) { + break; + } + } + } + if (!defined("OMIT_OTL_FIX_3") || OMIT_OTL_FIX_3 != 1) { + return $shift; + } /* OTL_FIX_3 */ + else { + return $InputGlyphCount; // should be + matched ignores in Input Sequence + } + } + } + return 0; + } //=========== + // Format 2: + //=========== + // Format 2: Class-based Chaining Context Glyph Substitution p257 + elseif ($SubstFormat == 2) { + // NB Format 2 specifies fixed class assignments (identical for each position in the backtrack, input, or lookahead sequence) and exclusive classes (a glyph cannot be in more than one class at a time) + + $CoverageTableOffset = $subtable_offset + $this->read_ushort(); + $BacktrackClassDefOffset = $subtable_offset + $this->read_ushort(); + $InputClassDefOffset = $subtable_offset + $this->read_ushort(); + $LookaheadClassDefOffset = $subtable_offset + $this->read_ushort(); + $ChainSubClassSetCnt = $this->read_ushort(); + $ChainSubClassSetOffset = []; + for ($b = 0; $b < $ChainSubClassSetCnt; $b++) { + $offset = $this->read_ushort(); + if ($offset == 0x0000) { + $ChainSubClassSetOffset[] = $offset; + } else { + $ChainSubClassSetOffset[] = $subtable_offset + $offset; + } + } + + $BacktrackClasses = $this->_getClasses($BacktrackClassDefOffset); + $InputClasses = $this->_getClasses($InputClassDefOffset); + $LookaheadClasses = $this->_getClasses($LookaheadClassDefOffset); + + for ($s = 0; $s < $ChainSubClassSetCnt; $s++) { // $ChainSubClassSet is ordered by input class-may be NULL + // Select $ChainSubClassSet if currGlyph is in First Input Class + if ($ChainSubClassSetOffset[$s] > 0 && isset($InputClasses[$s][$currGID])) { + $this->seek($ChainSubClassSetOffset[$s]); + $ChainSubClassRuleCnt = $this->read_ushort(); + $ChainSubClassRule = []; + for ($b = 0; $b < $ChainSubClassRuleCnt; $b++) { + $ChainSubClassRule[$b] = $ChainSubClassSetOffset[$s] + $this->read_ushort(); + } + + for ($b = 0; $b < $ChainSubClassRuleCnt; $b++) { // EACH RULE + $this->seek($ChainSubClassRule[$b]); + $BacktrackGlyphCount = $this->read_ushort(); + for ($r = 0; $r < $BacktrackGlyphCount; $r++) { + $Backtrack[$r] = $this->read_ushort(); + } + $InputGlyphCount = $this->read_ushort(); + for ($r = 1; $r < $InputGlyphCount; $r++) { + $Input[$r] = $this->read_ushort(); + } + $LookaheadGlyphCount = $this->read_ushort(); + for ($r = 0; $r < $LookaheadGlyphCount; $r++) { + $Lookahead[$r] = $this->read_ushort(); + } + + + // These contain classes of glyphs as arrays + // $InputClasses[(class)] e.g. 0x02E6,0x02E7,0x02E8 + // $LookaheadClasses[(class)] + // $BacktrackClasses[(class)] + // These contain arrays of classIndexes + // [Backtrack] [Lookahead] and [Input] (Input is from the second position only) + + + $inputClass = $s; //??? + + $inputGlyphs = []; + $inputGlyphs[0] = $InputClasses[$inputClass]; + + if ($InputGlyphCount > 1) { + // NB starts at 1 + for ($gcl = 1; $gcl < $InputGlyphCount; $gcl++) { + $classindex = $Input[$gcl]; + if (isset($InputClasses[$classindex])) { + $inputGlyphs[$gcl] = $InputClasses[$classindex]; + } else { + $inputGlyphs[$gcl] = ''; + } + } + } + + // Class 0 contains all the glyphs NOT in the other classes + $class0excl = []; + for ($gc = 1; $gc <= count($InputClasses); $gc++) { + if (isset($InputClasses[$gc])) { + $class0excl = $class0excl + $InputClasses[$gc]; + } + } + + if ($BacktrackGlyphCount) { + for ($gcl = 0; $gcl < $BacktrackGlyphCount; $gcl++) { + $classindex = $Backtrack[$gcl]; + if (isset($BacktrackClasses[$classindex])) { + $backtrackGlyphs[$gcl] = $BacktrackClasses[$classindex]; + } else { + $backtrackGlyphs[$gcl] = ''; + } + } + } else { + $backtrackGlyphs = []; + } + + // Class 0 contains all the glyphs NOT in the other classes + $bclass0excl = []; + for ($gc = 1; $gc <= count($BacktrackClasses); $gc++) { + if (isset($BacktrackClasses[$gc])) { + $bclass0excl = $bclass0excl + $BacktrackClasses[$gc]; + } + } + + + if ($LookaheadGlyphCount) { + for ($gcl = 0; $gcl < $LookaheadGlyphCount; $gcl++) { + $classindex = $Lookahead[$gcl]; + if (isset($LookaheadClasses[$classindex])) { + $lookaheadGlyphs[$gcl] = $LookaheadClasses[$classindex]; + } else { + $lookaheadGlyphs[$gcl] = ''; + } + } + } else { + $lookaheadGlyphs = []; + } + + // Class 0 contains all the glyphs NOT in the other classes + $lclass0excl = []; + for ($gc = 1; $gc <= count($LookaheadClasses); $gc++) { + if (isset($LookaheadClasses[$gc])) { + $lclass0excl = $lclass0excl + $LookaheadClasses[$gc]; + } + } + + + $matched = $this->checkContextMatchMultipleUni($inputGlyphs, $backtrackGlyphs, $lookaheadGlyphs, $ignore, $ptr, $class0excl, $bclass0excl, $lclass0excl); + if ($matched) { + if ($this->debugOTL) { + $this->_dumpproc('GSUB', $lookupID, $subtable, $Type, $SubstFormat, $ptr, $currGlyph, $level); + } + $SubstCount = $this->read_ushort(); + for ($p = 0; $p < $SubstCount; $p++) { // EACH LOOKUP + $SequenceIndex[$p] = $this->read_ushort(); + $LookupListIndex[$p] = $this->read_ushort(); + } + + for ($p = 0; $p < $SubstCount; $p++) { + // Apply $LookupListIndex at $SequenceIndex + if ($SequenceIndex[$p] >= $InputGlyphCount) { + continue; + } + $lu = $LookupListIndex[$p]; + $luType = $this->GSUBLookups[$lu]['Type']; + $luFlag = $this->GSUBLookups[$lu]['Flag']; + $luMarkFilteringSet = $this->GSUBLookups[$lu]['MarkFilteringSet']; + + $luptr = $matched[$SequenceIndex[$p]]; + $lucurrGlyph = $this->OTLdata[$luptr]['hex']; + $lucurrGID = $this->OTLdata[$luptr]['uni']; + + foreach ($this->GSUBLookups[$lu]['Subtables'] as $luc => $lusubtable_offset) { + $shift = $this->_applyGSUBsubtable($lu, $luc, $luptr, $lucurrGlyph, $lucurrGID, ($lusubtable_offset - $this->GSUB_offset), $luType, $luFlag, $luMarkFilteringSet, $this->GSLuCoverage[$lu][$luc], 1, $currentTag, $is_old_spec, $tagInt); + if ($shift) { + break; + } + } + } + + if (!defined("OMIT_OTL_FIX_3") || OMIT_OTL_FIX_3 != 1) { + return $shift; + } /* OTL_FIX_3 */ + else { + return $InputGlyphCount; // should be + matched ignores in Input Sequence + } + } + } + } + } + + return 0; + } //=========== + // Format 3: + //=========== + // Format 3: Coverage-based Chaining Context Glyph Substitution p259 + elseif ($SubstFormat == 3) { + $BacktrackGlyphCount = $this->read_ushort(); + for ($b = 0; $b < $BacktrackGlyphCount; $b++) { + $CoverageBacktrackOffset[] = $subtable_offset + $this->read_ushort(); // in glyph sequence order + } + $InputGlyphCount = $this->read_ushort(); + for ($b = 0; $b < $InputGlyphCount; $b++) { + $CoverageInputOffset[] = $subtable_offset + $this->read_ushort(); // in glyph sequence order + } + $LookaheadGlyphCount = $this->read_ushort(); + for ($b = 0; $b < $LookaheadGlyphCount; $b++) { + $CoverageLookaheadOffset[] = $subtable_offset + $this->read_ushort(); // in glyph sequence order + } + $SubstCount = $this->read_ushort(); + $save_pos = $this->_pos; // Save the point just after PosCount + + $CoverageBacktrackGlyphs = []; + for ($b = 0; $b < $BacktrackGlyphCount; $b++) { + $this->seek($CoverageBacktrackOffset[$b]); + $glyphs = $this->_getCoverage(); + $CoverageBacktrackGlyphs[$b] = implode("|", $glyphs); + } + $CoverageInputGlyphs = []; + for ($b = 0; $b < $InputGlyphCount; $b++) { + $this->seek($CoverageInputOffset[$b]); + $glyphs = $this->_getCoverage(); + $CoverageInputGlyphs[$b] = implode("|", $glyphs); + } + $CoverageLookaheadGlyphs = []; + for ($b = 0; $b < $LookaheadGlyphCount; $b++) { + $this->seek($CoverageLookaheadOffset[$b]); + $glyphs = $this->_getCoverage(); + $CoverageLookaheadGlyphs[$b] = implode("|", $glyphs); + } + + $matched = $this->checkContextMatchMultiple($CoverageInputGlyphs, $CoverageBacktrackGlyphs, $CoverageLookaheadGlyphs, $ignore, $ptr); + if ($matched) { + if ($this->debugOTL) { + $this->_dumpproc('GSUB', $lookupID, $subtable, $Type, $SubstFormat, $ptr, $currGlyph, $level); + } + + $this->seek($save_pos); // Return to just after PosCount + for ($p = 0; $p < $SubstCount; $p++) { + // SubstLookupRecord + $SubstLookupRecord[$p]['SequenceIndex'] = $this->read_ushort(); + $SubstLookupRecord[$p]['LookupListIndex'] = $this->read_ushort(); + } + for ($p = 0; $p < $SubstCount; $p++) { + // Apply $SubstLookupRecord[$p]['LookupListIndex'] at $SubstLookupRecord[$p]['SequenceIndex'] + if ($SubstLookupRecord[$p]['SequenceIndex'] >= $InputGlyphCount) { + continue; + } + $lu = $SubstLookupRecord[$p]['LookupListIndex']; + $luType = $this->GSUBLookups[$lu]['Type']; + $luFlag = $this->GSUBLookups[$lu]['Flag']; + $luMarkFilteringSet = $this->GSUBLookups[$lu]['MarkFilteringSet']; + + $luptr = $matched[$SubstLookupRecord[$p]['SequenceIndex']]; + $lucurrGlyph = $this->OTLdata[$luptr]['hex']; + $lucurrGID = $this->OTLdata[$luptr]['uni']; + + foreach ($this->GSUBLookups[$lu]['Subtables'] as $luc => $lusubtable_offset) { + $shift = $this->_applyGSUBsubtable($lu, $luc, $luptr, $lucurrGlyph, $lucurrGID, ($lusubtable_offset - $this->GSUB_offset), $luType, $luFlag, $luMarkFilteringSet, $this->GSLuCoverage[$lu][$luc], 1, $currentTag, $is_old_spec, $tagInt); + if ($shift) { + break; + } + } + } + if (!defined("OMIT_OTL_FIX_3") || OMIT_OTL_FIX_3 != 1) { + return (isset($shift) ? $shift : 0); + } /* OTL_FIX_3 */ + else { + return $InputGlyphCount; // should be + matched ignores in Input Sequence + } + } + + return 0; + } + } else { + throw new \Mpdf\MpdfException("GSUB Lookup Type " . $Type . " not supported."); + } + } + + function _updateLigatureMarks($pos, $n) + { + if ($n > 0) { + // Update position of Ligatures and associated Marks + // Foreach lig/assocMarks + // Any position lpos or mpos > $pos + count($substitute) + // $this->assocMarks = array(); // assocMarks[$pos mpos] => array(compID, ligPos) + // $this->assocLigs = array(); // Ligatures[$pos lpos] => nc + for ($p = count($this->OTLdata) - 1; $p >= ($pos + $n); $p--) { + if (isset($this->assocLigs[$p])) { + $tmp = $this->assocLigs[$p]; + unset($this->assocLigs[$p]); + $this->assocLigs[($p + $n)] = $tmp; + } + } + for ($p = count($this->OTLdata) - 1; $p >= 0; $p--) { + if (isset($this->assocMarks[$p])) { + if ($this->assocMarks[$p]['ligPos'] >= ($pos + $n)) { + $this->assocMarks[$p]['ligPos'] += $n; + } + if ($p >= ($pos + $n)) { + $tmp = $this->assocMarks[$p]; + unset($this->assocMarks[$p]); + $this->assocMarks[($p + $n)] = $tmp; + } + } + } + } elseif ($n < 1) { // glyphs removed + $nrem = -$n; + // Update position of pre-existing Ligatures and associated Marks + for ($p = ($pos + 1); $p < count($this->OTLdata); $p++) { + if (isset($this->assocLigs[$p])) { + $tmp = $this->assocLigs[$p]; + unset($this->assocLigs[$p]); + $this->assocLigs[($p - $nrem)] = $tmp; + } + } + for ($p = 0; $p < count($this->OTLdata); $p++) { + if (isset($this->assocMarks[$p])) { + if ($this->assocMarks[$p]['ligPos'] >= ($pos)) { + $this->assocMarks[$p]['ligPos'] -= $nrem; + } + if ($p > $pos) { + $tmp = $this->assocMarks[$p]; + unset($this->assocMarks[$p]); + $this->assocMarks[($p - $nrem)] = $tmp; + } + } + } + } + } + + function GSUBsubstitute($pos, $substitute, $Type, $GlyphPos = null) + { + + // LookupType 1: Simple Substitution Subtable : 1 to 1 + // LookupType 3: Alternate Forms : 1 to 1(n) + if ($Type == 1 || $Type == 3) { + $this->OTLdata[$pos]['uni'] = $substitute; + $this->OTLdata[$pos]['hex'] = $this->unicode_hex($substitute); + return 1; + } // LookupType 2: Multiple Substitution Subtable : 1 to n + elseif ($Type == 2) { + for ($i = 0; $i < count($substitute); $i++) { + $uni = $substitute[$i]; + $newOTLdata[$i] = []; + $newOTLdata[$i]['uni'] = $uni; + $newOTLdata[$i]['hex'] = $this->unicode_hex($uni); + + + // Get types of new inserted chars - or replicate type of char being replaced + // $bt = Ucdn::get_bidi_class($uni); + // if (!$bt) { + $bt = $this->OTLdata[$pos]['bidi_type']; + // } + + if (strpos($this->GlyphClassMarks, $newOTLdata[$i]['hex']) !== false) { + $gp = 'M'; + } elseif ($uni == 32) { + $gp = 'S'; + } else { + $gp = 'C'; + } + + // Need to update matra_type ??? of new glyphs inserted ??????????????????????????????????????? + + $newOTLdata[$i]['bidi_type'] = $bt; + $newOTLdata[$i]['group'] = $gp; + + // Need to update details of new glyphs inserted + $newOTLdata[$i]['general_category'] = $this->OTLdata[$pos]['general_category']; + + if ($this->shaper == 'I' || $this->shaper == 'K' || $this->shaper == 'S') { + $newOTLdata[$i]['indic_category'] = $this->OTLdata[$pos]['indic_category']; + $newOTLdata[$i]['indic_position'] = $this->OTLdata[$pos]['indic_position']; + } elseif ($this->shaper == 'M') { + $newOTLdata[$i]['myanmar_category'] = $this->OTLdata[$pos]['myanmar_category']; + $newOTLdata[$i]['myanmar_position'] = $this->OTLdata[$pos]['myanmar_position']; + } + if (isset($this->OTLdata[$pos]['mask'])) { + $newOTLdata[$i]['mask'] = $this->OTLdata[$pos]['mask']; + } + if (isset($this->OTLdata[$pos]['syllable'])) { + $newOTLdata[$i]['syllable'] = $this->OTLdata[$pos]['syllable']; + } + } + if ($this->shaper == 'K' || $this->shaper == 'T' || $this->shaper == 'L') { + if ($this->OTLdata[$pos]['wordend']) { + $newOTLdata[count($substitute) - 1]['wordend'] = true; + } + } + + array_splice($this->OTLdata, $pos, 1, $newOTLdata); // Replace 1 with n + // Update position of Ligatures and associated Marks + // count($substitute)-1 is the number of glyphs added + $nadd = count($substitute) - 1; + $this->_updateLigatureMarks($pos, $nadd); + return count($substitute); + } // LookupType 4: Ligature Substitution Subtable : n to 1 + elseif ($Type == 4) { + // Create Ligatures and associated Marks + $firstGlyph = $this->OTLdata[$pos]['hex']; + + // If all components of the ligature are marks (and in the same syllable), we call this a mark ligature. + $contains_marks = false; + $contains_nonmarks = false; + if (isset($this->OTLdata[$pos]['syllable'])) { + $current_syllable = $this->OTLdata[$pos]['syllable']; + } else { + $current_syllable = 0; + } + for ($i = 0; $i < count($GlyphPos); $i++) { + // If subsequent components are not Marks as well - don't ligate + $unistr = $this->OTLdata[$GlyphPos[$i]]['hex']; + if ($this->restrictToSyllable && isset($this->OTLdata[$GlyphPos[$i]]['syllable']) && $this->OTLdata[$GlyphPos[$i]]['syllable'] != $current_syllable) { + return 0; + } + if (strpos($this->GlyphClassMarks, $unistr) !== false) { + $contains_marks = true; + } else { + $contains_nonmarks = true; + } + } + if ($contains_marks && !$contains_nonmarks) { + // Mark Ligature (all components are Marks) + $firstMarkAssoc = ''; + if (isset($this->assocMarks[$pos])) { + $firstMarkAssoc = $this->assocMarks[$pos]; + } + // If all components of the ligature are marks, we call this a mark ligature. + for ($i = 1; $i < count($GlyphPos); $i++) { + // If subsequent components are not Marks as well - don't ligate + // $unistr = $this->OTLdata[$GlyphPos[$i]]['hex']; + // if (strpos($this->GlyphClassMarks, $unistr )===false) { return; } + + $nextMarkAssoc = ''; + if (isset($this->assocMarks[$GlyphPos[$i]])) { + $nextMarkAssoc = $this->assocMarks[$GlyphPos[$i]]; + } + // If first component was attached to a previous ligature component, + // all subsequent components should be attached to the same ligature + // component, otherwise we shouldn't ligate them. + // If first component was NOT attached to a previous ligature component, + // all subsequent components should also NOT be attached to any ligature component, + if ($firstMarkAssoc != $nextMarkAssoc) { + // unless they are attached to the first component itself! + // if (!is_array($nextMarkAssoc) || $nextMarkAssoc['ligPos']!= $pos) { return; } + // Update/Edit - In test with myanmartext font + // င်္က္ကျြွေိ + // => Lookup 17 E003 E066B E05A 102D + // E003 and 102D should form a mark ligature, but 102D is already associated with (non-mark) ligature E05A + // So instead of disallowing the mark ligature to form, just dissociate... + if (!is_array($nextMarkAssoc) || $nextMarkAssoc['ligPos'] != $pos) { + unset($this->assocMarks[$GlyphPos[$i]]); + } + } + } + + /* + * - If it *is* a mark ligature, we don't allocate a new ligature id, and leave + * the ligature to keep its old ligature id. This will allow it to attach to + * a base ligature in GPOS. Eg. if the sequence is: LAM,LAM,SHADDA,FATHA,HEH, + * and LAM,LAM,HEH form a ligature, they will leave SHADDA and FATHA wit a + * ligature id and component value of 2. Then if SHADDA,FATHA form a ligature + * later, we don't want them to lose their ligature id/component, otherwise + * GPOS will fail to correctly position the mark ligature on top of the + * LAM,LAM,HEH ligature. + */ + // So if is_array($firstMarkAssoc) - the new (Mark) ligature should keep this association + + $lastPos = $GlyphPos[(count($GlyphPos) - 1)]; + } else { + /* + * - Ligatures cannot be formed across glyphs attached to different components + * of previous ligatures. Eg. the sequence is LAM,SHADDA,LAM,FATHA,HEH, and + * LAM,LAM,HEH form a ligature, leaving SHADDA,FATHA next to eachother. + * However, it would be wrong to ligate that SHADDA,FATHA sequence. + * There is an exception to this: If a ligature tries ligating with marks that + * belong to it itself, go ahead, assuming that the font designer knows what + * they are doing (otherwise it can break Indic stuff when a matra wants to + * ligate with a conjunct...) + */ + + /* + * - If a ligature is formed of components that some of which are also ligatures + * themselves, and those ligature components had marks attached to *their* + * components, we have to attach the marks to the new ligature component + * positions! Now *that*'s tricky! And these marks may be following the + * last component of the whole sequence, so we should loop forward looking + * for them and update them. + * + * Eg. the sequence is LAM,LAM,SHADDA,FATHA,HEH, and the font first forms a + * 'calt' ligature of LAM,HEH, leaving the SHADDA and FATHA with a ligature + * id and component == 1. Now, during 'liga', the LAM and the LAM-HEH ligature + * form a LAM-LAM-HEH ligature. We need to reassign the SHADDA and FATHA to + * the new ligature with a component value of 2. + * + * This in fact happened to a font... See: + * https://bugzilla.gnome.org/show_bug.cgi?id=437633 + */ + + $currComp = 0; + for ($i = 0; $i < count($GlyphPos); $i++) { + if ($i > 0 && isset($this->assocLigs[$GlyphPos[$i]])) { // One of the other components is already a ligature + $nc = $this->assocLigs[$GlyphPos[$i]]; + } else { + $nc = 1; + } + // While next char to right is a mark (but not the next matched glyph) + // ?? + also include a Mark Ligature here + $ic = 1; + while ((($i == count($GlyphPos) - 1) || (isset($GlyphPos[$i + 1]) && ($GlyphPos[$i] + $ic) < $GlyphPos[$i + 1])) && isset($this->OTLdata[($GlyphPos[$i] + $ic)]) && strpos($this->GlyphClassMarks, $this->OTLdata[($GlyphPos[$i] + $ic)]['hex']) !== false) { + $newComp = $currComp; + if (isset($this->assocMarks[$GlyphPos[$i] + $ic])) { // One of the inbetween Marks is already associated with a Lig + // OK as long as it is associated with the current Lig + // if ($this->assocMarks[($GlyphPos[$i]+$ic)]['ligPos'] != ($GlyphPos[$i]+$ic)) { die("Problem #1"); } + $newComp += $this->assocMarks[($GlyphPos[$i] + $ic)]['compID']; + } + $this->assocMarks[($GlyphPos[$i] + $ic)] = ['compID' => $newComp, 'ligPos' => $pos]; + $ic++; + } + $currComp += $nc; + } + $lastPos = $GlyphPos[(count($GlyphPos) - 1)] + $ic - 1; + $this->assocLigs[$pos] = $currComp; // Number of components in new Ligature + } + + // Now remove the unwanted glyphs and associated metadata + $newOTLdata[0] = []; + + // Get types of new inserted chars - or replicate type of char being replaced + // $bt = Ucdn::get_bidi_class($substitute); + // if (!$bt) { + $bt = $this->OTLdata[$pos]['bidi_type']; + // } + + if (strpos($this->GlyphClassMarks, $this->unicode_hex($substitute)) !== false) { + $gp = 'M'; + } elseif ($substitute == 32) { + $gp = 'S'; + } else { + $gp = 'C'; + } + + // Need to update details of new glyphs inserted + $newOTLdata[0]['general_category'] = $this->OTLdata[$pos]['general_category']; + + $newOTLdata[0]['bidi_type'] = $bt; + $newOTLdata[0]['group'] = $gp; + + // KASHIDA: If forming a ligature when the last component was identified as a kashida point (final form) + // If previous/first component of ligature is a medial form, then keep this as a kashida point + // TEST (Arabic Typesetting) يَنتُم + $ka = 0; + if (isset($this->OTLdata[$GlyphPos[(count($GlyphPos) - 1)]]['GPOSinfo']['kashida'])) { + $ka = $this->OTLdata[$GlyphPos[(count($GlyphPos) - 1)]]['GPOSinfo']['kashida']; + } + if ($ka == 1 && isset($this->OTLdata[$pos]['form']) && $this->OTLdata[$pos]['form'] == 3) { + $newOTLdata[0]['GPOSinfo']['kashida'] = $ka; + } + + $newOTLdata[0]['uni'] = $substitute; + $newOTLdata[0]['hex'] = $this->unicode_hex($substitute); + + if ($this->shaper == 'I' || $this->shaper == 'K' || $this->shaper == 'S') { + $newOTLdata[0]['indic_category'] = $this->OTLdata[$pos]['indic_category']; + $newOTLdata[0]['indic_position'] = $this->OTLdata[$pos]['indic_position']; + } elseif ($this->shaper == 'M') { + $newOTLdata[0]['myanmar_category'] = $this->OTLdata[$pos]['myanmar_category']; + $newOTLdata[0]['myanmar_position'] = $this->OTLdata[$pos]['myanmar_position']; + } + if (isset($this->OTLdata[$pos]['mask'])) { + $newOTLdata[0]['mask'] = $this->OTLdata[$pos]['mask']; + } + if (isset($this->OTLdata[$pos]['syllable'])) { + $newOTLdata[0]['syllable'] = $this->OTLdata[$pos]['syllable']; + } + + $newOTLdata[0]['is_ligature'] = true; + + + array_splice($this->OTLdata, $pos, 1, $newOTLdata); + + // GlyphPos contains array of arr_pos to set null - not necessarily contiguous + // +- Remove any assocMarks or assocLigs from the main components (the ones that are deleted) + for ($i = count($GlyphPos) - 1; $i > 0; $i--) { + $gpos = $GlyphPos[$i]; + array_splice($this->OTLdata, $gpos, 1); + unset($this->assocLigs[$gpos]); + unset($this->assocMarks[$gpos]); + } + // $this->assocLigs = array(); // Ligatures[$posarr lpos] => nc + // $this->assocMarks = array(); // assocMarks[$posarr mpos] => array(compID, ligPos) + // Update position of pre-existing Ligatures and associated Marks + // Start after first GlyphPos + // count($GlyphPos)-1 is the number of glyphs removed from string + for ($p = ($GlyphPos[0] + 1); $p < (count($this->OTLdata) + count($GlyphPos) - 1); $p++) { + $nrem = 0; // Number of Glyphs removed at this point in the string + for ($i = 0; $i < count($GlyphPos); $i++) { + if ($i > 0 && $p > $GlyphPos[$i]) { + $nrem++; + } + } + if (isset($this->assocLigs[$p])) { + $tmp = $this->assocLigs[$p]; + unset($this->assocLigs[$p]); + $this->assocLigs[($p - $nrem)] = $tmp; + } + if (isset($this->assocMarks[$p])) { + $tmp = $this->assocMarks[$p]; + unset($this->assocMarks[$p]); + if ($tmp['ligPos'] > $GlyphPos[0]) { + $tmp['ligPos'] -= $nrem; + } + $this->assocMarks[($p - $nrem)] = $tmp; + } + } + return 1; + } else { + return 0; + } + } + + //////////////////////////////////////////////////////////////// + ////////// ARABIC ///////////////////////////////// + //////////////////////////////////////////////////////////////// + private function arabic_initialise() + { + // cf. http://unicode.org/Public/UNIDATA/ArabicShaping.txt + // http://unicode.org/Public/UNIDATA/extracted/DerivedJoiningType.txt + // JOIN TO FOLLOWING LETTER IN LOGICAL ORDER (i.e. AS INITIAL/MEDIAL FORM) = Unicode Left-Joining (+ Dual-Joining + Join_Causing 00640) + $this->arabLeftJoining = [ + 0x0620 => 1, 0x0626 => 1, 0x0628 => 1, 0x062A => 1, 0x062B => 1, 0x062C => 1, 0x062D => 1, 0x062E => 1, + 0x0633 => 1, 0x0634 => 1, 0x0635 => 1, 0x0636 => 1, 0x0637 => 1, 0x0638 => 1, 0x0639 => 1, 0x063A => 1, + 0x063B => 1, 0x063C => 1, 0x063D => 1, 0x063E => 1, 0x063F => 1, 0x0640 => 1, 0x0641 => 1, 0x0642 => 1, + 0x0643 => 1, 0x0644 => 1, 0x0645 => 1, 0x0646 => 1, 0x0647 => 1, 0x0649 => 1, 0x064A => 1, 0x066E => 1, + 0x066F => 1, 0x0678 => 1, 0x0679 => 1, 0x067A => 1, 0x067B => 1, 0x067C => 1, 0x067D => 1, 0x067E => 1, + 0x067F => 1, 0x0680 => 1, 0x0681 => 1, 0x0682 => 1, 0x0683 => 1, 0x0684 => 1, 0x0685 => 1, 0x0686 => 1, + 0x0687 => 1, 0x069A => 1, 0x069B => 1, 0x069C => 1, 0x069D => 1, 0x069E => 1, 0x069F => 1, 0x06A0 => 1, + 0x06A1 => 1, 0x06A2 => 1, 0x06A3 => 1, 0x06A4 => 1, 0x06A5 => 1, 0x06A6 => 1, 0x06A7 => 1, 0x06A8 => 1, + 0x06A9 => 1, 0x06AA => 1, 0x06AB => 1, 0x06AC => 1, 0x06AD => 1, 0x06AE => 1, 0x06AF => 1, 0x06B0 => 1, + 0x06B1 => 1, 0x06B2 => 1, 0x06B3 => 1, 0x06B4 => 1, 0x06B5 => 1, 0x06B6 => 1, 0x06B7 => 1, 0x06B8 => 1, + 0x06B9 => 1, 0x06BA => 1, 0x06BB => 1, 0x06BC => 1, 0x06BD => 1, 0x06BE => 1, 0x06BF => 1, 0x06C1 => 1, + 0x06C2 => 1, 0x06CC => 1, 0x06CE => 1, 0x06D0 => 1, 0x06D1 => 1, 0x06FA => 1, 0x06FB => 1, 0x06FC => 1, + 0x06FF => 1, + /* Arabic Supplement */ + 0x0750 => 1, 0x0751 => 1, 0x0752 => 1, 0x0753 => 1, 0x0754 => 1, 0x0755 => 1, 0x0756 => 1, 0x0757 => 1, + 0x0758 => 1, 0x075C => 1, 0x075D => 1, 0x075E => 1, 0x075F => 1, 0x0760 => 1, 0x0761 => 1, 0x0762 => 1, + 0x0763 => 1, 0x0764 => 1, 0x0765 => 1, 0x0766 => 1, 0x0767 => 1, 0x0768 => 1, 0x0769 => 1, 0x076A => 1, + 0x076D => 1, 0x076E => 1, 0x076F => 1, 0x0770 => 1, 0x0772 => 1, 0x0775 => 1, 0x0776 => 1, 0x0777 => 1, + 0x077A => 1, 0x077B => 1, 0x077C => 1, 0x077D => 1, 0x077E => 1, 0x077F => 1, + /* Extended Arabic */ + 0x08A0 => 1, 0x08A2 => 1, 0x08A3 => 1, 0x08A4 => 1, 0x08A5 => 1, 0x08A6 => 1, 0x08A7 => 1, 0x08A8 => 1, + 0x08A9 => 1, + /* 'syrc' Syriac */ + 0x0712 => 1, 0x0713 => 1, 0x0714 => 1, 0x071A => 1, 0x071B => 1, 0x071C => 1, 0x071D => 1, 0x071F => 1, + 0x0720 => 1, 0x0721 => 1, 0x0722 => 1, 0x0723 => 1, 0x0724 => 1, 0x0725 => 1, 0x0726 => 1, 0x0727 => 1, + 0x0729 => 1, 0x072B => 1, 0x072D => 1, 0x072E => 1, 0x074E => 1, 0x074F => 1, + /* N'Ko */ + 0x07CA => 1, 0x07CB => 1, 0x07CC => 1, 0x07CD => 1, 0x07CE => 1, 0x07CF => 1, 0x07D0 => 1, 0x07D1 => 1, + 0x07D2 => 1, 0x07D3 => 1, 0x07D4 => 1, 0x07D5 => 1, 0x07D6 => 1, 0x07D7 => 1, 0x07D8 => 1, 0x07D9 => 1, + 0x07DA => 1, 0x07DB => 1, 0x07DC => 1, 0x07DD => 1, 0x07DE => 1, 0x07DF => 1, 0x07E0 => 1, 0x07E1 => 1, + 0x07E2 => 1, 0x07E3 => 1, 0x07E4 => 1, 0x07E5 => 1, 0x07E6 => 1, 0x07E7 => 1, 0x07E8 => 1, 0x07E9 => 1, + 0x07EA => 1, 0x07FA => 1, + /* Mandaic */ + 0x0841 => 1, 0x0842 => 1, 0x0843 => 1, 0x0844 => 1, 0x0845 => 1, 0x0847 => 1, 0x0848 => 1, 0x084A => 1, + 0x084B => 1, 0x084C => 1, 0x084D => 1, 0x084E => 1, 0x0850 => 1, 0x0851 => 1, 0x0852 => 1, 0x0853 => 1, + 0x0855 => 1, + /* ZWJ U+200D */ + 0x0200D => 1]; + + /* JOIN TO PREVIOUS LETTER IN LOGICAL ORDER (i.e. AS FINAL/MEDIAL FORM) = Unicode Right-Joining (+ Dual-Joining + Join_Causing) */ + $this->arabRightJoining = [ + 0x0620 => 1, 0x0622 => 1, 0x0623 => 1, 0x0624 => 1, 0x0625 => 1, 0x0626 => 1, 0x0627 => 1, 0x0628 => 1, + 0x0629 => 1, 0x062A => 1, 0x062B => 1, 0x062C => 1, 0x062D => 1, 0x062E => 1, 0x062F => 1, 0x0630 => 1, + 0x0631 => 1, 0x0632 => 1, 0x0633 => 1, 0x0634 => 1, 0x0635 => 1, 0x0636 => 1, 0x0637 => 1, 0x0638 => 1, + 0x0639 => 1, 0x063A => 1, 0x063B => 1, 0x063C => 1, 0x063D => 1, 0x063E => 1, 0x063F => 1, 0x0640 => 1, + 0x0641 => 1, 0x0642 => 1, 0x0643 => 1, 0x0644 => 1, 0x0645 => 1, 0x0646 => 1, 0x0647 => 1, 0x0648 => 1, + 0x0649 => 1, 0x064A => 1, 0x066E => 1, 0x066F => 1, 0x0671 => 1, 0x0672 => 1, 0x0673 => 1, 0x0675 => 1, + 0x0676 => 1, 0x0677 => 1, 0x0678 => 1, 0x0679 => 1, 0x067A => 1, 0x067B => 1, 0x067C => 1, 0x067D => 1, + 0x067E => 1, 0x067F => 1, 0x0680 => 1, 0x0681 => 1, 0x0682 => 1, 0x0683 => 1, 0x0684 => 1, 0x0685 => 1, + 0x0686 => 1, 0x0687 => 1, 0x0688 => 1, 0x0689 => 1, 0x068A => 1, 0x068B => 1, 0x068C => 1, 0x068D => 1, + 0x068E => 1, 0x068F => 1, 0x0690 => 1, 0x0691 => 1, 0x0692 => 1, 0x0693 => 1, 0x0694 => 1, 0x0695 => 1, + 0x0696 => 1, 0x0697 => 1, 0x0698 => 1, 0x0699 => 1, 0x069A => 1, 0x069B => 1, 0x069C => 1, 0x069D => 1, + 0x069E => 1, 0x069F => 1, 0x06A0 => 1, 0x06A1 => 1, 0x06A2 => 1, 0x06A3 => 1, 0x06A4 => 1, 0x06A5 => 1, + 0x06A6 => 1, 0x06A7 => 1, 0x06A8 => 1, 0x06A9 => 1, 0x06AA => 1, 0x06AB => 1, 0x06AC => 1, 0x06AD => 1, + 0x06AE => 1, 0x06AF => 1, 0x06B0 => 1, 0x06B1 => 1, 0x06B2 => 1, 0x06B3 => 1, 0x06B4 => 1, 0x06B5 => 1, + 0x06B6 => 1, 0x06B7 => 1, 0x06B8 => 1, 0x06B9 => 1, 0x06BA => 1, 0x06BB => 1, 0x06BC => 1, 0x06BD => 1, + 0x06BE => 1, 0x06BF => 1, 0x06C0 => 1, 0x06C1 => 1, 0x06C2 => 1, 0x06C3 => 1, 0x06C4 => 1, 0x06C5 => 1, + 0x06C6 => 1, 0x06C7 => 1, 0x06C8 => 1, 0x06C9 => 1, 0x06CA => 1, 0x06CB => 1, 0x06CC => 1, 0x06CD => 1, + 0x06CE => 1, 0x06CF => 1, 0x06D0 => 1, 0x06D1 => 1, 0x06D2 => 1, 0x06D3 => 1, 0x06D5 => 1, 0x06EE => 1, + 0x06EF => 1, 0x06FA => 1, 0x06FB => 1, 0x06FC => 1, 0x06FF => 1, + /* Arabic Supplement */ + 0x0750 => 1, 0x0751 => 1, 0x0752 => 1, 0x0753 => 1, 0x0754 => 1, 0x0755 => 1, 0x0756 => 1, 0x0757 => 1, + 0x0758 => 1, 0x0759 => 1, 0x075A => 1, 0x075B => 1, 0x075C => 1, 0x075D => 1, 0x075E => 1, 0x075F => 1, + 0x0760 => 1, 0x0761 => 1, 0x0762 => 1, 0x0763 => 1, 0x0764 => 1, 0x0765 => 1, 0x0766 => 1, 0x0767 => 1, + 0x0768 => 1, 0x0769 => 1, 0x076A => 1, 0x076B => 1, 0x076C => 1, 0x076D => 1, 0x076E => 1, 0x076F => 1, + 0x0770 => 1, 0x0771 => 1, 0x0772 => 1, 0x0773 => 1, 0x0774 => 1, 0x0775 => 1, 0x0776 => 1, 0x0777 => 1, + 0x0778 => 1, 0x0779 => 1, 0x077A => 1, 0x077B => 1, 0x077C => 1, 0x077D => 1, 0x077E => 1, 0x077F => 1, + /* Extended Arabic */ + 0x08A0 => 1, 0x08A2 => 1, 0x08A3 => 1, 0x08A4 => 1, 0x08A5 => 1, 0x08A6 => 1, 0x08A7 => 1, 0x08A8 => 1, + 0x08A9 => 1, 0x08AA => 1, 0x08AB => 1, 0x08AC => 1, + /* 'syrc' Syriac */ + 0x0710 => 1, 0x0712 => 1, 0x0713 => 1, 0x0714 => 1, 0x0715 => 1, 0x0716 => 1, 0x0717 => 1, 0x0718 => 1, + 0x0719 => 1, 0x071A => 1, 0x071B => 1, 0x071C => 1, 0x071D => 1, 0x071E => 1, 0x071F => 1, 0x0720 => 1, + 0x0721 => 1, 0x0722 => 1, 0x0723 => 1, 0x0724 => 1, 0x0725 => 1, 0x0726 => 1, 0x0727 => 1, 0x0728 => 1, + 0x0729 => 1, 0x072A => 1, 0x072B => 1, 0x072C => 1, 0x072D => 1, 0x072E => 1, 0x072F => 1, 0x074D => 1, + 0x074E => 1, 0x074F, + /* N'Ko */ + 0x07CA => 1, 0x07CB => 1, 0x07CC => 1, 0x07CD => 1, 0x07CE => 1, 0x07CF => 1, 0x07D0 => 1, 0x07D1 => 1, + 0x07D2 => 1, 0x07D3 => 1, 0x07D4 => 1, 0x07D5 => 1, 0x07D6 => 1, 0x07D7 => 1, 0x07D8 => 1, 0x07D9 => 1, + 0x07DA => 1, 0x07DB => 1, 0x07DC => 1, 0x07DD => 1, 0x07DE => 1, 0x07DF => 1, 0x07E0 => 1, 0x07E1 => 1, + 0x07E2 => 1, 0x07E3 => 1, 0x07E4 => 1, 0x07E5 => 1, 0x07E6 => 1, 0x07E7 => 1, 0x07E8 => 1, 0x07E9 => 1, + 0x07EA => 1, 0x07FA => 1, + /* Mandaic */ + 0x0841 => 1, 0x0842 => 1, 0x0843 => 1, 0x0844 => 1, 0x0845 => 1, 0x0847 => 1, 0x0848 => 1, 0x084A => 1, + 0x084B => 1, 0x084C => 1, 0x084D => 1, 0x084E => 1, 0x0850 => 1, 0x0851 => 1, 0x0852 => 1, 0x0853 => 1, + 0x0855 => 1, + 0x0840 => 1, 0x0846 => 1, 0x0849 => 1, 0x084F => 1, 0x0854 => 1, /* Right joining */ + /* ZWJ U+200D */ + 0x0200D => 1]; + + /* VOWELS = TRANSPARENT-JOINING = Unicode Transparent-Joining type (not just vowels) */ + $this->arabTransparent = [ + 0x0610 => 1, 0x0611 => 1, 0x0612 => 1, 0x0613 => 1, 0x0614 => 1, 0x0615 => 1, 0x0616 => 1, 0x0617 => 1, + 0x0618 => 1, 0x0619 => 1, 0x061A => 1, 0x064B => 1, 0x064C => 1, 0x064D => 1, 0x064E => 1, 0x064F => 1, + 0x0650 => 1, 0x0651 => 1, 0x0652 => 1, 0x0653 => 1, 0x0654 => 1, 0x0655 => 1, 0x0656 => 1, 0x0657 => 1, + 0x0658 => 1, 0x0659 => 1, 0x065A => 1, 0x065B => 1, 0x065C => 1, 0x065D => 1, 0x065E => 1, 0x065F => 1, + 0x0670 => 1, 0x06D6 => 1, 0x06D7 => 1, 0x06D8 => 1, 0x06D9 => 1, 0x06DA => 1, 0x06DB => 1, 0x06DC => 1, + 0x06DF => 1, 0x06E0 => 1, 0x06E1 => 1, 0x06E2 => 1, 0x06E3 => 1, 0x06E4 => 1, 0x06E7 => 1, 0x06E8 => 1, + 0x06EA => 1, 0x06EB => 1, 0x06EC => 1, 0x06ED => 1, + /* Extended Arabic */ + 0x08E4 => 1, 0x08E5 => 1, 0x08E6 => 1, 0x08E7 => 1, 0x08E8 => 1, 0x08E9 => 1, 0x08EA => 1, 0x08EB => 1, + 0x08EC => 1, 0x08ED => 1, 0x08EE => 1, 0x08EF => 1, 0x08F0 => 1, 0x08F1 => 1, 0x08F2 => 1, 0x08F3 => 1, + 0x08F4 => 1, 0x08F5 => 1, 0x08F6 => 1, 0x08F7 => 1, 0x08F8 => 1, 0x08F9 => 1, 0x08FA => 1, 0x08FB => 1, + 0x08FC => 1, 0x08FD => 1, 0x08FE => 1, + /* Arabic ligatures in presentation form (converted in 'ccmp' in e.g. Arial and Times ? need to add others in this range) */ + 0xFC5E => 1, 0xFC5F => 1, 0xFC60 => 1, 0xFC61 => 1, 0xFC62 => 1, + /* 'syrc' Syriac */ + 0x070F => 1, 0x0711 => 1, 0x0730 => 1, 0x0731 => 1, 0x0732 => 1, 0x0733 => 1, 0x0734 => 1, 0x0735 => 1, + 0x0736 => 1, 0x0737 => 1, 0x0738 => 1, 0x0739 => 1, 0x073A => 1, 0x073B => 1, 0x073C => 1, 0x073D => 1, + 0x073E => 1, 0x073F => 1, 0x0740 => 1, 0x0741 => 1, 0x0742 => 1, 0x0743 => 1, 0x0744 => 1, 0x0745 => 1, + 0x0746 => 1, 0x0747 => 1, 0x0748 => 1, 0x0749 => 1, 0x074A => 1, + /* N'Ko */ + 0x07EB => 1, 0x07EC => 1, 0x07ED => 1, 0x07EE => 1, 0x07EF => 1, 0x07F0 => 1, 0x07F1 => 1, 0x07F2 => 1, + 0x07F3 => 1, + /* Mandaic */ + 0x0859 => 1, 0x085A => 1, 0x085B => 1, + ]; + } + + private function arabic_shaper($usetags, $scriptTag) + { + $chars = []; + for ($i = 0; $i < count($this->OTLdata); $i++) { + $chars[] = $this->OTLdata[$i]['hex']; + } + + $crntChar = null; + $prevChar = null; + $nextChar = null; + $output = []; + $max = count($chars); + for ($i = $max - 1; $i >= 0; $i--) { + $crntChar = $chars[$i]; + if ($i > 0) { + $prevChar = hexdec($chars[$i - 1]); + } else { + $prevChar = null; + } + if ($prevChar && isset($this->arabTransparentJoin[$prevChar]) && isset($chars[$i - 2])) { + $prevChar = hexdec($chars[$i - 2]); + if ($prevChar && isset($this->arabTransparentJoin[$prevChar]) && isset($chars[$i - 3])) { + $prevChar = hexdec($chars[$i - 3]); + if ($prevChar && isset($this->arabTransparentJoin[$prevChar]) && isset($chars[$i - 4])) { + $prevChar = hexdec($chars[$i - 4]); + } + } + } + if ($crntChar && isset($this->arabTransparentJoin[hexdec($crntChar)])) { + // If next_char = RightJoining && prev_char = LeftJoining: + if (isset($chars[$i + 1]) && $chars[$i + 1] && isset($this->arabRightJoining[hexdec($chars[$i + 1])]) && $prevChar && isset($this->arabLeftJoining[$prevChar])) { + $output[] = $this->get_arab_glyphs($crntChar, 1, $chars, $i, $scriptTag, $usetags); // <final> form + } else { + $output[] = $this->get_arab_glyphs($crntChar, 0, $chars, $i, $scriptTag, $usetags); // <isolated> form + } + continue; + } + if (hexdec($crntChar) < 128) { + $output[] = [$crntChar, 0]; + $nextChar = $crntChar; + continue; + } + // 0=ISOLATED FORM :: 1=FINAL :: 2=INITIAL :: 3=MEDIAL + $form = 0; + if ($prevChar && isset($this->arabLeftJoining[$prevChar])) { + $form++; + } + if ($nextChar && isset($this->arabRightJoining[hexdec($nextChar)])) { + $form += 2; + } + $output[] = $this->get_arab_glyphs($crntChar, $form, $chars, $i, $scriptTag, $usetags); + $nextChar = $crntChar; + } + $ra = array_reverse($output); + for ($i = 0; $i < count($this->OTLdata); $i++) { + $this->OTLdata[$i]['uni'] = hexdec($ra[$i][0]); + $this->OTLdata[$i]['hex'] = $ra[$i][0]; + $this->OTLdata[$i]['form'] = $ra[$i][1]; // Actaul form substituted 0=ISOLATED FORM :: 1=FINAL :: 2=INITIAL :: 3=MEDIAL + } + } + + private function get_arab_glyphs($char, $type, &$chars, $i, $scriptTag, $usetags) + { + // Optional Feature settings // doesn't control Syriac at present + if (($type === 0 && strpos($usetags, 'isol') === false) || ($type === 1 && strpos($usetags, 'fina') === false) || ($type === 2 && strpos($usetags, 'init') === false) || ($type === 3 && strpos($usetags, 'medi') === false)) { + return [$char, 0]; + } + + // 0=ISOLATED FORM :: 1=FINAL :: 2=INITIAL :: 3=MEDIAL (:: 4=MED2 :: 5=FIN2 :: 6=FIN3) + $retk = -1; + // Alaph 00710 in Syriac + if ($scriptTag == 'syrc' && $char == '00710') { + // if there is a preceding (base?) character *** should search back to previous base - ignoring vowels and change $n + // set $n as the position of the last base; for now we'll just do this: + $n = $i - 1; + // if the preceding (base) character cannot be joined to + // not in $this->arabLeftJoining i.e. not a char which can join to the next one + if (isset($chars[$n]) && isset($this->arabLeftJoining[hexdec($chars[$n])])) { + // if in the middle of Syriac words + if (isset($chars[$i + 1]) && preg_match('/[\x{0700}-\x{0745}]/u', UtfString::code2utf(hexdec($chars[$n]))) && preg_match('/[\x{0700}-\x{0745}]/u', UtfString::code2utf(hexdec($chars[$i + 1]))) && isset($this->arabGlyphs[$char][4])) { + $retk = 4; + } // if at the end of Syriac words + elseif (!isset($chars[$i + 1]) || !preg_match('/[\x{0700}-\x{0745}]/u', UtfString::code2utf(hexdec($chars[$i + 1])))) { + // if preceding base character IS (00715|00716|0072A) + if (strpos('0715|0716|072A', $chars[$n]) !== false && isset($this->arabGlyphs[$char][6])) { + $retk = 6; + } // elseif preceding base character is NOT (00715|00716|0072A) + elseif (isset($this->arabGlyphs[$char][5])) { + $retk = 5; + } + } + } + if ($retk != -1) { + return [$this->arabGlyphs[$char][$retk], $retk]; + } else { + return [$char, 0]; + } + } + + if (($type > 0 || $type === 0) && isset($this->arabGlyphs[$char][$type])) { + $retk = $type; + } elseif ($type == 3 && isset($this->arabGlyphs[$char][1])) { // if <medial> not defined, but <final>, return <final> + $retk = 1; + } elseif ($type == 2 && isset($this->arabGlyphs[$char][0])) { // if <initial> not defined, but <isolated>, return <isolated> + $retk = 0; + } + if ($retk != -1) { + $match = true; + // If GSUB includes a Backtrack or Lookahead condition (e.g. font ArabicTypesetting) + if (isset($this->arabGlyphs[$char]['prel'][$retk]) && $this->arabGlyphs[$char]['prel'][$retk]) { + $ig = 1; + foreach ($this->arabGlyphs[$char]['prel'][$retk] as $k => $v) { // $k starts 0, 1... + if (!isset($chars[$i - $ig - $k])) { + $match = false; + } elseif (strpos($v, $chars[$i - $ig - $k]) === false) { + while (strpos($this->arabGlyphs[$char]['ignore'][$retk], $chars[$i - $ig - $k]) !== false) { // ignore + $ig++; + } + if (!isset($chars[$i - $ig - $k])) { + $match = false; + } elseif (strpos($v, $chars[$i - $ig - $k]) === false) { + $match = false; + } + } + } + } + if (isset($this->arabGlyphs[$char]['postl'][$retk]) && $this->arabGlyphs[$char]['postl'][$retk]) { + $ig = 1; + foreach ($this->arabGlyphs[$char]['postl'][$retk] as $k => $v) { // $k starts 0, 1... + if (!isset($chars[$i + $ig + $k])) { + $match = false; + } elseif (strpos($v, $chars[$i + $ig + $k]) === false) { + while (strpos($this->arabGlyphs[$char]['ignore'][$retk], $chars[$i + $ig + $k]) !== false) { // ignore + $ig++; + } + if (!isset($chars[$i + $ig + $k])) { + $match = false; + } elseif (strpos($v, $chars[$i + $ig + $k]) === false) { + $match = false; + } + } + } + } + if ($match) { + return [$this->arabGlyphs[$char][$retk], $retk]; + } else { + return [$char, 0]; + } + } else { + return [$char, 0]; + } + } + + //////////////////////////////////////////////////////////////// + ///////////////// LINE BREAKING /////////////////////// + //////////////////////////////////////////////////////////////// + ///////////// TIBETAN LINE BREAKING /////////////////// + //////////////////////////////////////////////////////////////// + // Sets $this->OTLdata[$i]['wordend']=true at possible end of word boundaries + private function tibetanLineBreaking() + { + for ($ptr = 0; $ptr < count($this->OTLdata); $ptr++) { + // Break opportunities at U+0F0B Tsheg or U=0F0D + if (isset($this->OTLdata[$ptr]['uni']) && ($this->OTLdata[$ptr]['uni'] == 0x0F0B || $this->OTLdata[$ptr]['uni'] == 0x0F0D)) { + if (isset($this->OTLdata[$ptr + 1]['uni']) && ($this->OTLdata[$ptr + 1]['uni'] == 0x0F0D || $this->OTLdata[$ptr + 1]['uni'] == 0xF0E)) { + continue; + } + // Set end of word marker in OTLdata at matchpos + $this->OTLdata[$ptr]['wordend'] = true; + } + } + } + + /** + * South East Asian Linebreaking (Thai, Khmer and Lao) using dictionary of words + * + * Sets $this->OTLdata[$i]['wordend']=true at possible end of word boundaries + */ + private function seaLineBreaking() + { + // Load Line-breaking dictionary + if (!isset($this->lbdicts[$this->shaper]) && file_exists(__DIR__ . '/../data/linebrdict' . $this->shaper . '.dat')) { + $this->lbdicts[$this->shaper] = file_get_contents(__DIR__ . '/../data/linebrdict' . $this->shaper . '.dat'); + } + + $dict = &$this->lbdicts[$this->shaper]; + + // Find all word boundaries and mark end of word $this->OTLdata[$i]['wordend']=true on last character + // If Thai, allow for possible suffixes (not in Lao or Khmer) + // repeater/ellision characters + // (0x0E2F); // Ellision character THAI_PAIYANNOI 0x0E2F UTF-8 0xE0 0xB8 0xAF + // (0x0E46); // Repeat character THAI_MAIYAMOK 0x0E46 UTF-8 0xE0 0xB9 0x86 + // (0x0EC6); // Repeat character LAO UTF-8 0xE0 0xBB 0x86 + + $rollover = []; + $ptr = 0; + + while ($ptr < count($this->OTLdata) - 3) { + if (count($rollover)) { + $matches = $rollover; + $rollover = []; + } else { + $matches = $this->checkwordmatch($dict, $ptr); + } + if (count($matches) == 1) { + $matchpos = $matches[0]; + // Check for repeaters - if so $matchpos++ + if (isset($this->OTLdata[$matchpos + 1]['uni']) && ($this->OTLdata[$matchpos + 1]['uni'] == 0x0E2F || $this->OTLdata[$matchpos + 1]['uni'] == 0x0E46 || $this->OTLdata[$matchpos + 1]['uni'] == 0x0EC6)) { + $matchpos++; + } + // Set end of word marker in OTLdata at matchpos + $this->OTLdata[$matchpos]['wordend'] = true; + $ptr = $matchpos + 1; + } elseif (empty($matches)) { + $ptr++; + // Move past any ASCII characters + while (isset($this->OTLdata[$ptr]['uni']) && ($this->OTLdata[$ptr]['uni'] >> 8) == 0) { + $ptr++; + } + } else { // Multiple matches + $secondmatch = false; + for ($m = count($matches) - 1; $m >= 0; $m--) { + //for ($m=0;$m<count($matches);$m++) { + $firstmatch = $matches[$m]; + $matches2 = $this->checkwordmatch($dict, $firstmatch + 1); + if (count($matches2)) { + // Set end of word marker in OTLdata at matchpos + $this->OTLdata[$firstmatch]['wordend'] = true; + $ptr = $firstmatch + 1; + $rollover = $matches2; + $secondmatch = true; + break; + } + } + if (!$secondmatch) { + // Set end of word marker in OTLdata at end of longest first match + $this->OTLdata[$matches[count($matches) - 1]]['wordend'] = true; + $ptr = $matches[count($matches) - 1] + 1; + // Move past any ASCII characters + while (isset($this->OTLdata[$ptr]['uni']) && ($this->OTLdata[$ptr]['uni'] >> 8) == 0) { + $ptr++; + } + } + } + } + } + + private function checkwordmatch(&$dict, $ptr) + { + /* + Node type: Split. + Divide at < 98 >= 98 + Offset for >= 98 == 79 (long 4-byte unsigned) + + Node type: Linear match. + Char = 97 + + Intermediate match + + Final match + */ + + $dictptr = 0; + $ok = true; + $matches = []; + while ($ok) { + $x = ord($dict[$dictptr]); + $c = $this->OTLdata[$ptr]['uni'] & 0xFF; + if ($x == static::_DICT_INTERMEDIATE_MATCH) { +//echo "DICT_INTERMEDIATE_MATCH: ".dechex($c).'<br />'; + // Do not match if next character in text is a Mark + if (isset($this->OTLdata[$ptr]['uni']) && strpos($this->GlyphClassMarks, $this->OTLdata[$ptr]['hex']) === false) { + $matches[] = $ptr - 1; + } + $dictptr++; + } elseif ($x == static::_DICT_FINAL_MATCH) { +//echo "DICT_FINAL_MATCH: ".dechex($c).'<br />'; + // Do not match if next character in text is a Mark + if (isset($this->OTLdata[$ptr]['uni']) && strpos($this->GlyphClassMarks, $this->OTLdata[$ptr]['hex']) === false) { + $matches[] = $ptr - 1; + } + return $matches; + } elseif ($x == static::_DICT_NODE_TYPE_LINEAR) { +//echo "DICT_NODE_TYPE_LINEAR: ".dechex($c).'<br />'; + $dictptr++; + $m = ord($dict[$dictptr]); + if ($c == $m) { + $ptr++; + if ($ptr > count($this->OTLdata) - 1) { + $next = ord($dict[$dictptr + 1]); + if ($next == static::_DICT_INTERMEDIATE_MATCH || $next == static::_DICT_FINAL_MATCH) { + // Do not match if next character in text is a Mark + if (isset($this->OTLdata[$ptr]['uni']) && strpos($this->GlyphClassMarks, $this->OTLdata[$ptr]['hex']) === false) { + $matches[] = $ptr - 1; + } + } + return $matches; + } + $dictptr++; + continue; + } else { +//echo "DICT_NODE_TYPE_LINEAR NOT: ".dechex($c).'<br />'; + return $matches; + } + } elseif ($x == static::_DICT_NODE_TYPE_SPLIT) { +//echo "DICT_NODE_TYPE_SPLIT ON ".dechex($d).": ".dechex($c).'<br />'; + $dictptr++; + $d = ord($dict[$dictptr]); + if ($c < $d) { + $dictptr += 5; + } else { + $dictptr++; + // Unsigned long 32-bit offset + $offset = (ord($dict[$dictptr]) * 16777216) + (ord($dict[$dictptr + 1]) << 16) + (ord($dict[$dictptr + 2]) << 8) + ord($dict[$dictptr + 3]); + $dictptr = $offset; + } + } else { +//echo "PROBLEM: ".($x).'<br />'; + $ok = false; // Something has gone wrong + } + } + + return $matches; + } + + //////////////////////////////////////////////////////////////// + ////////// GPOS /////////////////////////////////////// + //////////////////////////////////////////////////////////////// + private function _applyGPOSrules($LookupList, $is_old_spec = false) + { + foreach ($LookupList as $lu => $tag) { + $Type = $this->GPOSLookups[$lu]['Type']; + $Flag = $this->GPOSLookups[$lu]['Flag']; + $MarkFilteringSet = ''; + if (isset($this->GPOSLookups[$lu]['MarkFilteringSet'])) { + $MarkFilteringSet = $this->GPOSLookups[$lu]['MarkFilteringSet']; + } + $ptr = 0; + // Test each glyph sequentially + while ($ptr < (count($this->OTLdata))) { // whilst there is another glyph ..0064 + $currGlyph = $this->OTLdata[$ptr]['hex']; + $currGID = $this->OTLdata[$ptr]['uni']; + $shift = 1; + foreach ($this->GPOSLookups[$lu]['Subtables'] as $c => $subtable_offset) { + // NB Coverage only looks at glyphs for position 1 (esp. 7.3 and 8.3) + if (isset($this->LuCoverage[$lu][$c][$currGID])) { + // Get rules from font GPOS subtable + if (isset($this->OTLdata[$ptr]['bidi_type'])) { // No need to check bidi_type - just a check that it exists + $shift = $this->_applyGPOSsubtable($lu, $c, $ptr, $currGlyph, $currGID, ($subtable_offset - $this->GPOS_offset + $this->GSUB_length), $Type, $Flag, $MarkFilteringSet, $this->LuCoverage[$lu][$c], $tag, 0, $is_old_spec); + if ($shift) { + break; + } + } + } + } + if ($shift == 0) { + $shift = 1; + } + $ptr += $shift; + } + } + } + + ////////////////////////////////////////////////////////////////////////////////// + // GPOS Types + // Lookup Type 1: Single Adjustment Positioning Subtable Adjust position of a single glyph + // Lookup Type 2: Pair Adjustment Positioning Subtable Adjust position of a pair of glyphs + // Lookup Type 3: Cursive Attachment Positioning Subtable Attach cursive glyphs + // Lookup Type 4: MarkToBase Attachment Positioning Subtable Attach a combining mark to a base glyph + // Lookup Type 5: MarkToLigature Attachment Positioning Subtable Attach a combining mark to a ligature + // Lookup Type 6: MarkToMark Attachment Positioning Subtable Attach a combining mark to another mark + // Lookup Type 7: Contextual Positioning Subtables Position one or more glyphs in context + // Lookup Type 8: Chaining Contextual Positioning Subtable Position one or more glyphs in chained context + // Lookup Type 9: Extension positioning + ////////////////////////////////////////////////////////////////////////////////// + private function _applyGPOSvaluerecord($basepos, $Value) + { + + // If current glyph is a mark with a defined width, any XAdvance is considered to REPLACE the character Advance Width + // Test case <div style="font-family:myanmartext">င်္က္ကျြွေိ</div> + if (strpos($this->GlyphClassMarks, $this->OTLdata[$basepos]['hex']) !== false) { + $cw = round($this->mpdf->_getCharWidth($this->mpdf->CurrentFont['cw'], $this->OTLdata[$basepos]['uni']) * $this->mpdf->CurrentFont['unitsPerEm'] / 1000); // convert back to font design units + } else { + $cw = 0; + } + + $apos = $this->_getXAdvancePos($basepos); + + if (isset($Value['XAdvance']) && ($Value['XAdvance'] - $cw) != 0) { + // However DON'T REPLACE the character Advance Width if Advance Width is negative + // Test case <div style="font-family: dejavusansmono">ру́сский</div> + if ($Value['XAdvance'] < 0) { + $cw = 0; + } + + // For LTR apply XAdvanceL to the last mark following the base = at $apos + // For RTL apply XAdvanceR to base = at $basepos + if (isset($this->OTLdata[$apos]['GPOSinfo']['XAdvanceL'])) { + $this->OTLdata[$apos]['GPOSinfo']['XAdvanceL'] += $Value['XAdvance'] - $cw; + } else { + $this->OTLdata[$apos]['GPOSinfo']['XAdvanceL'] = $Value['XAdvance'] - $cw; + } + if (isset($this->OTLdata[$basepos]['GPOSinfo']['XAdvanceR'])) { + $this->OTLdata[$basepos]['GPOSinfo']['XAdvanceR'] += $Value['XAdvance'] - $cw; + } else { + $this->OTLdata[$basepos]['GPOSinfo']['XAdvanceR'] = $Value['XAdvance'] - $cw; + } + } + + // Any XPlacement (? and Y Placement) apply to base and marks (from basepos to apos) + for ($a = $basepos; $a <= $apos; $a++) { + if (isset($Value['XPlacement'])) { + if (isset($this->OTLdata[$a]['GPOSinfo']['XPlacement'])) { + $this->OTLdata[$a]['GPOSinfo']['XPlacement'] += $Value['XPlacement']; + } else { + $this->OTLdata[$a]['GPOSinfo']['XPlacement'] = $Value['XPlacement']; + } + } + if (isset($Value['YPlacement'])) { + if (isset($this->OTLdata[$a]['GPOSinfo']['YPlacement'])) { + $this->OTLdata[$a]['GPOSinfo']['YPlacement'] += $Value['YPlacement']; + } else { + $this->OTLdata[$a]['GPOSinfo']['YPlacement'] = $Value['YPlacement']; + } + } + } + } + + // If XAdvance is aplied to $ptr - in order for PDF to position the Advance correctly need to place it on + // the last of any Marks which immediately follow the current glyph + private function _getXAdvancePos($pos) + { + // NB Not all fonts have all marks specified in GlyphClassMarks + // If the current glyph is not a base (but a mark) then ignore this, and apply to the current position + if (strpos($this->GlyphClassMarks, $this->OTLdata[$pos]['hex']) !== false) { + return $pos; + } + + while (isset($this->OTLdata[$pos + 1]['hex']) && strpos($this->GlyphClassMarks, $this->OTLdata[$pos + 1]['hex']) !== false) { + $pos++; + } + return $pos; + } + + private function _applyGPOSsubtable($lookupID, $subtable, $ptr, $currGlyph, $currGID, $subtable_offset, $Type, $Flag, $MarkFilteringSet, $LuCoverage, $tag, $level, $is_old_spec) + { + if (($Flag & 0x0001) == 1) { + $dir = 'RTL'; + } else { // only used for Type 3 + $dir = 'LTR'; + } + + $ignore = $this->_getGCOMignoreString($Flag, $MarkFilteringSet); + + // Lets start + $this->seek($subtable_offset); + $PosFormat = $this->read_ushort(); + + //////////////////////////////////////////////////////////////////////////////// + // LookupType 1: Single adjustment Adjust position of a single glyph (e.g. SmallCaps/Sups/Subs) + //////////////////////////////////////////////////////////////////////////////// + if ($Type == 1) { + //=========== + // Format 1: + //=========== + if ($PosFormat == 1) { + $Coverage = $subtable_offset + $this->read_ushort(); + $ValueFormat = $this->read_ushort(); + $Value = $this->_getValueRecord($ValueFormat); + } //=========== + // Format 2: + //=========== + elseif ($PosFormat == 2) { + $Coverage = $subtable_offset + $this->read_ushort(); + $ValueFormat = $this->read_ushort(); + $ValueCount = $this->read_ushort(); + $GlyphPos = $LuCoverage[$currGID]; + $this->skip($GlyphPos * 2 * $this->count_bits($ValueFormat)); + $Value = $this->_getValueRecord($ValueFormat); + } + $this->_applyGPOSvaluerecord($ptr, $Value); + if ($this->debugOTL) { + $this->_dumpproc('GPOS', $lookupID, $subtable, $Type, $PosFormat, $ptr, $currGlyph, $level); + } + return 1; + } //////////////////////////////////////////////////////////////////////////////// + // LookupType 2: Pair adjustment Adjust position of a pair of glyphs (Kerning) + //////////////////////////////////////////////////////////////////////////////// + elseif ($Type == 2) { + $Coverage = $subtable_offset + $this->read_ushort(); + $ValueFormat1 = $this->read_ushort(); + $ValueFormat2 = $this->read_ushort(); + $sizeOfPair = ( 2 * $this->count_bits($ValueFormat1) ) + ( 2 * $this->count_bits($ValueFormat2) ); + //=========== + // Format 1: + //=========== + if ($PosFormat == 1) { + $PairSetCount = $this->read_ushort(); + $PairSetOffset = []; + for ($p = 0; $p < $PairSetCount; $p++) { + $PairSetOffset[] = $subtable_offset + $this->read_ushort(); + } + for ($p = 0; $p < $PairSetCount; $p++) { + if (isset($LuCoverage[$currGID]) && $LuCoverage[$currGID] == $p) { + $this->seek($PairSetOffset[$p]); + //PairSet table + $PairValueCount = $this->read_ushort(); + for ($pv = 0; $pv < $PairValueCount; $pv++) { + //PairValueRecord + $gid = $this->read_ushort(); + $SecondGlyph = $this->glyphToChar($gid); + $FirstGlyph = $this->OTLdata[$ptr]['uni']; + + $checkpos = $ptr; + $checkpos++; + while (isset($this->OTLdata[$checkpos]) && strpos($ignore, $this->OTLdata[$checkpos]['hex']) !== false) { + $checkpos++; + } + if (isset($this->OTLdata[$checkpos]) && $this->OTLdata[$checkpos]['uni'] == $SecondGlyph) { + $matchedpos = $checkpos; + } else { + $matchedpos = false; + } + + if ($matchedpos !== false) { + $Value1 = $this->_getValueRecord($ValueFormat1); + $Value2 = $this->_getValueRecord($ValueFormat2); + if ($ValueFormat1) { + $this->_applyGPOSvaluerecord($ptr, $Value1); + } + if ($ValueFormat2) { + $this->_applyGPOSvaluerecord($matchedpos, $Value2); + if ($this->debugOTL) { + $this->_dumpproc('GPOS', $lookupID, $subtable, $Type, $PosFormat, $ptr, $currGlyph, $level); + } + return $matchedpos - $ptr + 1; + } + if ($this->debugOTL) { + $this->_dumpproc('GPOS', $lookupID, $subtable, $Type, $PosFormat, $ptr, $currGlyph, $level); + } + return $matchedpos - $ptr; + } else { + $this->skip($sizeOfPair); + } + } + } + } + return 0; + } //=========== + // Format 2: + //=========== + elseif ($PosFormat == 2) { + $ClassDef1 = $subtable_offset + $this->read_ushort(); + $ClassDef2 = $subtable_offset + $this->read_ushort(); + $Class1Count = $this->read_ushort(); + $Class2Count = $this->read_ushort(); + + $sizeOfValueRecords = $Class1Count * $Class2Count * $sizeOfPair; + + //$this->skip($sizeOfValueRecords ); ???? NOT NEEDED + // NB Class1Count includes Class 0 even though it is not defined by $ClassDef1 + // i.e. Class1Count = 5; Class1 will contain array(indices 1-4); + $Class1 = $this->_getClassDefinitionTable($ClassDef1); + $Class2 = $this->_getClassDefinitionTable($ClassDef2); + $FirstGlyph = $this->OTLdata[$ptr]['uni']; + $checkpos = $ptr; + $checkpos++; + while (isset($this->OTLdata[$checkpos]) && strpos($ignore, $this->OTLdata[$checkpos]['hex']) !== false) { + $checkpos++; + } + if (isset($this->OTLdata[$checkpos])) { + $matchedpos = $checkpos; + } else { + return 0; + } + + $SecondGlyph = $this->OTLdata[$matchedpos]['uni']; + for ($i = 0; $i < $Class1Count; $i++) { + if (isset($Class1[$i]) && count($Class1[$i])) { + $FirstClassPos = array_search($FirstGlyph, $Class1[$i]); + if ($FirstClassPos === false) { + continue; + } else { + for ($j = 0; $j < $Class2Count; $j++) { + if (isset($Class2[$j]) && count($Class2[$j])) { + $SecondClassPos = array_search($SecondGlyph, $Class2[$j]); + if ($SecondClassPos === false) { + continue; + } + + // Get ValueRecord[$i][$j] + $offs = ($i * $Class2Count * $sizeOfPair) + ($j * $sizeOfPair); + $this->seek($subtable_offset + 16 + $offs); + + $Value1 = $this->_getValueRecord($ValueFormat1); + $Value2 = $this->_getValueRecord($ValueFormat2); + if ($ValueFormat1) { + $this->_applyGPOSvaluerecord($ptr, $Value1); + } + if ($ValueFormat2) { + $this->_applyGPOSvaluerecord($matchedpos, $Value2); + if ($this->debugOTL) { + $this->_dumpproc('GPOS', $lookupID, $subtable, $Type, $PosFormat, $ptr, $currGlyph, $level); + } + return $matchedpos - $ptr + 1; + } + if ($this->debugOTL) { + $this->_dumpproc('GPOS', $lookupID, $subtable, $Type, $PosFormat, $ptr, $currGlyph, $level); + } + return $matchedpos - $ptr; + } + } + } + } + } + return 0; + } + } //////////////////////////////////////////////////////////////////////////////// + // LookupType 3: Cursive attachment Attach cursive glyphs + //////////////////////////////////////////////////////////////////////////////// + elseif ($Type == 3) { + $this->skip(4); + // Need default XAdvance for glyph + $pdfWidth = $this->mpdf->_getCharWidth($this->mpdf->CurrentFont['cw'], hexdec($currGlyph)); // DON'T convert back to design units + + $CPos = $LuCoverage[$currGID]; + $this->skip($CPos * 4); + $EntryAnchor = $this->read_ushort(); + $ExitAnchor = $this->read_ushort(); + if ($EntryAnchor != 0) { + $EntryAnchor += $subtable_offset; + list($x, $y) = $this->_getAnchorTable($EntryAnchor); + if ($dir == 'RTL') { + if (round($pdfWidth) == round($x * 1000 / $this->mpdf->CurrentFont['unitsPerEm'])) { + $x = 0; + } else { + $x = $x - ($pdfWidth * $this->mpdf->CurrentFont['unitsPerEm'] / 1000); + } + } + + $this->Entry[$ptr] = ['X' => $x, 'Y' => $y, 'dir' => $dir]; + } + if ($ExitAnchor != 0) { + $ExitAnchor += $subtable_offset; + list($x, $y) = $this->_getAnchorTable($ExitAnchor); + if ($dir == 'LTR') { + if (round($pdfWidth) == round($x * 1000 / $this->mpdf->CurrentFont['unitsPerEm'])) { + $x = 0; + } else { + $x = $x - ($pdfWidth * $this->mpdf->CurrentFont['unitsPerEm'] / 1000); + } + } + $this->Exit[$ptr] = ['X' => $x, 'Y' => $y, 'dir' => $dir]; + } + if ($this->debugOTL) { + $this->_dumpproc('GPOS', $lookupID, $subtable, $Type, $PosFormat, $ptr, $currGlyph, $level); + } + return 1; + } //////////////////////////////////////////////////////////////////////////////// + // LookupType 4: MarkToBase attachment Attach a combining mark to a base glyph + //////////////////////////////////////////////////////////////////////////////// + elseif ($Type == 4) { + $MarkCoverage = $subtable_offset + $this->read_ushort(); + //$MarkCoverage is already set in $LuCoverage 00065|00073 etc + $BaseCoverage = $subtable_offset + $this->read_ushort(); + $ClassCount = $this->read_ushort(); // Number of classes defined for marks = Number of mark glyphs in the MarkCoverage table + $MarkArray = $subtable_offset + $this->read_ushort(); // Offset to MarkArray table + $BaseArray = $subtable_offset + $this->read_ushort(); // Offset to BaseArray table + + $this->seek($BaseCoverage); + $BaseGlyphs = implode('|', $this->_getCoverage()); + + $checkpos = $ptr; + $checkpos--; + + // ZZZ93 + // In Lohit-Kannada font (old-spec), rules specify a Type 4 GPOS to attach below-forms to base glyph + // the repositioning does not happen in MS Word, and shouldn't happen comparing with other fonts + // ?Why not + // This Fix blocks the GPOS rule if the "mark" is not actually classified as a mark in the GlyphClasses of GDEF + // but only in Indic old-spec. + // Test cases: ನ್ನು and ಕ್ರೌ + if ($this->shaper == 'I' && $is_old_spec && strpos($this->GlyphClassMarks, $this->OTLdata[$ptr]['hex']) === false) { + return; + } + + + // "To identify the base glyph that combines with a mark, the text-processing client must look backward in the glyph string from the mark to the preceding base glyph." + while (isset($this->OTLdata[$checkpos]) && strpos($this->GlyphClassMarks, $this->OTLdata[$checkpos]['hex']) !== false) { + $checkpos--; + } + + if (isset($this->OTLdata[$checkpos]) && strpos($BaseGlyphs, $this->OTLdata[$checkpos]['hex']) !== false) { + $matchedpos = $checkpos; + } else { + $matchedpos = false; + } + + if ($matchedpos !== false) { + // Get the relevant MarkRecord + $MarkPos = $LuCoverage[$currGID]; + $MarkRecord = $this->_getMarkRecord($MarkArray, $MarkPos); // e.g. Array ( [Class] => 0 [AnchorX] => -549 [AnchorY] => 1548 ) + //Mark Class is = $MarkRecord['Class'] + // Get the relevant BaseRecord + $this->seek($BaseArray); + $BaseCount = $this->read_ushort(); + $BasePos = strpos($BaseGlyphs, $this->OTLdata[$matchedpos]['hex']) / 6; + + // Move to the BaseRecord we want + $nSkip = (2 * $BasePos * $ClassCount ); + $this->skip($nSkip); + + // Read BaseRecord we want for appropriate Class + $nSkip = 2 * $MarkRecord['Class']; + $this->skip($nSkip); + $BaseRecordOffset = $BaseArray + $this->read_ushort(); + list($x, $y) = $this->_getAnchorTable($BaseRecordOffset); + $BaseRecord = ['AnchorX' => $x, 'AnchorY' => $y]; // e.g. Array ( [AnchorX] => 660 [AnchorY] => 1556 ) + // Need default XAdvance for Base glyph + $BaseWidth = $this->mpdf->_getCharWidth($this->mpdf->CurrentFont['cw'], $this->OTLdata[$matchedpos]['uni']) * $this->mpdf->CurrentFont['unitsPerEm'] / 1000; // convert back to font design units + $this->OTLdata[$ptr]['GPOSinfo']['BaseWidth'] = $BaseWidth; + // And any intervening (ignored) characters + if (($ptr - $matchedpos) > 1) { + for ($i = $matchedpos + 1; $i < $ptr; $i++) { + $BaseWidthExtra = $this->mpdf->_getCharWidth($this->mpdf->CurrentFont['cw'], $this->OTLdata[$i]['uni']) * $this->mpdf->CurrentFont['unitsPerEm'] / 1000; // convert back to font design units + $this->OTLdata[$ptr]['GPOSinfo']['BaseWidth'] += $BaseWidthExtra; + } + } + + // Align to previous Glyph by attachment - so need to add to previous placement values + $prevXPlacement = (isset($this->OTLdata[$matchedpos]['GPOSinfo']['XPlacement']) ? $this->OTLdata[$matchedpos]['GPOSinfo']['XPlacement'] : 0); + $prevYPlacement = (isset($this->OTLdata[$matchedpos]['GPOSinfo']['YPlacement']) ? $this->OTLdata[$matchedpos]['GPOSinfo']['YPlacement'] : 0); + + $this->OTLdata[$ptr]['GPOSinfo']['XPlacement'] = $prevXPlacement + $BaseRecord['AnchorX'] - $MarkRecord['AnchorX']; + $this->OTLdata[$ptr]['GPOSinfo']['YPlacement'] = $prevYPlacement + $BaseRecord['AnchorY'] - $MarkRecord['AnchorY']; + if ($this->debugOTL) { + $this->_dumpproc('GPOS', $lookupID, $subtable, $Type, $PosFormat, $ptr, $currGlyph, $level); + } + return 1; + } + return 0; + } //////////////////////////////////////////////////////////////////////////////// + // LookupType 5: MarkToLigature attachment Attach a combining mark to a ligature + //////////////////////////////////////////////////////////////////////////////// + elseif ($Type == 5) { + $MarkCoverage = $subtable_offset + $this->read_ushort(); + //$MarkCoverage is already set in $LuCoverage 00065|00073 etc + $LigatureCoverage = $subtable_offset + $this->read_ushort(); + $ClassCount = $this->read_ushort(); // Number of classes defined for marks = Number of mark glyphs in the MarkCoverage table + $MarkArray = $subtable_offset + $this->read_ushort(); // Offset to MarkArray table + $LigatureArray = $subtable_offset + $this->read_ushort(); // Offset to LigatureArray table + + $this->seek($LigatureCoverage); + $LigatureGlyphs = implode('|', $this->_getCoverage()); + + + $checkpos = $ptr; + $checkpos--; + + // "To position a combining mark using a MarkToLigature attachment subtable, the text-processing client must work backward from the mark to the preceding ligature glyph." + while (isset($this->OTLdata[$checkpos]) && strpos($this->GlyphClassMarks, $this->OTLdata[$checkpos]['hex']) !== false) { + $checkpos--; + } + + if (isset($this->OTLdata[$checkpos]) && strpos($LigatureGlyphs, $this->OTLdata[$checkpos]['hex']) !== false) { + $matchedpos = $checkpos; + } else { + $matchedpos = false; + } + + if ($matchedpos !== false) { + // Get the relevant MarkRecord + $MarkPos = $LuCoverage[$currGID]; + $MarkRecord = $this->_getMarkRecord($MarkArray, $MarkPos); // e.g. Array ( [Class] => 0 [AnchorX] => -549 [AnchorY] => 1548 ) + //Mark Class is = $MarkRecord['Class'] + // Get the relevant LigatureRecord + $this->seek($LigatureArray); + $LigatureCount = $this->read_ushort(); + $LigaturePos = strpos($LigatureGlyphs, $this->OTLdata[$matchedpos]['hex']) / 6; + + // Move to the LigatureAttach table Record we want + $nSkip = (2 * $LigaturePos); + $this->skip($nSkip); + $LigatureAttachOffset = $LigatureArray + $this->read_ushort(); + $this->seek($LigatureAttachOffset); + $ComponentCount = $this->read_ushort(); + $offsets = []; + for ($comp = 0; $comp < $ComponentCount; $comp++) { + // ComponentRecords + for ($class = 0; $class < $ClassCount; $class++) { + $offsets[$comp][$class] = $this->read_ushort(); + } + } + + // Get the specific component for this mark attachment + if (isset($this->assocLigs[$matchedpos]) && isset($this->assocMarks[$ptr]['ligPos']) && $this->assocMarks[$ptr]['ligPos'] == $matchedpos) { + $component = $this->assocMarks[$ptr]['compID']; + } else { + $component = $ComponentCount - 1; + } + + $offset = $offsets[$component][$MarkRecord['Class']]; + if ($offset != 0) { + $LigatureRecordOffset = $offset + $LigatureAttachOffset; + list($x, $y) = $this->_getAnchorTable($LigatureRecordOffset); + $LigatureRecord = ['AnchorX' => $x, 'AnchorY' => $y]; + + // Need default XAdvance for Ligature glyph + $LigatureWidth = $this->mpdf->_getCharWidth($this->mpdf->CurrentFont['cw'], $this->OTLdata[$matchedpos]['uni']) * $this->mpdf->CurrentFont['unitsPerEm'] / 1000; // convert back to font design units + $this->OTLdata[$ptr]['GPOSinfo']['BaseWidth'] = $LigatureWidth; + // And any intervening (ignored)characters + if (($ptr - $matchedpos) > 1) { + for ($i = $matchedpos + 1; $i < $ptr; $i++) { + $LigatureWidthExtra = $this->mpdf->_getCharWidth($this->mpdf->CurrentFont['cw'], $this->OTLdata[$i]['uni']) * $this->mpdf->CurrentFont['unitsPerEm'] / 1000; // convert back to font design units + $this->OTLdata[$ptr]['GPOSinfo']['BaseWidth'] += $LigatureWidthExtra; + } + } + + // Align to previous Ligature by attachment - so need to add to previous placement values + if (isset($this->OTLdata[$matchedpos]['GPOSinfo']['XPlacement'])) { + $prevXPlacement = $this->OTLdata[$matchedpos]['GPOSinfo']['XPlacement']; + } else { + $prevXPlacement = 0; + } + if (isset($this->OTLdata[$matchedpos]['GPOSinfo']['YPlacement'])) { + $prevYPlacement = $this->OTLdata[$matchedpos]['GPOSinfo']['YPlacement']; + } else { + $prevYPlacement = 0; + } + + $this->OTLdata[$ptr]['GPOSinfo']['XPlacement'] = $prevXPlacement + $LigatureRecord['AnchorX'] - $MarkRecord['AnchorX']; + $this->OTLdata[$ptr]['GPOSinfo']['YPlacement'] = $prevYPlacement + $LigatureRecord['AnchorY'] - $MarkRecord['AnchorY']; + if ($this->debugOTL) { + $this->_dumpproc('GPOS', $lookupID, $subtable, $Type, $PosFormat, $ptr, $currGlyph, $level); + } + return 1; + } + } + return 0; + } //////////////////////////////////////////////////////////////////////////////// + // LookupType 6: MarkToMark attachment Attach a combining mark to another mark + //////////////////////////////////////////////////////////////////////////////// + elseif ($Type == 6) { + $Mark1Coverage = $subtable_offset + $this->read_ushort(); // Combining Mark + //$Mark1Coverage is already set in $LuCoverage 0065|0073 etc + $Mark2Coverage = $subtable_offset + $this->read_ushort(); // Base Mark + $ClassCount = $this->read_ushort(); // Number of classes defined for marks = No. of Combining mark1 glyphs in the MarkCoverage table + $Mark1Array = $subtable_offset + $this->read_ushort(); // Offset to MarkArray table + $Mark2Array = $subtable_offset + $this->read_ushort(); // Offset to Mark2Array table + $this->seek($Mark2Coverage); + $Mark2Glyphs = implode('|', $this->_getCoverage()); + $checkpos = $ptr; + $checkpos--; + while (isset($this->OTLdata[$checkpos]) && strpos($ignore, $this->OTLdata[$checkpos]['hex']) !== false) { + $checkpos--; + } + if (isset($this->OTLdata[$checkpos]) && strpos($Mark2Glyphs, $this->OTLdata[$checkpos]['hex']) !== false) { + $matchedpos = $checkpos; + } else { + $matchedpos = false; + } + + if ($matchedpos !== false) { + // Get the relevant MarkRecord + $Mark1Pos = $LuCoverage[$currGID]; + $Mark1Record = $this->_getMarkRecord($Mark1Array, $Mark1Pos); // e.g. Array ( [Class] => 0 [AnchorX] => -549 [AnchorY] => 1548 ) + //Mark Class is = $Mark1Record['Class'] + // Get the relevant Mark2Record + $this->seek($Mark2Array); + $Mark2Count = $this->read_ushort(); + $Mark2Pos = strpos($Mark2Glyphs, $this->OTLdata[$matchedpos]['hex']) / 6; + + // Move to the Mark2Record we want + $nSkip = (2 * $Mark2Pos * $ClassCount ); + $this->skip($nSkip); + + // Read Mark2Record we want for appropriate Class + $nSkip = 2 * $Mark1Record['Class']; + $this->skip($nSkip); + $Mark2RecordOffset = $Mark2Array + $this->read_ushort(); + list($x, $y) = $this->_getAnchorTable($Mark2RecordOffset); + $Mark2Record = ['AnchorX' => $x, 'AnchorY' => $y]; // e.g. Array ( [AnchorX] => 660 [AnchorY] => 1556 ) + // Need default XAdvance for Mark2 glyph + $Mark2Width = $this->mpdf->_getCharWidth($this->mpdf->CurrentFont['cw'], $this->OTLdata[$matchedpos]['uni']) * $this->mpdf->CurrentFont['unitsPerEm'] / 1000; // convert back to font design units + // IF combining marks are set on different components of a ligature glyph, do not apply this rule + // Test: arabictypesetting: إِلَىٰٓ + // Test: arabictypesetting: بَّيْنَكُمْ + $prevLig = -1; + $thisLig = -1; + $prevComp = -1; + $thisComp = -1; + if (isset($this->assocMarks[$matchedpos])) { + $prevLig = $this->assocMarks[$matchedpos]['ligPos']; + $prevComp = $this->assocMarks[$matchedpos]['compID']; + } + if (isset($this->assocMarks[$ptr])) { + $thisLig = $this->assocMarks[$ptr]['ligPos']; + $thisComp = $this->assocMarks[$ptr]['compID']; + } + + // However IF Mark2 (first in logical order, i.e. being attached to) is not associated with a base, carry on + // This happens in Indic when the Mark being attached to e.g. [Halant Ma lig] -> MatraU, [U+0B4D + U+B2E as E0F5]-> U+0B41 become E135 + if (!defined("OMIT_OTL_FIX_1") || OMIT_OTL_FIX_1 != 1) { + /* OTL_FIX_1 */ + if (isset($this->assocMarks[$matchedpos]) && ($prevLig != $thisLig || $prevComp != $thisComp )) { + return 0; + } + } else { + /* Original code */ + if ($prevLig != $thisLig || $prevComp != $thisComp) { + return 0; + } + } + + + if (!defined("OMIT_OTL_FIX_2") || OMIT_OTL_FIX_2 != 1) { + /* OTL_FIX_2 */ + if (!isset($this->OTLdata[$matchedpos]['GPOSinfo']['BaseWidth']) || !$this->OTLdata[$matchedpos]['GPOSinfo']['BaseWidth']) { + $this->OTLdata[$ptr]['GPOSinfo']['BaseWidth'] = $Mark2Width; + } + } + + // ZZZ99Q - Test Case font-family: garuda น้ำ + if (isset($this->OTLdata[$matchedpos]['GPOSinfo']['BaseWidth']) && $this->OTLdata[$matchedpos]['GPOSinfo']['BaseWidth']) { + $this->OTLdata[$ptr]['GPOSinfo']['BaseWidth'] = $this->OTLdata[$matchedpos]['GPOSinfo']['BaseWidth']; + } + + // Align to previous Mark by attachment - so need to add the previous placement values + $prevXPlacement = (isset($this->OTLdata[$matchedpos]['GPOSinfo']['XPlacement']) ? $this->OTLdata[$matchedpos]['GPOSinfo']['XPlacement'] : 0); + $prevYPlacement = (isset($this->OTLdata[$matchedpos]['GPOSinfo']['YPlacement']) ? $this->OTLdata[$matchedpos]['GPOSinfo']['YPlacement'] : 0); + $this->OTLdata[$ptr]['GPOSinfo']['XPlacement'] = $prevXPlacement + $Mark2Record['AnchorX'] - $Mark1Record['AnchorX']; + $this->OTLdata[$ptr]['GPOSinfo']['YPlacement'] = $prevYPlacement + $Mark2Record['AnchorY'] - $Mark1Record['AnchorY']; + if ($this->debugOTL) { + $this->_dumpproc('GPOS', $lookupID, $subtable, $Type, $PosFormat, $ptr, $currGlyph, $level); + } + return 1; + } + return 0; + } //////////////////////////////////////////////////////////////////////////////// + // LookupType 7: Context positioning Position one or more glyphs in context + //////////////////////////////////////////////////////////////////////////////// + elseif ($Type == 7) { + //=========== + // Format 1: + //=========== + if ($PosFormat == 1) { + throw new \Mpdf\MpdfException("GPOS Lookup Type " . $Type . " Format " . $PosFormat . " not TESTED YET."); + } //=========== + // Format 2: + //=========== + elseif ($PosFormat == 2) { + $CoverageTableOffset = $subtable_offset + $this->read_ushort(); + $InputClassDefOffset = $subtable_offset + $this->read_ushort(); + $PosClassSetCnt = $this->read_ushort(); + $PosClassSetOffset = []; + for ($b = 0; $b < $PosClassSetCnt; $b++) { + $offset = $this->read_ushort(); + if ($offset == 0x0000) { + $PosClassSetOffset[] = $offset; + } else { + $PosClassSetOffset[] = $subtable_offset + $offset; + } + } + + $InputClasses = $this->_getClasses($InputClassDefOffset); + + for ($s = 0; $s < $PosClassSetCnt; $s++) { // $ChainPosClassSet is ordered by input class-may be NULL + // Select $PosClassSet if currGlyph is in First Input Class + if ($PosClassSetOffset[$s] > 0 && isset($InputClasses[$s][$currGID])) { + $this->seek($PosClassSetOffset[$s]); + $PosClassRuleCnt = $this->read_ushort(); + $PosClassRule = []; + for ($b = 0; $b < $PosClassRuleCnt; $b++) { + $PosClassRule[$b] = $PosClassSetOffset[$s] + $this->read_ushort(); + } + + for ($b = 0; $b < $PosClassRuleCnt; $b++) { // EACH RULE + $this->seek($PosClassRule[$b]); + $InputGlyphCount = $this->read_ushort(); + $PosCount = $this->read_ushort(); + + $Input = []; + for ($r = 1; $r < $InputGlyphCount; $r++) { + $Input[$r] = $this->read_ushort(); + } + $inputClass = $s; + + $inputGlyphs = []; + $inputGlyphs[0] = $InputClasses[$inputClass]; + + if ($InputGlyphCount > 1) { + // NB starts at 1 + for ($gcl = 1; $gcl < $InputGlyphCount; $gcl++) { + $classindex = $Input[$gcl]; + if (isset($InputClasses[$classindex])) { + $inputGlyphs[$gcl] = $InputClasses[$classindex]; + } else { + $inputGlyphs[$gcl] = ''; + } + } + } + + // Class 0 contains all the glyphs NOT in the other classes + $class0excl = []; + for ($gc = 1; $gc <= count($InputClasses); $gc++) { + if (is_array($InputClasses[$gc])) { + $class0excl = $class0excl + $InputClasses[$gc]; + } + } + + $backtrackGlyphs = []; + $lookaheadGlyphs = []; + + $matched = $this->checkContextMatchMultipleUni($inputGlyphs, $backtrackGlyphs, $lookaheadGlyphs, $ignore, $ptr, $class0excl); + if ($matched) { + for ($p = 0; $p < $PosCount; $p++) { // EACH LOOKUP + $SequenceIndex[$p] = $this->read_ushort(); + $LookupListIndex[$p] = $this->read_ushort(); + } + + for ($p = 0; $p < $PosCount; $p++) { + // Apply $LookupListIndex at $SequenceIndex + if ($SequenceIndex[$p] >= $InputGlyphCount) { + continue; + } + $lu = $LookupListIndex[$p]; + $luType = $this->GPOSLookups[$lu]['Type']; + $luFlag = $this->GPOSLookups[$lu]['Flag']; + $luMarkFilteringSet = $this->GPOSLookups[$lu]['MarkFilteringSet']; + + $luptr = $matched[$SequenceIndex[$p]]; + $lucurrGlyph = $this->OTLdata[$luptr]['hex']; + $lucurrGID = $this->OTLdata[$luptr]['uni']; + + foreach ($this->GPOSLookups[$lu]['Subtables'] as $luc => $lusubtable_offset) { + $shift = $this->_applyGPOSsubtable($lu, $luc, $luptr, $lucurrGlyph, $lucurrGID, ($lusubtable_offset - $this->GPOS_offset + $this->GSUB_length), $luType, $luFlag, $luMarkFilteringSet, $this->LuCoverage[$lu][$luc], $tag, 1, $is_old_spec); + if ($this->debugOTL && $shift) { + $this->_dumpproc('GPOS', $lookupID, $subtable, $Type, $PosFormat, $ptr, $currGlyph, $level); + } + if ($shift) { + break; + } + } + } + + if (!defined("OMIT_OTL_FIX_3") || OMIT_OTL_FIX_3 != 1) { + return $shift; + } /* OTL_FIX_3 */ + else { + return $InputGlyphCount; // should be + matched ignores in Input Sequence + } + } + } + } + } + + return 0; + } //=========== + // Format 3: + //=========== + elseif ($PosFormat == 3) { + throw new \Mpdf\MpdfException("GPOS Lookup Type " . $Type . " Format " . $PosFormat . " not TESTED YET."); + } else { + throw new \Mpdf\MpdfException("GPOS Lookup Type " . $Type . ", Format " . $PosFormat . " not supported."); + } + } //////////////////////////////////////////////////////////////////////////////// + // LookupType 8: Chained Context positioning Position one or more glyphs in chained context + //////////////////////////////////////////////////////////////////////////////// + elseif ($Type == 8) { + //=========== + // Format 1: + //=========== + if ($PosFormat == 1) { + throw new \Mpdf\MpdfException("GPOS Lookup Type " . $Type . " Format " . $PosFormat . " not TESTED YET."); + return 0; + } //=========== + // Format 2: + //=========== + elseif ($PosFormat == 2) { + $CoverageTableOffset = $subtable_offset + $this->read_ushort(); + $BacktrackClassDefOffset = $subtable_offset + $this->read_ushort(); + $InputClassDefOffset = $subtable_offset + $this->read_ushort(); + $LookaheadClassDefOffset = $subtable_offset + $this->read_ushort(); + $ChainPosClassSetCnt = $this->read_ushort(); + $ChainPosClassSetOffset = []; + for ($b = 0; $b < $ChainPosClassSetCnt; $b++) { + $offset = $this->read_ushort(); + if ($offset == 0x0000) { + $ChainPosClassSetOffset[] = $offset; + } else { + $ChainPosClassSetOffset[] = $subtable_offset + $offset; + } + } + + $BacktrackClasses = $this->_getClasses($BacktrackClassDefOffset); + $InputClasses = $this->_getClasses($InputClassDefOffset); + $LookaheadClasses = $this->_getClasses($LookaheadClassDefOffset); + + for ($s = 0; $s < $ChainPosClassSetCnt; $s++) { // $ChainPosClassSet is ordered by input class-may be NULL + // Select $ChainPosClassSet if currGlyph is in First Input Class + if ($ChainPosClassSetOffset[$s] > 0 && isset($InputClasses[$s][$currGID])) { + $this->seek($ChainPosClassSetOffset[$s]); + $ChainPosClassRuleCnt = $this->read_ushort(); + $ChainPosClassRule = []; + for ($b = 0; $b < $ChainPosClassRuleCnt; $b++) { + $ChainPosClassRule[$b] = $ChainPosClassSetOffset[$s] + $this->read_ushort(); + } + + for ($b = 0; $b < $ChainPosClassRuleCnt; $b++) { // EACH RULE + $this->seek($ChainPosClassRule[$b]); + $BacktrackGlyphCount = $this->read_ushort(); + $Backtrack = []; + for ($r = 0; $r < $BacktrackGlyphCount; $r++) { + $Backtrack[$r] = $this->read_ushort(); + } + $InputGlyphCount = $this->read_ushort(); + $Input = []; + for ($r = 1; $r < $InputGlyphCount; $r++) { + $Input[$r] = $this->read_ushort(); + } + $LookaheadGlyphCount = $this->read_ushort(); + $Lookahead = []; + for ($r = 0; $r < $LookaheadGlyphCount; $r++) { + $Lookahead[$r] = $this->read_ushort(); + } + + $inputClass = $s; //??? + + $inputGlyphs = []; + $inputGlyphs[0] = $InputClasses[$inputClass]; + + if ($InputGlyphCount > 1) { + // NB starts at 1 + for ($gcl = 1; $gcl < $InputGlyphCount; $gcl++) { + $classindex = $Input[$gcl]; + if (isset($InputClasses[$classindex])) { + $inputGlyphs[$gcl] = $InputClasses[$classindex]; + } else { + $inputGlyphs[$gcl] = ''; + } + } + } + + // Class 0 contains all the glyphs NOT in the other classes + $class0excl = []; + for ($gc = 1; $gc <= count($InputClasses); $gc++) { + if (isset($InputClasses[$gc]) && is_array($InputClasses[$gc])) { + $class0excl = $class0excl + $InputClasses[$gc]; + } + } + + if ($BacktrackGlyphCount) { + $backtrackGlyphs = []; + for ($gcl = 0; $gcl < $BacktrackGlyphCount; $gcl++) { + $classindex = $Backtrack[$gcl]; + if (isset($BacktrackClasses[$classindex])) { + $backtrackGlyphs[$gcl] = $BacktrackClasses[$classindex]; + } else { + $backtrackGlyphs[$gcl] = ''; + } + } + } else { + $backtrackGlyphs = []; + } + + // Class 0 contains all the glyphs NOT in the other classes + $bclass0excl = []; + for ($gc = 1; $gc <= count($BacktrackClasses); $gc++) { + if (isset($BacktrackClasses[$gc]) && is_array($BacktrackClasses[$gc])) { + $bclass0excl = $bclass0excl + $BacktrackClasses[$gc]; + } + } + + if ($LookaheadGlyphCount) { + $lookaheadGlyphs = []; + for ($gcl = 0; $gcl < $LookaheadGlyphCount; $gcl++) { + $classindex = $Lookahead[$gcl]; + if (isset($LookaheadClasses[$classindex])) { + $lookaheadGlyphs[$gcl] = $LookaheadClasses[$classindex]; + } else { + $lookaheadGlyphs[$gcl] = ''; + } + } + } else { + $lookaheadGlyphs = []; + } + + // Class 0 contains all the glyphs NOT in the other classes + $lclass0excl = []; + for ($gc = 1; $gc <= count($LookaheadClasses); $gc++) { + if (isset($LookaheadClasses[$gc]) && is_array($LookaheadClasses[$gc])) { + $lclass0excl = $lclass0excl + $LookaheadClasses[$gc]; + } + } + + $matched = $this->checkContextMatchMultipleUni($inputGlyphs, $backtrackGlyphs, $lookaheadGlyphs, $ignore, $ptr, $class0excl, $bclass0excl, $lclass0excl); + if ($matched) { + $PosCount = $this->read_ushort(); + $SequenceIndex = []; + $LookupListIndex = []; + for ($p = 0; $p < $PosCount; $p++) { // EACH LOOKUP + $SequenceIndex[$p] = $this->read_ushort(); + $LookupListIndex[$p] = $this->read_ushort(); + } + + for ($p = 0; $p < $PosCount; $p++) { + // Apply $LookupListIndex at $SequenceIndex + if ($SequenceIndex[$p] >= $InputGlyphCount) { + continue; + } + $lu = $LookupListIndex[$p]; + $luType = $this->GPOSLookups[$lu]['Type']; + $luFlag = $this->GPOSLookups[$lu]['Flag']; + $luMarkFilteringSet = $this->GPOSLookups[$lu]['MarkFilteringSet']; + + $luptr = $matched[$SequenceIndex[$p]]; + $lucurrGlyph = $this->OTLdata[$luptr]['hex']; + $lucurrGID = $this->OTLdata[$luptr]['uni']; + + foreach ($this->GPOSLookups[$lu]['Subtables'] as $luc => $lusubtable_offset) { + $shift = $this->_applyGPOSsubtable($lu, $luc, $luptr, $lucurrGlyph, $lucurrGID, ($lusubtable_offset - $this->GPOS_offset + $this->GSUB_length), $luType, $luFlag, $luMarkFilteringSet, $this->LuCoverage[$lu][$luc], $tag, 1, $is_old_spec); + if ($this->debugOTL && $shift) { + $this->_dumpproc('GPOS', $lookupID, $subtable, $Type, $PosFormat, $ptr, $currGlyph, $level); + } + if ($shift) { + break; + } + } + } + + if (!defined("OMIT_OTL_FIX_3") || OMIT_OTL_FIX_3 != 1) { + return $shift; + } /* OTL_FIX_3 */ + else { + return $InputGlyphCount; // should be + matched ignores in Input Sequence + } + } + } + } + } + + return 0; + } //=========== + // Format 3: + //=========== + elseif ($PosFormat == 3) { + $BacktrackGlyphCount = $this->read_ushort(); + for ($b = 0; $b < $BacktrackGlyphCount; $b++) { + $CoverageBacktrackOffset[] = $subtable_offset + $this->read_ushort(); // in glyph sequence order + } + $InputGlyphCount = $this->read_ushort(); + for ($b = 0; $b < $InputGlyphCount; $b++) { + $CoverageInputOffset[] = $subtable_offset + $this->read_ushort(); // in glyph sequence order + } + $LookaheadGlyphCount = $this->read_ushort(); + for ($b = 0; $b < $LookaheadGlyphCount; $b++) { + $CoverageLookaheadOffset[] = $subtable_offset + $this->read_ushort(); // in glyph sequence order + } + $PosCount = $this->read_ushort(); + $save_pos = $this->_pos; // Save the point just after PosCount + + $CoverageBacktrackGlyphs = []; + for ($b = 0; $b < $BacktrackGlyphCount; $b++) { + $this->seek($CoverageBacktrackOffset[$b]); + $glyphs = $this->_getCoverage(); + $CoverageBacktrackGlyphs[$b] = implode("|", $glyphs); + } + $CoverageInputGlyphs = []; + for ($b = 0; $b < $InputGlyphCount; $b++) { + $this->seek($CoverageInputOffset[$b]); + $glyphs = $this->_getCoverage(); + $CoverageInputGlyphs[$b] = implode("|", $glyphs); + } + $CoverageLookaheadGlyphs = []; + for ($b = 0; $b < $LookaheadGlyphCount; $b++) { + $this->seek($CoverageLookaheadOffset[$b]); + $glyphs = $this->_getCoverage(); + $CoverageLookaheadGlyphs[$b] = implode("|", $glyphs); + } + $matched = $this->checkContextMatchMultiple($CoverageInputGlyphs, $CoverageBacktrackGlyphs, $CoverageLookaheadGlyphs, $ignore, $ptr); + if ($matched) { + $this->seek($save_pos); // Return to just after PosCount + for ($p = 0; $p < $PosCount; $p++) { + // PosLookupRecord + $PosLookupRecord[$p]['SequenceIndex'] = $this->read_ushort(); + $PosLookupRecord[$p]['LookupListIndex'] = $this->read_ushort(); + } + for ($p = 0; $p < $PosCount; $p++) { + // Apply $PosLookupRecord[$p]['LookupListIndex'] at $PosLookupRecord[$p]['SequenceIndex'] + if ($PosLookupRecord[$p]['SequenceIndex'] >= $InputGlyphCount) { + continue; + } + $lu = $PosLookupRecord[$p]['LookupListIndex']; + $luType = $this->GPOSLookups[$lu]['Type']; + $luFlag = $this->GPOSLookups[$lu]['Flag']; + if (isset($this->GPOSLookups[$lu]['MarkFilteringSet'])) { + $luMarkFilteringSet = $this->GPOSLookups[$lu]['MarkFilteringSet']; + } else { + $luMarkFilteringSet = ''; + } + + $luptr = $matched[$PosLookupRecord[$p]['SequenceIndex']]; + $lucurrGlyph = $this->OTLdata[$luptr]['hex']; + $lucurrGID = $this->OTLdata[$luptr]['uni']; + + foreach ($this->GPOSLookups[$lu]['Subtables'] as $luc => $lusubtable_offset) { + $shift = $this->_applyGPOSsubtable($lu, $luc, $luptr, $lucurrGlyph, $lucurrGID, ($lusubtable_offset - $this->GPOS_offset + $this->GSUB_length), $luType, $luFlag, $luMarkFilteringSet, $this->LuCoverage[$lu][$luc], $tag, 1, $is_old_spec); + if ($this->debugOTL && $shift) { + $this->_dumpproc('GPOS', $lookupID, $subtable, $Type, $PosFormat, $ptr, $currGlyph, $level); + } + if ($shift) { + break; + } + } + } + } + } else { + throw new \Mpdf\MpdfException("GPOS Lookup Type " . $Type . ", Format " . $PosFormat . " not supported."); + } + } else { + throw new \Mpdf\MpdfException("GPOS Lookup Type " . $Type . " not supported."); + } + } + + ////////////////////////////////////////////////////////////////////////////////// + // GPOS / GSUB / GCOM (common) functions + ////////////////////////////////////////////////////////////////////////////////// + private function checkContextMatch($Input, $Backtrack, $Lookahead, $ignore, $ptr) + { + // Input etc are single numbers - GSUB Format 6.1 + // Input starts with (1=>xxx) + // return false if no match, else an array of ptr for matches (0=>0, 1=>3,...) + + $current_syllable = (isset($this->OTLdata[$ptr]['syllable']) ? $this->OTLdata[$ptr]['syllable'] : 0); + + // BACKTRACK + $checkpos = $ptr; + for ($i = 0; $i < count($Backtrack); $i++) { + $checkpos--; + while (isset($this->OTLdata[$checkpos]) && strpos($ignore, $this->OTLdata[$checkpos]['hex']) !== false) { + $checkpos--; + } + // If outside scope of current syllable - return no match + if ($this->restrictToSyllable && isset($this->OTLdata[$checkpos]['syllable']) && $this->OTLdata[$checkpos]['syllable'] != $current_syllable) { + return false; + } elseif (!isset($this->OTLdata[$checkpos]) || $this->OTLdata[$checkpos]['uni'] != $Backtrack[$i]) { + return false; + } + } + + // INPUT + $matched = [0 => $ptr]; + $checkpos = $ptr; + for ($i = 1; $i < count($Input); $i++) { + $checkpos++; + while (isset($this->OTLdata[$checkpos]) && strpos($ignore, $this->OTLdata[$checkpos]['hex']) !== false) { + $checkpos++; + } + // If outside scope of current syllable - return no match + if ($this->restrictToSyllable && isset($this->OTLdata[$checkpos]['syllable']) && $this->OTLdata[$checkpos]['syllable'] != $current_syllable) { + return false; + } elseif (isset($this->OTLdata[$checkpos]) && $this->OTLdata[$checkpos]['uni'] == $Input[$i]) { + $matched[] = $checkpos; + } else { + return false; + } + } + + // LOOKAHEAD + for ($i = 0; $i < count($Lookahead); $i++) { + $checkpos++; + while (isset($this->OTLdata[$checkpos]) && strpos($ignore, $this->OTLdata[$checkpos]['hex']) !== false) { + $checkpos++; + } + // If outside scope of current syllable - return no match + if ($this->restrictToSyllable && isset($this->OTLdata[$checkpos]['syllable']) && $this->OTLdata[$checkpos]['syllable'] != $current_syllable) { + return false; + } elseif (!isset($this->OTLdata[$checkpos]) || $this->OTLdata[$checkpos]['uni'] != $Lookahead[$i]) { + return false; + } + } + + return $matched; + } + + private function checkContextMatchMultiple($Input, $Backtrack, $Lookahead, $ignore, $ptr, $class0excl = '', $bclass0excl = '', $lclass0excl = '') + { + // Input etc are string/array of glyph strings - GSUB Format 5.2, 5.3, 6.2, 6.3, GPOS Format 7.2, 7.3, 8.2, 8.3 + // Input starts with (1=>xxx) + // return false if no match, else an array of ptr for matches (0=>0, 1=>3,...) + // $class0excl is the string of glyphs in all classes except Class 0 (GSUB 5.2, 6.2, GPOS 7.2, 8.2) + // $bclass0excl & $lclass0excl are the same for lookahead and backtrack (GSUB 6.2, GPOS 8.2) + + $current_syllable = (isset($this->OTLdata[$ptr]['syllable']) ? $this->OTLdata[$ptr]['syllable'] : 0); + + // BACKTRACK + $checkpos = $ptr; + for ($i = 0; $i < count($Backtrack); $i++) { + $checkpos--; + while (isset($this->OTLdata[$checkpos]) && strpos($ignore, $this->OTLdata[$checkpos]['hex']) !== false) { + $checkpos--; + } + // If outside scope of current syllable - return no match + if ($this->restrictToSyllable && isset($this->OTLdata[$checkpos]['syllable']) && $this->OTLdata[$checkpos]['syllable'] != $current_syllable) { + return false; + } // If Class 0 specified, matches anything NOT in $bclass0excl + elseif (!$Backtrack[$i] && isset($this->OTLdata[$checkpos]) && strpos($bclass0excl, $this->OTLdata[$checkpos]['hex']) !== false) { + return false; + } elseif (!isset($this->OTLdata[$checkpos]) || strpos($Backtrack[$i], $this->OTLdata[$checkpos]['hex']) === false) { + return false; + } + } + + // INPUT + $matched = [0 => $ptr]; + $checkpos = $ptr; + for ($i = 1; $i < count($Input); $i++) { // Start at 1 - already matched the first InputGlyph + $checkpos++; + while (isset($this->OTLdata[$checkpos]) && strpos($ignore, $this->OTLdata[$checkpos]['hex']) !== false) { + $checkpos++; + } + // If outside scope of current syllable - return no match + if ($this->restrictToSyllable && isset($this->OTLdata[$checkpos]['syllable']) && $this->OTLdata[$checkpos]['syllable'] != $current_syllable) { + return false; + } // If Input Class 0 specified, matches anything NOT in $class0excl + elseif (!$Input[$i] && isset($this->OTLdata[$checkpos]) && strpos($class0excl, $this->OTLdata[$checkpos]['hex']) === false) { + $matched[] = $checkpos; + } elseif (isset($this->OTLdata[$checkpos]) && strpos($Input[$i], $this->OTLdata[$checkpos]['hex']) !== false) { + $matched[] = $checkpos; + } else { + return false; + } + } + + // LOOKAHEAD + for ($i = 0; $i < count($Lookahead); $i++) { + $checkpos++; + while (isset($this->OTLdata[$checkpos]) && strpos($ignore, $this->OTLdata[$checkpos]['hex']) !== false) { + $checkpos++; + } + // If outside scope of current syllable - return no match + if ($this->restrictToSyllable && isset($this->OTLdata[$checkpos]['syllable']) && $this->OTLdata[$checkpos]['syllable'] != $current_syllable) { + return false; + } // If Class 0 specified, matches anything NOT in $lclass0excl + elseif (!$Lookahead[$i] && isset($this->OTLdata[$checkpos]) && strpos($lclass0excl, $this->OTLdata[$checkpos]['hex']) !== false) { + return false; + } elseif (!isset($this->OTLdata[$checkpos]) || strpos($Lookahead[$i], $this->OTLdata[$checkpos]['hex']) === false) { + return false; + } + } + return $matched; + } + + private function checkContextMatchMultipleUni($Input, $Backtrack, $Lookahead, $ignore, $ptr, $class0excl = [], $bclass0excl = [], $lclass0excl = []) + { + // Input etc are array of glyphs - GSUB Format 5.2, 5.3, 6.2, 6.3, GPOS Format 7.2, 7.3, 8.2, 8.3 + // Input starts with (1=>xxx) + // return false if no match, else an array of ptr for matches (0=>0, 1=>3,...) + // $class0excl is array of glyphs in all classes except Class 0 (GSUB 5.2, 6.2, GPOS 7.2, 8.2) + // $bclass0excl & $lclass0excl are the same for lookahead and backtrack (GSUB 6.2, GPOS 8.2) + + $current_syllable = (isset($this->OTLdata[$ptr]['syllable']) ? $this->OTLdata[$ptr]['syllable'] : 0); + + // BACKTRACK + $checkpos = $ptr; + for ($i = 0; $i < count($Backtrack); $i++) { + $checkpos--; + while (isset($this->OTLdata[$checkpos]) && strpos($ignore, $this->OTLdata[$checkpos]['hex']) !== false) { + $checkpos--; + } + // If outside scope of current syllable - return no match + if ($this->restrictToSyllable && isset($this->OTLdata[$checkpos]['syllable']) && $this->OTLdata[$checkpos]['syllable'] != $current_syllable) { + return false; + } // If Class 0 specified, matches anything NOT in $bclass0excl + elseif (!$Backtrack[$i] && isset($this->OTLdata[$checkpos]) && isset($bclass0excl[$this->OTLdata[$checkpos]['uni']])) { + return false; + } elseif (!isset($this->OTLdata[$checkpos]) || !isset($Backtrack[$i][$this->OTLdata[$checkpos]['uni']])) { + return false; + } + } + + // INPUT + $matched = [0 => $ptr]; + $checkpos = $ptr; + for ($i = 1; $i < count($Input); $i++) { // Start at 1 - already matched the first InputGlyph + $checkpos++; + while (isset($this->OTLdata[$checkpos]) && strpos($ignore, $this->OTLdata[$checkpos]['hex']) !== false) { + $checkpos++; + } + // If outside scope of current syllable - return no match + if ($this->restrictToSyllable && isset($this->OTLdata[$checkpos]['syllable']) && $this->OTLdata[$checkpos]['syllable'] != $current_syllable) { + return false; + } // If Input Class 0 specified, matches anything NOT in $class0excl + elseif (!$Input[$i] && isset($this->OTLdata[$checkpos]) && !isset($class0excl[$this->OTLdata[$checkpos]['uni']])) { + $matched[] = $checkpos; + } elseif (isset($this->OTLdata[$checkpos]) && isset($Input[$i][$this->OTLdata[$checkpos]['uni']])) { + $matched[] = $checkpos; + } else { + return false; + } + } + + // LOOKAHEAD + for ($i = 0; $i < count($Lookahead); $i++) { + $checkpos++; + while (isset($this->OTLdata[$checkpos]) && strpos($ignore, $this->OTLdata[$checkpos]['hex']) !== false) { + $checkpos++; + } + // If outside scope of current syllable - return no match + if ($this->restrictToSyllable && isset($this->OTLdata[$checkpos]['syllable']) && $this->OTLdata[$checkpos]['syllable'] != $current_syllable) { + return false; + } // If Class 0 specified, matches anything NOT in $lclass0excl + elseif (!$Lookahead[$i] && isset($this->OTLdata[$checkpos]) && isset($lclass0excl[$this->OTLdata[$checkpos]['uni']])) { + return false; + } elseif (!isset($this->OTLdata[$checkpos]) || !isset($Lookahead[$i][$this->OTLdata[$checkpos]['uni']])) { + return false; + } + } + return $matched; + } + + private function _getClassDefinitionTable($offset) + { + if (isset($this->LuDataCache[$this->fontkey][$offset])) { + $GlyphByClass = $this->LuDataCache[$this->fontkey][$offset]; + } else { + $this->seek($offset); + $ClassFormat = $this->read_ushort(); + $GlyphClass = []; + // $GlyphByClass = array(0=>array()); // NB This forces an index[0] + if ($ClassFormat == 1) { + $StartGlyph = $this->read_ushort(); + $GlyphCount = $this->read_ushort(); + for ($i = 0; $i < $GlyphCount; $i++) { + $GlyphClass[$i]['startGlyphID'] = $StartGlyph + $i; + $GlyphClass[$i]['endGlyphID'] = $StartGlyph + $i; + $GlyphClass[$i]['class'] = $this->read_ushort(); + for ($g = $GlyphClass[$i]['startGlyphID']; $g <= $GlyphClass[$i]['endGlyphID']; $g++) { + $GlyphByClass[$GlyphClass[$i]['class']][] = $this->glyphToChar($g); + } + } + } elseif ($ClassFormat == 2) { + $tableCount = $this->read_ushort(); + for ($i = 0; $i < $tableCount; $i++) { + $GlyphClass[$i]['startGlyphID'] = $this->read_ushort(); + $GlyphClass[$i]['endGlyphID'] = $this->read_ushort(); + $GlyphClass[$i]['class'] = $this->read_ushort(); + for ($g = $GlyphClass[$i]['startGlyphID']; $g <= $GlyphClass[$i]['endGlyphID']; $g++) { + $GlyphByClass[$GlyphClass[$i]['class']][] = $this->glyphToChar($g); + } + } + } + ksort($GlyphByClass); + $this->LuDataCache[$this->fontkey][$offset] = $GlyphByClass; + } + return $GlyphByClass; + } + + private function count_bits($n) + { + for ($c = 0; $n; $c++) { + $n &= $n - 1; // clear the least significant bit set + } + return $c; + } + + private function _getValueRecord($ValueFormat) + { + // Common ValueRecord for GPOS + // Only returns 3 possible: $vra['XPlacement'] $vra['YPlacement'] $vra['XAdvance'] + $vra = []; + // Horizontal adjustment for placement - in design units + if (($ValueFormat & 0x0001) == 0x0001) { + $vra['XPlacement'] = $this->read_short(); + } + // Vertical adjustment for placement - in design units + if (($ValueFormat & 0x0002) == 0x0002) { + $vra['YPlacement'] = $this->read_short(); + } + // Horizontal adjustment for advance - in design units (only used for horizontal writing) + if (($ValueFormat & 0x0004) == 0x0004) { + $vra['XAdvance'] = $this->read_short(); + } + // Vertical adjustment for advance - in design units (only used for vertical writing) + if (($ValueFormat & 0x0008) == 0x0008) { + $this->read_short(); + } + // Offset to Device table for horizontal placement-measured from beginning of PosTable (may be NULL) + if (($ValueFormat & 0x0010) == 0x0010) { + $this->read_ushort(); + } + // Offset to Device table for vertical placement-measured from beginning of PosTable (may be NULL) + if (($ValueFormat & 0x0020) == 0x0020) { + $this->read_ushort(); + } + // Offset to Device table for horizontal advance-measured from beginning of PosTable (may be NULL) + if (($ValueFormat & 0x0040) == 0x0040) { + $this->read_ushort(); + } + // Offset to Device table for vertical advance-measured from beginning of PosTable (may be NULL) + if (($ValueFormat & 0x0080) == 0x0080) { + $this->read_ushort(); + } + return $vra; + } + + private function _getAnchorTable($offset = 0) + { + if ($offset) { + $this->seek($offset); + } + $AnchorFormat = $this->read_ushort(); + $XCoordinate = $this->read_short(); + $YCoordinate = $this->read_short(); + // Format 2 specifies additional link to contour point; Format 3 additional Device table + return [$XCoordinate, $YCoordinate]; + } + + private function _getMarkRecord($offset, $MarkPos) + { + $this->seek($offset); + $MarkCount = $this->read_ushort(); + $this->skip($MarkPos * 4); + $Class = $this->read_ushort(); + $MarkAnchor = $offset + $this->read_ushort(); // = Offset to anchor table + list($x, $y) = $this->_getAnchorTable($MarkAnchor); + $MarkRecord = ['Class' => $Class, 'AnchorX' => $x, 'AnchorY' => $y]; + return $MarkRecord; + } + + private function _getGCOMignoreString($flag, $MarkFilteringSet) + { + // If ignoreFlag set, combine all ignore glyphs into -> "(?:( 0FBA1| 0FBA2| 0FBA3)*)" + // else "()" + // for Input - set on secondary Lookup table if in Context, and set Backtrack and Lookahead on Context Lookup + $str = ""; + $ignoreflag = 0; + + // Flag & 0xFF?? = MarkAttachmentType + if ($flag & 0xFF00) { + // "a lookup must ignore any mark glyphs that are not in the specified mark attachment class" + // $this->MarkAttachmentType is already adjusted for this i.e. contains all Marks except those in the MarkAttachmentClassDef table + $MarkAttachmentType = $flag >> 8; + $ignoreflag = $flag; + $str = $this->MarkAttachmentType[$MarkAttachmentType]; + } + + // Flag & 0x0010 = UseMarkFilteringSet + if ($flag & 0x0010) { + throw new \Mpdf\MpdfException("This font [" . $this->fontkey . "] contains MarkGlyphSets - Not tested yet"); + // Change also in ttfontsuni.php + if ($MarkFilteringSet == '') { + throw new \Mpdf\MpdfException("This font [" . $this->fontkey . "] contains MarkGlyphSets - but MarkFilteringSet not set"); + } + $str = $this->MarkGlyphSets[$MarkFilteringSet]; + } + + // If Ignore Marks set, supercedes any above + // Flag & 0x0008 = Ignore Marks - (unless already done with MarkAttachmentType) + if (($flag & 0x0008) == 0x0008 && ($flag & 0xFF00) == 0) { + $ignoreflag = 8; + $str = $this->GlyphClassMarks; + } + + // Flag & 0x0004 = Ignore Ligatures + if (($flag & 0x0004) == 0x0004) { + $ignoreflag += 4; + if ($str) { + $str .= "|"; + } + $str .= $this->GlyphClassLigatures; + } + // Flag & 0x0002 = Ignore BaseGlyphs + if (($flag & 0x0002) == 0x0002) { + $ignoreflag += 2; + if ($str) { + $str .= "|"; + } + $str .= $this->GlyphClassBases; + } + if ($str) { + return "((?:(?:" . $str . "))*)"; + } else { + return "()"; + } + } + + private function _checkGCOMignore($flag, $glyph, $MarkFilteringSet) + { + $ignore = false; + // Flag & 0x0008 = Ignore Marks - (unless already done with MarkAttachmentType) + if (($flag & 0x0008 && ($flag & 0xFF00) == 0) && strpos($this->GlyphClassMarks, $glyph)) { + $ignore = true; + } + if (($flag & 0x0004) && strpos($this->GlyphClassLigatures, $glyph)) { + $ignore = true; + } + if (($flag & 0x0002) && strpos($this->GlyphClassBases, $glyph)) { + $ignore = true; + } + // Flag & 0xFF?? = MarkAttachmentType + if ($flag & 0xFF00) { + // "a lookup must ignore any mark glyphs that are not in the specified mark attachment class" + // $this->MarkAttachmentType is already adjusted for this i.e. contains all Marks except those in the MarkAttachmentClassDef table + if (strpos($this->MarkAttachmentType[($flag >> 8)], $glyph)) { + $ignore = true; + } + } + // Flag & 0x0010 = UseMarkFilteringSet + if (($flag & 0x0010) && strpos($this->MarkGlyphSets[$MarkFilteringSet], $glyph)) { + $ignore = true; + } + return $ignore; + } + + /** + * Bidi algorithm + * + * These functions are called from mpdf after GSUB/GPOS has taken place + * At this stage the bidi-type is in string form + * + * Bidirectional Character Types + * ============================= + * Type Description General Scope + * Strong + * L Left-to-Right LRM, most alphabetic, syllabic, Han ideographs, non-European or non-Arabic digits, ... + * LRE Left-to-Right Embedding LRE + * LRO Left-to-Right Override LRO + * R Right-to-Left RLM, Hebrew alphabet, and related punctuation + * AL Right-to-Left Arabic Arabic, Thaana, and Syriac alphabets, most punctuation specific to those scripts, ... + * RLE Right-to-Left Embedding RLE + * RLO Right-to-Left Override RLO + * Weak + * PDF Pop Directional Format PDF + * EN European Number European digits, Eastern Arabic-Indic digits, ... + * ES European Number Separator Plus sign, minus sign + * ET European Number Terminator Degree sign, currency symbols, ... + * AN Arabic Number Arabic-Indic digits, Arabic decimal and thousands separators, ... + * CS Common Number Separator Colon, comma, full stop (period), No-break space, ... + * NSM Nonspacing Mark Characters marked Mn (Nonspacing_Mark) and Me (Enclosing_Mark) in the Unicode Character Database + * BN Boundary Neutral Default ignorables, non-characters, and control characters, other than those explicitly given other types. + * Neutral + * B Paragraph Separator Paragraph separator, appropriate Newline Functions, higher-level protocol paragraph determination + * S Segment Separator Tab + * WS Whitespace Space, figure space, line separator, form feed, General Punctuation spaces, ... + * ON Other Neutrals All other characters, including OBJECT REPLACEMENT CHARACTER + */ + public function bidiSort($ta, $str, $dir, &$chunkOTLdata, $useGPOS) + { + + $pel = 0; // paragraph embedding level + $maxlevel = 0; + $numchars = count($chunkOTLdata['char_data']); + + // Set the initial paragraph embedding level + if ($dir == 'rtl') { + $pel = 1; + } else { + $pel = 0; + } + + // X1. Begin by setting the current embedding level to the paragraph embedding level. Set the directional override status to neutral. + // Current Embedding Level + $cel = $pel; + // directional override status (-1 is Neutral) + $dos = -1; + $remember = []; + + // Array of characters data + $chardata = []; + + // Process each character iteratively, applying rules X2 through X9. Only embedding levels from 0 to 61 are valid in this phase. + // In the resolution of levels in rules I1 and I2, the maximum embedding level of 62 can be reached. + for ($i = 0; $i < $numchars; ++$i) { + if ($chunkOTLdata['char_data'][$i]['uni'] == 8235) { // RLE + // X2. With each RLE, compute the least greater odd embedding level. + // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to neutral. + // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status. + $next_level = $cel + ($cel % 2) + 1; + if ($next_level < 62) { + $remember[] = ['num' => 8235, 'cel' => $cel, 'dos' => $dos]; + $cel = $next_level; + $dos = -1; + } + } elseif ($chunkOTLdata['char_data'][$i]['uni'] == 8234) { // LRE + // X3. With each LRE, compute the least greater even embedding level. + // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to neutral. + // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status. + $next_level = $cel + 2 - ($cel % 2); + if ($next_level < 62) { + $remember[] = ['num' => 8234, 'cel' => $cel, 'dos' => $dos]; + $cel = $next_level; + $dos = -1; + } + } elseif ($chunkOTLdata['char_data'][$i]['uni'] == 8238) { // RLO + // X4. With each RLO, compute the least greater odd embedding level. + // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to right-to-left. + // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status. + $next_level = $cel + ($cel % 2) + 1; + if ($next_level < 62) { + $remember[] = ['num' => 8238, 'cel' => $cel, 'dos' => $dos]; + $cel = $next_level; + $dos = Ucdn::BIDI_CLASS_R; + } + } elseif ($chunkOTLdata['char_data'][$i]['uni'] == 8237) { // LRO + // X5. With each LRO, compute the least greater even embedding level. + // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to left-to-right. + // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status. + $next_level = $cel + 2 - ($cel % 2); + if ($next_level < 62) { + $remember[] = ['num' => 8237, 'cel' => $cel, 'dos' => $dos]; + $cel = $next_level; + $dos = Ucdn::BIDI_CLASS_L; + } + } elseif ($chunkOTLdata['char_data'][$i]['uni'] == 8236) { // PDF + // X7. With each PDF, determine the matching embedding or override code. If there was a valid matching code, restore (pop) the last remembered (pushed) embedding level and directional override. + if (count($remember)) { + $last = count($remember) - 1; + if (($remember[$last]['num'] == 8235) || ($remember[$last]['num'] == 8234) || ($remember[$last]['num'] == 8238) || + ($remember[$last]['num'] == 8237)) { + $match = array_pop($remember); + $cel = $match['cel']; + $dos = $match['dos']; + } + } + } elseif ($chunkOTLdata['char_data'][$i]['uni'] == 10) { // NEW LINE + // Reset to start values + $cel = $pel; + $dos = -1; + $remember = []; + } else { + // X6. For all types besides RLE, LRE, RLO, LRO, and PDF: + // a. Set the level of the current character to the current embedding level. + // b. When the directional override status is not neutral, reset the current character type to directional override status. + if ($dos != -1) { + $chardir = $dos; + } else { + $chardir = $chunkOTLdata['char_data'][$i]['bidi_class']; + } + // stores string characters and other information + if (isset($chunkOTLdata['GPOSinfo'][$i])) { + $gpos = $chunkOTLdata['GPOSinfo'][$i]; + } else { + $gpos = ''; + } + $chardata[] = ['char' => $chunkOTLdata['char_data'][$i]['uni'], 'level' => $cel, 'type' => $chardir, 'group' => $chunkOTLdata['group'][$i], 'GPOSinfo' => $gpos]; + } + } + + $numchars = count($chardata); + + // X8. All explicit directional embeddings and overrides are completely terminated at the end of each paragraph. + // Paragraph separators are not included in the embedding. + // X9. Remove all RLE, LRE, RLO, LRO, and PDF codes. + // This is effectively done by only saving other codes to chardata + // X10. Determine the start-of-sequence (sor) and end-of-sequence (eor) types, either L or R, for each isolating run sequence. These depend on the higher of the two levels on either side of the sequence boundary: + // For sor, compare the level of the first character in the sequence with the level of the character preceding it in the paragraph or if there is none, with the paragraph embedding level. + // For eor, compare the level of the last character in the sequence with the level of the character following it in the paragraph or if there is none, with the paragraph embedding level. + // If the higher level is odd, the sor or eor is R; otherwise, it is L. + + $prelevel = $pel; + $postlevel = $pel; + $cel = $prelevel; // current embedding level + for ($i = 0; $i < $numchars; ++$i) { + $level = $chardata[$i]['level']; + if ($i == 0) { + $left = $prelevel; + } else { + $left = $chardata[$i - 1]['level']; + } + if ($i == ($numchars - 1)) { + $right = $postlevel; + } else { + $right = $chardata[$i + 1]['level']; + } + $chardata[$i]['sor'] = max($left, $level) % 2 ? Ucdn::BIDI_CLASS_R : Ucdn::BIDI_CLASS_L; + $chardata[$i]['eor'] = max($right, $level) % 2 ? Ucdn::BIDI_CLASS_R : Ucdn::BIDI_CLASS_L; + } + + + + // 3.3.3 Resolving Weak Types + // Weak types are now resolved one level run at a time. At level run boundaries where the type of the character on the other side of the boundary is required, the type assigned to sor or eor is used. + // Nonspacing marks are now resolved based on the previous characters. + // W1. Examine each nonspacing mark (NSM) in the level run, and change the type of the NSM to the type of the previous character. If the NSM is at the start of the level run, it will get the type of sor. + for ($i = 0; $i < $numchars; ++$i) { + if ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_NSM) { + if ($i == 0 || $chardata[$i]['level'] != $chardata[$i - 1]['level']) { + $chardata[$i]['type'] = $chardata[$i]['sor']; + } else { + $chardata[$i]['type'] = $chardata[($i - 1)]['type']; + } + } + } + + // W2. Search backward from each instance of a European number until the first strong type (R, L, AL, or sor) is found. If an AL is found, change the type of the European number to Arabic number. + $prevlevel = -1; + $levcount = 0; + for ($i = 0; $i < $numchars; ++$i) { + if ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_EN) { + $found = false; + for ($j = $levcount; $j >= 0; $j--) { + if ($chardata[$j]['type'] == Ucdn::BIDI_CLASS_AL) { + $chardata[$i]['type'] = Ucdn::BIDI_CLASS_AN; + $found = true; + break; + } elseif (($chardata[$j]['type'] == Ucdn::BIDI_CLASS_L) || ($chardata[$j]['type'] == Ucdn::BIDI_CLASS_R)) { + $found = true; + break; + } + } + } + if ($chardata[$i]['level'] != $prevlevel) { + $levcount = 0; + } else { + ++$levcount; + } + $prevlevel = $chardata[$i]['level']; + } + + // W3. Change all ALs to R. + for ($i = 0; $i < $numchars; ++$i) { + if ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_AL) { + $chardata[$i]['type'] = Ucdn::BIDI_CLASS_R; + } + } + + // W4. A single European separator between two European numbers changes to a European number. A single common separator between two numbers of the same type changes to that type. + for ($i = 1; $i < $numchars; ++$i) { + if (($i + 1) < $numchars && $chardata[($i)]['level'] == $chardata[($i + 1)]['level'] && $chardata[($i)]['level'] == $chardata[($i - 1)]['level']) { + if ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_ES && $chardata[($i - 1)]['type'] == Ucdn::BIDI_CLASS_EN && $chardata[($i + 1)]['type'] == Ucdn::BIDI_CLASS_EN) { + $chardata[$i]['type'] = Ucdn::BIDI_CLASS_EN; + } elseif ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_CS && $chardata[($i - 1)]['type'] == Ucdn::BIDI_CLASS_EN && $chardata[($i + 1)]['type'] == Ucdn::BIDI_CLASS_EN) { + $chardata[$i]['type'] = Ucdn::BIDI_CLASS_EN; + } elseif ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_CS && $chardata[($i - 1)]['type'] == Ucdn::BIDI_CLASS_AN && $chardata[($i + 1)]['type'] == Ucdn::BIDI_CLASS_AN) { + $chardata[$i]['type'] = Ucdn::BIDI_CLASS_AN; + } + } + } + + // W5. A sequence of European terminators adjacent to European numbers changes to all European numbers. + for ($i = 0; $i < $numchars; ++$i) { + if ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_ET) { + if ($i > 0 && $chardata[($i - 1)]['type'] == Ucdn::BIDI_CLASS_EN && $chardata[($i)]['level'] == $chardata[($i - 1)]['level']) { + $chardata[$i]['type'] = Ucdn::BIDI_CLASS_EN; + } else { + $j = $i + 1; + while ($j < $numchars && $chardata[$j]['level'] == $chardata[$i]['level']) { + if ($chardata[$j]['type'] == Ucdn::BIDI_CLASS_EN) { + $chardata[$i]['type'] = Ucdn::BIDI_CLASS_EN; + break; + } elseif ($chardata[$j]['type'] != Ucdn::BIDI_CLASS_ET) { + break; + } + ++$j; + } + } + } + } + + // W6. Otherwise, separators and terminators change to Other Neutral. + for ($i = 0; $i < $numchars; ++$i) { + if (($chardata[$i]['type'] == Ucdn::BIDI_CLASS_ET) || ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_ES) || ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_CS)) { + $chardata[$i]['type'] = Ucdn::BIDI_CLASS_ON; + } + } + + //W7. Search backward from each instance of a European number until the first strong type (R, L, or sor) is found. If an L is found, then change the type of the European number to L. + for ($i = 0; $i < $numchars; ++$i) { + if ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_EN) { + if ($i == 0) { // Start of Level run + if ($chardata[$i]['sor'] == Ucdn::BIDI_CLASS_L) { + $chardata[$i]['type'] = $chardata[$i]['sor']; + } + } else { + for ($j = $i - 1; $j >= 0; $j--) { + if ($chardata[$j]['level'] != $chardata[$i]['level']) { // Level run boundary + if ($chardata[$j + 1]['sor'] == Ucdn::BIDI_CLASS_L) { + $chardata[$i]['type'] = $chardata[$j + 1]['sor']; + } + break; + } elseif ($chardata[$j]['type'] == Ucdn::BIDI_CLASS_L) { + $chardata[$i]['type'] = Ucdn::BIDI_CLASS_L; + break; + } elseif ($chardata[$j]['type'] == Ucdn::BIDI_CLASS_R) { + break; + } + } + } + } + } + + // N1. A sequence of neutrals takes the direction of the surrounding strong text if the text on both sides has the same direction. European and Arabic numbers act as if they were R in terms of their influence on neutrals. Start-of-level-run (sor) and end-of-level-run (eor) are used at level run boundaries. + for ($i = 0; $i < $numchars; ++$i) { + if ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_ON || $chardata[$i]['type'] == Ucdn::BIDI_CLASS_WS) { + $left = -1; + // LEFT + if ($i == 0) { // first char + $left = $chardata[($i)]['sor']; + } elseif ($chardata[($i - 1)]['level'] != $chardata[($i)]['level']) { // run boundary + $left = $chardata[($i)]['sor']; + } elseif ($chardata[($i - 1)]['type'] == Ucdn::BIDI_CLASS_L) { + $left = Ucdn::BIDI_CLASS_L; + } elseif ($chardata[($i - 1)]['type'] == Ucdn::BIDI_CLASS_R || $chardata[($i - 1)]['type'] == Ucdn::BIDI_CLASS_EN || $chardata[($i - 1)]['type'] == Ucdn::BIDI_CLASS_AN) { + $left = Ucdn::BIDI_CLASS_R; + } + // RIGHT + $right = -1; + $j = $i; + // move to the right of any following neutrals OR hit a run boundary + while (($chardata[$j]['type'] == Ucdn::BIDI_CLASS_ON || $chardata[$j]['type'] == Ucdn::BIDI_CLASS_WS) && $j <= ($numchars - 1)) { + if ($j == ($numchars - 1)) { // last char + $right = $chardata[($j)]['eor']; + break; + } elseif ($chardata[($j + 1)]['level'] != $chardata[($j)]['level']) { // run boundary + $right = $chardata[($j)]['eor']; + break; + } elseif ($chardata[($j + 1)]['type'] == Ucdn::BIDI_CLASS_L) { + $right = Ucdn::BIDI_CLASS_L; + break; + } elseif ($chardata[($j + 1)]['type'] == Ucdn::BIDI_CLASS_R || $chardata[($j + 1)]['type'] == Ucdn::BIDI_CLASS_EN || $chardata[($j + 1)]['type'] == Ucdn::BIDI_CLASS_AN) { + $right = Ucdn::BIDI_CLASS_R; + break; + } + $j++; + } + if ($left > -1 && $left == $right) { + $chardata[$i]['orig_type'] = $chardata[$i]['type']; // Need to store the original 'WS' for reference in L1 below + $chardata[$i]['type'] = $left; + } + } + } + + // N2. Any remaining neutrals take the embedding direction + for ($i = 0; $i < $numchars; ++$i) { + if ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_ON || $chardata[$i]['type'] == Ucdn::BIDI_CLASS_WS) { + $chardata[$i]['type'] = ($chardata[$i]['level'] % 2) ? Ucdn::BIDI_CLASS_R : Ucdn::BIDI_CLASS_L; + $chardata[$i]['orig_type'] = $chardata[$i]['type']; // Need to store the original 'WS' for reference in L1 below + } + } + + // I1. For all characters with an even (left-to-right) embedding direction, those of type R go up one level and those of type AN or EN go up two levels. + // I2. For all characters with an odd (right-to-left) embedding direction, those of type L, EN or AN go up one level. + for ($i = 0; $i < $numchars; ++$i) { + $odd = $chardata[$i]['level'] % 2; + if ($odd) { + if (($chardata[$i]['type'] == Ucdn::BIDI_CLASS_L) || ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_AN) || ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_EN)) { + $chardata[$i]['level'] += 1; + } + } else { + if ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_R) { + $chardata[$i]['level'] += 1; + } elseif (($chardata[$i]['type'] == Ucdn::BIDI_CLASS_AN) || ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_EN)) { + $chardata[$i]['level'] += 2; + } + } + $maxlevel = max($chardata[$i]['level'], $maxlevel); + } + + // NB + // Separate into lines at this point************ + // + // L1. On each line, reset the embedding level of the following characters to the paragraph embedding level: + // 1. Segment separators (Tab) 'S', + // 2. Paragraph separators 'B', + // 3. Any sequence of whitespace characters 'WS' preceding a segment separator or paragraph separator, and + // 4. Any sequence of whitespace characters 'WS' at the end of the line. + // The types of characters used here are the original types, not those modified by the previous phase cf N1 and N2******* + // Because a Paragraph Separator breaks lines, there will be at most one per line, at the end of that line. + + for ($i = ($numchars - 1); $i > 0; $i--) { + if ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_WS || (isset($chardata[$i]['orig_type']) && $chardata[$i]['orig_type'] == Ucdn::BIDI_CLASS_WS)) { + $chardata[$i]['level'] = $pel; + } else { + break; + } + } + + + // L2. From the highest level found in the text to the lowest odd level on each line, including intermediate levels not actually present in the text, reverse any contiguous sequence of characters that are at that level or higher. + for ($j = $maxlevel; $j > 0; $j--) { + $ordarray = []; + $revarr = []; + $onlevel = false; + for ($i = 0; $i < $numchars; ++$i) { + if ($chardata[$i]['level'] >= $j) { + $onlevel = true; + + // L4. A character is depicted by a mirrored glyph if and only if (a) the resolved directionality of that character is R, and (b) the Bidi_Mirrored property value of that character is true. + if (isset(Ucdn::$mirror_pairs[$chardata[$i]['char']]) && $chardata[$i]['type'] == Ucdn::BIDI_CLASS_R) { + $chardata[$i]['char'] = Ucdn::$mirror_pairs[$chardata[$i]['char']]; + } + + $revarr[] = $chardata[$i]; + } else { + if ($onlevel) { + $revarr = array_reverse($revarr); + $ordarray = array_merge($ordarray, $revarr); + $revarr = []; + $onlevel = false; + } + $ordarray[] = $chardata[$i]; + } + } + if ($onlevel) { + $revarr = array_reverse($revarr); + $ordarray = array_merge($ordarray, $revarr); + } + $chardata = $ordarray; + } + + $group = ''; + $e = ''; + $GPOS = []; + $cctr = 0; + $rtl_content = 0x0; + foreach ($chardata as $cd) { + $e .= UtfString::code2utf($cd['char']); + $group .= $cd['group']; + if ($useGPOS && is_array($cd['GPOSinfo'])) { + $GPOS[$cctr] = $cd['GPOSinfo']; + $GPOS[$cctr]['wDir'] = ($cd['level'] % 2) ? 'RTL' : 'LTR'; + } + if ($cd['type'] == Ucdn::BIDI_CLASS_L) { + $rtl_content |= 1; + } elseif ($cd['type'] == Ucdn::BIDI_CLASS_R) { + $rtl_content |= 2; + } + $cctr++; + } + + + $chunkOTLdata['group'] = $group; + if ($useGPOS) { + $chunkOTLdata['GPOSinfo'] = $GPOS; + } + + return [$e, $rtl_content]; + } + + /** + * The following versions for BidiSort work on amalgamated chunks to process the whole paragraph + * + * Firstly set the level in the OTLdata - called from fn printbuffer() [_bidiPrepare] + * Secondly re-order - called from fn writeFlowingBlock and FinishFlowingBlock, when already divided into lines. [_bidiReorder] + */ + public function bidiPrepare(&$para, $dir) + { + + // Set the initial paragraph embedding level + $pel = 0; // paragraph embedding level + if ($dir == 'rtl') { + $pel = 1; + } + + // X1. Begin by setting the current embedding level to the paragraph embedding level. Set the directional override status to neutral. + // Current Embedding Level + $cel = $pel; + // directional override status (-1 is Neutral) + $dos = -1; + $remember = []; + $controlchars = false; + $strongrtl = false; + $diid = 0; // direction isolate ID + $dictr = 0; // direction isolate counter + // Process each character iteratively, applying rules X2 through X9. Only embedding levels from 0 to 61 are valid in this phase. + // In the resolution of levels in rules I1 and I2, the maximum embedding level of 62 can be reached. + $numchunks = count($para); + for ($nc = 0; $nc < $numchunks; $nc++) { + $chunkOTLdata = & $para[$nc][18]; + + $numchars = count($chunkOTLdata['char_data']); + for ($i = 0; $i < $numchars; ++$i) { + if ($chunkOTLdata['char_data'][$i]['uni'] == 8235) { // RLE + // X2. With each RLE, compute the least greater odd embedding level. + // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to neutral. + // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status. + $next_level = $cel + ($cel % 2) + 1; + if ($next_level < 62) { + $remember[] = ['num' => 8235, 'cel' => $cel, 'dos' => $dos]; + $cel = $next_level; + $dos = -1; + $controlchars = true; + } + } elseif ($chunkOTLdata['char_data'][$i]['uni'] == 8234) { // LRE + // X3. With each LRE, compute the least greater even embedding level. + // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to neutral. + // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status. + $next_level = $cel + 2 - ($cel % 2); + if ($next_level < 62) { + $remember[] = ['num' => 8234, 'cel' => $cel, 'dos' => $dos]; + $cel = $next_level; + $dos = -1; + $controlchars = true; + } + } elseif ($chunkOTLdata['char_data'][$i]['uni'] == 8238) { // RLO + // X4. With each RLO, compute the least greater odd embedding level. + // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to right-to-left. + // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status. + $next_level = $cel + ($cel % 2) + 1; + if ($next_level < 62) { + $remember[] = ['num' => 8238, 'cel' => $cel, 'dos' => $dos]; + $cel = $next_level; + $dos = Ucdn::BIDI_CLASS_R; + $controlchars = true; + } + } elseif ($chunkOTLdata['char_data'][$i]['uni'] == 8237) { // LRO + // X5. With each LRO, compute the least greater even embedding level. + // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to left-to-right. + // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status. + $next_level = $cel + 2 - ($cel % 2); + if ($next_level < 62) { + $remember[] = ['num' => 8237, 'cel' => $cel, 'dos' => $dos]; + $cel = $next_level; + $dos = Ucdn::BIDI_CLASS_L; + $controlchars = true; + } + } elseif ($chunkOTLdata['char_data'][$i]['uni'] == 8236) { // PDF + // X7. With each PDF, determine the matching embedding or override code. If there was a valid matching code, restore (pop) the last remembered (pushed) embedding level and directional override. + if (count($remember)) { + $last = count($remember) - 1; + if (($remember[$last]['num'] == 8235) || ($remember[$last]['num'] == 8234) || ($remember[$last]['num'] == 8238) || + ($remember[$last]['num'] == 8237)) { + $match = array_pop($remember); + $cel = $match['cel']; + $dos = $match['dos']; + } + } + } elseif ($chunkOTLdata['char_data'][$i]['uni'] == 8294 || $chunkOTLdata['char_data'][$i]['uni'] == 8295 || + $chunkOTLdata['char_data'][$i]['uni'] == 8296) { // LRI // RLI // FSI + // X5a. With each RLI: + // X5b. With each LRI: + // X5c. With each FSI, apply rules P2 and P3 for First Strong character + // Set the RLI/LRI/FSI embedding level to the embedding level of the last entry on the directional status stack. + if ($dos != -1) { + $chardir = $dos; + } else { + $chardir = $chunkOTLdata['char_data'][$i]['bidi_class']; + } + $chunkOTLdata['char_data'][$i]['level'] = $cel; + $chunkOTLdata['char_data'][$i]['type'] = $chardir; + $chunkOTLdata['char_data'][$i]['diid'] = $diid; + + $fsi = ''; + // X5c. With each FSI, apply rules P2 and P3 within the isolate run for First Strong character + if ($chunkOTLdata['char_data'][$i]['uni'] == 8296) { // FSI + $lvl = 0; + $nc2 = $nc; + $i2 = $i; + while (!($nc2 == ($numchunks - 1) && $i2 == ((count($para[$nc2][18]['char_data'])) - 1))) { // while not at end of last chunk + $i2++; + if ($i2 >= count($para[$nc2][18]['char_data'])) { + $nc2++; + $i2 = 0; + } + if ($lvl > 0) { + continue; + } + if ($para[$nc2][18]['char_data'][$i2]['uni'] == 8294 || $para[$nc2][18]['char_data'][$i2]['uni'] == 8295 || $para[$nc2][18]['char_data'][$i2]['uni'] == 8296) { + $lvl++; + continue; + } + if ($para[$nc2][18]['char_data'][$i2]['uni'] == 8297) { + $lvl--; + if ($lvl < 0) { + break; + } + } + if ($para[$nc2][18]['char_data'][$i2]['bidi_class'] === Ucdn::BIDI_CLASS_L || $para[$nc2][18]['char_data'][$i2]['bidi_class'] == Ucdn::BIDI_CLASS_AL || $para[$nc2][18]['char_data'][$i2]['bidi_class'] === Ucdn::BIDI_CLASS_R) { + $fsi = $para[$nc2][18]['char_data'][$i2]['bidi_class']; + break; + } + } + // if fsi not found, fsi is same as paragraph embedding level + if (!$fsi && $fsi !== 0) { + if ($pel == 1) { + $fsi = Ucdn::BIDI_CLASS_R; + } else { + $fsi = Ucdn::BIDI_CLASS_L; + } + } + } + + if ($chunkOTLdata['char_data'][$i]['uni'] == 8294 || $fsi === Ucdn::BIDI_CLASS_L) { // LRI or FSI-L + // Compute the least even embedding level greater than the embedding level of the last entry on the directional status stack. + $next_level = $cel + 2 - ($cel % 2); + } elseif ($chunkOTLdata['char_data'][$i]['uni'] == 8295 || $fsi == Ucdn::BIDI_CLASS_R || $fsi == Ucdn::BIDI_CLASS_AL) { // RLI or FSI-R + // Compute the least odd embedding level greater than the embedding level of the last entry on the directional status stack. + $next_level = $cel + ($cel % 2) + 1; + } + + + // Increment the isolate count by one, and push an entry consisting of the new embedding level, + // neutral directional override status, and true directional isolate status onto the directional status stack. + $remember[] = ['num' => $chunkOTLdata['char_data'][$i]['uni'], 'cel' => $cel, 'dos' => $dos, 'diid' => $diid]; + $cel = $next_level; + $dos = -1; + $diid = ++$dictr; // Set new direction isolate ID after incrementing direction isolate counter + + $controlchars = true; + } elseif ($chunkOTLdata['char_data'][$i]['uni'] == 8297) { // PDI + // X6a. With each PDI, perform the following steps: + // Pop the last entry from the directional status stack and decrement the isolate count by one. + while (count($remember)) { + $last = count($remember) - 1; + if (($remember[$last]['num'] == 8294) || ($remember[$last]['num'] == 8295) || ($remember[$last]['num'] == 8296)) { + $match = array_pop($remember); + $cel = $match['cel']; + $dos = $match['dos']; + $diid = $match['diid']; + break; + } // End/close any open embedding states not explicitly closed during the isolate + elseif (($remember[$last]['num'] == 8235) || ($remember[$last]['num'] == 8234) || ($remember[$last]['num'] == 8238) || + ($remember[$last]['num'] == 8237)) { + $match = array_pop($remember); + } + } + // In all cases, set the PDI’s level to the embedding level of the last entry on the directional status stack left after the steps above. + // NB The level assigned to an isolate initiator is always the same as that assigned to the matching PDI. + if ($dos != -1) { + $chardir = $dos; + } else { + $chardir = $chunkOTLdata['char_data'][$i]['bidi_class']; + } + $chunkOTLdata['char_data'][$i]['level'] = $cel; + $chunkOTLdata['char_data'][$i]['type'] = $chardir; + $chunkOTLdata['char_data'][$i]['diid'] = $diid; + $controlchars = true; + } elseif ($chunkOTLdata['char_data'][$i]['uni'] == 10) { // NEW LINE + // Reset to start values + $cel = $pel; + $dos = -1; + $remember = []; + } else { + // X6. For all types besides RLE, LRE, RLO, LRO, and PDF: + // a. Set the level of the current character to the current embedding level. + // b. When the directional override status is not neutral, reset the current character type to directional override status. + if ($dos != -1) { + $chardir = $dos; + } else { + $chardir = $chunkOTLdata['char_data'][$i]['bidi_class']; + if ($chardir == Ucdn::BIDI_CLASS_R || $chardir == Ucdn::BIDI_CLASS_AL) { + $strongrtl = true; + } + } + $chunkOTLdata['char_data'][$i]['level'] = $cel; + $chunkOTLdata['char_data'][$i]['type'] = $chardir; + $chunkOTLdata['char_data'][$i]['diid'] = $diid; + } + } + // X8. All explicit directional embeddings and overrides are completely terminated at the end of each paragraph. + // Paragraph separators are not included in the embedding. + // X9. Remove all RLE, LRE, RLO, LRO, and PDF codes. + if ($controlchars) { + $this->removeChar($para[$nc][0], $para[$nc][18], "\xe2\x80\xaa"); + $this->removeChar($para[$nc][0], $para[$nc][18], "\xe2\x80\xab"); + $this->removeChar($para[$nc][0], $para[$nc][18], "\xe2\x80\xac"); + $this->removeChar($para[$nc][0], $para[$nc][18], "\xe2\x80\xad"); + $this->removeChar($para[$nc][0], $para[$nc][18], "\xe2\x80\xae"); + preg_replace("/\x{202a}-\x{202e}/u", '', $para[$nc][0]); + } + } + + // Remove any blank chunks made by removing directional codes + $numchunks = count($para); + for ($nc = ($numchunks - 1); $nc >= 0; $nc--) { + if (count($para[$nc][18]['char_data']) == 0) { + array_splice($para, $nc, 1); + } + } + if ($dir != 'rtl' && !$strongrtl && !$controlchars) { + return; + } + + $numchunks = count($para); + + // X10. Determine the start-of-sequence (sor) and end-of-sequence (eor) types, either L or R, for each isolating run sequence. These depend on the higher of the two levels on either side of the sequence boundary: + // For sor, compare the level of the first character in the sequence with the level of the character preceding it in the paragraph or if there is none, with the paragraph embedding level. + // For eor, compare the level of the last character in the sequence with the level of the character following it in the paragraph or if there is none, with the paragraph embedding level. + // If the higher level is odd, the sor or eor is R; otherwise, it is L. + + for ($ir = 0; $ir <= $dictr; $ir++) { + $prelevel = $pel; + $postlevel = $pel; + $firstchar = true; + for ($nc = 0; $nc < $numchunks; $nc++) { + $chardata = & $para[$nc][18]['char_data']; + $numchars = count($chardata); + for ($i = 0; $i < $numchars; ++$i) { + if (!isset($chardata[$i]['diid']) || $chardata[$i]['diid'] != $ir) { + continue; + } // Ignore characters in a different isolate run + $right = $postlevel; + $nc2 = $nc; + $i2 = $i; + while (!($nc2 == ($numchunks - 1) && $i2 == ((count($para[$nc2][18]['char_data'])) - 1))) { // while not at end of last chunk + $i2++; + if ($i2 >= count($para[$nc2][18]['char_data'])) { + $nc2++; + $i2 = 0; + } + + if (isset($para[$nc2][18]['char_data'][$i2]['diid']) && $para[$nc2][18]['char_data'][$i2]['diid'] == $ir) { + $right = $para[$nc2][18]['char_data'][$i2]['level']; + break; + } + } + + $level = $chardata[$i]['level']; + if ($firstchar || $level != $prelevel) { + $chardata[$i]['sor'] = max($prelevel, $level) % 2 ? Ucdn::BIDI_CLASS_R : Ucdn::BIDI_CLASS_L; + } + if (($nc == ($numchunks - 1) && $i == ($numchars - 1)) || $level != $right) { + $chardata[$i]['eor'] = max($right, $level) % 2 ? Ucdn::BIDI_CLASS_R : Ucdn::BIDI_CLASS_L; + } + $prelevel = $level; + $firstchar = false; + } + } + } + + + // 3.3.3 Resolving Weak Types + // Weak types are now resolved one level run at a time. At level run boundaries where the type of the character on the other side of the boundary is required, the type assigned to sor or eor is used. + // Nonspacing marks are now resolved based on the previous characters. + // W1. Examine each nonspacing mark (NSM) in the level run, and change the type of the NSM to the type of the previous character. If the NSM is at the start of the level run, it will get the type of sor. + for ($ir = 0; $ir <= $dictr; $ir++) { + $prevtype = 0; + for ($nc = 0; $nc < $numchunks; $nc++) { + $chardata = & $para[$nc][18]['char_data']; + $numchars = count($chardata); + for ($i = 0; $i < $numchars; ++$i) { + if (!isset($chardata[$i]['diid']) || $chardata[$i]['diid'] != $ir) { + continue; + } // Ignore characters in a different isolate run + if ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_NSM) { + if (isset($chardata[$i]['sor'])) { + $chardata[$i]['type'] = $chardata[$i]['sor']; + } else { + $chardata[$i]['type'] = $prevtype; + } + } + $prevtype = $chardata[$i]['type']; + } + } + } + + // W2. Search backward from each instance of a European number until the first strong type (R, L, AL or sor) is found. If an AL is found, change the type of the European number to Arabic number. + for ($ir = 0; $ir <= $dictr; $ir++) { + $laststrongtype = -1; + for ($nc = 0; $nc < $numchunks; $nc++) { + $chardata = & $para[$nc][18]['char_data']; + $numchars = count($chardata); + for ($i = 0; $i < $numchars; ++$i) { + if (!isset($chardata[$i]['diid']) || $chardata[$i]['diid'] != $ir) { + continue; + } // Ignore characters in a different isolate run + if (isset($chardata[$i]['sor'])) { + $laststrongtype = $chardata[$i]['sor']; + } + if ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_EN && $laststrongtype == Ucdn::BIDI_CLASS_AL) { + $chardata[$i]['type'] = Ucdn::BIDI_CLASS_AN; + } + if ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_L || $chardata[$i]['type'] == Ucdn::BIDI_CLASS_R || $chardata[$i]['type'] == Ucdn::BIDI_CLASS_AL) { + $laststrongtype = $chardata[$i]['type']; + } + } + } + } + + + // W3. Change all ALs to R. + for ($nc = 0; $nc < $numchunks; $nc++) { + $chardata = & $para[$nc][18]['char_data']; + $numchars = count($chardata); + for ($i = 0; $i < $numchars; ++$i) { + if (isset($chardata[$i]['type']) && $chardata[$i]['type'] == Ucdn::BIDI_CLASS_AL) { + $chardata[$i]['type'] = Ucdn::BIDI_CLASS_R; + } + } + } + + + // W4. A single European separator between two European numbers changes to a European number. A single common separator between two numbers of the same type changes to that type. + for ($ir = 0; $ir <= $dictr; $ir++) { + $prevtype = -1; + $nexttype = -1; + for ($nc = 0; $nc < $numchunks; $nc++) { + $chardata = & $para[$nc][18]['char_data']; + $numchars = count($chardata); + for ($i = 0; $i < $numchars; ++$i) { + if (!isset($chardata[$i]['diid']) || $chardata[$i]['diid'] != $ir) { + continue; + } // Ignore characters in a different isolate run + // Get next type + $nexttype = -1; + $nc2 = $nc; + $i2 = $i; + while (!($nc2 == ($numchunks - 1) && $i2 == ((count($para[$nc2][18]['char_data'])) - 1))) { // while not at end of last chunk + $i2++; + if ($i2 >= count($para[$nc2][18]['char_data'])) { + $nc2++; + $i2 = 0; + } + + if (isset($para[$nc2][18]['char_data'][$i2]['diid']) && $para[$nc2][18]['char_data'][$i2]['diid'] == $ir) { + $nexttype = $para[$nc2][18]['char_data'][$i2]['type']; + break; + } + } + + if (!isset($chardata[$i]['sor']) && !isset($chardata[$i]['eor'])) { + if ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_ES && $prevtype == Ucdn::BIDI_CLASS_EN && $nexttype == Ucdn::BIDI_CLASS_EN) { + $chardata[$i]['type'] = Ucdn::BIDI_CLASS_EN; + } elseif ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_CS && $prevtype == Ucdn::BIDI_CLASS_EN && $nexttype == Ucdn::BIDI_CLASS_EN) { + $chardata[$i]['type'] = Ucdn::BIDI_CLASS_EN; + } elseif ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_CS && $prevtype == Ucdn::BIDI_CLASS_AN && $nexttype == Ucdn::BIDI_CLASS_AN) { + $chardata[$i]['type'] = Ucdn::BIDI_CLASS_AN; + } + } + $prevtype = $chardata[$i]['type']; + } + } + } + + // W5. A sequence of European terminators adjacent to European numbers changes to all European numbers. + for ($ir = 0; $ir <= $dictr; $ir++) { + $prevtype = -1; + $nexttype = -1; + for ($nc = 0; $nc < $numchunks; $nc++) { + $chardata = & $para[$nc][18]['char_data']; + $numchars = count($chardata); + for ($i = 0; $i < $numchars; ++$i) { + if (!isset($chardata[$i]['diid']) || $chardata[$i]['diid'] != $ir) { + continue; + } // Ignore characters in a different isolate run + if (isset($chardata[$i]['sor'])) { + $prevtype = $chardata[$i]['sor']; + } + + if ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_ET) { + if ($prevtype == Ucdn::BIDI_CLASS_EN) { + $chardata[$i]['type'] = Ucdn::BIDI_CLASS_EN; + } elseif (!isset($chardata[$i]['eor'])) { + $nexttype = -1; + $nc2 = $nc; + $i2 = $i; + while (!($nc2 == ($numchunks - 1) && $i2 == ((count($para[$nc2][18]['char_data'])) - 1))) { // while not at end of last chunk + $i2++; + if ($i2 >= count($para[$nc2][18]['char_data'])) { + $nc2++; + $i2 = 0; + } + if (!isset($para[$nc2][18]['char_data'][$i2]['diid']) || $para[$nc2][18]['char_data'][$i2]['diid'] != $ir) { + continue; + } + $nexttype = $para[$nc2][18]['char_data'][$i2]['type']; + if (isset($para[$nc2][18]['char_data'][$i2]['sor'])) { + break; + } + if ($nexttype == Ucdn::BIDI_CLASS_EN) { + $chardata[$i]['type'] = Ucdn::BIDI_CLASS_EN; + break; + } elseif ($nexttype != Ucdn::BIDI_CLASS_ET) { + break; + } + } + } + } + $prevtype = $chardata[$i]['type']; + } + } + } + + // W6. Otherwise, separators and terminators change to Other Neutral. + for ($nc = 0; $nc < $numchunks; $nc++) { + $chardata = & $para[$nc][18]['char_data']; + $numchars = count($chardata); + for ($i = 0; $i < $numchars; ++$i) { + if (isset($chardata[$i]['type']) && (($chardata[$i]['type'] == Ucdn::BIDI_CLASS_ET) || ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_ES) || ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_CS))) { + $chardata[$i]['type'] = Ucdn::BIDI_CLASS_ON; + } + } + } + + //W7. Search backward from each instance of a European number until the first strong type (R, L, or sor) is found. If an L is found, then change the type of the European number to L. + for ($ir = 0; $ir <= $dictr; $ir++) { + $laststrongtype = -1; + for ($nc = 0; $nc < $numchunks; $nc++) { + $chardata = & $para[$nc][18]['char_data']; + $numchars = count($chardata); + for ($i = 0; $i < $numchars; ++$i) { + if (!isset($chardata[$i]['diid']) || $chardata[$i]['diid'] != $ir) { + continue; + } // Ignore characters in a different isolate run + if (isset($chardata[$i]['sor'])) { + $laststrongtype = $chardata[$i]['sor']; + } + if (isset($chardata[$i]['type']) && $chardata[$i]['type'] == Ucdn::BIDI_CLASS_EN && $laststrongtype == Ucdn::BIDI_CLASS_L) { + $chardata[$i]['type'] = Ucdn::BIDI_CLASS_L; + } + if (isset($chardata[$i]['type']) && ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_L || $chardata[$i]['type'] == Ucdn::BIDI_CLASS_R || $chardata[$i]['type'] == Ucdn::BIDI_CLASS_AL)) { + $laststrongtype = $chardata[$i]['type']; + } + } + } + } + + // N1. A sequence of neutrals takes the direction of the surrounding strong text if the text on both sides has the same direction. European and Arabic numbers act as if they were R in terms of their influence on neutrals. Start-of-level-run (sor) and end-of-level-run (eor) are used at level run boundaries. + for ($ir = 0; $ir <= $dictr; $ir++) { + $laststrongtype = -1; + for ($nc = 0; $nc < $numchunks; $nc++) { + $chardata = & $para[$nc][18]['char_data']; + $numchars = count($chardata); + for ($i = 0; $i < $numchars; ++$i) { + if (!isset($chardata[$i]['diid']) || $chardata[$i]['diid'] != $ir) { + continue; + } // Ignore characters in a different isolate run + if (isset($chardata[$i]['sor'])) { + $laststrongtype = $chardata[$i]['sor']; + } + if ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_ON || $chardata[$i]['type'] == Ucdn::BIDI_CLASS_WS) { + $left = -1; + // LEFT + if ($laststrongtype == Ucdn::BIDI_CLASS_R || $laststrongtype == Ucdn::BIDI_CLASS_EN || $laststrongtype == Ucdn::BIDI_CLASS_AN) { + $left = Ucdn::BIDI_CLASS_R; + } elseif ($laststrongtype == Ucdn::BIDI_CLASS_L) { + $left = Ucdn::BIDI_CLASS_L; + } + // RIGHT + $right = -1; + // move to the right of any following neutrals OR hit a run boundary + + if (isset($chardata[$i]['eor'])) { + $right = $chardata[$i]['eor']; + } else { + $nexttype = -1; + $nc2 = $nc; + $i2 = $i; + while (!($nc2 == ($numchunks - 1) && $i2 == ((count($para[$nc2][18]['char_data'])) - 1))) { // while not at end of last chunk + $i2++; + if ($i2 >= count($para[$nc2][18]['char_data'])) { + $nc2++; + $i2 = 0; + } + if (!isset($para[$nc2][18]['char_data'][$i2]['diid']) || $para[$nc2][18]['char_data'][$i2]['diid'] != $ir) { + continue; + } + $nexttype = $para[$nc2][18]['char_data'][$i2]['type']; + if ($nexttype == Ucdn::BIDI_CLASS_R || $nexttype == Ucdn::BIDI_CLASS_EN || $nexttype == Ucdn::BIDI_CLASS_AN) { + $right = Ucdn::BIDI_CLASS_R; + break; + } elseif ($nexttype == Ucdn::BIDI_CLASS_L) { + $right = Ucdn::BIDI_CLASS_L; + break; + } elseif (isset($para[$nc2][18]['char_data'][$i2]['eor'])) { + $right = $para[$nc2][18]['char_data'][$i2]['eor']; + break; + } + } + } + + if ($left > -1 && $left == $right) { + $chardata[$i]['orig_type'] = $chardata[$i]['type']; // Need to store the original 'WS' for reference in L1 below + $chardata[$i]['type'] = $left; + } + } elseif ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_L || $chardata[$i]['type'] == Ucdn::BIDI_CLASS_R || $chardata[$i]['type'] == Ucdn::BIDI_CLASS_EN || $chardata[$i]['type'] == Ucdn::BIDI_CLASS_AN) { + $laststrongtype = $chardata[$i]['type']; + } + } + } + } + + // N2. Any remaining neutrals take the embedding direction + for ($nc = 0; $nc < $numchunks; $nc++) { + $chardata = & $para[$nc][18]['char_data']; + $numchars = count($chardata); + for ($i = 0; $i < $numchars; ++$i) { + if (isset($chardata[$i]['type']) && ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_ON || $chardata[$i]['type'] == Ucdn::BIDI_CLASS_WS)) { + $chardata[$i]['orig_type'] = $chardata[$i]['type']; // Need to store the original 'WS' for reference in L1 below + $chardata[$i]['type'] = ($chardata[$i]['level'] % 2) ? Ucdn::BIDI_CLASS_R : Ucdn::BIDI_CLASS_L; + } + } + } + + // I1. For all characters with an even (left-to-right) embedding direction, those of type R go up one level and those of type AN or EN go up two levels. + // I2. For all characters with an odd (right-to-left) embedding direction, those of type L, EN or AN go up one level. + for ($nc = 0; $nc < $numchunks; $nc++) { + $chardata = & $para[$nc][18]['char_data']; + $numchars = count($chardata); + for ($i = 0; $i < $numchars; ++$i) { + if (isset($chardata[$i]['level'])) { + $odd = $chardata[$i]['level'] % 2; + if ($odd) { + if (($chardata[$i]['type'] == Ucdn::BIDI_CLASS_L) || ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_AN) || ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_EN)) { + $chardata[$i]['level'] += 1; + } + } else { + if ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_R) { + $chardata[$i]['level'] += 1; + } elseif (($chardata[$i]['type'] == Ucdn::BIDI_CLASS_AN) || ($chardata[$i]['type'] == Ucdn::BIDI_CLASS_EN)) { + $chardata[$i]['level'] += 2; + } + } + } + } + } + + // Remove Isolate formatters + $numchunks = count($para); + if ($controlchars) { + for ($nc = 0; $nc < $numchunks; $nc++) { + $this->removeChar($para[$nc][0], $para[$nc][18], "\xe2\x81\xa6"); + $this->removeChar($para[$nc][0], $para[$nc][18], "\xe2\x81\xa7"); + $this->removeChar($para[$nc][0], $para[$nc][18], "\xe2\x81\xa8"); + $this->removeChar($para[$nc][0], $para[$nc][18], "\xe2\x81\xa9"); + preg_replace("/\x{2066}-\x{2069}/u", '', $para[$nc][0]); + } + // Remove any blank chunks made by removing directional codes + for ($nc = ($numchunks - 1); $nc >= 0; $nc--) { + if (count($para[$nc][18]['char_data']) == 0) { + array_splice($para, $nc, 1); + } + } + } + } + + /** + * Reorder, once divided into lines + */ + public function bidiReorder(&$chunkorder, &$content, &$cOTLdata, $blockdir) + { + + $bidiData = []; + + // First combine into one array (and get the highest level in use) + $numchunks = count($content); + $maxlevel = 0; + for ($nc = 0; $nc < $numchunks; $nc++) { + $numchars = isset($cOTLdata[$nc]['char_data']) ? count($cOTLdata[$nc]['char_data']) : 0; + for ($i = 0; $i < $numchars; ++$i) { + $carac = []; + if (isset($cOTLdata[$nc]['GPOSinfo'][$i])) { + $carac['GPOSinfo'] = $cOTLdata[$nc]['GPOSinfo'][$i]; + } + $carac['uni'] = $cOTLdata[$nc]['char_data'][$i]['uni']; + if (isset($cOTLdata[$nc]['char_data'][$i]['type'])) { + $carac['type'] = $cOTLdata[$nc]['char_data'][$i]['type']; + } + if (isset($cOTLdata[$nc]['char_data'][$i]['level'])) { + $carac['level'] = $cOTLdata[$nc]['char_data'][$i]['level']; + } + if (isset($cOTLdata[$nc]['char_data'][$i]['orig_type'])) { + $carac['orig_type'] = $cOTLdata[$nc]['char_data'][$i]['orig_type']; + } + $carac['group'] = $cOTLdata[$nc]['group'][$i]; + $carac['chunkid'] = $chunkorder[$nc]; // gives font id and/or object ID + + $maxlevel = max((isset($carac['level']) ? $carac['level'] : 0), $maxlevel); + $bidiData[] = $carac; + } + } + if ($maxlevel == 0) { + return; + } + + $numchars = count($bidiData); + + // L1. On each line, reset the embedding level of the following characters to the paragraph embedding level: + // 1. Segment separators (Tab) 'S', + // 2. Paragraph separators 'B', + // 3. Any sequence of whitespace characters 'WS' preceding a segment separator or paragraph separator, and + // 4. Any sequence of whitespace characters 'WS' at the end of the line. + // The types of characters used here are the original types, not those modified by the previous phase cf N1 and N2******* + // Because a Paragraph Separator breaks lines, there will be at most one per line, at the end of that line. + // Set the initial paragraph embedding level + if ($blockdir == 'rtl') { + $pel = 1; + } else { + $pel = 0; + } + + for ($i = ($numchars - 1); $i > 0; $i--) { + if ($bidiData[$i]['type'] == Ucdn::BIDI_CLASS_WS || (isset($bidiData[$i]['orig_type']) && $bidiData[$i]['orig_type'] == Ucdn::BIDI_CLASS_WS)) { + $bidiData[$i]['level'] = $pel; + } else { + break; + } + } + + // L2. From the highest level found in the text to the lowest odd level on each line, including intermediate levels not actually present in the text, reverse any contiguous sequence of characters that are at that level or higher. + for ($j = $maxlevel; $j > 0; $j--) { + $ordarray = []; + $revarr = []; + $onlevel = false; + for ($i = 0; $i < $numchars; ++$i) { + if ($bidiData[$i]['level'] >= $j) { + $onlevel = true; + // L4. A character is depicted by a mirrored glyph if and only if (a) the resolved directionality of that character is R, and (b) the Bidi_Mirrored property value of that character is true. + if (isset(Ucdn::$mirror_pairs[$bidiData[$i]['uni']]) && $bidiData[$i]['type'] == Ucdn::BIDI_CLASS_R) { + $bidiData[$i]['uni'] = Ucdn::$mirror_pairs[$bidiData[$i]['uni']]; + } + + $revarr[] = $bidiData[$i]; + } else { + if ($onlevel) { + $revarr = array_reverse($revarr); + $ordarray = array_merge($ordarray, $revarr); + $revarr = []; + $onlevel = false; + } + $ordarray[] = $bidiData[$i]; + } + } + if ($onlevel) { + $revarr = array_reverse($revarr); + $ordarray = array_merge($ordarray, $revarr); + } + $bidiData = $ordarray; + } + + $content = []; + $cOTLdata = []; + $chunkorder = []; + + $nc = -1; // New chunk order ID + $chunkid = -1; + + foreach ($bidiData as $carac) { + if ($carac['chunkid'] != $chunkid) { + $nc++; + $chunkorder[$nc] = $carac['chunkid']; + $cctr = 0; + $content[$nc] = ''; + $cOTLdata[$nc]['group'] = ''; + } + if ($carac['uni'] != 0xFFFC) { // Object replacement character (65532) + $content[$nc] .= UtfString::code2utf($carac['uni']); + $cOTLdata[$nc]['group'] .= $carac['group']; + if (!empty($carac['GPOSinfo'])) { + if (isset($carac['GPOSinfo'])) { + $cOTLdata[$nc]['GPOSinfo'][$cctr] = $carac['GPOSinfo']; + } + $cOTLdata[$nc]['GPOSinfo'][$cctr]['wDir'] = ($carac['level'] % 2) ? 'RTL' : 'LTR'; + } + } + $chunkid = $carac['chunkid']; + $cctr++; + } + } + + public function splitOTLdata(&$cOTLdata, $OTLcutoffpos, $OTLrestartpos = '') + { + if (!$OTLrestartpos) { + $OTLrestartpos = $OTLcutoffpos; + } + $newOTLdata = ['GPOSinfo' => [], 'char_data' => []]; + $newOTLdata['group'] = substr($cOTLdata['group'], $OTLrestartpos); + $cOTLdata['group'] = substr($cOTLdata['group'], 0, $OTLcutoffpos); + + if (isset($cOTLdata['GPOSinfo']) && $cOTLdata['GPOSinfo']) { + foreach ($cOTLdata['GPOSinfo'] as $k => $val) { + if ($k >= $OTLrestartpos) { + $newOTLdata['GPOSinfo'][($k - $OTLrestartpos)] = $val; + } + if ($k >= $OTLcutoffpos) { + unset($cOTLdata['GPOSinfo'][$k]); + //$cOTLdata['GPOSinfo'][$k] = array(); + } + } + } + if (isset($cOTLdata['char_data'])) { + $newOTLdata['char_data'] = array_slice($cOTLdata['char_data'], $OTLrestartpos); + array_splice($cOTLdata['char_data'], $OTLcutoffpos); + } + + // Not necessary - easier to debug + if (isset($cOTLdata['GPOSinfo'])) { + ksort($cOTLdata['GPOSinfo']); + } + if (isset($newOTLdata['GPOSinfo'])) { + ksort($newOTLdata['GPOSinfo']); + } + + return $newOTLdata; + } + + public function sliceOTLdata($OTLdata, $pos, $len) + { + $newOTLdata = ['GPOSinfo' => [], 'char_data' => []]; + $newOTLdata['group'] = substr($OTLdata['group'], $pos, $len); + + if ($OTLdata['GPOSinfo']) { + foreach ($OTLdata['GPOSinfo'] as $k => $val) { + if ($k >= $pos && $k < ($pos + $len)) { + $newOTLdata['GPOSinfo'][($k - $pos)] = $val; + } + } + } + + if (isset($OTLdata['char_data'])) { + $newOTLdata['char_data'] = array_slice($OTLdata['char_data'], $pos, $len); + } + + // Not necessary - easier to debug + if ($newOTLdata['GPOSinfo']) { + ksort($newOTLdata['GPOSinfo']); + } + + return $newOTLdata; + } + + /** + * Remove one or more occurrences of $char (single character) from $txt and adjust OTLdata + */ + public function removeChar(&$txt, &$cOTLdata, $char) + { + while (mb_strpos($txt, $char, 0, $this->mpdf->mb_enc) !== false) { + $pos = mb_strpos($txt, $char, 0, $this->mpdf->mb_enc); + $newGPOSinfo = []; + $cOTLdata['group'] = substr_replace($cOTLdata['group'], '', $pos, 1); + if ($cOTLdata['GPOSinfo']) { + foreach ($cOTLdata['GPOSinfo'] as $k => $val) { + if ($k > $pos) { + $newGPOSinfo[($k - 1)] = $val; + } elseif ($k != $pos) { + $newGPOSinfo[$k] = $val; + } + } + $cOTLdata['GPOSinfo'] = $newGPOSinfo; + } + if (isset($cOTLdata['char_data'])) { + array_splice($cOTLdata['char_data'], $pos, 1); + } + + $txt = preg_replace("/" . $char . "/", '', $txt, 1); + } + } + + /** + * Remove one or more occurrences of $char (single character) from $txt and adjust OTLdata + */ + public function replaceSpace(&$txt, &$cOTLdata) + { + $char = chr(194) . chr(160); // NBSP + while (mb_strpos($txt, $char, 0, $this->mpdf->mb_enc) !== false) { + $pos = mb_strpos($txt, $char, 0, $this->mpdf->mb_enc); + if ($cOTLdata['char_data'][$pos]['uni'] == 160) { + $cOTLdata['char_data'][$pos]['uni'] = 32; + } + $txt = preg_replace("/" . $char . "/", ' ', $txt, 1); + } + } + + public function trimOTLdata(&$cOTLdata, $Left = true, $Right = true) + { + $len = (!is_array($cOTLdata) || $cOTLdata['char_data'] === null) ? 0 : count($cOTLdata['char_data']); + $nLeft = 0; + $nRight = 0; + for ($i = 0; $i < $len; $i++) { + if ($cOTLdata['char_data'][$i]['uni'] == 32 || $cOTLdata['char_data'][$i]['uni'] == 12288) { + $nLeft++; + } // 12288 = 0x3000 = CJK space + else { + break; + } + } + for ($i = ($len - 1); $i >= 0; $i--) { + if ($cOTLdata['char_data'][$i]['uni'] == 32 || $cOTLdata['char_data'][$i]['uni'] == 12288) { + $nRight++; + } // 12288 = 0x3000 = CJK space + else { + break; + } + } + + // Trim Right + if ($Right && $nRight) { + $cOTLdata['group'] = substr($cOTLdata['group'], 0, strlen($cOTLdata['group']) - $nRight); + if ($cOTLdata['GPOSinfo']) { + foreach ($cOTLdata['GPOSinfo'] as $k => $val) { + if ($k >= $len - $nRight) { + unset($cOTLdata['GPOSinfo'][$k]); + } + } + } + if (isset($cOTLdata['char_data'])) { + for ($i = 0; $i < $nRight; $i++) { + array_pop($cOTLdata['char_data']); + } + } + } + // Trim Left + if ($Left && $nLeft) { + $cOTLdata['group'] = substr($cOTLdata['group'], $nLeft); + if ($cOTLdata['GPOSinfo']) { + $newPOSinfo = []; + foreach ($cOTLdata['GPOSinfo'] as $k => $val) { + if ($k >= $nLeft) { + $newPOSinfo[$k - $nLeft] = $cOTLdata['GPOSinfo'][$k]; + } + } + $cOTLdata['GPOSinfo'] = $newPOSinfo; + } + if (isset($cOTLdata['char_data'])) { + for ($i = 0; $i < $nLeft; $i++) { + array_shift($cOTLdata['char_data']); + } + } + } + } + + //////////////////////////////////////////////////////////////// + ////////// GENERAL OTL FUNCTIONS ///////////////// + //////////////////////////////////////////////////////////////// + + private function glyphToChar($gid) + { + return (ord($this->glyphIDtoUni[$gid * 3]) << 16) + (ord($this->glyphIDtoUni[$gid * 3 + 1]) << 8) + ord($this->glyphIDtoUni[$gid * 3 + 2]); + } + + private function unicode_hex($unicode_dec) + { + return (str_pad(strtoupper(dechex($unicode_dec)), 5, '0', STR_PAD_LEFT)); + } + + private function seek($pos) + { + $this->_pos = $pos; + } + + private function skip($delta) + { + $this->_pos += $delta; + } + + private function read_short() + { + $a = (ord($this->ttfOTLdata[$this->_pos]) << 8) + ord($this->ttfOTLdata[$this->_pos + 1]); + if ($a & (1 << 15)) { + $a = ($a - (1 << 16)); + } + $this->_pos += 2; + return $a; + } + + private function read_ushort() + { + $a = (ord($this->ttfOTLdata[$this->_pos]) << 8) + ord($this->ttfOTLdata[$this->_pos + 1]); + $this->_pos += 2; + return $a; + } + + private function _getCoverageGID() + { + // Called from Lookup Type 1, Format 1 - returns glyphIDs rather than hexstrings + // Need to do this separately to cache separately + // Otherwise the same as fn below _getCoverage + $offset = $this->_pos; + if (isset($this->LuDataCache[$this->fontkey]['GID'][$offset])) { + $g = $this->LuDataCache[$this->fontkey]['GID'][$offset]; + } else { + $g = []; + $CoverageFormat = $this->read_ushort(); + if ($CoverageFormat == 1) { + $CoverageGlyphCount = $this->read_ushort(); + for ($gid = 0; $gid < $CoverageGlyphCount; $gid++) { + $glyphID = $this->read_ushort(); + $g[] = $glyphID; + } + } + if ($CoverageFormat == 2) { + $RangeCount = $this->read_ushort(); + for ($r = 0; $r < $RangeCount; $r++) { + $start = $this->read_ushort(); + $end = $this->read_ushort(); + $StartCoverageIndex = $this->read_ushort(); // n/a + for ($glyphID = $start; $glyphID <= $end; $glyphID++) { + $g[] = $glyphID; + } + } + } + $this->LuDataCache[$this->fontkey]['GID'][$offset] = $g; + } + return $g; + } + + private function _getCoverage() + { + $offset = $this->_pos; + if (isset($this->LuDataCache[$this->fontkey][$offset])) { + $g = $this->LuDataCache[$this->fontkey][$offset]; + } else { + $g = []; + $CoverageFormat = $this->read_ushort(); + if ($CoverageFormat == 1) { + $CoverageGlyphCount = $this->read_ushort(); + for ($gid = 0; $gid < $CoverageGlyphCount; $gid++) { + $glyphID = $this->read_ushort(); + $g[] = $this->unicode_hex($this->glyphToChar($glyphID)); + } + } + if ($CoverageFormat == 2) { + $RangeCount = $this->read_ushort(); + for ($r = 0; $r < $RangeCount; $r++) { + $start = $this->read_ushort(); + $end = $this->read_ushort(); + $StartCoverageIndex = $this->read_ushort(); // n/a + for ($glyphID = $start; $glyphID <= $end; $glyphID++) { + $g[] = $this->unicode_hex($this->glyphToChar($glyphID)); + } + } + } + $this->LuDataCache[$this->fontkey][$offset] = $g; + } + return $g; + } + + private function _getClasses($offset) + { + if (isset($this->LuDataCache[$this->fontkey][$offset])) { + $GlyphByClass = $this->LuDataCache[$this->fontkey][$offset]; + } else { + $this->seek($offset); + $ClassFormat = $this->read_ushort(); + $GlyphByClass = []; + if ($ClassFormat == 1) { + $StartGlyph = $this->read_ushort(); + $GlyphCount = $this->read_ushort(); + for ($i = 0; $i < $GlyphCount; $i++) { + $startGlyphID = $StartGlyph + $i; + $endGlyphID = $StartGlyph + $i; + $class = $this->read_ushort(); + // Note: Font FreeSerif , tag "blws" + // $BacktrackClasses[0] is defined ? a mistake in the font ??? + // Let's ignore for now + if ($class > 0) { + for ($g = $startGlyphID; $g <= $endGlyphID; $g++) { + if ($this->glyphToChar($g)) { + $GlyphByClass[$class][$this->glyphToChar($g)] = 1; + } + } + } + } + } elseif ($ClassFormat == 2) { + $tableCount = $this->read_ushort(); + for ($i = 0; $i < $tableCount; $i++) { + $startGlyphID = $this->read_ushort(); + $endGlyphID = $this->read_ushort(); + $class = $this->read_ushort(); + // Note: Font FreeSerif , tag "blws" + // $BacktrackClasses[0] is defined ? a mistake in the font ??? + // Let's ignore for now + if ($class > 0) { + for ($g = $startGlyphID; $g <= $endGlyphID; $g++) { + if ($this->glyphToChar($g)) { + $GlyphByClass[$class][$this->glyphToChar($g)] = 1; + } + } + } + } + } + $this->LuDataCache[$this->fontkey][$offset] = $GlyphByClass; + } + return $GlyphByClass; + } + + private function _getOTLscriptTag($ScriptLang, $scripttag, $scriptblock, $shaper, $useOTL, $mode) + { + // ScriptLang is the array of available script/lang tags supported by the font + // $scriptblock is the (number/code) for the script of the actual text string based on Unicode properties (Ucdn::$uni_scriptblock) + // $scripttag is the default tag derived from $scriptblock + /* + http://www.microsoft.com/typography/otspec/ttoreg.htm + http://www.microsoft.com/typography/otspec/scripttags.htm + + Values for useOTL + + Bit dn hn Value + 1 1 0x0001 GSUB/GPOS - Latin scripts + 2 2 0x0002 GSUB/GPOS - Cyrillic scripts + 3 4 0x0004 GSUB/GPOS - Greek scripts + 4 8 0x0008 GSUB/GPOS - CJK scripts (excluding Hangul-Jamo) + 5 16 0x0010 (Reserved) + 6 32 0x0020 (Reserved) + 7 64 0x0040 (Reserved) + 8 128 0x0080 GSUB/GPOS - All other scripts (including all RTL scripts, complex scripts with shapers etc) + + NB If change for RTL - cf. function magic_reverse_dir in mpdf.php to update + + */ + + + if ($scriptblock == Ucdn::SCRIPT_LATIN) { + if (!($useOTL & 0x01)) { + return ['', false]; + } + } elseif ($scriptblock == Ucdn::SCRIPT_CYRILLIC) { + if (!($useOTL & 0x02)) { + return ['', false]; + } + } elseif ($scriptblock == Ucdn::SCRIPT_GREEK) { + if (!($useOTL & 0x04)) { + return ['', false]; + } + } elseif ($scriptblock >= Ucdn::SCRIPT_HIRAGANA && $scriptblock <= Ucdn::SCRIPT_YI) { + if (!($useOTL & 0x08)) { + return ['', false]; + } + } else { + if (!($useOTL & 0x80)) { + return ['', false]; + } + } + + // If availabletags includes scripttag - choose + if (isset($ScriptLang[$scripttag])) { + return [$scripttag, false]; + } + + // If INDIC (or Myanmar) and available tag not includes new version, check if includes old version & choose old version + if ($shaper) { + switch ($scripttag) { + case 'bng2': + if (isset($ScriptLang['beng'])) { + return ['beng', true]; + } + // fallthrough + case 'dev2': + if (isset($ScriptLang['deva'])) { + return ['deva', true]; + } + // fallthrough + case 'gjr2': + if (isset($ScriptLang['gujr'])) { + return ['gujr', true]; + } + // fallthrough + case 'gur2': + if (isset($ScriptLang['guru'])) { + return ['guru', true]; + } + // fallthrough + case 'knd2': + if (isset($ScriptLang['knda'])) { + return ['knda', true]; + } + // fallthrough + case 'mlm2': + if (isset($ScriptLang['mlym'])) { + return ['mlym', true]; + } + // fallthrough + case 'ory2': + if (isset($ScriptLang['orya'])) { + return ['orya', true]; + } + // fallthrough + case 'tml2': + if (isset($ScriptLang['taml'])) { + return ['taml', true]; + } + // fallthrough + case 'tel2': + if (isset($ScriptLang['telu'])) { + return ['telu', true]; + } + // fallthrough + case 'mym2': + if (isset($ScriptLang['mymr'])) { + return ['mymr', true]; + } + } + } + + // choose DFLT if present + if (isset($ScriptLang['DFLT'])) { + return ['DFLT', false]; + } + // else choose dflt if present + if (isset($ScriptLang['dflt'])) { + return ['dflt', false]; + } + // else return no scriptTag + if (isset($ScriptLang['latn'])) { + return ['latn', false]; + } + // else return no scriptTag + return ['', false]; + } + + // LangSys tags + private function _getOTLLangTag($ietf, $available) + { + // http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes + // http://www.microsoft.com/typography/otspec/languagetags.htm + // IETF tag = e.g. en-US, und-Arab, sr-Cyrl cf. class LangToFont + if ($available == '') { + return ''; + } + $tags = preg_split('/-/', $ietf); + $lang = ''; + $country = ''; + $script = ''; + $lang = strtolower($tags[0]); + if (isset($tags[1]) && $tags[1]) { + if (strlen($tags[1]) == 2) { + $country = strtolower($tags[1]); + } + } + if (isset($tags[2]) && $tags[2]) { + $country = strtolower($tags[2]); + } + + if ($lang != '' && isset(Ucdn::$ot_languages[$lang])) { + $langsys = Ucdn::$ot_languages[$lang]; + } elseif ($lang != '' && $country != '' && isset(Ucdn::$ot_languages[$lang . '' . $country])) { + $langsys = Ucdn::$ot_languages[$lang . '' . $country]; + } else { + $langsys = "DFLT"; + } + if (strpos($available, $langsys) === false) { + if (strpos($available, "DFLT") !== false) { + return "DFLT"; + } else { + return ''; + } + } + return $langsys; + } + + private function _dumpproc($GPOSSUB, $lookupID, $subtable, $Type, $Format, $ptr, $currGlyph, $level) + { + echo '<div style="padding-left: ' . ($level * 2) . 'em;">'; + echo $GPOSSUB . ' LookupID #' . $lookupID . ' Subtable#' . $subtable . ' Type: ' . $Type . ' Format: ' . $Format . '<br />'; + echo '<div style="font-family:monospace">'; + echo 'Glyph position: ' . $ptr . ' Current Glyph: ' . $currGlyph . '<br />'; + + for ($i = 0; $i < count($this->OTLdata); $i++) { + if ($i == $ptr) { + echo '<b>'; + } + echo $this->OTLdata[$i]['hex'] . ' '; + if ($i == $ptr) { + echo '</b>'; + } + } + echo '<br />'; + + for ($i = 0; $i < count($this->OTLdata); $i++) { + if ($i == $ptr) { + echo '<b>'; + } + echo str_pad($this->OTLdata[$i]['uni'], 5) . ' '; + if ($i == $ptr) { + echo '</b>'; + } + } + echo '<br />'; + + if ($GPOSSUB == 'GPOS') { + for ($i = 0; $i < count($this->OTLdata); $i++) { + if (!empty($this->OTLdata[$i]['GPOSinfo'])) { + echo $this->OTLdata[$i]['hex'] . ' &#x' . $this->OTLdata[$i]['hex'] . '; '; + print_r($this->OTLdata[$i]['GPOSinfo']); + echo ' '; + } + } + } + + echo '</div>'; + echo '</div>'; + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/OtlDump.php b/src/bb-vendor/mpdf/mpdf/src/OtlDump.php new file mode 100644 index 000000000..024c54d7d --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/OtlDump.php @@ -0,0 +1,4369 @@ +<?php + +namespace Mpdf; + +// Define the value used in the "head" table of a created TTF file +// 0x74727565 "true" for Mac +// 0x00010000 for Windows +// Either seems to work for a font embedded in a PDF file +// when read by Adobe Reader on a Windows PC(!) +use Mpdf\Fonts\GlyphOperator; + +if (!defined('_TTF_MAC_HEADER')) { + define("_TTF_MAC_HEADER", false); +} + +// Recalculate correct metadata/profiles when making subset fonts (not SIP/SMP) +// e.g. xMin, xMax, maxNContours +if (!defined('_RECALC_PROFILE')) { + define("_RECALC_PROFILE", false); +} + +// mPDF 5.7.1 +if (!function_exists('Mpdf\unicode_hex')) { + function unicode_hex($unicode_dec) + { + return (sprintf("%05s", strtoupper(dechex($unicode_dec)))); + } +} + +class OtlDump +{ + + var $GPOSFeatures; // mPDF 5.7.1 + + var $GPOSLookups; // mPDF 5.7.1 + + var $GPOSScriptLang; // mPDF 5.7.1 + + var $ignoreStrings; // mPDF 5.7.1 + + var $MarkAttachmentType; // mPDF 5.7.1 + + var $MarkGlyphSets; // mPDF 7.5.1 + + var $GlyphClassMarks; // mPDF 5.7.1 + + var $GlyphClassLigatures; // mPDF 5.7.1 + + var $GlyphClassBases; // mPDF 5.7.1 + + var $GlyphClassComponents; // mPDF 5.7.1 + + var $GSUBScriptLang; // mPDF 5.7.1 + + var $rtlPUAstr; // mPDF 5.7.1 + + var $rtlPUAarr; // mPDF 5.7.1 + + var $fontkey; // mPDF 5.7.1 + + var $useOTL; // mPDF 5.7.1 + + var $panose; + + var $maxUni; + + var $sFamilyClass; + + var $sFamilySubClass; + + var $sipset; + + var $smpset; + + var $_pos; + + var $numTables; + + var $searchRange; + + var $entrySelector; + + var $rangeShift; + + var $tables; + + var $otables; + + var $filename; + + var $fh; + + var $glyphPos; + + var $charToGlyph; + + var $ascent; + + var $descent; + + var $name; + + var $familyName; + + var $styleName; + + var $fullName; + + var $uniqueFontID; + + var $unitsPerEm; + + var $bbox; + + var $capHeight; + + var $stemV; + + var $italicAngle; + + var $flags; + + var $underlinePosition; + + var $underlineThickness; + + var $charWidths; + + var $defaultWidth; + + var $maxStrLenRead; + + var $numTTCFonts; + + var $TTCFonts; + + var $maxUniChar; + + var $kerninfo; + + var $mode; + + var $glyphToChar; + + var $fontRevision; + + var $glyphdata; + + var $glyphIDtoUn; + + var $restrictedUse; + + var $GSUBFeatures; + + var $GSUBLookups; + + var $glyphIDtoUni; + + var $GSLuCoverage; + + var $version; + + private $mpdf; + + public function __construct(Mpdf $mpdf) + { + $this->mpdf = $mpdf; + $this->maxStrLenRead = 200000; // Maximum size of glyf table to read in as string (otherwise reads each glyph from file) + } + + function getMetrics($file, $fontkey, $TTCfontID = 0, $debug = false, $BMPonly = false, $kerninfo = false, $useOTL = 0, $mode = null) + { + // mPDF 5.7.1 + $this->mode = $mode; + $this->useOTL = $useOTL; // mPDF 5.7.1 + $this->fontkey = $fontkey; // mPDF 5.7.1 + $this->filename = $file; + $this->fh = fopen($file, 'rb'); + + if (!$this->fh) { + throw new \Mpdf\MpdfException(sprintf('Unable to open file "%s"', $file)); + } + + $this->_pos = 0; + $this->charWidths = ''; + $this->glyphPos = []; + $this->charToGlyph = []; + $this->tables = []; + $this->otables = []; + $this->kerninfo = []; + $this->ascent = 0; + $this->descent = 0; + $this->numTTCFonts = 0; + $this->TTCFonts = []; + $this->version = $version = $this->read_ulong(); + $this->panose = []; + + if ($version == 0x4F54544F) { + throw new \Mpdf\MpdfException("Postscript outlines are not supported"); + } + + if ($version == 0x74746366 && !$TTCfontID) { + throw new \Mpdf\MpdfException("TTCfontID for a TrueType Collection has to be defined in ttfontdata configuration key (" . $file . ")"); + } + + if (!in_array($version, [0x00010000, 0x74727565]) && !$TTCfontID) { + throw new \Mpdf\MpdfException("Not a TrueType font: version=" . $version); + } + + if ($TTCfontID > 0) { + $this->version = $version = $this->read_ulong(); // TTC Header version now + if (!in_array($version, [0x00010000, 0x00020000])) { + throw new \Mpdf\MpdfException("Error parsing TrueType Collection: version=" . $version . " - " . $file); + } + $this->numTTCFonts = $this->read_ulong(); + for ($i = 1; $i <= $this->numTTCFonts; $i++) { + $this->TTCFonts[$i]['offset'] = $this->read_ulong(); + } + $this->seek($this->TTCFonts[$TTCfontID]['offset']); + $this->version = $version = $this->read_ulong(); // TTFont version again now + } + $this->readTableDirectory($debug); + $this->extractInfo($debug, $BMPonly, $kerninfo, $useOTL); + fclose($this->fh); + } + + function readTableDirectory($debug = false) + { + $this->numTables = $this->read_ushort(); + $this->searchRange = $this->read_ushort(); + $this->entrySelector = $this->read_ushort(); + $this->rangeShift = $this->read_ushort(); + $this->tables = []; + for ($i = 0; $i < $this->numTables; $i++) { + $record = []; + $record['tag'] = $this->read_tag(); + $record['checksum'] = [$this->read_ushort(), $this->read_ushort()]; + $record['offset'] = $this->read_ulong(); + $record['length'] = $this->read_ulong(); + $this->tables[$record['tag']] = $record; + } + if ($debug) { + $this->checksumTables(); + } + } + + function checksumTables() + { + // Check the checksums for all tables + foreach ($this->tables as $t) { + if ($t['length'] > 0 && $t['length'] < $this->maxStrLenRead) { // 1.02 + $table = $this->get_chunk($t['offset'], $t['length']); + $checksum = $this->calcChecksum($table); + if ($t['tag'] == 'head') { + $up = unpack('n*', substr($table, 8, 4)); + $adjustment[0] = $up[1]; + $adjustment[1] = $up[2]; + $checksum = $this->sub32($checksum, $adjustment); + } + $xchecksum = $t['checksum']; + if ($xchecksum != $checksum) { + throw new \Mpdf\MpdfException(sprintf('TTF file "%s": invalid checksum %s table: %s (expected %s)', $this->filename, dechex($checksum[0]) . dechex($checksum[1]), $t['tag'], dechex($xchecksum[0]) . dechex($xchecksum[1]))); + } + } + } + } + + function sub32($x, $y) + { + $xlo = $x[1]; + $xhi = $x[0]; + $ylo = $y[1]; + $yhi = $y[0]; + if ($ylo > $xlo) { + $xlo += 1 << 16; + $yhi += 1; + } + $reslo = $xlo - $ylo; + if ($yhi > $xhi) { + $xhi += 1 << 16; + } + $reshi = $xhi - $yhi; + $reshi = $reshi & 0xFFFF; + + return [$reshi, $reslo]; + } + + function calcChecksum($data) + { + if (strlen($data) % 4) { + $data .= str_repeat("\0", (4 - (strlen($data) % 4))); + } + $len = strlen($data); + $hi = 0x0000; + $lo = 0x0000; + for ($i = 0; $i < $len; $i += 4) { + $hi += (ord($data[$i]) << 8) + ord($data[$i + 1]); + $lo += (ord($data[$i + 2]) << 8) + ord($data[$i + 3]); + $hi += ($lo >> 16) & 0xFFFF; + $lo = $lo & 0xFFFF; + } + + return [$hi, $lo]; + } + + function get_table_pos($tag) + { + $offset = isset($this->tables[$tag]['offset']) ? $this->tables[$tag]['offset'] : null; + $length = isset($this->tables[$tag]['length']) ? $this->tables[$tag]['length'] : null; + + return [$offset, $length]; + } + + function seek($pos) + { + $this->_pos = $pos; + fseek($this->fh, $this->_pos); + } + + function skip($delta) + { + $this->_pos = $this->_pos + $delta; + fseek($this->fh, $delta, SEEK_CUR); + } + + function seek_table($tag, $offset_in_table = 0) + { + $tpos = $this->get_table_pos($tag); + $this->_pos = $tpos[0] + $offset_in_table; + fseek($this->fh, $this->_pos); + + return $this->_pos; + } + + function read_tag() + { + $this->_pos += 4; + + return fread($this->fh, 4); + } + + function read_short() + { + $this->_pos += 2; + $s = fread($this->fh, 2); + $a = (ord($s[0]) << 8) + ord($s[1]); + if ($a & (1 << 15)) { + $a = ($a - (1 << 16)); + } + + return $a; + } + + function unpack_short($s) + { + $a = (ord($s[0]) << 8) + ord($s[1]); + if ($a & (1 << 15)) { + $a = ($a - (1 << 16)); + } + + return $a; + } + + function read_ushort() + { + $this->_pos += 2; + $s = fread($this->fh, 2); + + return (ord($s[0]) << 8) + ord($s[1]); + } + + function read_ulong() + { + $this->_pos += 4; + $s = fread($this->fh, 4); + + // if large uInt32 as an integer, PHP converts it to -ve + return (ord($s[0]) * 16777216) + (ord($s[1]) << 16) + (ord($s[2]) << 8) + ord($s[3]); // 16777216 = 1<<24 + } + + function get_ushort($pos) + { + fseek($this->fh, $pos); + $s = fread($this->fh, 2); + + return (ord($s[0]) << 8) + ord($s[1]); + } + + function get_ulong($pos) + { + fseek($this->fh, $pos); + $s = fread($this->fh, 4); + + // iF large uInt32 as an integer, PHP converts it to -ve + return (ord($s[0]) * 16777216) + (ord($s[1]) << 16) + (ord($s[2]) << 8) + ord($s[3]); // 16777216 = 1<<24 + } + + function pack_short($val) + { + if ($val < 0) { + $val = abs($val); + $val = ~$val; + $val += 1; + } + + return pack("n", $val); + } + + function splice($stream, $offset, $value) + { + return substr($stream, 0, $offset) . $value . substr($stream, $offset + strlen($value)); + } + + function _set_ushort($stream, $offset, $value) + { + $up = pack("n", $value); + + return $this->splice($stream, $offset, $up); + } + + function _set_short($stream, $offset, $val) + { + if ($val < 0) { + $val = abs($val); + $val = ~$val; + $val += 1; + } + $up = pack("n", $val); + + return $this->splice($stream, $offset, $up); + } + + function get_chunk($pos, $length) + { + fseek($this->fh, $pos); + if ($length < 1) { + return ''; + } + + return (fread($this->fh, $length)); + } + + function get_table($tag) + { + list($pos, $length) = $this->get_table_pos($tag); + if ($length == 0) { + return ''; + } + fseek($this->fh, $pos); + + return (fread($this->fh, $length)); + } + + function add($tag, $data) + { + if ($tag == 'head') { + $data = $this->splice($data, 8, "\0\0\0\0"); + } + $this->otables[$tag] = $data; + } + + ///////////////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////////////////////////////////////////////////////////////// + + function extractInfo($debug = false, $BMPonly = false, $kerninfo = false, $useOTL = 0) + { + $this->panose = []; + $this->sFamilyClass = 0; + $this->sFamilySubClass = 0; + /////////////////////////////////// + // name - Naming table + /////////////////////////////////// + $name_offset = $this->seek_table("name"); + $format = $this->read_ushort(); + if ($format != 0 && $format != 1) { + throw new \Mpdf\MpdfException("Unknown name table format " . $format); + } + $numRecords = $this->read_ushort(); + $string_data_offset = $name_offset + $this->read_ushort(); + $names = [1 => '', 2 => '', 3 => '', 4 => '', 6 => '']; + $K = array_keys($names); + $nameCount = count($names); + for ($i = 0; $i < $numRecords; $i++) { + $platformId = $this->read_ushort(); + $encodingId = $this->read_ushort(); + $languageId = $this->read_ushort(); + $nameId = $this->read_ushort(); + $length = $this->read_ushort(); + $offset = $this->read_ushort(); + if (!in_array($nameId, $K)) { + continue; + } + $N = ''; + if ($platformId == 3 && $encodingId == 1 && $languageId == 0x409) { // Microsoft, Unicode, US English, PS Name + $opos = $this->_pos; + $this->seek($string_data_offset + $offset); + if ($length % 2 != 0) { + throw new \Mpdf\MpdfException("PostScript name is UTF-16BE string of odd length"); + } + $length /= 2; + $N = ''; + while ($length > 0) { + $char = $this->read_ushort(); + $N .= (chr($char)); + $length -= 1; + } + $this->_pos = $opos; + $this->seek($opos); + } else { + if ($platformId == 1 && $encodingId == 0 && $languageId == 0) { // Macintosh, Roman, English, PS Name + $opos = $this->_pos; + $N = $this->get_chunk($string_data_offset + $offset, $length); + $this->_pos = $opos; + $this->seek($opos); + } + } + if ($N && $names[$nameId] == '') { + $names[$nameId] = $N; + $nameCount -= 1; + if ($nameCount == 0) { + break; + } + } + } + if ($names[6]) { + $psName = $names[6]; + } else { + if ($names[4]) { + $psName = preg_replace('/ /', '-', $names[4]); + } else { + if ($names[1]) { + $psName = preg_replace('/ /', '-', $names[1]); + } else { + $psName = ''; + } + } + } + if (!$psName) { + throw new \Mpdf\MpdfException("Could not find PostScript font name: " . $this->filename); + } + if ($debug) { + for ($i = 0; $i < count($psName); $i++) { + $c = $psName[$i]; + $oc = ord($c); + if ($oc > 126 || strpos(' [](){}<>/%', $c) !== false) { + throw new \Mpdf\MpdfException("psName=" . $psName . " contains invalid character " . $c . " ie U+" . ord(c)); + } + } + } + $this->name = $psName; + if ($names[1]) { + $this->familyName = $names[1]; + } else { + $this->familyName = $psName; + } + if ($names[2]) { + $this->styleName = $names[2]; + } else { + $this->styleName = 'Regular'; + } + if ($names[4]) { + $this->fullName = $names[4]; + } else { + $this->fullName = $psName; + } + if ($names[3]) { + $this->uniqueFontID = $names[3]; + } else { + $this->uniqueFontID = $psName; + } + + if ($names[6]) { + $this->fullName = $names[6]; + } + + /////////////////////////////////// + // head - Font header table + /////////////////////////////////// + $this->seek_table("head"); + if ($debug) { + $ver_maj = $this->read_ushort(); + $ver_min = $this->read_ushort(); + if ($ver_maj != 1) { + throw new \Mpdf\MpdfException('Unknown head table version ' . $ver_maj . '.' . $ver_min); + } + $this->fontRevision = $this->read_ushort() . $this->read_ushort(); + + $this->skip(4); + $magic = $this->read_ulong(); + if ($magic != 0x5F0F3CF5) { + throw new \Mpdf\MpdfException('Invalid head table magic ' . $magic); + } + $this->skip(2); + } else { + $this->skip(18); + } + $this->unitsPerEm = $unitsPerEm = $this->read_ushort(); + $scale = 1000 / $unitsPerEm; + $this->skip(16); + $xMin = $this->read_short(); + $yMin = $this->read_short(); + $xMax = $this->read_short(); + $yMax = $this->read_short(); + $this->bbox = [($xMin * $scale), ($yMin * $scale), ($xMax * $scale), ($yMax * $scale)]; + $this->skip(3 * 2); + $indexToLocFormat = $this->read_ushort(); + $glyphDataFormat = $this->read_ushort(); + if ($glyphDataFormat != 0) { + throw new \Mpdf\MpdfException('Unknown glyph data format ' . $glyphDataFormat); + } + + /////////////////////////////////// + // hhea metrics table + /////////////////////////////////// + // ttf2t1 seems to use this value rather than the one in OS/2 - so put in for compatibility + if (isset($this->tables["hhea"])) { + $this->seek_table("hhea"); + $this->skip(4); + $hheaAscender = $this->read_short(); + $hheaDescender = $this->read_short(); + $this->ascent = ($hheaAscender * $scale); + $this->descent = ($hheaDescender * $scale); + } + + /////////////////////////////////// + // OS/2 - OS/2 and Windows metrics table + /////////////////////////////////// + if (isset($this->tables["OS/2"])) { + $this->seek_table("OS/2"); + $version = $this->read_ushort(); + $this->skip(2); + $usWeightClass = $this->read_ushort(); + $this->skip(2); + $fsType = $this->read_ushort(); + if ($fsType == 0x0002 || ($fsType & 0x0300) != 0) { + global $overrideTTFFontRestriction; + if (!$overrideTTFFontRestriction) { + throw new \Mpdf\MpdfException('ERROR - Font file ' . $this->filename . ' cannot be embedded due to copyright restrictions.'); + } + $this->restrictedUse = true; + } + $this->skip(20); + $sF = $this->read_short(); + $this->sFamilyClass = ($sF >> 8); + $this->sFamilySubClass = ($sF & 0xFF); + $this->_pos += 10; //PANOSE = 10 byte length + $panose = fread($this->fh, 10); + $this->panose = []; + for ($p = 0; $p < strlen($panose); $p++) { + $this->panose[] = ord($panose[$p]); + } + $this->skip(26); + $sTypoAscender = $this->read_short(); + $sTypoDescender = $this->read_short(); + if (!$this->ascent) { + $this->ascent = ($sTypoAscender * $scale); + } + if (!$this->descent) { + $this->descent = ($sTypoDescender * $scale); + } + if ($version > 1) { + $this->skip(16); + $sCapHeight = $this->read_short(); + $this->capHeight = ($sCapHeight * $scale); + } else { + $this->capHeight = $this->ascent; + } + } else { + $usWeightClass = 500; + if (!$this->ascent) { + $this->ascent = ($yMax * $scale); + } + if (!$this->descent) { + $this->descent = ($yMin * $scale); + } + $this->capHeight = $this->ascent; + } + $this->stemV = 50 + intval(pow(($usWeightClass / 65.0), 2)); + + /////////////////////////////////// + // post - PostScript table + /////////////////////////////////// + $this->seek_table("post"); + if ($debug) { + $ver_maj = $this->read_ushort(); + $ver_min = $this->read_ushort(); + if ($ver_maj < 1 || $ver_maj > 4) { + throw new \Mpdf\MpdfException('Unknown post table version ' . $ver_maj); + } + } else { + $this->skip(4); + } + $this->italicAngle = $this->read_short() + $this->read_ushort() / 65536.0; + $this->underlinePosition = $this->read_short() * $scale; + $this->underlineThickness = $this->read_short() * $scale; + $isFixedPitch = $this->read_ulong(); + + $this->flags = 4; + + if ($this->italicAngle != 0) { + $this->flags = $this->flags | 64; + } + if ($usWeightClass >= 600) { + $this->flags = $this->flags | 262144; + } + if ($isFixedPitch) { + $this->flags = $this->flags | 1; + } + + /////////////////////////////////// + // hhea - Horizontal header table + /////////////////////////////////// + $this->seek_table("hhea"); + if ($debug) { + $ver_maj = $this->read_ushort(); + $ver_min = $this->read_ushort(); + if ($ver_maj != 1) { + throw new \Mpdf\MpdfException('Unknown hhea table version ' . $ver_maj); + } + $this->skip(28); + } else { + $this->skip(32); + } + $metricDataFormat = $this->read_ushort(); + if ($metricDataFormat != 0) { + throw new \Mpdf\MpdfException('Unknown horizontal metric data format ' . $metricDataFormat); + } + $numberOfHMetrics = $this->read_ushort(); + if ($numberOfHMetrics == 0) { + throw new \Mpdf\MpdfException('Number of horizontal metrics is 0'); + } + + /////////////////////////////////// + // maxp - Maximum profile table + /////////////////////////////////// + $this->seek_table("maxp"); + if ($debug) { + $ver_maj = $this->read_ushort(); + $ver_min = $this->read_ushort(); + if ($ver_maj != 1) { + throw new \Mpdf\MpdfException('Unknown maxp table version ' . $ver_maj); + } + } else { + $this->skip(4); + } + $numGlyphs = $this->read_ushort(); + + /////////////////////////////////// + // cmap - Character to glyph index mapping table + /////////////////////////////////// + $cmap_offset = $this->seek_table("cmap"); + $this->skip(2); + $cmapTableCount = $this->read_ushort(); + $unicode_cmap_offset = 0; + for ($i = 0; $i < $cmapTableCount; $i++) { + $platformID = $this->read_ushort(); + $encodingID = $this->read_ushort(); + $offset = $this->read_ulong(); + $save_pos = $this->_pos; + if (($platformID == 3 && $encodingID == 1) || $platformID == 0) { // Microsoft, Unicode + $format = $this->get_ushort($cmap_offset + $offset); + if ($format == 4) { + if (!$unicode_cmap_offset) { + $unicode_cmap_offset = $cmap_offset + $offset; + } + if ($BMPonly) { + break; + } + } + } // Microsoft, Unicode Format 12 table HKCS + else { + if ((($platformID == 3 && $encodingID == 10) || $platformID == 0) && !$BMPonly) { + $format = $this->get_ushort($cmap_offset + $offset); + if ($format == 12) { + $unicode_cmap_offset = $cmap_offset + $offset; + break; + } + } + } + $this->seek($save_pos); + } + + if (!$unicode_cmap_offset) { + throw new \Mpdf\MpdfException('Font (' . $this->filename . ') does not have cmap for Unicode (platform 3, encoding 1, format 4, or platform 0, any encoding, format 4)'); + } + + $sipset = false; + $smpset = false; + + // mPDF 5.7.1 + $this->GSUBScriptLang = []; + $this->rtlPUAstr = ''; + $this->rtlPUAarr = []; + $this->GSUBFeatures = []; + $this->GSUBLookups = []; + $this->GPOSScriptLang = []; + $this->GPOSFeatures = []; + $this->GPOSLookups = []; + $this->glyphIDtoUni = ''; + + // Format 12 CMAP does characters above Unicode BMP i.e. some HKCS characters U+20000 and above + if ($format == 12 && !$BMPonly) { + $this->maxUniChar = 0; + $this->seek($unicode_cmap_offset + 4); + $length = $this->read_ulong(); + $limit = $unicode_cmap_offset + $length; + $this->skip(4); + + $nGroups = $this->read_ulong(); + + $glyphToChar = []; + $charToGlyph = []; + for ($i = 0; $i < $nGroups; $i++) { + $startCharCode = $this->read_ulong(); + $endCharCode = $this->read_ulong(); + $startGlyphCode = $this->read_ulong(); + if ($endCharCode > 0x20000 && $endCharCode < 0x2FFFF) { + $sipset = true; + } else { + if ($endCharCode > 0x10000 && $endCharCode < 0x1FFFF) { + $smpset = true; + } + } + $offset = 0; + for ($unichar = $startCharCode; $unichar <= $endCharCode; $unichar++) { + $glyph = $startGlyphCode + $offset; + $offset++; + if ($unichar < 0x30000) { + $charToGlyph[$unichar] = $glyph; + $this->maxUniChar = max($unichar, $this->maxUniChar); + $glyphToChar[$glyph][] = $unichar; + } + } + } + } else { + $glyphToChar = []; + $charToGlyph = []; + $this->getCMAP4($unicode_cmap_offset, $glyphToChar, $charToGlyph); + } + $this->sipset = $sipset; + $this->smpset = $smpset; + + /////////////////////////////////// + // mPDF 5.7.1 + // Map Unmapped glyphs - from $numGlyphs + if ($this->useOTL) { + $bctr = 0xE000; + for ($gid = 1; $gid < $numGlyphs; $gid++) { + if (!isset($glyphToChar[$gid])) { + while (isset($charToGlyph[$bctr])) { + $bctr++; + } // Avoid overwriting a glyph already mapped in PUA + if (($bctr > 0xF8FF) && ($bctr < 0x2CEB0)) { + if (!$BMPonly) { + $bctr = 0x2CEB0; // Use unassigned area 0x2CEB0 to 0x2F7FF (space for 10,000 characters) + $this->sipset = $sipset = true; // forces subsetting; also ensure charwidths are saved + while (isset($charToGlyph[$bctr])) { + $bctr++; + } + } else { + throw new \Mpdf\MpdfException($names[1] . " : WARNING - The font does not have enough space to map all (unmapped) included glyphs into Private Use Area U+E000 - U+F8FF"); + } + } + $glyphToChar[$gid][] = $bctr; + $charToGlyph[$bctr] = $gid; + $this->maxUniChar = max($bctr, $this->maxUniChar); + $bctr++; + } + } + } + $this->glyphToChar = $glyphToChar; + $this->charToGlyph = $charToGlyph; + /////////////////////////////////// + // mPDF 5.7.1 OpenType Layout tables + $this->GSUBScriptLang = []; + $this->rtlPUAstr = ''; + $this->rtlPUAarr = []; + if ($useOTL) { + $this->_getGDEFtables(); + list($this->GSUBScriptLang, $this->GSUBFeatures, $this->GSUBLookups, $this->rtlPUAstr, $this->rtlPUAarr) = $this->_getGSUBtables(); + list($this->GPOSScriptLang, $this->GPOSFeatures, $this->GPOSLookups) = $this->_getGPOStables(); + $this->glyphIDtoUni = str_pad('', 256 * 256 * 3, "\x00"); + foreach ($glyphToChar as $gid => $arr) { + if (isset($glyphToChar[$gid][0])) { + $char = $glyphToChar[$gid][0]; + if ($char != 0 && $char != 65535) { + $this->glyphIDtoUni[$gid * 3] = chr($char >> 16); + $this->glyphIDtoUni[$gid * 3 + 1] = chr(($char >> 8) & 0xFF); + $this->glyphIDtoUni[$gid * 3 + 2] = chr($char & 0xFF); + } + } + } + } + /////////////////////////////////// + /////////////////////////////////// + // hmtx - Horizontal metrics table + /////////////////////////////////// + $this->getHMTX($numberOfHMetrics, $numGlyphs, $glyphToChar, $scale); + + /////////////////////////////////// + // kern - Kerning pair table + /////////////////////////////////// + if ($kerninfo) { + // Recognises old form of Kerning table - as required by Windows - Format 0 only + $kern_offset = $this->seek_table("kern"); + $version = $this->read_ushort(); + $nTables = $this->read_ushort(); + // subtable header + $sversion = $this->read_ushort(); + $slength = $this->read_ushort(); + $scoverage = $this->read_ushort(); + $format = $scoverage >> 8; + if ($kern_offset && $version == 0 && $format == 0) { + // Format 0 + $nPairs = $this->read_ushort(); + $this->skip(6); + for ($i = 0; $i < $nPairs; $i++) { + $left = $this->read_ushort(); + $right = $this->read_ushort(); + $val = $this->read_short(); + if (count($glyphToChar[$left]) == 1 && count($glyphToChar[$right]) == 1) { + if ($left != 32 && $right != 32) { + $this->kerninfo[$glyphToChar[$left][0]][$glyphToChar[$right][0]] = intval($val * $scale); + } + } + } + } + } + } + + ///////////////////////////////////////////////////////////////////////////////////////// + function _getGDEFtables() + { + /////////////////////////////////// + // GDEF - Glyph Definition + /////////////////////////////////// + // http://www.microsoft.com/typography/otspec/gdef.htm + if (isset($this->tables["GDEF"])) { + if ($this->mode == 'summary') { + $this->mpdf->WriteHTML('<h1>GDEF table</h1>'); + } + $gdef_offset = $this->seek_table("GDEF"); + // ULONG Version of the GDEF table-currently 0x00010000 + $ver_maj = $this->read_ushort(); + $ver_min = $this->read_ushort(); + // Version 0x00010002 of GDEF header contains additional Offset to a list defining mark glyph set definitions (MarkGlyphSetDef) + $GlyphClassDef_offset = $this->read_ushort(); + $AttachList_offset = $this->read_ushort(); + $LigCaretList_offset = $this->read_ushort(); + $MarkAttachClassDef_offset = $this->read_ushort(); + if ($ver_min == 2) { + $MarkGlyphSetsDef_offset = $this->read_ushort(); + } + + // GlyphClassDef + $this->seek($gdef_offset + $GlyphClassDef_offset); + /* + 1 Base glyph (single character, spacing glyph) + 2 Ligature glyph (multiple character, spacing glyph) + 3 Mark glyph (non-spacing combining glyph) + 4 Component glyph (part of single character, spacing glyph) + */ + $GlyphByClass = $this->_getClassDefinitionTable(); + + if ($this->mode == 'summary') { + $this->mpdf->WriteHTML('<h2>Glyph classes</h2>'); + } + + if (isset($GlyphByClass[1]) && count($GlyphByClass[1]) > 0) { + $this->GlyphClassBases = $this->formatClassArr($GlyphByClass[1]); + if ($this->mode == 'summary') { + $this->mpdf->WriteHTML('<h3>Glyph class 1</h3>'); + $this->mpdf->WriteHTML('<h5>Base glyph (single character, spacing glyph)</h5>'); + $html = ''; + $html .= '<div class="glyphs">'; + foreach ($GlyphByClass[1] as $g) { + $html .= '&#x' . $g . '; '; + } + $html .= '</div>'; + $this->mpdf->WriteHTML($html); + } + } else { + $this->GlyphClassBases = ''; + } + if (isset($GlyphByClass[2]) && count($GlyphByClass[2]) > 0) { + $this->GlyphClassLigatures = $this->formatClassArr($GlyphByClass[2]); + if ($this->mode == 'summary') { + $this->mpdf->WriteHTML('<h3>Glyph class 2</h3>'); + $this->mpdf->WriteHTML('<h5>Ligature glyph (multiple character, spacing glyph)</h5>'); + $html = ''; + $html .= '<div class="glyphs">'; + foreach ($GlyphByClass[2] as $g) { + $html .= '&#x' . $g . '; '; + } + $html .= '</div>'; + $this->mpdf->WriteHTML($html); + } + } else { + $this->GlyphClassLigatures = ''; + } + if (isset($GlyphByClass[3]) && count($GlyphByClass[3]) > 0) { + $this->GlyphClassMarks = $this->formatClassArr($GlyphByClass[3]); + if ($this->mode == 'summary') { + $this->mpdf->WriteHTML('<h3>Glyph class 3</h3>'); + $this->mpdf->WriteHTML('<h5>Mark glyph (non-spacing combining glyph)</h5>'); + $html = ''; + $html .= '<div class="glyphs">'; + foreach ($GlyphByClass[3] as $g) { + $html .= '◌&#x' . $g . '; '; + } + $html .= '</div>'; + $this->mpdf->WriteHTML($html); + } + } else { + $this->GlyphClassMarks = ''; + } + if (isset($GlyphByClass[4]) && count($GlyphByClass[4]) > 0) { + $this->GlyphClassComponents = $this->formatClassArr($GlyphByClass[4]); + if ($this->mode == 'summary') { + $this->mpdf->WriteHTML('<h3>Glyph class 4</h3>'); + $this->mpdf->WriteHTML('<h5>Component glyph (part of single character, spacing glyph)</h5>'); + $html = ''; + $html .= '<div class="glyphs">'; + foreach ($GlyphByClass[4] as $g) { + $html .= '&#x' . $g . '; '; + } + $html .= '</div>'; + $this->mpdf->WriteHTML($html); + } + } else { + $this->GlyphClassComponents = ''; + } + + $Marks = $GlyphByClass[3]; // to use for MarkAttachmentType + + /* Required for GPOS + // Attachment List + if ($AttachList_offset) { + $this->seek($gdef_offset+$AttachList_offset ); + } + The Attachment Point List table (AttachmentList) identifies all the attachment points defined in the GPOS table and their associated glyphs so a client can quickly access coordinates for each glyph's attachment points. As a result, the client can cache coordinates for attachment points along with glyph bitmaps and avoid recalculating the attachment points each time it displays a glyph. Without this table, processing speed would be slower because the client would have to decode the GPOS lookups that define attachment points and compile the points in a list. + + The Attachment List table (AttachList) may be used to cache attachment point coordinates along with glyph bitmaps. + + The table consists of an offset to a Coverage table (Coverage) listing all glyphs that define attachment points in the GPOS table, a count of the glyphs with attachment points (GlyphCount), and an array of offsets to AttachPoint tables (AttachPoint). The array lists the AttachPoint tables, one for each glyph in the Coverage table, in the same order as the Coverage Index. + AttachList table + Type Name Description + Offset Coverage Offset to Coverage table - from beginning of AttachList table + uint16 GlyphCount Number of glyphs with attachment points + Offset AttachPoint[GlyphCount] Array of offsets to AttachPoint tables-from beginning of AttachList table-in Coverage Index order + + An AttachPoint table consists of a count of the attachment points on a single glyph (PointCount) and an array of contour indices of those points (PointIndex), listed in increasing numerical order. + + AttachPoint table + Type Name Description + uint16 PointCount Number of attachment points on this glyph + uint16 PointIndex[PointCount] Array of contour point indices -in increasing numerical order + + See Example 3 - http://www.microsoft.com/typography/otspec/gdef.htm + */ + + // Ligature Caret List + // The Ligature Caret List table (LigCaretList) defines caret positions for all the ligatures in a font. + // Not required for mDPF + // MarkAttachmentType + if ($MarkAttachClassDef_offset) { + if ($this->mode == 'summary') { + $this->mpdf->WriteHTML('<h1>Mark Attachment Types</h1>'); + } + $this->seek($gdef_offset + $MarkAttachClassDef_offset); + $MarkAttachmentTypes = $this->_getClassDefinitionTable(); + foreach ($MarkAttachmentTypes as $class => $glyphs) { + if (is_array($Marks) && count($Marks)) { + $mat = array_diff($Marks, $MarkAttachmentTypes[$class]); + sort($mat, SORT_STRING); + } else { + $mat = []; + } + + $this->MarkAttachmentType[$class] = $this->formatClassArr($mat); + + if ($this->mode == 'summary') { + $this->mpdf->WriteHTML('<h3>Mark Attachment Type: ' . $class . '</h3>'); + $html = ''; + $html .= '<div class="glyphs">'; + foreach ($glyphs as $g) { + $html .= '◌&#x' . $g . '; '; + } + $html .= '</div>'; + $this->mpdf->WriteHTML($html); + } + } + } else { + $this->MarkAttachmentType = []; + } + + // MarkGlyphSets only in Version 0x00010002 of GDEF + if ($ver_min == 2 && $MarkGlyphSetsDef_offset) { + if ($this->mode == 'summary') { + $this->mpdf->WriteHTML('<h1>Mark Glyph Sets</h1>'); + } + $this->seek($gdef_offset + $MarkGlyphSetsDef_offset); + $MarkSetTableFormat = $this->read_ushort(); + $MarkSetCount = $this->read_ushort(); + $MarkSetOffset = []; + for ($i = 0; $i < $MarkSetCount; $i++) { + $MarkSetOffset[] = $this->read_ulong(); + } + for ($i = 0; $i < $MarkSetCount; $i++) { + $this->seek($MarkSetOffset[$i]); + $glyphs = $this->_getCoverage(); + $this->MarkGlyphSets[$i] = $this->formatClassArr($glyphs); + if ($this->mode == 'summary') { + $this->mpdf->WriteHTML('<h3>Mark Glyph Set class: ' . $i . '</h3>'); + $html = ''; + $html .= '<div class="glyphs">'; + foreach ($glyphs as $g) { + $html .= '◌&#x' . $g . '; '; + } + $html .= '</div>'; + $this->mpdf->WriteHTML($html); + } + } + } else { + $this->MarkGlyphSets = []; + } + } else { + $this->mpdf->WriteHTML('<div>GDEF table not defined</div>'); + } + +//echo $this->GlyphClassMarks ; exit; +//print_r($GlyphClass); exit; +//print_r($GlyphByClass); exit; + } + + function _getClassDefinitionTable($offset = 0) + { + + if ($offset > 0) { + $this->seek($offset); + } + + // NB Any glyph not included in the range of covered GlyphIDs automatically belongs to Class 0. This is not returned by this function + $ClassFormat = $this->read_ushort(); + $GlyphByClass = []; + if ($ClassFormat == 1) { + $StartGlyph = $this->read_ushort(); + $GlyphCount = $this->read_ushort(); + for ($i = 0; $i < $GlyphCount; $i++) { + $gid = $StartGlyph + $i; + $class = $this->read_ushort(); + $GlyphByClass[$class][] = unicode_hex($this->glyphToChar[$gid][0]); + } + } else { + if ($ClassFormat == 2) { + $tableCount = $this->read_ushort(); + for ($i = 0; $i < $tableCount; $i++) { + $startGlyphID = $this->read_ushort(); + $endGlyphID = $this->read_ushort(); + $class = $this->read_ushort(); + for ($gid = $startGlyphID; $gid <= $endGlyphID; $gid++) { + $GlyphByClass[$class][] = unicode_hex($this->glyphToChar[$gid][0]); + } + } + } + } + ksort($GlyphByClass); + + return $GlyphByClass; + } + + function _getGSUBtables() + { + /////////////////////////////////// + // GSUB - Glyph Substitution + /////////////////////////////////// + if (isset($this->tables["GSUB"])) { + $this->mpdf->WriteHTML('<h1>GSUB Tables</h1>'); + $ffeats = []; + $gsub_offset = $this->seek_table("GSUB"); + $this->skip(4); + $ScriptList_offset = $gsub_offset + $this->read_ushort(); + $FeatureList_offset = $gsub_offset + $this->read_ushort(); + $LookupList_offset = $gsub_offset + $this->read_ushort(); + + // ScriptList + $this->seek($ScriptList_offset); + $ScriptCount = $this->read_ushort(); + for ($i = 0; $i < $ScriptCount; $i++) { + $ScriptTag = $this->read_tag(); // = "beng", "deva" etc. + $ScriptTableOffset = $this->read_ushort(); + $ffeats[$ScriptTag] = $ScriptList_offset + $ScriptTableOffset; + } + + // Script Table + foreach ($ffeats as $t => $o) { + $ls = []; + $this->seek($o); + $DefLangSys_offset = $this->read_ushort(); + if ($DefLangSys_offset > 0) { + $ls['DFLT'] = $DefLangSys_offset + $o; + } + $LangSysCount = $this->read_ushort(); + for ($i = 0; $i < $LangSysCount; $i++) { + $LangTag = $this->read_tag(); // = + $LangTableOffset = $this->read_ushort(); + $ls[$LangTag] = $o + $LangTableOffset; + } + $ffeats[$t] = $ls; + } +//print_r($ffeats); exit; + // Get FeatureIndexList + // LangSys Table - from first listed langsys + foreach ($ffeats as $st => $scripts) { + foreach ($scripts as $t => $o) { + $FeatureIndex = []; + $langsystable_offset = $o; + $this->seek($langsystable_offset); + $LookUpOrder = $this->read_ushort(); //==NULL + $ReqFeatureIndex = $this->read_ushort(); + if ($ReqFeatureIndex != 0xFFFF) { + $FeatureIndex[] = $ReqFeatureIndex; + } + $FeatureCount = $this->read_ushort(); + for ($i = 0; $i < $FeatureCount; $i++) { + $FeatureIndex[] = $this->read_ushort(); // = index of feature + } + $ffeats[$st][$t] = $FeatureIndex; + } + } +//print_r($ffeats); exit; + // Feauture List => LookupListIndex es + $this->seek($FeatureList_offset); + $FeatureCount = $this->read_ushort(); + $Feature = []; + for ($i = 0; $i < $FeatureCount; $i++) { + $Feature[$i] = ['tag' => $this->read_tag()]; + $Feature[$i]['offset'] = $FeatureList_offset + $this->read_ushort(); + } + for ($i = 0; $i < $FeatureCount; $i++) { + $this->seek($Feature[$i]['offset']); + $this->read_ushort(); // null + $Feature[$i]['LookupCount'] = $Lookupcount = $this->read_ushort(); + $Feature[$i]['LookupListIndex'] = []; + for ($c = 0; $c < $Lookupcount; $c++) { + $Feature[$i]['LookupListIndex'][] = $this->read_ushort(); + } + } + + foreach ($ffeats as $st => $scripts) { + foreach ($scripts as $t => $o) { + $FeatureIndex = $ffeats[$st][$t]; + foreach ($FeatureIndex as $k => $fi) { + $ffeats[$st][$t][$k] = $Feature[$fi]; + } + } + } + //===================================================================================== + $gsub = []; + $GSUBScriptLang = []; + foreach ($ffeats as $st => $scripts) { + foreach ($scripts as $t => $langsys) { + $lg = []; + foreach ($langsys as $ft) { + $lg[$ft['LookupListIndex'][0]] = $ft; + } + // list of Lookups in order they need to be run i.e. order listed in Lookup table + ksort($lg); + foreach ($lg as $ft) { + $gsub[$st][$t][$ft['tag']] = $ft['LookupListIndex']; + } + if (!isset($GSUBScriptLang[$st])) { + $GSUBScriptLang[$st] = ''; + } + $GSUBScriptLang[$st] .= $t . ' '; + } + } + +//print_r($gsub); exit; + + if ($this->mode == 'summary') { + $this->mpdf->WriteHTML('<h3>GSUB Scripts & Languages</h3>'); + $this->mpdf->WriteHTML('<div class="glyphs">'); + $html = ''; + if (count($gsub)) { + foreach ($gsub as $st => $g) { + $html .= '<h5>' . $st . '</h5>'; + foreach ($g as $l => $t) { + $html .= '<div><a href="font_dump_OTL.php?script=' . $st . '&lang=' . $l . '">' . $l . '</a></b>: '; + foreach ($t as $tag => $o) { + $html .= $tag . ' '; + } + $html .= '</div>'; + } + } + } else { + $html .= '<div>No entries in GSUB table.</div>'; + } + $this->mpdf->WriteHTML($html); + $this->mpdf->WriteHTML('</div>'); + + return 0; + } + + //===================================================================================== + // Get metadata and offsets for whole Lookup List table + $this->seek($LookupList_offset); + $LookupCount = $this->read_ushort(); + $GSLookup = []; + $Offsets = []; + $SubtableCount = []; + for ($i = 0; $i < $LookupCount; $i++) { + $Offsets[$i] = $LookupList_offset + $this->read_ushort(); + } + for ($i = 0; $i < $LookupCount; $i++) { + $this->seek($Offsets[$i]); + $GSLookup[$i]['Type'] = $this->read_ushort(); + $GSLookup[$i]['Flag'] = $flag = $this->read_ushort(); + $GSLookup[$i]['SubtableCount'] = $SubtableCount[$i] = $this->read_ushort(); + for ($c = 0; $c < $SubtableCount[$i]; $c++) { + $GSLookup[$i]['Subtables'][$c] = $Offsets[$i] + $this->read_ushort(); + } + // MarkFilteringSet = Index (base 0) into GDEF mark glyph sets structure + if (($flag & 0x0010) == 0x0010) { + $GSLookup[$i]['MarkFilteringSet'] = $this->read_ushort(); + } + // else { $GSLookup[$i]['MarkFilteringSet'] = ''; } + // Lookup Type 7: Extension + if ($GSLookup[$i]['Type'] == 7) { + // Overwrites new offset (32-bit) for each subtable, and a new lookup Type + for ($c = 0; $c < $SubtableCount[$i]; $c++) { + $this->seek($GSLookup[$i]['Subtables'][$c]); + $ExtensionPosFormat = $this->read_ushort(); + $type = $this->read_ushort(); + $GSLookup[$i]['Subtables'][$c] = $GSLookup[$i]['Subtables'][$c] + $this->read_ulong(); + } + $GSLookup[$i]['Type'] = $type; + } + } + +//print_r($GSLookup); exit; + //===================================================================================== + // Process Whole LookupList - Get LuCoverage = Lookup coverage just for first glyph + $this->GSLuCoverage = []; + for ($i = 0; $i < $LookupCount; $i++) { + for ($c = 0; $c < $GSLookup[$i]['SubtableCount']; $c++) { + $this->seek($GSLookup[$i]['Subtables'][$c]); + $PosFormat = $this->read_ushort(); + + if ($GSLookup[$i]['Type'] == 5 && $PosFormat == 3) { + $this->skip(4); + } else { + if ($GSLookup[$i]['Type'] == 6 && $PosFormat == 3) { + $BacktrackGlyphCount = $this->read_ushort(); + $this->skip(2 * $BacktrackGlyphCount + 2); + } + } + // NB Coverage only looks at glyphs for position 1 (i.e. 5.3 and 6.3) // NEEDS TO READ ALL ******************** + $Coverage = $GSLookup[$i]['Subtables'][$c] + $this->read_ushort(); + $this->seek($Coverage); + $glyphs = $this->_getCoverage(); + $this->GSLuCoverage[$i][$c] = implode('|', $glyphs); + } + } + +// $this->GSLuCoverage and $GSLookup + //===================================================================================== + $s = '<?php +$GSLuCoverage = ' . var_export($this->GSLuCoverage, true) . '; +?>'; + + //===================================================================================== + $s = '<?php +$GlyphClassBases = \'' . $this->GlyphClassBases . '\'; +$GlyphClassMarks = \'' . $this->GlyphClassMarks . '\'; +$GlyphClassLigatures = \'' . $this->GlyphClassLigatures . '\'; +$GlyphClassComponents = \'' . $this->GlyphClassComponents . '\'; +$MarkGlyphSets = ' . var_export($this->MarkGlyphSets, true) . '; +$MarkAttachmentType = ' . var_export($this->MarkAttachmentType, true) . '; +?>'; + + //===================================================================================== + //===================================================================================== + //===================================================================================== +// Now repeats as original to get Substitution rules + //===================================================================================== + //===================================================================================== + //===================================================================================== + // Get metadata and offsets for whole Lookup List table + $this->seek($LookupList_offset); + $LookupCount = $this->read_ushort(); + $Lookup = []; + for ($i = 0; $i < $LookupCount; $i++) { + $Lookup[$i]['offset'] = $LookupList_offset + $this->read_ushort(); + } + for ($i = 0; $i < $LookupCount; $i++) { + $this->seek($Lookup[$i]['offset']); + $Lookup[$i]['Type'] = $this->read_ushort(); + $Lookup[$i]['Flag'] = $flag = $this->read_ushort(); + $Lookup[$i]['SubtableCount'] = $this->read_ushort(); + for ($c = 0; $c < $Lookup[$i]['SubtableCount']; $c++) { + $Lookup[$i]['Subtable'][$c]['Offset'] = $Lookup[$i]['offset'] + $this->read_ushort(); + } + // MarkFilteringSet = Index (base 0) into GDEF mark glyph sets structure + if (($flag & 0x0010) == 0x0010) { + $Lookup[$i]['MarkFilteringSet'] = $this->read_ushort(); + } else { + $Lookup[$i]['MarkFilteringSet'] = ''; + } + + // Lookup Type 7: Extension + if ($Lookup[$i]['Type'] == 7) { + // Overwrites new offset (32-bit) for each subtable, and a new lookup Type + for ($c = 0; $c < $Lookup[$i]['SubtableCount']; $c++) { + $this->seek($Lookup[$i]['Subtable'][$c]['Offset']); + $ExtensionPosFormat = $this->read_ushort(); + $type = $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['Offset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ulong(); + } + $Lookup[$i]['Type'] = $type; + } + } + +//print_r($Lookup); exit; + //===================================================================================== + // Process (1) Whole LookupList + for ($i = 0; $i < $LookupCount; $i++) { + for ($c = 0; $c < $Lookup[$i]['SubtableCount']; $c++) { + $this->seek($Lookup[$i]['Subtable'][$c]['Offset']); + $SubstFormat = $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['Format'] = $SubstFormat; + + /* + Lookup['Type'] Enumeration table for glyph substitution + Value Type Description + 1 Single Replace one glyph with one glyph + 2 Multiple Replace one glyph with more than one glyph + 3 Alternate Replace one glyph with one of many glyphs + 4 Ligature Replace multiple glyphs with one glyph + 5 Context Replace one or more glyphs in context + 6 Chaining Context Replace one or more glyphs in chained context + 7 Extension Substitution Extension mechanism for other substitutions (i.e. this excludes the Extension type substitution itself) + 8 Reverse chaining context single Applied in reverse order, replace single glyph in chaining context + */ + + // LookupType 1: Single Substitution Subtable + if ($Lookup[$i]['Type'] == 1) { + $Lookup[$i]['Subtable'][$c]['CoverageTableOffset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + if ($SubstFormat == 1) { // Calculated output glyph indices + $Lookup[$i]['Subtable'][$c]['DeltaGlyphID'] = $this->read_short(); + } else { + if ($SubstFormat == 2) { // Specified output glyph indices + $GlyphCount = $this->read_ushort(); + for ($g = 0; $g < $GlyphCount; $g++) { + $Lookup[$i]['Subtable'][$c]['Glyphs'][] = $this->read_ushort(); + } + } + } + } // LookupType 2: Multiple Substitution Subtable + else { + if ($Lookup[$i]['Type'] == 2) { + $Lookup[$i]['Subtable'][$c]['CoverageTableOffset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['SequenceCount'] = $SequenceCount = $this->read_short(); + for ($s = 0; $s < $SequenceCount; $s++) { + $Lookup[$i]['Subtable'][$c]['Sequences'][$s]['Offset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_short(); + } + for ($s = 0; $s < $SequenceCount; $s++) { + // Sequence Tables + $this->seek($Lookup[$i]['Subtable'][$c]['Sequences'][$s]['Offset']); + $Lookup[$i]['Subtable'][$c]['Sequences'][$s]['GlyphCount'] = $this->read_short(); + for ($g = 0; $g < $Lookup[$i]['Subtable'][$c]['Sequences'][$s]['GlyphCount']; $g++) { + $Lookup[$i]['Subtable'][$c]['Sequences'][$s]['SubstituteGlyphID'][] = $this->read_ushort(); + } + } + } // LookupType 3: Alternate Forms + else { + if ($Lookup[$i]['Type'] == 3) { + $Lookup[$i]['Subtable'][$c]['CoverageTableOffset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['AlternateSetCount'] = $AlternateSetCount = $this->read_short(); + for ($s = 0; $s < $AlternateSetCount; $s++) { + $Lookup[$i]['Subtable'][$c]['AlternateSets'][$s]['Offset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_short(); + } + + for ($s = 0; $s < $AlternateSetCount; $s++) { + // AlternateSet Tables + $this->seek($Lookup[$i]['Subtable'][$c]['AlternateSets'][$s]['Offset']); + $Lookup[$i]['Subtable'][$c]['AlternateSets'][$s]['GlyphCount'] = $this->read_short(); + for ($g = 0; $g < $Lookup[$i]['Subtable'][$c]['AlternateSets'][$s]['GlyphCount']; $g++) { + $Lookup[$i]['Subtable'][$c]['AlternateSets'][$s]['SubstituteGlyphID'][] = $this->read_ushort(); + } + } + } // LookupType 4: Ligature Substitution Subtable + else { + if ($Lookup[$i]['Type'] == 4) { + $Lookup[$i]['Subtable'][$c]['CoverageTableOffset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['LigSetCount'] = $LigSetCount = $this->read_short(); + for ($s = 0; $s < $LigSetCount; $s++) { + $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['Offset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_short(); + } + for ($s = 0; $s < $LigSetCount; $s++) { + // LigatureSet Tables + $this->seek($Lookup[$i]['Subtable'][$c]['LigSet'][$s]['Offset']); + $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['LigCount'] = $this->read_short(); + for ($g = 0; $g < $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['LigCount']; $g++) { + $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['LigatureOffset'][$g] = $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['Offset'] + $this->read_ushort(); + } + } + for ($s = 0; $s < $LigSetCount; $s++) { + for ($g = 0; $g < $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['LigCount']; $g++) { + // Ligature tables + $this->seek($Lookup[$i]['Subtable'][$c]['LigSet'][$s]['LigatureOffset'][$g]); + $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['Ligature'][$g]['LigGlyph'] = $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['Ligature'][$g]['CompCount'] = $this->read_ushort(); + for ($l = 1; $l < $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['Ligature'][$g]['CompCount']; $l++) { + $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['Ligature'][$g]['GlyphID'][$l] = $this->read_ushort(); + } + } + } + } // LookupType 5: Contextual Substitution Subtable + else { + if ($Lookup[$i]['Type'] == 5) { + // Format 1: Context Substitution + if ($SubstFormat == 1) { + $Lookup[$i]['Subtable'][$c]['CoverageTableOffset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['SubRuleSetCount'] = $SubRuleSetCount = $this->read_short(); + for ($s = 0; $s < $SubRuleSetCount; $s++) { + $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['Offset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_short(); + } + for ($s = 0; $s < $SubRuleSetCount; $s++) { + // SubRuleSet Tables + $this->seek($Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['Offset']); + $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRuleCount'] = $this->read_short(); + for ($g = 0; $g < $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRuleCount']; $g++) { + $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRuleOffset'][$g] = $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['Offset'] + $this->read_ushort(); + } + } + for ($s = 0; $s < $SubRuleSetCount; $s++) { + // SubRule Tables + for ($g = 0; $g < $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRuleCount']; $g++) { + // Ligature tables + $this->seek($Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRuleOffset'][$g]); + + $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRule'][$g]['GlyphCount'] = $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRule'][$g]['SubstCount'] = $this->read_ushort(); + // "Input"::[GlyphCount - 1]::Array of input GlyphIDs-start with second glyph + for ($l = 1; $l < $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRule'][$g]['GlyphCount']; $l++) { + $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRule'][$g]['Input'][$l] = $this->read_ushort(); + } + // "SubstLookupRecord"::[SubstCount]::Array of SubstLookupRecords-in design order + for ($l = 0; $l < $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRule'][$g]['SubstCount']; $l++) { + $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRule'][$g]['SubstLookupRecord'][$l]['SequenceIndex'] = $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRule'][$g]['SubstLookupRecord'][$l]['LookupListIndex'] = $this->read_ushort(); + } + } + } + } // Format 2: Class-based Context Glyph Substitution + else { + if ($SubstFormat == 2) { + $Lookup[$i]['Subtable'][$c]['CoverageTableOffset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['ClassDefOffset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['SubClassSetCnt'] = $this->read_ushort(); + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['SubClassSetCnt']; $b++) { + $offset = $this->read_ushort(); + if ($offset == 0x0000) { + $Lookup[$i]['Subtable'][$c]['SubClassSetOffset'][] = 0; + } else { + $Lookup[$i]['Subtable'][$c]['SubClassSetOffset'][] = $Lookup[$i]['Subtable'][$c]['Offset'] + $offset; + } + } + } else { + throw new \Mpdf\MpdfException("GPOS Lookup Type " . $Lookup[$i]['Type'] . ", Format " . $SubstFormat . " not supported (ttfontsuni.php)."); + } + } + } // LookupType 6: Chaining Contextual Substitution Subtable + else { + if ($Lookup[$i]['Type'] == 6) { + // Format 1: Simple Chaining Context Glyph Substitution p255 + if ($SubstFormat == 1) { + $Lookup[$i]['Subtable'][$c]['CoverageTableOffset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['ChainSubRuleSetCount'] = $this->read_ushort(); + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['ChainSubRuleSetCount']; $b++) { + $Lookup[$i]['Subtable'][$c]['ChainSubRuleSetOffset'][] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + } + } // Format 2: Class-based Chaining Context Glyph Substitution p257 + else { + if ($SubstFormat == 2) { + $Lookup[$i]['Subtable'][$c]['CoverageTableOffset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['BacktrackClassDefOffset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['InputClassDefOffset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['LookaheadClassDefOffset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['ChainSubClassSetCnt'] = $this->read_ushort(); + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['ChainSubClassSetCnt']; $b++) { + $offset = $this->read_ushort(); + if ($offset == 0x0000) { + $Lookup[$i]['Subtable'][$c]['ChainSubClassSetOffset'][] = $offset; + } else { + $Lookup[$i]['Subtable'][$c]['ChainSubClassSetOffset'][] = $Lookup[$i]['Subtable'][$c]['Offset'] + $offset; + } + } + } // Format 3: Coverage-based Chaining Context Glyph Substitution p259 + else { + if ($SubstFormat == 3) { + $Lookup[$i]['Subtable'][$c]['BacktrackGlyphCount'] = $this->read_ushort(); + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['BacktrackGlyphCount']; $b++) { + $Lookup[$i]['Subtable'][$c]['CoverageBacktrack'][] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + } + $Lookup[$i]['Subtable'][$c]['InputGlyphCount'] = $this->read_ushort(); + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['InputGlyphCount']; $b++) { + $Lookup[$i]['Subtable'][$c]['CoverageInput'][] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + } + $Lookup[$i]['Subtable'][$c]['LookaheadGlyphCount'] = $this->read_ushort(); + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['LookaheadGlyphCount']; $b++) { + $Lookup[$i]['Subtable'][$c]['CoverageLookahead'][] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + } + $Lookup[$i]['Subtable'][$c]['SubstCount'] = $this->read_ushort(); + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['SubstCount']; $b++) { + $Lookup[$i]['Subtable'][$c]['SubstLookupRecord'][$b]['SequenceIndex'] = $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['SubstLookupRecord'][$b]['LookupListIndex'] = $this->read_ushort(); + /* + Substitution Lookup Record + All contextual substitution subtables specify the substitution data in a Substitution Lookup Record (SubstLookupRecord). Each record contains a SequenceIndex, which indicates the position where the substitution will occur in the glyph sequence. In addition, a LookupListIndex identifies the lookup to be applied at the glyph position specified by the SequenceIndex. + */ + } + } + } + } + } else { + throw new \Mpdf\MpdfException("Lookup Type " . $Lookup[$i]['Type'] . " not supported."); + } + } + } + } + } + } + } + } +//print_r($Lookup); exit; + //===================================================================================== + // Process (2) Whole LookupList + // Get Coverage tables and prepare preg_replace + for ($i = 0; $i < $LookupCount; $i++) { + for ($c = 0; $c < $Lookup[$i]['SubtableCount']; $c++) { + $SubstFormat = $Lookup[$i]['Subtable'][$c]['Format']; + + // LookupType 1: Single Substitution Subtable 1 => 1 + if ($Lookup[$i]['Type'] == 1) { + $this->seek($Lookup[$i]['Subtable'][$c]['CoverageTableOffset']); + $glyphs = $this->_getCoverage(false); + for ($g = 0; $g < count($glyphs); $g++) { + $replace = []; + $substitute = []; + $replace[] = unicode_hex($this->glyphToChar[$glyphs[$g]][0]); + // Flag = Ignore + if ($this->_checkGSUBignore($Lookup[$i]['Flag'], $replace[0], $Lookup[$i]['MarkFilteringSet'])) { + continue; + } + if (isset($Lookup[$i]['Subtable'][$c]['DeltaGlyphID'])) { // Format 1 + $substitute[] = unicode_hex($this->glyphToChar[($glyphs[$g] + $Lookup[$i]['Subtable'][$c]['DeltaGlyphID'])][0]); + } else { // Format 2 + $substitute[] = unicode_hex($this->glyphToChar[($Lookup[$i]['Subtable'][$c]['Glyphs'][$g])][0]); + } + $Lookup[$i]['Subtable'][$c]['subs'][] = ['Replace' => $replace, 'substitute' => $substitute]; + } + } // LookupType 2: Multiple Substitution Subtable 1 => n + else { + if ($Lookup[$i]['Type'] == 2) { + $this->seek($Lookup[$i]['Subtable'][$c]['CoverageTableOffset']); + $glyphs = $this->_getCoverage(); + for ($g = 0; $g < count($glyphs); $g++) { + $replace = []; + $substitute = []; + $replace[] = $glyphs[$g]; + // Flag = Ignore + if ($this->_checkGSUBignore($Lookup[$i]['Flag'], $replace[0], $Lookup[$i]['MarkFilteringSet'])) { + continue; + } + if (!isset($Lookup[$i]['Subtable'][$c]['Sequences'][$g]['SubstituteGlyphID']) || count($Lookup[$i]['Subtable'][$c]['Sequences'][$g]['SubstituteGlyphID']) == 0) { + continue; + } // Illegal for GlyphCount to be 0; either error in font, or something has gone wrong - lets carry on for now! + foreach ($Lookup[$i]['Subtable'][$c]['Sequences'][$g]['SubstituteGlyphID'] as $sub) { + $substitute[] = unicode_hex($this->glyphToChar[$sub][0]); + } + $Lookup[$i]['Subtable'][$c]['subs'][] = ['Replace' => $replace, 'substitute' => $substitute]; + } + } // LookupType 3: Alternate Forms 1 => 1 (only first alternate form is used) + else { + if ($Lookup[$i]['Type'] == 3) { + $this->seek($Lookup[$i]['Subtable'][$c]['CoverageTableOffset']); + $glyphs = $this->_getCoverage(); + for ($g = 0; $g < count($glyphs); $g++) { + $replace = []; + $substitute = []; + $replace[] = $glyphs[$g]; + // Flag = Ignore + if ($this->_checkGSUBignore($Lookup[$i]['Flag'], $replace[0], $Lookup[$i]['MarkFilteringSet'])) { + continue; + } + + for ($gl = 0; $gl < $Lookup[$i]['Subtable'][$c]['AlternateSets'][$g]['GlyphCount']; $gl++) { + $gid = $Lookup[$i]['Subtable'][$c]['AlternateSets'][$g]['SubstituteGlyphID'][$gl]; + $substitute[] = unicode_hex($this->glyphToChar[$gid][0]); + } + + //$gid = $Lookup[$i]['Subtable'][$c]['AlternateSets'][$g]['SubstituteGlyphID'][0]; + //$substitute[] = unicode_hex($this->glyphToChar[$gid][0]); + + $Lookup[$i]['Subtable'][$c]['subs'][] = ['Replace' => $replace, 'substitute' => $substitute]; + } + if ($i == 166) { + print_r($Lookup[$i]['Subtable']); + exit; + } + } // LookupType 4: Ligature Substitution Subtable n => 1 + else { + if ($Lookup[$i]['Type'] == 4) { + $this->seek($Lookup[$i]['Subtable'][$c]['CoverageTableOffset']); + $glyphs = $this->_getCoverage(); + $LigSetCount = $Lookup[$i]['Subtable'][$c]['LigSetCount']; + for ($s = 0; $s < $LigSetCount; $s++) { + for ($g = 0; $g < $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['LigCount']; $g++) { + $replace = []; + $substitute = []; + $replace[] = $glyphs[$s]; + // Flag = Ignore + if ($this->_checkGSUBignore($Lookup[$i]['Flag'], $replace[0], $Lookup[$i]['MarkFilteringSet'])) { + continue; + } + for ($l = 1; $l < $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['Ligature'][$g]['CompCount']; $l++) { + $gid = $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['Ligature'][$g]['GlyphID'][$l]; + $rpl = unicode_hex($this->glyphToChar[$gid][0]); + // Flag = Ignore + if ($this->_checkGSUBignore($Lookup[$i]['Flag'], $rpl, $Lookup[$i]['MarkFilteringSet'])) { + continue 2; + } + $replace[] = $rpl; + } + $gid = $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['Ligature'][$g]['LigGlyph']; + $substitute[] = unicode_hex($this->glyphToChar[$gid][0]); + $Lookup[$i]['Subtable'][$c]['subs'][] = ['Replace' => $replace, 'substitute' => $substitute, 'CompCount' => $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['Ligature'][$g]['CompCount']]; + } + } + } // LookupType 5: Contextual Substitution Subtable + else { + if ($Lookup[$i]['Type'] == 5) { + // Format 1: Context Substitution + if ($SubstFormat == 1) { + $this->seek($Lookup[$i]['Subtable'][$c]['CoverageTableOffset']); + $Lookup[$i]['Subtable'][$c]['CoverageGlyphs'] = $CoverageGlyphs = $this->_getCoverage(); + + for ($s = 0; $s < $Lookup[$i]['Subtable'][$c]['SubRuleSetCount']; $s++) { + $SubRuleSet = $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]; + $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['FirstGlyph'] = $CoverageGlyphs[$s]; + for ($r = 0; $r < $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRuleCount']; $r++) { + $GlyphCount = $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRule'][$r]['GlyphCount']; + for ($g = 1; $g < $GlyphCount; $g++) { + $glyphID = $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRule'][$r]['Input'][$g]; + $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRule'][$r]['InputGlyphs'][$g] = unicode_hex($this->glyphToChar[$glyphID][0]); + } + } + } + } // Format 2: Class-based Context Glyph Substitution + else { + if ($SubstFormat == 2) { + $this->seek($Lookup[$i]['Subtable'][$c]['CoverageTableOffset']); + $Lookup[$i]['Subtable'][$c]['CoverageGlyphs'] = $CoverageGlyphs = $this->_getCoverage(); + + $InputClasses = $this->_getClasses($Lookup[$i]['Subtable'][$c]['ClassDefOffset']); + $Lookup[$i]['Subtable'][$c]['InputClasses'] = $InputClasses; + + for ($s = 0; $s < $Lookup[$i]['Subtable'][$c]['SubClassSetCnt']; $s++) { + if ($Lookup[$i]['Subtable'][$c]['SubClassSetOffset'][$s] > 0) { + $this->seek($Lookup[$i]['Subtable'][$c]['SubClassSetOffset'][$s]); + $Lookup[$i]['Subtable'][$c]['SubClassSet'][$s]['SubClassRuleCnt'] = $SubClassRuleCnt = $this->read_ushort(); + $SubClassRule = []; + for ($b = 0; $b < $SubClassRuleCnt; $b++) { + $SubClassRule[$b] = $Lookup[$i]['Subtable'][$c]['SubClassSetOffset'][$s] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['SubClassSet'][$s]['SubClassRule'][$b] = $SubClassRule[$b]; + } + } + } + + for ($s = 0; $s < $Lookup[$i]['Subtable'][$c]['SubClassSetCnt']; $s++) { + $SubClassRuleCnt = $Lookup[$i]['Subtable'][$c]['SubClassSet'][$s]['SubClassRuleCnt']; + for ($b = 0; $b < $SubClassRuleCnt; $b++) { + if ($Lookup[$i]['Subtable'][$c]['SubClassSetOffset'][$s] > 0) { + $this->seek($Lookup[$i]['Subtable'][$c]['SubClassSet'][$s]['SubClassRule'][$b]); + $Rule = []; + $Rule['InputGlyphCount'] = $this->read_ushort(); + $Rule['SubstCount'] = $this->read_ushort(); + for ($r = 1; $r < $Rule['InputGlyphCount']; $r++) { + $Rule['Input'][$r] = $this->read_ushort(); + } + for ($r = 0; $r < $Rule['SubstCount']; $r++) { + $Rule['SequenceIndex'][$r] = $this->read_ushort(); + $Rule['LookupListIndex'][$r] = $this->read_ushort(); + } + + $Lookup[$i]['Subtable'][$c]['SubClassSet'][$s]['SubClassRule'][$b] = $Rule; + } + } + } + } // Format 3: Coverage-based Context Glyph Substitution + else { + if ($SubstFormat == 3) { + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['InputGlyphCount']; $b++) { + $this->seek($Lookup[$i]['Subtable'][$c]['CoverageInput'][$b]); + $glyphs = $this->_getCoverage(); + $Lookup[$i]['Subtable'][$c]['CoverageInputGlyphs'][] = implode("|", $glyphs); + } + throw new \Mpdf\MpdfException("Lookup Type 5, SubstFormat 3 not tested. Please report this with the name of font used - " . $this->fontkey); + } + } + } + } // LookupType 6: Chaining Contextual Substitution Subtable + else { + if ($Lookup[$i]['Type'] == 6) { + // Format 1: Simple Chaining Context Glyph Substitution p255 + if ($SubstFormat == 1) { + $this->seek($Lookup[$i]['Subtable'][$c]['CoverageTableOffset']); + $Lookup[$i]['Subtable'][$c]['CoverageGlyphs'] = $CoverageGlyphs = $this->_getCoverage(); + + $ChainSubRuleSetCnt = $Lookup[$i]['Subtable'][$c]['ChainSubRuleSetCount']; + + for ($s = 0; $s < $ChainSubRuleSetCnt; $s++) { + $this->seek($Lookup[$i]['Subtable'][$c]['ChainSubRuleSetOffset'][$s]); + $ChainSubRuleCnt = $Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRuleCount'] = $this->read_ushort(); + for ($r = 0; $r < $ChainSubRuleCnt; $r++) { + $Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRuleOffset'][$r] = $Lookup[$i]['Subtable'][$c]['ChainSubRuleSetOffset'][$s] + $this->read_ushort(); + } + } + for ($s = 0; $s < $ChainSubRuleSetCnt; $s++) { + $ChainSubRuleCnt = $Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRuleCount']; + for ($r = 0; $r < $ChainSubRuleCnt; $r++) { + // ChainSubRule + $this->seek($Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRuleOffset'][$r]); + + $BacktrackGlyphCount = $Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRule'][$r]['BacktrackGlyphCount'] = $this->read_ushort(); + for ($g = 0; $g < $BacktrackGlyphCount; $g++) { + $glyphID = $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRule'][$r]['BacktrackGlyphs'][$g] = unicode_hex($this->glyphToChar[$glyphID][0]); + } + + $InputGlyphCount = $Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRule'][$r]['InputGlyphCount'] = $this->read_ushort(); + for ($g = 1; $g < $InputGlyphCount; $g++) { + $glyphID = $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRule'][$r]['InputGlyphs'][$g] = unicode_hex($this->glyphToChar[$glyphID][0]); + } + + $LookaheadGlyphCount = $Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRule'][$r]['LookaheadGlyphCount'] = $this->read_ushort(); + for ($g = 0; $g < $LookaheadGlyphCount; $g++) { + $glyphID = $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRule'][$r]['LookaheadGlyphs'][$g] = unicode_hex($this->glyphToChar[$glyphID][0]); + } + + $SubstCount = $Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRule'][$r]['SubstCount'] = $this->read_ushort(); + for ($lu = 0; $lu < $SubstCount; $lu++) { + $Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRule'][$r]['SequenceIndex'][$lu] = $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRule'][$r]['LookupListIndex'][$lu] = $this->read_ushort(); + } + } + } + } // Format 2: Class-based Chaining Context Glyph Substitution p257 + else { + if ($SubstFormat == 2) { + $this->seek($Lookup[$i]['Subtable'][$c]['CoverageTableOffset']); + $Lookup[$i]['Subtable'][$c]['CoverageGlyphs'] = $CoverageGlyphs = $this->_getCoverage(); + + $BacktrackClasses = $this->_getClasses($Lookup[$i]['Subtable'][$c]['BacktrackClassDefOffset']); + $Lookup[$i]['Subtable'][$c]['BacktrackClasses'] = $BacktrackClasses; + + $InputClasses = $this->_getClasses($Lookup[$i]['Subtable'][$c]['InputClassDefOffset']); + $Lookup[$i]['Subtable'][$c]['InputClasses'] = $InputClasses; + + $LookaheadClasses = $this->_getClasses($Lookup[$i]['Subtable'][$c]['LookaheadClassDefOffset']); + $Lookup[$i]['Subtable'][$c]['LookaheadClasses'] = $LookaheadClasses; + + for ($s = 0; $s < $Lookup[$i]['Subtable'][$c]['ChainSubClassSetCnt']; $s++) { + if ($Lookup[$i]['Subtable'][$c]['ChainSubClassSetOffset'][$s] > 0) { + $this->seek($Lookup[$i]['Subtable'][$c]['ChainSubClassSetOffset'][$s]); + $Lookup[$i]['Subtable'][$c]['ChainSubClassSet'][$s]['ChainSubClassRuleCnt'] = $ChainSubClassRuleCnt = $this->read_ushort(); + $ChainSubClassRule = []; + for ($b = 0; $b < $ChainSubClassRuleCnt; $b++) { + $ChainSubClassRule[$b] = $Lookup[$i]['Subtable'][$c]['ChainSubClassSetOffset'][$s] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['ChainSubClassSet'][$s]['ChainSubClassRule'][$b] = $ChainSubClassRule[$b]; + } + } + } + + for ($s = 0; $s < $Lookup[$i]['Subtable'][$c]['ChainSubClassSetCnt']; $s++) { + $ChainSubClassRuleCnt = $Lookup[$i]['Subtable'][$c]['ChainSubClassSet'][$s]['ChainSubClassRuleCnt']; + for ($b = 0; $b < $ChainSubClassRuleCnt; $b++) { + if ($Lookup[$i]['Subtable'][$c]['ChainSubClassSetOffset'][$s] > 0) { + $this->seek($Lookup[$i]['Subtable'][$c]['ChainSubClassSet'][$s]['ChainSubClassRule'][$b]); + $Rule = []; + $Rule['BacktrackGlyphCount'] = $this->read_ushort(); + for ($r = 0; $r < $Rule['BacktrackGlyphCount']; $r++) { + $Rule['Backtrack'][$r] = $this->read_ushort(); + } + $Rule['InputGlyphCount'] = $this->read_ushort(); + for ($r = 1; $r < $Rule['InputGlyphCount']; $r++) { + $Rule['Input'][$r] = $this->read_ushort(); + } + $Rule['LookaheadGlyphCount'] = $this->read_ushort(); + for ($r = 0; $r < $Rule['LookaheadGlyphCount']; $r++) { + $Rule['Lookahead'][$r] = $this->read_ushort(); + } + $Rule['SubstCount'] = $this->read_ushort(); + for ($r = 0; $r < $Rule['SubstCount']; $r++) { + $Rule['SequenceIndex'][$r] = $this->read_ushort(); + $Rule['LookupListIndex'][$r] = $this->read_ushort(); + } + + $Lookup[$i]['Subtable'][$c]['ChainSubClassSet'][$s]['ChainSubClassRule'][$b] = $Rule; + } + } + } + } // Format 3: Coverage-based Chaining Context Glyph Substitution p259 + else { + if ($SubstFormat == 3) { + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['BacktrackGlyphCount']; $b++) { + $this->seek($Lookup[$i]['Subtable'][$c]['CoverageBacktrack'][$b]); + $glyphs = $this->_getCoverage(); + $Lookup[$i]['Subtable'][$c]['CoverageBacktrackGlyphs'][] = implode("|", $glyphs); + } + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['InputGlyphCount']; $b++) { + $this->seek($Lookup[$i]['Subtable'][$c]['CoverageInput'][$b]); + $glyphs = $this->_getCoverage(); + $Lookup[$i]['Subtable'][$c]['CoverageInputGlyphs'][] = implode("|", $glyphs); + // Don't use above value as these are ordered numerically not as need to process + } + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['LookaheadGlyphCount']; $b++) { + $this->seek($Lookup[$i]['Subtable'][$c]['CoverageLookahead'][$b]); + $glyphs = $this->_getCoverage(); + $Lookup[$i]['Subtable'][$c]['CoverageLookaheadGlyphs'][] = implode("|", $glyphs); + } + } + } + } + } + } + } + } + } + } + } + } + + //===================================================================================== + //===================================================================================== + //===================================================================================== + + $st = $this->mpdf->OTLscript; + $t = $this->mpdf->OTLlang; + $langsys = $gsub[$st][$t]; + + $lul = []; // array of LookupListIndexes + $tags = []; // corresponding array of feature tags e.g. 'ccmp' + foreach ($langsys as $tag => $ft) { + foreach ($ft as $ll) { + $lul[$ll] = $tag; + } + } + ksort($lul); // Order the Lookups in the order they are in the GUSB table, regardless of Feature order + $this->_getGSUBarray($Lookup, $lul, $st); +//print_r($lul); exit; + } + +//print_r($Lookup); exit; + + return [$GSUBScriptLang, $gsub, $GSLookup, $rtlPUAstr, $rtlPUAarr]; + } + +///////////////////////////////////////////////////////////////////////////////////////// + // GSUB functions + function _getGSUBarray(&$Lookup, &$lul, $scripttag, $level = 1, $coverage = '', $exB = '', $exL = '') + { + // Process (3) LookupList for specific Script-LangSys + // Generate preg_replace + $html = ''; + if ($level == 1) { + $html .= '<bookmark level="0" content="GSUB features">'; + } + foreach ($lul as $i => $tag) { + $html .= '<div class="level' . $level . '">'; + $html .= '<h5 class="level' . $level . '">'; + if ($level == 1) { + $html .= '<bookmark level="1" content="' . $tag . ' [#' . $i . ']">'; + } + $html .= 'Lookup #' . $i . ' [tag: <span style="color:#000066;">' . $tag . '</span>]</h5>'; + $ignore = $this->_getGSUBignoreString($Lookup[$i]['Flag'], $Lookup[$i]['MarkFilteringSet']); + if ($ignore) { + $html .= '<div class="ignore">Ignoring: ' . $ignore . '</div> '; + } + + $Type = $Lookup[$i]['Type']; + $Flag = $Lookup[$i]['Flag']; + if (($Flag & 0x0001) == 1) { + $dir = 'RTL'; + } else { + $dir = 'LTR'; + } + + for ($c = 0; $c < $Lookup[$i]['SubtableCount']; $c++) { + $html .= '<div class="subtable">Subtable #' . $c; + if ($level == 1) { + $html .= '<bookmark level="2" content="Subtable #' . $c . '">'; + } + $html .= '</div>'; + + $SubstFormat = $Lookup[$i]['Subtable'][$c]['Format']; + + // LookupType 1: Single Substitution Subtable + if ($Lookup[$i]['Type'] == 1) { + $html .= '<div class="lookuptype">LookupType 1: Single Substitution Subtable</div>'; + for ($s = 0; $s < count($Lookup[$i]['Subtable'][$c]['subs']); $s++) { + $inputGlyphs = $Lookup[$i]['Subtable'][$c]['subs'][$s]['Replace']; + $substitute = $Lookup[$i]['Subtable'][$c]['subs'][$s]['substitute'][0]; + if ($level == 2 && strpos($coverage, $inputGlyphs[0]) === false) { + continue; + } + $html .= '<div class="substitution">'; + $html .= '<span class="unicode">' . $this->formatUni($inputGlyphs[0]) . ' </span> '; + if ($level == 2 && $exB) { + $html .= $exB; + } + $html .= '<span class="unchanged"> ' . $this->formatEntity($inputGlyphs[0]) . '</span>'; + if ($level == 2 && $exL) { + $html .= $exL; + } + $html .= '  » »  '; + if ($level == 2 && $exB) { + $html .= $exB; + } + $html .= '<span class="changed"> ' . $this->formatEntity($substitute) . '</span>'; + if ($level == 2 && $exL) { + $html .= $exL; + } + $html .= '  <span class="unicode">' . $this->formatUni($substitute) . '</span> '; + $html .= '</div>'; + } + } // LookupType 2: Multiple Substitution Subtable + else { + if ($Lookup[$i]['Type'] == 2) { + $html .= '<div class="lookuptype">LookupType 2: Multiple Substitution Subtable</div>'; + for ($s = 0; $s < count($Lookup[$i]['Subtable'][$c]['subs']); $s++) { + $inputGlyphs = $Lookup[$i]['Subtable'][$c]['subs'][$s]['Replace']; + $substitute = $Lookup[$i]['Subtable'][$c]['subs'][$s]['substitute']; + if ($level == 2 && strpos($coverage, $inputGlyphs[0]) === false) { + continue; + } + $html .= '<div class="substitution">'; + $html .= '<span class="unicode">' . $this->formatUni($inputGlyphs[0]) . ' </span> '; + if ($level == 2 && $exB) { + $html .= $exB; + } + $html .= '<span class="unchanged"> ' . $this->formatEntity($inputGlyphs[0]) . '</span>'; + if ($level == 2 && $exL) { + $html .= $exL; + } + $html .= '  » »  '; + if ($level == 2 && $exB) { + $html .= $exB; + } + $html .= '<span class="changed"> ' . $this->formatEntityArr($substitute) . '</span>'; + if ($level == 2 && $exL) { + $html .= $exL; + } + $html .= '  <span class="unicode">' . $this->formatUniArr($substitute) . '</span> '; + $html .= '</div>'; + } + } // LookupType 3: Alternate Forms + else { + if ($Lookup[$i]['Type'] == 3) { + $html .= '<div class="lookuptype">LookupType 3: Alternate Forms</div>'; + for ($s = 0; $s < count($Lookup[$i]['Subtable'][$c]['subs']); $s++) { + $inputGlyphs = $Lookup[$i]['Subtable'][$c]['subs'][$s]['Replace']; + $substitute = $Lookup[$i]['Subtable'][$c]['subs'][$s]['substitute'][0]; + if ($level == 2 && strpos($coverage, $inputGlyphs[0]) === false) { + continue; + } + $html .= '<div class="substitution">'; + $html .= '<span class="unicode">' . $this->formatUni($inputGlyphs[0]) . ' </span> '; + if ($level == 2 && $exB) { + $html .= $exB; + } + $html .= '<span class="unchanged"> ' . $this->formatEntity($inputGlyphs[0]) . '</span>'; + if ($level == 2 && $exL) { + $html .= $exL; + } + $html .= '  » »  '; + if ($level == 2 && $exB) { + $html .= $exB; + } + $html .= '<span class="changed"> ' . $this->formatEntity($substitute) . '</span>'; + if ($level == 2 && $exL) { + $html .= $exL; + } + $html .= '  <span class="unicode">' . $this->formatUni($substitute) . '</span> '; + if (count($Lookup[$i]['Subtable'][$c]['subs'][$s]['substitute']) > 1) { + for ($alt = 1; $alt < count($Lookup[$i]['Subtable'][$c]['subs'][$s]['substitute']); $alt++) { + $substitute = $Lookup[$i]['Subtable'][$c]['subs'][$s]['substitute'][$alt]; + $html .= '  |   ALT #' . $alt . '   '; + $html .= '<span class="changed"> ' . $this->formatEntity($substitute) . '</span>'; + $html .= '  <span class="unicode">' . $this->formatUni($substitute) . '</span> '; + } + } + $html .= '</div>'; + } + } // LookupType 4: Ligature Substitution Subtable + else { + if ($Lookup[$i]['Type'] == 4) { + $html .= '<div class="lookuptype">LookupType 4: Ligature Substitution Subtable</div>'; + for ($s = 0; $s < count($Lookup[$i]['Subtable'][$c]['subs']); $s++) { + $inputGlyphs = $Lookup[$i]['Subtable'][$c]['subs'][$s]['Replace']; + $substitute = $Lookup[$i]['Subtable'][$c]['subs'][$s]['substitute'][0]; + if ($level == 2 && strpos($coverage, $inputGlyphs[0]) === false) { + continue; + } + $html .= '<div class="substitution">'; + $html .= '<span class="unicode">' . $this->formatUniArr($inputGlyphs) . ' </span> '; + if ($level == 2 && $exB) { + $html .= $exB; + } + $html .= '<span class="unchanged"> ' . $this->formatEntityArr($inputGlyphs) . '</span>'; + if ($level == 2 && $exL) { + $html .= $exL; + } + $html .= '  » »  '; + if ($level == 2 && $exB) { + $html .= $exB; + } + $html .= '<span class="changed"> ' . $this->formatEntity($substitute) . '</span>'; + if ($level == 2 && $exL) { + $html .= $exL; + } + $html .= '  <span class="unicode">' . $this->formatUni($substitute) . '</span> '; + $html .= '</div>'; + } + } // LookupType 5: Contextual Substitution Subtable + else { + if ($Lookup[$i]['Type'] == 5) { + $html .= '<div class="lookuptype">LookupType 5: Contextual Substitution Subtable</div>'; + // Format 1: Context Substitution + if ($SubstFormat == 1) { + $html .= '<div class="lookuptypesub">Format 1: Context Substitution</div>'; + for ($s = 0; $s < $Lookup[$i]['Subtable'][$c]['SubRuleSetCount']; $s++) { + // SubRuleSet + $subRule = []; + $html .= '<div class="rule">Subrule Set: ' . $s . '</div>'; + foreach ($Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRule'] as $rctr => $rule) { + // SubRule + $html .= '<div class="rule">SubRule: ' . $rctr . '</div>'; + $inputGlyphs = []; + if ($rule['GlyphCount'] > 1) { + $inputGlyphs = $rule['InputGlyphs']; + } + $inputGlyphs[0] = $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['FirstGlyph']; + ksort($inputGlyphs); + $nInput = count($inputGlyphs); + + $exampleI = []; + $html .= '<div class="context">CONTEXT: '; + for ($ff = 0; $ff < count($inputGlyphs); $ff++) { + $html .= '<div>Input #' . $ff . ': <span class="unchanged"> ' . $this->formatEntityStr($inputGlyphs[$ff]) . ' </span></div>'; + $exampleI[] = $this->formatEntityFirst($inputGlyphs[$ff]); + } + $html .= '</div>'; + + for ($b = 0; $b < $rule['SubstCount']; $b++) { + $lup = $rule['SubstLookupRecord'][$b]['LookupListIndex']; + $seqIndex = $rule['SubstLookupRecord'][$b]['SequenceIndex']; + + // GENERATE exampleI[<seqIndex] .... exampleI[>seqIndex] + $exB = ''; + $exL = ''; + if ($seqIndex > 0) { + $exB .= '<span class="inputother">'; + for ($ip = 0; $ip < $seqIndex; $ip++) { + $exB .= $this->formatEntity($inputGlyphs[$ip]) . '‍'; + } + $exB .= '</span>'; + } + if (count($inputGlyphs) > ($seqIndex + 1)) { + $exL .= '<span class="inputother">'; + for ($ip = $seqIndex + 1; $ip < count($inputGlyphs); $ip++) { + $exL .= $this->formatEntity($inputGlyphs[$ip]) . '‍'; + } + $exL .= '</span>'; + } + $html .= '<div class="sequenceIndex">Substitution Position: ' . $seqIndex . '</div>'; + + $lul2 = [$lup => $tag]; + + // Only apply if the (first) 'Replace' glyph from the + // Lookup list is in the [inputGlyphs] at ['SequenceIndex'] + // Pass $inputGlyphs[$seqIndex] e.g. 00636|00645|00656 + // to level 2 and only apply if first Replace glyph is in this list + $html .= $this->_getGSUBarray($Lookup, $lul2, $scripttag, 2, $inputGlyphs[$seqIndex], $exB, $exL); + } + + if (count($subRule['rules'])) { + $volt[] = $subRule; + } + } + } + } // Format 2: Class-based Context Glyph Substitution + else { + if ($SubstFormat == 2) { + $html .= '<div class="lookuptypesub">Format 2: Class-based Context Glyph Substitution</div>'; + foreach ($Lookup[$i]['Subtable'][$c]['SubClassSet'] as $inputClass => $cscs) { + $html .= '<div class="rule">Input Class: ' . $inputClass . '</div>'; + for ($cscrule = 0; $cscrule < $cscs['SubClassRuleCnt']; $cscrule++) { + $html .= '<div class="rule">Rule: ' . $cscrule . '</div>'; + $rule = $cscs['SubClassRule'][$cscrule]; + + $inputGlyphs = []; + + $inputGlyphs[0] = $Lookup[$i]['Subtable'][$c]['InputClasses'][$inputClass]; + + if ($rule['InputGlyphCount'] > 1) { + // NB starts at 1 + for ($gcl = 1; $gcl < $rule['InputGlyphCount']; $gcl++) { + $classindex = $rule['Input'][$gcl]; + $inputGlyphs[$gcl] = $Lookup[$i]['Subtable'][$c]['InputClasses'][$classindex]; + } + } + + // Class 0 contains all the glyphs NOT in the other classes + $class0excl = implode('|', $Lookup[$i]['Subtable'][$c]['InputClasses']); + + $exampleI = []; + $html .= '<div class="context">CONTEXT: '; + for ($ff = 0; $ff < count($inputGlyphs); $ff++) { + if (!$inputGlyphs[$ff]) { + $html .= '<div>Input #' . $ff . ': <span class="unchanged"> [NOT ' . $this->formatEntityStr($class0excl) . '] </span></div>'; + $exampleI[] = '[NOT ' . $this->formatEntityFirst($class0excl) . ']'; + } else { + $html .= '<div>Input #' . $ff . ': <span class="unchanged"> ' . $this->formatEntityStr($inputGlyphs[$ff]) . ' </span></div>'; + $exampleI[] = $this->formatEntityFirst($inputGlyphs[$ff]); + } + } + $html .= '</div>'; + + for ($b = 0; $b < $rule['SubstCount']; $b++) { + $lup = $rule['LookupListIndex'][$b]; + $seqIndex = $rule['SequenceIndex'][$b]; + + // GENERATE exampleI[<seqIndex] .... exampleI[>seqIndex] + $exB = ''; + $exL = ''; + + if ($seqIndex > 0) { + $exB .= '<span class="inputother">'; + for ($ip = 0; $ip < $seqIndex; $ip++) { + if (!$inputGlyphs[$ip]) { + $exB .= '[*]'; + } else { + $exB .= $this->formatEntityFirst($inputGlyphs[$ip]) . '‍'; + } + } + $exB .= '</span>'; + } + + if (count($inputGlyphs) > ($seqIndex + 1)) { + $exL .= '<span class="inputother">'; + for ($ip = $seqIndex + 1; $ip < count($inputGlyphs); $ip++) { + if (!$inputGlyphs[$ip]) { + $exL .= '[*]'; + } else { + $exL .= $this->formatEntityFirst($inputGlyphs[$ip]) . '‍'; + } + } + $exL .= '</span>'; + } + + $html .= '<div class="sequenceIndex">Substitution Position: ' . $seqIndex . '</div>'; + + $lul2 = [$lup => $tag]; + + // Only apply if the (first) 'Replace' glyph from the + // Lookup list is in the [inputGlyphs] at ['SequenceIndex'] + // Pass $inputGlyphs[$seqIndex] e.g. 00636|00645|00656 + // to level 2 and only apply if first Replace glyph is in this list + $html .= $this->_getGSUBarray($Lookup, $lul2, $scripttag, 2, $inputGlyphs[$seqIndex], $exB, $exL); + } + if (count($subRule['rules'])) { + $volt[] = $subRule; + } + } + } + } // Format 3: Coverage-based Context Glyph Substitution p259 + else { + if ($SubstFormat == 3) { + $html .= '<div class="lookuptypesub">Format 3: Coverage-based Context Glyph Substitution </div>'; + // IgnoreMarks flag set on main Lookup table + $inputGlyphs = $Lookup[$i]['Subtable'][$c]['CoverageInputGlyphs']; + $CoverageInputGlyphs = implode('|', $inputGlyphs); + $nInput = $Lookup[$i]['Subtable'][$c]['InputGlyphCount']; + + $exampleI = []; + $html .= '<div class="context">CONTEXT: '; + for ($ff = 0; $ff < count($inputGlyphs); $ff++) { + $html .= '<div>Input #' . $ff . ': <span class="unchanged"> ' . $this->formatEntityStr($inputGlyphs[$ff]) . ' </span></div>'; + $exampleI[] = $this->formatEntityFirst($inputGlyphs[$ff]); + } + $html .= '</div>'; + + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['SubstCount']; $b++) { + $lup = $Lookup[$i]['Subtable'][$c]['SubstLookupRecord'][$b]['LookupListIndex']; + $seqIndex = $Lookup[$i]['Subtable'][$c]['SubstLookupRecord'][$b]['SequenceIndex']; + // GENERATE exampleI[<seqIndex] .... exampleI[>seqIndex] + $exB = ''; + $exL = ''; + if ($seqIndex > 0) { + $exB .= '<span class="inputother">'; + for ($ip = 0; $ip < $seqIndex; $ip++) { + $exB .= $exampleI[$ip] . '‍'; + } + $exB .= '</span>'; + } + + if (count($inputGlyphs) > ($seqIndex + 1)) { + $exL .= '<span class="inputother">'; + for ($ip = $seqIndex + 1; $ip < count($inputGlyphs); $ip++) { + $exL .= $exampleI[$ip] . '‍'; + } + $exL .= '</span>'; + } + + $html .= '<div class="sequenceIndex">Substitution Position: ' . $seqIndex . '</div>'; + + $lul2 = [$lup => $tag]; + + // Only apply if the (first) 'Replace' glyph from the + // Lookup list is in the [inputGlyphs] at ['SequenceIndex'] + // Pass $inputGlyphs[$seqIndex] e.g. 00636|00645|00656 + // to level 2 and only apply if first Replace glyph is in this list + $html .= $this->_getGSUBarray($Lookup, $lul2, $scripttag, 2, $inputGlyphs[$seqIndex], $exB, $exL); + } + if (count($subRule['rules'])) { + $volt[] = $subRule; + } + } + } + } + +//print_r($Lookup[$i]); +//print_r($volt[(count($volt)-1)]); exit; + } // LookupType 6: Chaining Contextual Substitution Subtable + else { + if ($Lookup[$i]['Type'] == 6) { + $html .= '<div class="lookuptype">LookupType 6: Chaining Contextual Substitution Subtable</div>'; + // Format 1: Simple Chaining Context Glyph Substitution p255 + if ($SubstFormat == 1) { + $html .= '<div class="lookuptypesub">Format 1: Simple Chaining Context Glyph Substitution </div>'; + for ($s = 0; $s < $Lookup[$i]['Subtable'][$c]['ChainSubRuleSetCount']; $s++) { + // ChainSubRuleSet + $subRule = []; + $html .= '<div class="rule">Subrule Set: ' . $s . '</div>'; + $firstInputGlyph = $Lookup[$i]['Subtable'][$c]['CoverageGlyphs'][$s]; // First input gyyph + foreach ($Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRule'] as $rctr => $rule) { + $html .= '<div class="rule">SubRule: ' . $rctr . '</div>'; + // ChainSubRule + $inputGlyphs = []; + if ($rule['InputGlyphCount'] > 1) { + $inputGlyphs = $rule['InputGlyphs']; + } + $inputGlyphs[0] = $firstInputGlyph; + ksort($inputGlyphs); + $nInput = count($inputGlyphs); + + if ($rule['BacktrackGlyphCount']) { + $backtrackGlyphs = $rule['BacktrackGlyphs']; + } else { + $backtrackGlyphs = []; + } + + if ($rule['LookaheadGlyphCount']) { + $lookaheadGlyphs = $rule['LookaheadGlyphs']; + } else { + $lookaheadGlyphs = []; + } + + $exampleB = []; + $exampleI = []; + $exampleL = []; + $html .= '<div class="context">CONTEXT: '; + for ($ff = count($backtrackGlyphs) - 1; $ff >= 0; $ff--) { + $html .= '<div>Backtrack #' . $ff . ': <span class="unicode">' . $this->formatUniStr($backtrackGlyphs[$ff]) . '</span></div>'; + $exampleB[] = $this->formatEntityFirst($backtrackGlyphs[$ff]); + } + for ($ff = 0; $ff < count($inputGlyphs); $ff++) { + $html .= '<div>Input #' . $ff . ': <span class="unchanged"> ' . $this->formatEntityStr($inputGlyphs[$ff]) . ' </span></div>'; + $exampleI[] = $this->formatEntityFirst($inputGlyphs[$ff]); + } + for ($ff = 0; $ff < count($lookaheadGlyphs); $ff++) { + $html .= '<div>Lookahead #' . $ff . ': <span class="unicode">' . $this->formatUniStr($lookaheadGlyphs[$ff]) . '</span></div>'; + $exampleL[] = $this->formatEntityFirst($lookaheadGlyphs[$ff]); + } + $html .= '</div>'; + + for ($b = 0; $b < $rule['SubstCount']; $b++) { + $lup = $rule['LookupListIndex'][$b]; + $seqIndex = $rule['SequenceIndex'][$b]; + + // GENERATE exampleB[n] exampleI[<seqIndex] .... exampleI[>seqIndex] exampleL[n] + $exB = ''; + $exL = ''; + if (count($exampleB)) { + $exB .= '<span class="backtrack">' . implode('‍', $exampleB) . '</span>'; + } + + if ($seqIndex > 0) { + $exB .= '<span class="inputother">'; + for ($ip = 0; $ip < $seqIndex; $ip++) { + $exB .= $this->formatEntity($inputGlyphs[$ip]) . '‍'; + } + $exB .= '</span>'; + } + + if (count($inputGlyphs) > ($seqIndex + 1)) { + $exL .= '<span class="inputother">'; + for ($ip = $seqIndex + 1; $ip < count($inputGlyphs); $ip++) { + $exL .= $this->formatEntity($inputGlyphs[$ip]) . '‍'; + } + $exL .= '</span>'; + } + + if (count($exampleL)) { + $exL .= '<span class="lookahead">' . implode('‍', $exampleL) . '</span>'; + } + + $html .= '<div class="sequenceIndex">Substitution Position: ' . $seqIndex . '</div>'; + + $lul2 = [$lup => $tag]; + + // Only apply if the (first) 'Replace' glyph from the + // Lookup list is in the [inputGlyphs] at ['SequenceIndex'] + // Pass $inputGlyphs[$seqIndex] e.g. 00636|00645|00656 + // to level 2 and only apply if first Replace glyph is in this list + $html .= $this->_getGSUBarray($Lookup, $lul2, $scripttag, 2, $inputGlyphs[$seqIndex], $exB, $exL); + } + + if (count($subRule['rules'])) { + $volt[] = $subRule; + } + } + } + } // Format 2: Class-based Chaining Context Glyph Substitution p257 + else { + if ($SubstFormat == 2) { + $html .= '<div class="lookuptypesub">Format 2: Class-based Chaining Context Glyph Substitution </div>'; + foreach ($Lookup[$i]['Subtable'][$c]['ChainSubClassSet'] as $inputClass => $cscs) { + $html .= '<div class="rule">Input Class: ' . $inputClass . '</div>'; + for ($cscrule = 0; $cscrule < $cscs['ChainSubClassRuleCnt']; $cscrule++) { + $html .= '<div class="rule">Rule: ' . $cscrule . '</div>'; + $rule = $cscs['ChainSubClassRule'][$cscrule]; + + // These contain classes of glyphs as strings + // $Lookup[$i]['Subtable'][$c]['InputClasses'][(class)] e.g. 02E6|02E7|02E8 + // $Lookup[$i]['Subtable'][$c]['LookaheadClasses'][(class)] + // $Lookup[$i]['Subtable'][$c]['BacktrackClasses'][(class)] + // These contain arrays of classIndexes + // [Backtrack] [Lookahead] and [Input] (Input is from the second position only) + + $inputGlyphs = []; + + $inputGlyphs[0] = $Lookup[$i]['Subtable'][$c]['InputClasses'][$inputClass]; + if ($rule['InputGlyphCount'] > 1) { + // NB starts at 1 + for ($gcl = 1; $gcl < $rule['InputGlyphCount']; $gcl++) { + $classindex = $rule['Input'][$gcl]; + $inputGlyphs[$gcl] = $Lookup[$i]['Subtable'][$c]['InputClasses'][$classindex]; + } + } + // Class 0 contains all the glyphs NOT in the other classes + $class0excl = implode('|', $Lookup[$i]['Subtable'][$c]['InputClasses']); + + $nInput = $rule['InputGlyphCount']; + + if ($rule['BacktrackGlyphCount']) { + for ($gcl = 0; $gcl < $rule['BacktrackGlyphCount']; $gcl++) { + $classindex = $rule['Backtrack'][$gcl]; + $backtrackGlyphs[$gcl] = $Lookup[$i]['Subtable'][$c]['BacktrackClasses'][$classindex]; + } + } else { + $backtrackGlyphs = []; + } + + if ($rule['LookaheadGlyphCount']) { + for ($gcl = 0; $gcl < $rule['LookaheadGlyphCount']; $gcl++) { + $classindex = $rule['Lookahead'][$gcl]; + $lookaheadGlyphs[$gcl] = $Lookup[$i]['Subtable'][$c]['LookaheadClasses'][$classindex]; + } + } else { + $lookaheadGlyphs = []; + } + + $exampleB = []; + $exampleI = []; + $exampleL = []; + $html .= '<div class="context">CONTEXT: '; + for ($ff = count($backtrackGlyphs) - 1; $ff >= 0; $ff--) { + if (!$backtrackGlyphs[$ff]) { + $html .= '<div>Backtrack #' . $ff . ': <span class="unchanged"> [NOT ' . $this->formatEntityStr($class0excl) . '] </span></div>'; + $exampleB[] = '[NOT ' . $this->formatEntityFirst($class0excl) . ']'; + } else { + $html .= '<div>Backtrack #' . $ff . ': <span class="unicode">' . $this->formatUniStr($backtrackGlyphs[$ff]) . '</span></div>'; + $exampleB[] = $this->formatEntityFirst($backtrackGlyphs[$ff]); + } + } + for ($ff = 0; $ff < count($inputGlyphs); $ff++) { + if (!$inputGlyphs[$ff]) { + $html .= '<div>Input #' . $ff . ': <span class="unchanged"> [NOT ' . $this->formatEntityStr($class0excl) . '] </span></div>'; + $exampleI[] = '[NOT ' . $this->formatEntityFirst($class0excl) . ']'; + } else { + $html .= '<div>Input #' . $ff . ': <span class="unchanged"> ' . $this->formatEntityStr($inputGlyphs[$ff]) . ' </span></div>'; + $exampleI[] = $this->formatEntityFirst($inputGlyphs[$ff]); + } + } + for ($ff = 0; $ff < count($lookaheadGlyphs); $ff++) { + if (!$lookaheadGlyphs[$ff]) { + $html .= '<div>Lookahead #' . $ff . ': <span class="unchanged"> [NOT ' . $this->formatEntityStr($class0excl) . '] </span></div>'; + $exampleL[] = '[NOT ' . $this->formatEntityFirst($class0excl) . ']'; + } else { + $html .= '<div>Lookahead #' . $ff . ': <span class="unicode">' . $this->formatUniStr($lookaheadGlyphs[$ff]) . '</span></div>'; + $exampleL[] = $this->formatEntityFirst($lookaheadGlyphs[$ff]); + } + } + $html .= '</div>'; + + for ($b = 0; $b < $rule['SubstCount']; $b++) { + $lup = $rule['LookupListIndex'][$b]; + $seqIndex = $rule['SequenceIndex'][$b]; + + // GENERATE exampleB[n] exampleI[<seqIndex] .... exampleI[>seqIndex] exampleL[n] + $exB = ''; + $exL = ''; + if (count($exampleB)) { + $exB .= '<span class="backtrack">' . implode('‍', $exampleB) . '</span>'; + } + + if ($seqIndex > 0) { + $exB .= '<span class="inputother">'; + for ($ip = 0; $ip < $seqIndex; $ip++) { + if (!$inputGlyphs[$ip]) { + $exB .= '[*]'; + } else { + $exB .= $this->formatEntityFirst($inputGlyphs[$ip]) . '‍'; + } + } + $exB .= '</span>'; + } + + if (count($inputGlyphs) > ($seqIndex + 1)) { + $exL .= '<span class="inputother">'; + for ($ip = $seqIndex + 1; $ip < count($inputGlyphs); $ip++) { + if (!$inputGlyphs[$ip]) { + $exL .= '[*]'; + } else { + $exL .= $this->formatEntityFirst($inputGlyphs[$ip]) . '‍'; + } + } + $exL .= '</span>'; + } + + if (count($exampleL)) { + $exL .= '<span class="lookahead">' . implode('‍', $exampleL) . '</span>'; + } + + $html .= '<div class="sequenceIndex">Substitution Position: ' . $seqIndex . '</div>'; + + $lul2 = [$lup => $tag]; + + // Only apply if the (first) 'Replace' glyph from the + // Lookup list is in the [inputGlyphs] at ['SequenceIndex'] + // Pass $inputGlyphs[$seqIndex] e.g. 00636|00645|00656 + // to level 2 and only apply if first Replace glyph is in this list + $html .= $this->_getGSUBarray($Lookup, $lul2, $scripttag, 2, $inputGlyphs[$seqIndex], $exB, $exL); + } + } + } + +//print_r($Lookup[$i]['Subtable'][$c]); exit; + } // Format 3: Coverage-based Chaining Context Glyph Substitution p259 + else { + if ($SubstFormat == 3) { + $html .= '<div class="lookuptypesub">Format 3: Coverage-based Chaining Context Glyph Substitution </div>'; + // IgnoreMarks flag set on main Lookup table + $inputGlyphs = $Lookup[$i]['Subtable'][$c]['CoverageInputGlyphs']; + $CoverageInputGlyphs = implode('|', $inputGlyphs); + $nInput = $Lookup[$i]['Subtable'][$c]['InputGlyphCount']; + + if ($Lookup[$i]['Subtable'][$c]['BacktrackGlyphCount']) { + $backtrackGlyphs = $Lookup[$i]['Subtable'][$c]['CoverageBacktrackGlyphs']; + } else { + $backtrackGlyphs = []; + } + + if ($Lookup[$i]['Subtable'][$c]['LookaheadGlyphCount']) { + $lookaheadGlyphs = $Lookup[$i]['Subtable'][$c]['CoverageLookaheadGlyphs']; + } else { + $lookaheadGlyphs = []; + } + + $exampleB = []; + $exampleI = []; + $exampleL = []; + $html .= '<div class="context">CONTEXT: '; + for ($ff = count($backtrackGlyphs) - 1; $ff >= 0; $ff--) { + $html .= '<div>Backtrack #' . $ff . ': <span class="unicode">' . $this->formatUniStr($backtrackGlyphs[$ff]) . '</span></div>'; + $exampleB[] = $this->formatEntityFirst($backtrackGlyphs[$ff]); + } + for ($ff = 0; $ff < count($inputGlyphs); $ff++) { + $html .= '<div>Input #' . $ff . ': <span class="unchanged"> ' . $this->formatEntityStr($inputGlyphs[$ff]) . ' </span></div>'; + $exampleI[] = $this->formatEntityFirst($inputGlyphs[$ff]); + } + for ($ff = 0; $ff < count($lookaheadGlyphs); $ff++) { + $html .= '<div>Lookahead #' . $ff . ': <span class="unicode">' . $this->formatUniStr($lookaheadGlyphs[$ff]) . '</span></div>'; + $exampleL[] = $this->formatEntityFirst($lookaheadGlyphs[$ff]); + } + $html .= '</div>'; + + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['SubstCount']; $b++) { + $lup = $Lookup[$i]['Subtable'][$c]['SubstLookupRecord'][$b]['LookupListIndex']; + $seqIndex = $Lookup[$i]['Subtable'][$c]['SubstLookupRecord'][$b]['SequenceIndex']; + + // GENERATE exampleB[n] exampleI[<seqIndex] .... exampleI[>seqIndex] exampleL[n] + $exB = ''; + $exL = ''; + if (count($exampleB)) { + $exB .= '<span class="backtrack">' . implode('‍', $exampleB) . '</span>'; + } + + if ($seqIndex > 0) { + $exB .= '<span class="inputother">'; + for ($ip = 0; $ip < $seqIndex; $ip++) { + $exB .= $exampleI[$ip] . '‍'; + } + $exB .= '</span>'; + } + + if (count($inputGlyphs) > ($seqIndex + 1)) { + $exL .= '<span class="inputother">'; + for ($ip = $seqIndex + 1; $ip < count($inputGlyphs); $ip++) { + $exL .= $exampleI[$ip] . '‍'; + } + $exL .= '</span>'; + } + + if (count($exampleL)) { + $exL .= '<span class="lookahead">' . implode('‍', $exampleL) . '</span>'; + } + + $html .= '<div class="sequenceIndex">Substitution Position: ' . $seqIndex . '</div>'; + + $lul2 = [$lup => $tag]; + + // Only apply if the (first) 'Replace' glyph from the + // Lookup list is in the [inputGlyphs] at ['SequenceIndex'] + // Pass $inputGlyphs[$seqIndex] e.g. 00636|00645|00656 + // to level 2 and only apply if first Replace glyph is in this list + $html .= $this->_getGSUBarray($Lookup, $lul2, $scripttag, 2, $inputGlyphs[$seqIndex], $exB, $exL); + } + } + } + } + } + } + } + } + } + } + } + $html .= '</div>'; + } + if ($level == 1) { + $this->mpdf->WriteHTML($html); + } else { + return $html; + } +//print_r($Lookup); exit; + } + + //===================================================================================== + //===================================================================================== + // mPDF 5.7.1 + function _checkGSUBignore($flag, $glyph, $MarkFilteringSet) + { + $ignore = false; + // Flag & 0x0008 = Ignore Marks + if ((($flag & 0x0008) == 0x0008) && strpos($this->GlyphClassMarks, $glyph)) { + $ignore = true; + } + if ((($flag & 0x0004) == 0x0004) && strpos($this->GlyphClassLigatures, $glyph)) { + $ignore = true; + } + if ((($flag & 0x0002) == 0x0002) && strpos($this->GlyphClassBases, $glyph)) { + $ignore = true; + } + // Flag & 0xFF?? = MarkAttachmentType + if (($flag & 0xFF00) && strpos($this->MarkAttachmentType[($flag >> 8)], $glyph)) { + $ignore = true; + } + // Flag & 0x0010 = UseMarkFilteringSet + if (($flag & 0x0010) && strpos($this->MarkGlyphSets[$MarkFilteringSet], $glyph)) { + $ignore = true; + } + + return $ignore; + } + + function _getGSUBignoreString($flag, $MarkFilteringSet) + { + // If ignoreFlag set, combine all ignore glyphs into -> "((?:(?: FBA1| FBA2| FBA3))*)" + // else "()" + // for Input - set on secondary Lookup table if in Context, and set Backtrack and Lookahead on Context Lookup + $str = ""; + $ignoreflag = 0; + + // Flag & 0xFF?? = MarkAttachmentType + if ($flag & 0xFF00) { + $MarkAttachmentType = $flag >> 8; + $ignoreflag = $flag; + //$str = $this->MarkAttachmentType[$MarkAttachmentType]; + $str = "MarkAttachmentType[" . $MarkAttachmentType . "] "; + } + + // Flag & 0x0010 = UseMarkFilteringSet + if ($flag & 0x0010) { + throw new \Mpdf\MpdfException("This font " . $this->fontkey . " contains MarkGlyphSets"); + $str = "Mark Glyph Set: "; + $str .= $this->MarkGlyphSets[$MarkFilteringSet]; + } + + // If Ignore Marks set, supercedes any above + // Flag & 0x0008 = Ignore Marks + if (($flag & 0x0008) == 0x0008) { + $ignoreflag = 8; + //$str = $this->GlyphClassMarks; + $str = "Mark Glyphs "; + } + + // Flag & 0x0004 = Ignore Ligatures + if (($flag & 0x0004) == 0x0004) { + $ignoreflag += 4; + if ($str) { + $str .= "|"; + } + //$str .= $this->GlyphClassLigatures; + $str .= "Ligature Glyphs "; + } + // Flag & 0x0002 = Ignore BaseGlyphs + if (($flag & 0x0002) == 0x0002) { + $ignoreflag += 2; + if ($str) { + $str .= "|"; + } + //$str .= $this->GlyphClassBases; + $str .= "Base Glyphs "; + } + if ($str) { + return $str; + } else { + return ""; + } + } + + // GSUB Patterns + + /* + BACKTRACK INPUT LOOKAHEAD + ================================== ================== ================================== + (FEEB|FEEC)(ign) ¦(FD12|FD13)(ign) ¦(0612)¦(ign) (0613)¦(ign) (FD12|FD13)¦(ign) (FEEB|FEEC) + ---------------- ---------------- ----- ------------ --------------- --------------- + Backtrack 1 Backtrack 2 Input 1 Input 2 Lookahead 1 Lookahead 2 + -------- --- --------- --- ---- --- ---- --- --------- --- ------- + \${1} \${2} \${3} \${4} \${5+} \${6+} \${7+} \${8+} + + nBacktrack = 2 nInput = 2 nLookahead = 2 + + nBsubs = 2xnBack nIsubs = (nBsubs+) nLsubs = (nBsubs+nIsubs+) 2xnLookahead + "\${1}\${2} " (nInput*2)-1 "\${5+} \${6+}" + "REPL" + + ¦\${1}\${2} ¦\${3}\${4} ¦REPL¦\${5+} \${6+}¦\${7+} \${8+}¦ + + + INPUT nInput = 5 + ============================================================ + ¦(0612)¦(ign) (0613)¦(ign) (0614)¦(ign) (0615)¦(ign) (0615)¦ + \${1} \${2} \${3} \${4} \${5} \${6} \${7} \${8} \${9} (All backreference numbers are + nBsubs) + ----- ------------ ------------ ------------ ------------ + Input 1 Input 2 Input 3 Input 4 Input 5 + + A====== SequenceIndex=1 ; Lookup match nGlyphs=1 + B=================== SequenceIndex=1 ; Lookup match nGlyphs=2 + C=============================== SequenceIndex=1 ; Lookup match nGlyphs=3 + D======================= SequenceIndex=2 ; Lookup match nGlyphs=2 + E===================================== SequenceIndex=2 ; Lookup match nGlyphs=3 + F====================== SequenceIndex=4 ; Lookup match nGlyphs=2 + + All backreference numbers are + nBsubs + A - "REPL\${2} \${3}\${4} \${5}\${6} \${7}\${8} \${9}" + B - "REPL\${2}\${4} \${5}\${6} \${7}\${8} \${9}" + C - "REPL\${2}\${4}\${6} \${7}\${8} \${9}" + D - "\${1} REPL\${2}\${4}\${6} \${7}\${8} \${9}" + E - "\${1} REPL\${2}\${4}\${6}\${8} \${9}" + F - "\${1}\${2} \${3}\${4} \${5} REPL\${6}\${8}" + */ + + function _makeGSUBcontextInputMatch($inputGlyphs, $ignore, $lookupGlyphs, $seqIndex) + { + // $ignore = "((?:(?: FBA1| FBA2| FBA3))*)" or "()" + // Returns e.g. ¦(0612)¦(ignore) (0613)¦(ignore) (0614)¦ + // $inputGlyphs = array of glyphs(glyphstrings) making up Input sequence in Context + // $lookupGlyphs = array of glyphs (single Glyphs) making up Lookup Input sequence + $mLen = count($lookupGlyphs); // nGlyphs in the secondary Lookup match + $nInput = count($inputGlyphs); // nGlyphs in the Primary Input sequence + $str = ""; + for ($i = 0; $i < $nInput; $i++) { + if ($i > 0) { + $str .= $ignore . " "; + } + if ($i >= $seqIndex && $i < ($seqIndex + $mLen)) { + $str .= "" . $lookupGlyphs[($i - $seqIndex)] . ""; + } else { + $str .= "" . $inputGlyphs[($i)] . ""; + } + } + + return $str; + } + + function _makeGSUBinputMatch($inputGlyphs, $ignore) + { + // $ignore = "((?:(?: FBA1| FBA2| FBA3))*)" or "()" + // Returns e.g. ¦(0612)¦(ignore) (0613)¦(ignore) (0614)¦ + // $inputGlyphs = array of glyphs(glyphstrings) making up Input sequence in Context + // $lookupGlyphs = array of glyphs making up Lookup Input sequence - if applicable + $str = ""; + for ($i = 1; $i <= count($inputGlyphs); $i++) { + if ($i > 1) { + $str .= $ignore . " "; + } + $str .= "" . $inputGlyphs[($i - 1)] . ""; + } + + return $str; + } + + function _makeGSUBbacktrackMatch($backtrackGlyphs, $ignore) + { + // $ignore = "((?:(?: FBA1| FBA2| FBA3))*)" or "()" + // Returns e.g. ¦(FEEB|FEEC)(ignore) ¦(FD12|FD13)(ignore) ¦ + // $backtrackGlyphs = array of glyphstrings making up Backtrack sequence + // 3 2 1 0 + // each item being e.g. E0AD|E0AF|F1FD + $str = ""; + for ($i = (count($backtrackGlyphs) - 1); $i >= 0; $i--) { + $str .= "" . $backtrackGlyphs[$i] . " " . $ignore . " "; + } + + return $str; + } + + function _makeGSUBlookaheadMatch($lookaheadGlyphs, $ignore) + { + // $ignore = "((?:(?: FBA1| FBA2| FBA3))*)" or "()" + // Returns e.g. ¦(ignore) (FD12|FD13)¦(ignore) (FEEB|FEEC)¦ + // $lookaheadGlyphs = array of glyphstrings making up Lookahead sequence + // 0 1 2 3 + // each item being e.g. E0AD|E0AF|F1FD + $str = ""; + for ($i = 0; $i < count($lookaheadGlyphs); $i++) { + $str .= $ignore . " " . $lookaheadGlyphs[$i] . ""; + } + + return $str; + } + + function _makeGSUBinputReplacement($nInput, $REPL, $ignore, $nBsubs, $mLen, $seqIndex) + { + // Returns e.g. "REPL\${6}\${8}" or "\${1}\${2} \${3} REPL\${4}\${6}\${8} \${9}" + // $nInput nGlyphs in the Primary Input sequence + // $REPL replacement glyphs from secondary lookup + // $ignore = "((?:(?: FBA1| FBA2| FBA3))*)" or "()" + // $nBsubs Number of Backtrack substitutions (= 2x Number of Backtrack glyphs) + // $mLen nGlyphs in the secondary Lookup match - if no secondary lookup, should=$nInput + // $seqIndex Sequence Index to apply the secondary match + if ($ignore == "()") { + $ign = false; + } else { + $ign = true; + } + $str = ""; + if ($nInput == 1) { + $str = $REPL; + } else { + if ($nInput > 1) { + if ($mLen == $nInput) { // whole string replaced + $str = $REPL; + if ($ign) { + // for every nInput over 1, add another replacement backreference, to move IGNORES after replacement + for ($x = 2; $x <= $nInput; $x++) { + $str .= '\\' . ($nBsubs + (2 * ($x - 1))); + } + } + } else { // if only part of string replaced: + for ($x = 1; $x < ($seqIndex + 1); $x++) { + if ($x == 1) { + $str .= '\\' . ($nBsubs + 1); + } else { + if ($ign) { + $str .= '\\' . ($nBsubs + (2 * ($x - 1))); + } + $str .= ' \\' . ($nBsubs + 1 + (2 * ($x - 1))); + } + } + if ($seqIndex > 0) { + $str .= " "; + } + $str .= $REPL; + if ($ign) { + for ($x = (max(($seqIndex + 1), 2)); $x < ($seqIndex + 1 + $mLen); $x++) { // move IGNORES after replacement + $str .= '\\' . ($nBsubs + (2 * ($x - 1))); + } + } + for ($x = ($seqIndex + 1 + $mLen); $x <= $nInput; $x++) { + if ($ign) { + $str .= '\\' . ($nBsubs + (2 * ($x - 1))); + } + $str .= ' \\' . ($nBsubs + 1 + (2 * ($x - 1))); + } + } + } + } + + return $str; + } + + ////////////////////////////////////////////////////////////////////////////////// + function _getCoverage($convert2hex = true) + { + $g = []; + $CoverageFormat = $this->read_ushort(); + if ($CoverageFormat == 1) { + $CoverageGlyphCount = $this->read_ushort(); + for ($gid = 0; $gid < $CoverageGlyphCount; $gid++) { + $glyphID = $this->read_ushort(); + if ($convert2hex) { + $g[] = unicode_hex($this->glyphToChar[$glyphID][0]); + } else { + $g[] = $glyphID; + } + } + } + if ($CoverageFormat == 2) { + $RangeCount = $this->read_ushort(); + for ($r = 0; $r < $RangeCount; $r++) { + $start = $this->read_ushort(); + $end = $this->read_ushort(); + $StartCoverageIndex = $this->read_ushort(); // n/a + for ($gid = $start; $gid <= $end; $gid++) { + $glyphID = $gid; + if ($convert2hex) { + $g[] = unicode_hex($this->glyphToChar[$glyphID][0]); + } else { + $g[] = $glyphID; + } + } + } + } + + return $g; + } + + ////////////////////////////////////////////////////////////////////////////////// + function _getClasses($offset) + { + $this->seek($offset); + $ClassFormat = $this->read_ushort(); + $GlyphByClass = []; + if ($ClassFormat == 1) { + $StartGlyph = $this->read_ushort(); + $GlyphCount = $this->read_ushort(); + for ($i = 0; $i < $GlyphCount; $i++) { + $startGlyphID = $StartGlyph + $i; + $endGlyphID = $StartGlyph + $i; + $class = $this->read_ushort(); + for ($g = $startGlyphID; $g <= $endGlyphID; $g++) { + if ($this->glyphToChar[$g][0]) { + $GlyphByClass[$class][] = unicode_hex($this->glyphToChar[$g][0]); + } + } + } + } else { + if ($ClassFormat == 2) { + $tableCount = $this->read_ushort(); + for ($i = 0; $i < $tableCount; $i++) { + $startGlyphID = $this->read_ushort(); + $endGlyphID = $this->read_ushort(); + $class = $this->read_ushort(); + for ($g = $startGlyphID; $g <= $endGlyphID; $g++) { + if ($this->glyphToChar[$g][0]) { + $GlyphByClass[$class][] = unicode_hex($this->glyphToChar[$g][0]); + } + } + } + } + } + $gbc = []; + foreach ($GlyphByClass as $class => $garr) { + $gbc[$class] = implode('|', $garr); + } + + return $gbc; + } + + ////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////////// + function _getGPOStables() + { + /////////////////////////////////// + // GPOS - Glyph Positioning + /////////////////////////////////// + if (isset($this->tables["GPOS"])) { + $this->mpdf->WriteHTML('<h1>GPOS Tables</h1>'); + $ffeats = []; + $gpos_offset = $this->seek_table("GPOS"); + $this->skip(4); + $ScriptList_offset = $gpos_offset + $this->read_ushort(); + $FeatureList_offset = $gpos_offset + $this->read_ushort(); + $LookupList_offset = $gpos_offset + $this->read_ushort(); + + // ScriptList + $this->seek($ScriptList_offset); + $ScriptCount = $this->read_ushort(); + for ($i = 0; $i < $ScriptCount; $i++) { + $ScriptTag = $this->read_tag(); // = "beng", "deva" etc. + $ScriptTableOffset = $this->read_ushort(); + $ffeats[$ScriptTag] = $ScriptList_offset + $ScriptTableOffset; + } + + // Script Table + foreach ($ffeats as $t => $o) { + $ls = []; + $this->seek($o); + $DefLangSys_offset = $this->read_ushort(); + if ($DefLangSys_offset > 0) { + $ls['DFLT'] = $DefLangSys_offset + $o; + } + $LangSysCount = $this->read_ushort(); + for ($i = 0; $i < $LangSysCount; $i++) { + $LangTag = $this->read_tag(); // = + $LangTableOffset = $this->read_ushort(); + $ls[$LangTag] = $o + $LangTableOffset; + } + $ffeats[$t] = $ls; + } + + // Get FeatureIndexList + // LangSys Table - from first listed langsys + foreach ($ffeats as $st => $scripts) { + foreach ($scripts as $t => $o) { + $FeatureIndex = []; + $langsystable_offset = $o; + $this->seek($langsystable_offset); + $LookUpOrder = $this->read_ushort(); //==NULL + $ReqFeatureIndex = $this->read_ushort(); + if ($ReqFeatureIndex != 0xFFFF) { + $FeatureIndex[] = $ReqFeatureIndex; + } + $FeatureCount = $this->read_ushort(); + for ($i = 0; $i < $FeatureCount; $i++) { + $FeatureIndex[] = $this->read_ushort(); // = index of feature + } + $ffeats[$st][$t] = $FeatureIndex; + } + } +//print_r($ffeats); exit; + // Feauture List => LookupListIndex es + $this->seek($FeatureList_offset); + $FeatureCount = $this->read_ushort(); + $Feature = []; + for ($i = 0; $i < $FeatureCount; $i++) { + $Feature[$i] = ['tag' => $this->read_tag()]; + $Feature[$i]['offset'] = $FeatureList_offset + $this->read_ushort(); + } + for ($i = 0; $i < $FeatureCount; $i++) { + $this->seek($Feature[$i]['offset']); + $this->read_ushort(); // null + $Feature[$i]['LookupCount'] = $Lookupcount = $this->read_ushort(); + $Feature[$i]['LookupListIndex'] = []; + for ($c = 0; $c < $Lookupcount; $c++) { + $Feature[$i]['LookupListIndex'][] = $this->read_ushort(); + } + } + + foreach ($ffeats as $st => $scripts) { + foreach ($scripts as $t => $o) { + $FeatureIndex = $ffeats[$st][$t]; + foreach ($FeatureIndex as $k => $fi) { + $ffeats[$st][$t][$k] = $Feature[$fi]; + } + } + } +//print_r($ffeats); exit; + //===================================================================================== + $gpos = []; + $GPOSScriptLang = []; + foreach ($ffeats as $st => $scripts) { + foreach ($scripts as $t => $langsys) { + $lg = []; + foreach ($langsys as $ft) { + $lg[$ft['LookupListIndex'][0]] = $ft; + } + // list of Lookups in order they need to be run i.e. order listed in Lookup table + ksort($lg); + foreach ($lg as $ft) { + $gpos[$st][$t][$ft['tag']] = $ft['LookupListIndex']; + } + if (!isset($GPOSScriptLang[$st])) { + $GPOSScriptLang[$st] = ''; + } + $GPOSScriptLang[$st] .= $t . ' '; + } + } + if ($this->mode == 'summary') { + $this->mpdf->WriteHTML('<h3>GPOS Scripts & Languages</h3>'); + $html = ''; + if (count($gpos)) { + foreach ($gpos as $st => $g) { + $html .= '<h5>' . $st . '</h5>'; + foreach ($g as $l => $t) { + $html .= '<div><a href="font_dump_OTL.php?script=' . $st . '&lang=' . $l . '">' . $l . '</a></b>: '; + foreach ($t as $tag => $o) { + $html .= $tag . ' '; + } + $html .= '</div>'; + } + } + } else { + $html .= '<div>No entries in GPOS table.</div>'; + } + $this->mpdf->WriteHTML($html); + $this->mpdf->WriteHTML('</div>'); + + return 0; + } + + //===================================================================================== + // Get metadata and offsets for whole Lookup List table + $this->seek($LookupList_offset); + $LookupCount = $this->read_ushort(); + $Lookup = []; + $Offsets = []; + $SubtableCount = []; + for ($i = 0; $i < $LookupCount; $i++) { + $Offsets[$i] = $LookupList_offset + $this->read_ushort(); + } + for ($i = 0; $i < $LookupCount; $i++) { + $this->seek($Offsets[$i]); + $Lookup[$i]['Type'] = $this->read_ushort(); + $Lookup[$i]['Flag'] = $flag = $this->read_ushort(); + $Lookup[$i]['SubtableCount'] = $SubtableCount[$i] = $this->read_ushort(); + for ($c = 0; $c < $SubtableCount[$i]; $c++) { + $Lookup[$i]['Subtables'][$c] = $Offsets[$i] + $this->read_ushort(); + } + // MarkFilteringSet = Index (base 0) into GDEF mark glyph sets structure + if (($flag & 0x0010) == 0x0010) { + $Lookup[$i]['MarkFilteringSet'] = $this->read_ushort(); + } + // else { $Lookup[$i]['MarkFilteringSet'] = ''; } + // Lookup Type 9: Extension + if ($Lookup[$i]['Type'] == 9) { + // Overwrites new offset (32-bit) for each subtable, and a new lookup Type + for ($c = 0; $c < $SubtableCount[$i]; $c++) { + $this->seek($Lookup[$i]['Subtables'][$c]); + $ExtensionPosFormat = $this->read_ushort(); + $type = $this->read_ushort(); + $Lookup[$i]['Subtables'][$c] = $Lookup[$i]['Subtables'][$c] + $this->read_ulong(); + } + $Lookup[$i]['Type'] = $type; + } + } + + //===================================================================================== + + $st = $this->mpdf->OTLscript; + $t = $this->mpdf->OTLlang; + $langsys = $gpos[$st][$t]; + + $lul = []; // array of LookupListIndexes + $tags = []; // corresponding array of feature tags e.g. 'ccmp' + if (count($langsys)) { + foreach ($langsys as $tag => $ft) { + foreach ($ft as $ll) { + $lul[$ll] = $tag; + } + } + } + ksort($lul); // Order the Lookups in the order they are in the GUSB table, regardless of Feature order + $this->_getGPOSarray($Lookup, $lul, $st); + +//print_r($lul); exit; + + return [$GPOSScriptLang, $gpos, $Lookup]; + } // end if GPOS + } + + ////////////////////////////////////////////////////////////////////////////////// + //===================================================================================== + //===================================================================================== + //===================================================================================== +///////////////////////////////////////////////////////////////////////////////////////// + // GPOS functions + function _getGPOSarray(&$Lookup, $lul, $scripttag, $level = 1, $lcoverage = '', $exB = '', $exL = '') + { + // Process (3) LookupList for specific Script-LangSys + $html = ''; + if ($level == 1) { + $html .= '<bookmark level="0" content="GPOS features">'; + } + foreach ($lul as $luli => $tag) { + $html .= '<div class="level' . $level . '">'; + $html .= '<h5 class="level' . $level . '">'; + if ($level == 1) { + $html .= '<bookmark level="1" content="' . $tag . ' [#' . $luli . ']">'; + } + $html .= 'Lookup #' . $luli . ' [tag: <span style="color:#000066;">' . $tag . '</span>]</h5>'; + $ignore = $this->_getGSUBignoreString($Lookup[$luli]['Flag'], $Lookup[$luli]['MarkFilteringSet']); + if ($ignore) { + $html .= '<div class="ignore">Ignoring: ' . $ignore . '</div> '; + } + + $Type = $Lookup[$luli]['Type']; + $Flag = $Lookup[$luli]['Flag']; + if (($Flag & 0x0001) == 1) { + $dir = 'RTL'; + } else { + $dir = 'LTR'; + } + + for ($c = 0; $c < $Lookup[$luli]['SubtableCount']; $c++) { + $html .= '<div class="subtable">Subtable #' . $c; + if ($level == 1) { + $html .= '<bookmark level="2" content="Subtable #' . $c . '">'; + } + $html .= '</div>'; + + // Lets start + $subtable_offset = $Lookup[$luli]['Subtables'][$c]; + $this->seek($subtable_offset); + $PosFormat = $this->read_ushort(); + + //////////////////////////////////////////////////////////////////////////////// + // LookupType 1: Single adjustment Adjust position of a single glyph (e.g. SmallCaps/Sups/Subs) + //////////////////////////////////////////////////////////////////////////////// + if ($Lookup[$luli]['Type'] == 1) { + $html .= '<div class="lookuptype">LookupType 1: Single adjustment [Format ' . $PosFormat . ']</div>'; + //=========== + // Format 1: + //=========== + if ($PosFormat == 1) { + $Coverage = $subtable_offset + $this->read_ushort(); + $ValueFormat = $this->read_ushort(); + $Value = $this->_getValueRecord($ValueFormat); + + $this->seek($Coverage); + $glyphs = $this->_getCoverage(); // Array of Hex Glyphs + for ($g = 0; $g < count($glyphs); $g++) { + if ($level == 2 && strpos($lcoverage, $glyphs[$g]) === false) { + continue; + } + + $html .= '<div class="substitution">'; + $html .= '<span class="unicode">' . $this->formatUni($glyphs[$g]) . ' </span> '; + if ($level == 2 && $exB) { + $html .= $exB; + } + $html .= '<span class="unchanged"> ' . $this->formatEntity($glyphs[$g]) . '</span>'; + if ($level == 2 && $exL) { + $html .= $exL; + } + $html .= '  » »  '; + if ($level == 2 && $exB) { + $html .= $exB; + } + $html .= '<span class="changed" style="font-feature-settings:\'' . $tag . '\' 1;"> ' . $this->formatEntity($glyphs[$g]) . '</span>'; + if ($level == 2 && $exL) { + $html .= $exL; + } + $html .= ' <span class="unicode">'; + if ($Value['XPlacement']) { + $html .= ' Xpl: ' . $Value['XPlacement'] . ';'; + } + if ($Value['YPlacement']) { + $html .= ' YPl: ' . $Value['YPlacement'] . ';'; + } + if ($Value['XAdvance']) { + $html .= ' Xadv: ' . $Value['XAdvance']; + } + $html .= '</span>'; + $html .= '</div>'; + } + } //=========== + // Format 2: + //=========== + else { + if ($PosFormat == 2) { + $Coverage = $subtable_offset + $this->read_ushort(); + $ValueFormat = $this->read_ushort(); + $ValueCount = $this->read_ushort(); + $Values = []; + for ($v = 0; $v < $ValueCount; $v++) { + $Values[] = $this->_getValueRecord($ValueFormat); + } + + $this->seek($Coverage); + $glyphs = $this->_getCoverage(); // Array of Hex Glyphs + + for ($g = 0; $g < count($glyphs); $g++) { + if ($level == 2 && strpos($lcoverage, $glyphs[$g]) === false) { + continue; + } + $Value = $Values[$g]; + + $html .= '<div class="substitution">'; + $html .= '<span class="unicode">' . $this->formatUni($glyphs[$g]) . ' </span> '; + if ($level == 2 && $exB) { + $html .= $exB; + } + $html .= '<span class="unchanged"> ' . $this->formatEntity($glyphs[$g]) . '</span>'; + if ($level == 2 && $exL) { + $html .= $exL; + } + $html .= '  » »  '; + if ($level == 2 && $exB) { + $html .= $exB; + } + $html .= '<span class="changed" style="font-feature-settings:\'' . $tag . '\' 1;"> ' . $this->formatEntity($glyphs[$g]) . '</span>'; + if ($level == 2 && $exL) { + $html .= $exL; + } + $html .= ' <span class="unicode">'; + if ($Value['XPlacement']) { + $html .= ' Xpl: ' . $Value['XPlacement'] . ';'; + } + if ($Value['YPlacement']) { + $html .= ' YPl: ' . $Value['YPlacement'] . ';'; + } + if ($Value['XAdvance']) { + $html .= ' Xadv: ' . $Value['XAdvance']; + } + $html .= '</span>'; + $html .= '</div>'; + } + } + } + } //////////////////////////////////////////////////////////////////////////////// + // LookupType 2: Pair adjustment Adjust position of a pair of glyphs (Kerning) + //////////////////////////////////////////////////////////////////////////////// + else { + if ($Lookup[$luli]['Type'] == 2) { + $html .= '<div class="lookuptype">LookupType 2: Pair adjustment e.g. Kerning [Format ' . $PosFormat . ']</div>'; + $Coverage = $subtable_offset + $this->read_ushort(); + $ValueFormat1 = $this->read_ushort(); + $ValueFormat2 = $this->read_ushort(); + //=========== + // Format 1: + //=========== + if ($PosFormat == 1) { + $PairSetCount = $this->read_ushort(); + $PairSetOffset = []; + for ($p = 0; $p < $PairSetCount; $p++) { + $PairSetOffset[] = $subtable_offset + $this->read_ushort(); + } + $this->seek($Coverage); + $glyphs = $this->_getCoverage(); // Array of Hex Glyphs + for ($p = 0; $p < $PairSetCount; $p++) { + if ($level == 2 && strpos($lcoverage, $glyphs[$p]) === false) { + continue; + } + $this->seek($PairSetOffset[$p]); + // First Glyph = $glyphs[$p] +// Takes too long e.g. Calibri font - just list kerning pairs with this: + $html .= '<div class="glyphs">'; + $html .= '<span class="unchanged"> ' . $this->formatEntity($glyphs[$p]) . ' </span>'; + + //PairSet table + $PairValueCount = $this->read_ushort(); + for ($pv = 0; $pv < $PairValueCount; $pv++) { + //PairValueRecord + $gid = $this->read_ushort(); + $SecondGlyph = unicode_hex($this->glyphToChar[$gid][0]); + $Value1 = $this->_getValueRecord($ValueFormat1); + $Value2 = $this->_getValueRecord($ValueFormat2); + + // If RTL pairs, GPOS declares a XPlacement e.g. -180 for an XAdvance of -180 to take + // account of direction. mPDF does not need the XPlacement adjustment + if ($dir == 'RTL' && $Value1['XPlacement']) { + $Value1['XPlacement'] -= $Value1['XAdvance']; + } + + if ($ValueFormat2) { + // If RTL pairs, GPOS declares a XPlacement e.g. -180 for an XAdvance of -180 to take + // account of direction. mPDF does not need the XPlacement adjustment + if ($dir == 'RTL' && $Value2['XPlacement'] && $Value2['XAdvance']) { + $Value2['XPlacement'] -= $Value2['XAdvance']; + } + } + + $html .= ' ' . $this->formatEntity($SecondGlyph) . ' '; + + /* + $html .= '<div class="substitution">'; + $html .= '<span class="unicode">'.$this->formatUni($glyphs[$p]).' </span> '; + if ($level==2 && $exB) { $html .= $exB; } + $html .= '<span class="unchanged"> '.$this->formatEntity($glyphs[$p]).$this->formatEntity($SecondGlyph).'</span>'; + if ($level==2 && $exL) { $html .= $exL; } + $html .= '  » »  '; + if ($level==2 && $exB) { $html .= $exB; } + $html .= '<span class="changed" style="font-feature-settings:\''.$tag.'\' 1;"> '.$this->formatEntity($glyphs[$p]).$this->formatEntity($SecondGlyph).'</span>'; + if ($level==2 && $exL) { $html .= $exL; } + $html .= ' <span class="unicode">'; + if ($Value1['XPlacement']) { $html .= ' Xpl[1]: '.$Value1['XPlacement'].';'; } + if ($Value1['YPlacement']) { $html .= ' YPl[1]: '.$Value1['YPlacement'].';'; } + if ($Value1['XAdvance']) { $html .= ' Xadv[1]: '.$Value1['XAdvance']; } + if ($Value2['XPlacement']) { $html .= ' Xpl[2]: '.$Value2['XPlacement'].';'; } + if ($Value2['YPlacement']) { $html .= ' YPl[2]: '.$Value2['YPlacement'].';'; } + if ($Value2['XAdvance']) { $html .= ' Xadv[2]: '.$Value2['XAdvance']; } + $html .= '</span>'; + $html .= '</div>'; + */ + } + $html .= '</div>'; + } + } //=========== + // Format 2: + //=========== + else { + if ($PosFormat == 2) { + $ClassDef1 = $subtable_offset + $this->read_ushort(); + $ClassDef2 = $subtable_offset + $this->read_ushort(); + $Class1Count = $this->read_ushort(); + $Class2Count = $this->read_ushort(); + + $sizeOfPair = (2 * $this->count_bits($ValueFormat1)) + (2 * $this->count_bits($ValueFormat2)); + $sizeOfValueRecords = $Class1Count * $Class2Count * $sizeOfPair; + + // NB Class1Count includes Class 0 even though it is not defined by $ClassDef1 + // i.e. Class1Count = 5; Class1 will contain array(indices 1-4); + $Class1 = $this->_getClassDefinitionTable($ClassDef1); + $Class2 = $this->_getClassDefinitionTable($ClassDef2); + + $this->seek($subtable_offset + 16); + + for ($i = 0; $i < $Class1Count; $i++) { + for ($j = 0; $j < $Class2Count; $j++) { + $Value1 = $this->_getValueRecord($ValueFormat1); + $Value2 = $this->_getValueRecord($ValueFormat2); + + // If RTL pairs, GPOS declares a XPlacement e.g. -180 for an XAdvance of -180 + // of direction. mPDF does not need the XPlacement adjustment + if ($dir == 'RTL' && $Value1['XPlacement'] && $Value1['XAdvance']) { + $Value1['XPlacement'] -= $Value1['XAdvance']; + } + if ($ValueFormat2) { + if ($dir == 'RTL' && $Value2['XPlacement'] && $Value2['XAdvance']) { + $Value2['XPlacement'] -= $Value2['XAdvance']; + } + } + + for ($c1 = 0; $c1 < count($Class1[$i]); $c1++) { + $FirstGlyph = $Class1[$i][$c1]; + if ($level == 2 && strpos($lcoverage, $FirstGlyph) === false) { + continue; + } + + for ($c2 = 0; $c2 < count($Class2[$j]); $c2++) { + $SecondGlyph = $Class2[$j][$c2]; + + if (!$Value1['XPlacement'] && !$Value1['YPlacement'] && !$Value1['XAdvance'] && !$Value2['XPlacement'] && !$Value2['YPlacement'] && !$Value2['XAdvance']) { + continue; + } + + $html .= '<div class="substitution">'; + $html .= '<span class="unicode">' . $this->formatUni($FirstGlyph) . ' </span> '; + if ($level == 2 && $exB) { + $html .= $exB; + } + $html .= '<span class="unchanged"> ' . $this->formatEntity($FirstGlyph) . $this->formatEntity($SecondGlyph) . '</span>'; + if ($level == 2 && $exL) { + $html .= $exL; + } + $html .= '  » »  '; + if ($level == 2 && $exB) { + $html .= $exB; + } + $html .= '<span class="changed" style="font-feature-settings:\'' . $tag . '\' 1;"> ' . $this->formatEntity($FirstGlyph) . $this->formatEntity($SecondGlyph) . '</span>'; + if ($level == 2 && $exL) { + $html .= $exL; + } + $html .= ' <span class="unicode">'; + if ($Value1['XPlacement']) { + $html .= ' Xpl[1]: ' . $Value1['XPlacement'] . ';'; + } + if ($Value1['YPlacement']) { + $html .= ' YPl[1]: ' . $Value1['YPlacement'] . ';'; + } + if ($Value1['XAdvance']) { + $html .= ' Xadv[1]: ' . $Value1['XAdvance']; + } + if ($Value2['XPlacement']) { + $html .= ' Xpl[2]: ' . $Value2['XPlacement'] . ';'; + } + if ($Value2['YPlacement']) { + $html .= ' YPl[2]: ' . $Value2['YPlacement'] . ';'; + } + if ($Value2['XAdvance']) { + $html .= ' Xadv[2]: ' . $Value2['XAdvance']; + } + $html .= '</span>'; + $html .= '</div>'; + } + } + } + } + } + } + } //////////////////////////////////////////////////////////////////////////////// + // LookupType 3: Cursive attachment Attach cursive glyphs + //////////////////////////////////////////////////////////////////////////////// + else { + if ($Lookup[$luli]['Type'] == 3) { + $html .= '<div class="lookuptype">LookupType 3: Cursive attachment </div>'; + $Coverage = $subtable_offset + $this->read_ushort(); + $EntryExitCount = $this->read_ushort(); + $EntryAnchors = []; + $ExitAnchors = []; + for ($i = 0; $i < $EntryExitCount; $i++) { + $EntryAnchors[$i] = $this->read_ushort(); + $ExitAnchors[$i] = $this->read_ushort(); + } + + $this->seek($Coverage); + $Glyphs = $this->_getCoverage(); + for ($i = 0; $i < $EntryExitCount; $i++) { + // Need default XAdvance for glyph + $pdfWidth = $this->mpdf->_getCharWidth($this->mpdf->fonts[$this->fontkey]['cw'], hexdec($Glyphs[$i])); + $EntryAnchor = $EntryAnchors[$i]; + $ExitAnchor = $ExitAnchors[$i]; + $html .= '<div class="glyphs">'; + $html .= '<span class="unchanged">' . $this->formatEntity($Glyphs[$i]) . ' </span> '; + $html .= '<span class="unicode"> ' . $this->formatUni($Glyphs[$i]) . ' => '; + + if ($EntryAnchor != 0) { + $EntryAnchor += $subtable_offset; + list($x, $y) = $this->_getAnchorTable($EntryAnchor); + if ($dir == 'RTL') { + if (round($pdfWidth) == round($x * 1000 / $this->mpdf->fonts[$this->fontkey]['desc']['unitsPerEm'])) { + $x = 0; + } else { + $x = $x - ($pdfWidth * $this->mpdf->fonts[$this->fontkey]['desc']['unitsPerEm'] / 1000); + } + } + $html .= " Entry X: " . $x . " Y: " . $y . "; "; + } + if ($ExitAnchor != 0) { + $ExitAnchor += $subtable_offset; + list($x, $y) = $this->_getAnchorTable($ExitAnchor); + if ($dir == 'LTR') { + if (round($pdfWidth) == round($x * 1000 / $this->mpdf->fonts[$this->fontkey]['desc']['unitsPerEm'])) { + $x = 0; + } else { + $x = $x - ($pdfWidth * $this->mpdf->fonts[$this->fontkey]['desc']['unitsPerEm'] / 1000); + } + } + $html .= " Exit X: " . $x . " Y: " . $y . "; "; + } + + $html .= '</span></div>'; + } + } //////////////////////////////////////////////////////////////////////////////// + // LookupType 4: MarkToBase attachment Attach a combining mark to a base glyph + //////////////////////////////////////////////////////////////////////////////// + else { + if ($Lookup[$luli]['Type'] == 4) { + $html .= '<div class="lookuptype">LookupType 4: MarkToBase attachment </div>'; + $MarkCoverage = $subtable_offset + $this->read_ushort(); + $BaseCoverage = $subtable_offset + $this->read_ushort(); + + $this->seek($MarkCoverage); + $MarkGlyphs = $this->_getCoverage(); + + $this->seek($BaseCoverage); + $BaseGlyphs = $this->_getCoverage(); + + $firstMark = ''; + $html .= '<div class="glyphs">Marks: '; + for ($i = 0; $i < count($MarkGlyphs); $i++) { + if ($level == 2 && strpos($lcoverage, $MarkGlyphs[$i]) === false) { + continue; + } else { + if (!$firstMark) { + $firstMark = $MarkGlyphs[$i]; + } + } + $html .= ' ' . $this->formatEntity($MarkGlyphs[$i]) . ' '; + } + $html .= '</div>'; + if (!$firstMark) { + return; + } + + $html .= '<div class="glyphs">Bases: '; + for ($j = 0; $j < count($BaseGlyphs); $j++) { + $html .= ' ' . $this->formatEntity($BaseGlyphs[$j]) . ' '; + } + $html .= '</div>'; + + // Example + $html .= '<div class="glyphs" style="font-feature-settings:\'' . $tag . '\' 1;">Example(s): '; + for ($j = 0; $j < min(count($BaseGlyphs), 20); $j++) { + $html .= ' ' . $this->formatEntity($BaseGlyphs[$j]) . $this->formatEntity($firstMark, true) . '   '; + } + $html .= '</div>'; + } //////////////////////////////////////////////////////////////////////////////// + // LookupType 5: MarkToLigature attachment Attach a combining mark to a ligature + //////////////////////////////////////////////////////////////////////////////// + else { + if ($Lookup[$luli]['Type'] == 5) { + $html .= '<div class="lookuptype">LookupType 5: MarkToLigature attachment </div>'; + $MarkCoverage = $subtable_offset + $this->read_ushort(); + //$MarkCoverage is already set in $lcoverage 00065|00073 etc + $LigatureCoverage = $subtable_offset + $this->read_ushort(); + $ClassCount = $this->read_ushort(); // Number of classes defined for marks = Number of mark glyphs in the MarkCoverage table + $MarkArray = $subtable_offset + $this->read_ushort(); // Offset to MarkArray table + $LigatureArray = $subtable_offset + $this->read_ushort(); // Offset to LigatureArray table + + $this->seek($MarkCoverage); + $MarkGlyphs = $this->_getCoverage(); + $this->seek($LigatureCoverage); + $LigatureGlyphs = $this->_getCoverage(); + + $firstMark = ''; + $html .= '<div class="glyphs">Marks: <span class="unchanged">'; + $MarkRecord = []; + for ($i = 0; $i < count($MarkGlyphs); $i++) { + if ($level == 2 && strpos($lcoverage, $MarkGlyphs[$i]) === false) { + continue; + } else { + if (!$firstMark) { + $firstMark = $MarkGlyphs[$i]; + } + } + // Get the relevant MarkRecord + $MarkRecord[$i] = $this->_getMarkRecord($MarkArray, $i); + //Mark Class is = $MarkRecord[$i]['Class'] + $html .= ' ' . $this->formatEntity($MarkGlyphs[$i]) . ' '; + } + $html .= '</span></div>'; + if (!$firstMark) { + return; + } + + $this->seek($LigatureArray); + $LigatureCount = $this->read_ushort(); + $LigatureAttach = []; + $html .= '<div class="glyphs">Ligatures: <span class="unchanged">'; + for ($j = 0; $j < count($LigatureGlyphs); $j++) { + // Get the relevant LigatureRecord + $LigatureAttach[$j] = $LigatureArray + $this->read_ushort(); + $html .= ' ' . $this->formatEntity($LigatureGlyphs[$j]) . ' '; + } + $html .= '</span></div>'; + + /* + for ($i=0;$i<count($MarkGlyphs);$i++) { + $html .= '<div class="glyphs">'; + $html .= '<span class="unchanged">'.$this->formatEntity($MarkGlyphs[$i]).'</span>'; + + for ($j=0;$j<count($LigatureGlyphs);$j++) { + $this->seek($LigatureAttach[$j]); + $ComponentCount = $this->read_ushort(); + $html .= '<span class="unchanged">'.$this->formatEntity($LigatureGlyphs[$j]).'</span>'; + $offsets = array(); + for ($comp=0;$comp<$ComponentCount;$comp++) { + // ComponentRecords + for ($class=0;$class<$ClassCount;$class++) { + $offset = $this->read_ushort(); + if ($offset!= 0 && $class == $MarkRecord[$i]['Class']) { + + $html .= ' ['.$comp.'] '; + + } + } + } + } + $html .= '</span></div>'; + } + */ + } //////////////////////////////////////////////////////////////////////////////// + // LookupType 6: MarkToMark attachment Attach a combining mark to another mark + //////////////////////////////////////////////////////////////////////////////// + else { + if ($Lookup[$luli]['Type'] == 6) { + $html .= '<div class="lookuptype">LookupType 6: MarkToMark attachment </div>'; + $Mark1Coverage = $subtable_offset + $this->read_ushort(); // Combining Mark + //$Mark1Coverage is already set in $LuCoverage 0065|0073 etc + $Mark2Coverage = $subtable_offset + $this->read_ushort(); // Base Mark + $ClassCount = $this->read_ushort(); // Number of classes defined for marks = No. of Combining mark1 glyphs in the MarkCoverage table + $this->seek($Mark1Coverage); + $Mark1Glyphs = $this->_getCoverage(); + $this->seek($Mark2Coverage); + $Mark2Glyphs = $this->_getCoverage(); + + $firstMark = ''; + $html .= '<div class="glyphs">Marks: <span class="unchanged">'; + for ($i = 0; $i < count($Mark1Glyphs); $i++) { + if ($level == 2 && strpos($lcoverage, $Mark1Glyphs[$i]) === false) { + continue; + } else { + if (!$firstMark) { + $firstMark = $Mark1Glyphs[$i]; + } + } + $html .= ' ' . $this->formatEntity($Mark1Glyphs[$i]) . ' '; + } + $html .= '</span></div>'; + + if ($firstMark) { + $html .= '<div class="glyphs">Bases: <span class="unchanged">'; + for ($j = 0; $j < count($Mark2Glyphs); $j++) { + $html .= ' ' . $this->formatEntity($Mark2Glyphs[$j]) . ' '; + } + $html .= '</span></div>'; + + // Example + $html .= '<div class="glyphs" style="font-feature-settings:\'' . $tag . '\' 1;">Example(s): <span class="changed">'; + for ($j = 0; $j < min(count($Mark2Glyphs), 20); $j++) { + $html .= ' ' . $this->formatEntity($Mark2Glyphs[$j]) . $this->formatEntity($firstMark, true) . '   '; + } + $html .= '</span></div>'; + } + } //////////////////////////////////////////////////////////////////////////////// + // LookupType 7: Context positioning Position one or more glyphs in context + //////////////////////////////////////////////////////////////////////////////// + else { + if ($Lookup[$luli]['Type'] == 7) { + $html .= '<div class="lookuptype">LookupType 7: Context positioning [Format ' . $PosFormat . ']</div>'; + //=========== + // Format 1: + //=========== + if ($PosFormat == 1) { + throw new \Mpdf\MpdfException("GPOS Lookup Type " . $Type . " Format " . $PosFormat . " not YET TESTED."); + } //=========== + // Format 2: + //=========== + else { + if ($PosFormat == 2) { + throw new \Mpdf\MpdfException("GPOS Lookup Type " . $Type . " Format " . $PosFormat . " not YET TESTED."); + } //=========== + // Format 3: + //=========== + else { + if ($PosFormat == 3) { + throw new \Mpdf\MpdfException("GPOS Lookup Type " . $Type . " Format " . $PosFormat . " not YET TESTED."); + } else { + throw new \Mpdf\MpdfException("GPOS Lookup Type " . $Type . ", Format " . $PosFormat . " not supported."); + } + } + } + } //////////////////////////////////////////////////////////////////////////////// + // LookupType 8: Chained Context positioning Position one or more glyphs in chained context + //////////////////////////////////////////////////////////////////////////////// + else { + if ($Lookup[$luli]['Type'] == 8) { + $html .= '<div class="lookuptype">LookupType 8: Chained Context positioning [Format ' . $PosFormat . ']</div>'; + //=========== + // Format 1: + //=========== + if ($PosFormat == 1) { + throw new \Mpdf\MpdfException("GPOS Lookup Type " . $Type . " Format " . $PosFormat . " not TESTED YET."); + } //=========== + // Format 2: + //=========== + else { + if ($PosFormat == 2) { + $html .= '<div>GPOS Lookup Type 8: Format 2 not yet supported in OTL dump</div>'; + continue; + /* NB When developing - cf. GSUB 6.2 */ + throw new \Mpdf\MpdfException("GPOS Lookup Type " . $Type . " Format " . $PosFormat . " not TESTED YET."); + } //=========== + // Format 3: + //=========== + else { + if ($PosFormat == 3) { + $BacktrackGlyphCount = $this->read_ushort(); + $CoverageBacktrackOffset = []; + for ($b = 0; $b < $BacktrackGlyphCount; $b++) { + $CoverageBacktrackOffset[] = $subtable_offset + $this->read_ushort(); // in glyph sequence order + } + $InputGlyphCount = $this->read_ushort(); + $CoverageInputOffset = []; + for ($b = 0; $b < $InputGlyphCount; $b++) { + $CoverageInputOffset[] = $subtable_offset + $this->read_ushort(); // in glyph sequence order + } + $LookaheadGlyphCount = $this->read_ushort(); + $CoverageLookaheadOffset = []; + for ($b = 0; $b < $LookaheadGlyphCount; $b++) { + $CoverageLookaheadOffset[] = $subtable_offset + $this->read_ushort(); // in glyph sequence order + } + $PosCount = $this->read_ushort(); + + $PosLookupRecord = []; + for ($p = 0; $p < $PosCount; $p++) { + // PosLookupRecord + $PosLookupRecord[$p]['SequenceIndex'] = $this->read_ushort(); + $PosLookupRecord[$p]['LookupListIndex'] = $this->read_ushort(); + } + + $backtrackGlyphs = []; + for ($b = 0; $b < $BacktrackGlyphCount; $b++) { + $this->seek($CoverageBacktrackOffset[$b]); + $backtrackGlyphs[$b] = implode('|', $this->_getCoverage()); + } + $inputGlyphs = []; + for ($b = 0; $b < $InputGlyphCount; $b++) { + $this->seek($CoverageInputOffset[$b]); + $inputGlyphs[$b] = implode('|', $this->_getCoverage()); + } + $lookaheadGlyphs = []; + for ($b = 0; $b < $LookaheadGlyphCount; $b++) { + $this->seek($CoverageLookaheadOffset[$b]); + $lookaheadGlyphs[$b] = implode('|', $this->_getCoverage()); + } + + $exampleB = []; + $exampleI = []; + $exampleL = []; + $html .= '<div class="context">CONTEXT: '; + for ($ff = count($backtrackGlyphs) - 1; $ff >= 0; $ff--) { + $html .= '<div>Backtrack #' . $ff . ': <span class="unicode">' . $this->formatUniStr($backtrackGlyphs[$ff]) . '</span></div>'; + $exampleB[] = $this->formatEntityFirst($backtrackGlyphs[$ff]); + } + for ($ff = 0; $ff < count($inputGlyphs); $ff++) { + $html .= '<div>Input #' . $ff . ': <span class="unchanged"> ' . $this->formatEntityStr($inputGlyphs[$ff]) . ' </span></div>'; + $exampleI[] = $this->formatEntityFirst($inputGlyphs[$ff]); + } + for ($ff = 0; $ff < count($lookaheadGlyphs); $ff++) { + $html .= '<div>Lookahead #' . $ff . ': <span class="unicode">' . $this->formatUniStr($lookaheadGlyphs[$ff]) . '</span></div>'; + $exampleL[] = $this->formatEntityFirst($lookaheadGlyphs[$ff]); + } + $html .= '</div>'; + + for ($p = 0; $p < $PosCount; $p++) { + $lup = $PosLookupRecord[$p]['LookupListIndex']; + $seqIndex = $PosLookupRecord[$p]['SequenceIndex']; + + // GENERATE exampleB[n] exampleI[<seqIndex] .... exampleI[>seqIndex] exampleL[n] + $exB = ''; + $exL = ''; + if (count($exampleB)) { + $exB .= '<span class="backtrack">' . implode('‍', $exampleB) . '</span>'; + } + + if ($seqIndex > 0) { + $exB .= '<span class="inputother">'; + for ($ip = 0; $ip < $seqIndex; $ip++) { + $exB .= $exampleI[$ip] . '‍'; + } + $exB .= '</span>'; + } + + if (count($inputGlyphs) > ($seqIndex + 1)) { + $exL .= '<span class="inputother">'; + for ($ip = $seqIndex + 1; $ip < count($inputGlyphs); $ip++) { + $exL .= '‍' . $exampleI[$ip]; + } + $exL .= '</span>'; + } + + if (count($exampleL)) { + $exL .= '<span class="lookahead">' . implode('‍', $exampleL) . '</span>'; + } + + $html .= '<div class="sequenceIndex">Substitution Position: ' . $seqIndex . '</div>'; + + $lul2 = [$lup => $tag]; + + // Only apply if the (first) 'Replace' glyph from the + // Lookup list is in the [inputGlyphs] at ['SequenceIndex'] + // Pass $inputGlyphs[$seqIndex] e.g. 00636|00645|00656 + // to level 2 and only apply if first Replace glyph is in this list + $html .= $this->_getGPOSarray($Lookup, $lul2, $scripttag, 2, $inputGlyphs[$seqIndex], $exB, $exL); + } + } + } + } + } + } + } + } + } + } + } + } + } + $html .= '</div>'; + } + if ($level == 1) { + $this->mpdf->WriteHTML($html); + } else { + return $html; + } +//print_r($Lookup); exit; + } + + //===================================================================================== + //===================================================================================== + // GPOS FUNCTIONS + //===================================================================================== + + function count_bits($n) + { + for ($c = 0; $n; $c++) { + $n &= $n - 1; // clear the least significant bit set + } + + return $c; + } + + function _getValueRecord($ValueFormat) + { + // Common ValueRecord for GPOS + // Only returns 3 possible: $vra['XPlacement'] $vra['YPlacement'] $vra['XAdvance'] + $vra = []; + // Horizontal adjustment for placement-in design units + if (($ValueFormat & 0x0001) == 0x0001) { + $vra['XPlacement'] = $this->read_short(); + } + // Vertical adjustment for placement-in design units + if (($ValueFormat & 0x0002) == 0x0002) { + $vra['YPlacement'] = $this->read_short(); + } + // Horizontal adjustment for advance-in design units (only used for horizontal writing) + if (($ValueFormat & 0x0004) == 0x0004) { + $vra['XAdvance'] = $this->read_short(); + } + // Vertical adjustment for advance-in design units (only used for vertical writing) + if (($ValueFormat & 0x0008) == 0x0008) { + $this->read_short(); + } + // Offset to Device table for horizontal placement-measured from beginning of PosTable (may be NULL) + if (($ValueFormat & 0x0010) == 0x0010) { + $this->read_ushort(); + } + // Offset to Device table for vertical placement-measured from beginning of PosTable (may be NULL) + if (($ValueFormat & 0x0020) == 0x0020) { + $this->read_ushort(); + } + // Offset to Device table for horizontal advance-measured from beginning of PosTable (may be NULL) + if (($ValueFormat & 0x0040) == 0x0040) { + $this->read_ushort(); + } + // Offset to Device table for vertical advance-measured from beginning of PosTable (may be NULL) + if (($ValueFormat & 0x0080) == 0x0080) { + $this->read_ushort(); + } + + return $vra; + } + + function _getAnchorTable($offset = 0) + { + if ($offset) { + $this->seek($offset); + } + $AnchorFormat = $this->read_ushort(); + $XCoordinate = $this->read_short(); + $YCoordinate = $this->read_short(); + + // Format 2 specifies additional link to contour point; Format 3 additional Device table + return [$XCoordinate, $YCoordinate]; + } + + function _getMarkRecord($offset, $MarkPos) + { + $this->seek($offset); + $MarkCount = $this->read_ushort(); + $this->skip($MarkPos * 4); + $Class = $this->read_ushort(); + $MarkAnchor = $offset + $this->read_ushort(); // = Offset to anchor table + list($x, $y) = $this->_getAnchorTable($MarkAnchor); + $MarkRecord = ['Class' => $Class, 'AnchorX' => $x, 'AnchorY' => $y]; + + return $MarkRecord; + } + + ////////////////////////////////////////////////////////////////////////////////// + // Recursively get composite glyph data + function getGlyphData($originalGlyphIdx, &$maxdepth, &$depth, &$points, &$contours) + { + $depth++; + $maxdepth = max($maxdepth, $depth); + if (count($this->glyphdata[$originalGlyphIdx]['compGlyphs'])) { + foreach ($this->glyphdata[$originalGlyphIdx]['compGlyphs'] as $glyphIdx) { + $this->getGlyphData($glyphIdx, $maxdepth, $depth, $points, $contours); + } + } else { + if (($this->glyphdata[$originalGlyphIdx]['nContours'] > 0) && $depth > 0) { // simple + $contours += $this->glyphdata[$originalGlyphIdx]['nContours']; + $points += $this->glyphdata[$originalGlyphIdx]['nPoints']; + } + } + $depth--; + } + + ////////////////////////////////////////////////////////////////////////////////// + // Recursively get composite glyphs + function getGlyphs($originalGlyphIdx, &$start, &$glyphSet, &$subsetglyphs) + { + $glyphPos = $this->glyphPos[$originalGlyphIdx]; + $glyphLen = $this->glyphPos[$originalGlyphIdx + 1] - $glyphPos; + if (!$glyphLen) { + return; + } + $this->seek($start + $glyphPos); + $numberOfContours = $this->read_short(); + if ($numberOfContours < 0) { + $this->skip(8); + $flags = GlyphOperator::MORE; + while ($flags & GlyphOperator::MORE) { + $flags = $this->read_ushort(); + } + $glyphIdx = $this->read_ushort(); + if (!isset($glyphSet[$glyphIdx])) { + $glyphSet[$glyphIdx] = count($subsetglyphs); // old glyphID to new glyphID + $subsetglyphs[$glyphIdx] = true; + } + $savepos = ftell($this->fh); + $this->getGlyphs($glyphIdx, $start, $glyphSet, $subsetglyphs); + $this->seek($savepos); + if ($flags & GlyphOperator::WORDS) { + $this->skip(4); + } else { + $this->skip(2); + } + if ($flags & GlyphOperator::SCALE) { + $this->skip(2); + } else { + if ($flags & GlyphOperator::XYSCALE) { + $this->skip(4); + } else { + if ($flags & GlyphOperator::TWOBYTWO) { + $this->skip(8); + } + } + } + } + } + + + ////////////////////////////////////////////////////////////////////////////////// + + function getHMTX($numberOfHMetrics, $numGlyphs, &$glyphToChar, $scale) + { + $start = $this->seek_table("hmtx"); + $aw = 0; + $this->charWidths = str_pad('', 256 * 256 * 2, "\x00"); + if ($this->maxUniChar > 65536) { + $this->charWidths .= str_pad('', 256 * 256 * 2, "\x00"); + } // Plane 1 SMP + if ($this->maxUniChar > 131072) { + $this->charWidths .= str_pad('', 256 * 256 * 2, "\x00"); + } // Plane 2 SMP + $nCharWidths = 0; + if (($numberOfHMetrics * 4) < $this->maxStrLenRead) { + $data = $this->get_chunk($start, ($numberOfHMetrics * 4)); + $arr = unpack("n*", $data); + } else { + $this->seek($start); + } + for ($glyph = 0; $glyph < $numberOfHMetrics; $glyph++) { + if (($numberOfHMetrics * 4) < $this->maxStrLenRead) { + $aw = $arr[($glyph * 2) + 1]; + } else { + $aw = $this->read_ushort(); + $lsb = $this->read_ushort(); + } + if (isset($glyphToChar[$glyph]) || $glyph == 0) { + if ($aw >= (1 << 15)) { + $aw = 0; + } // 1.03 Some (arabic) fonts have -ve values for width + // although should be unsigned value - comes out as e.g. 65108 (intended -50) + if ($glyph == 0) { + $this->defaultWidth = $scale * $aw; + continue; + } + foreach ($glyphToChar[$glyph] as $char) { + //$this->charWidths[$char] = intval(round($scale*$aw)); + if ($char != 0 && $char != 65535) { + $w = intval(round($scale * $aw)); + if ($w == 0) { + $w = 65535; + } + if ($char < 196608) { + $this->charWidths[$char * 2] = chr($w >> 8); + $this->charWidths[$char * 2 + 1] = chr($w & 0xFF); + $nCharWidths++; + } + } + } + } + } + $data = $this->get_chunk(($start + $numberOfHMetrics * 4), ($numGlyphs * 2)); + $arr = unpack("n*", $data); + $diff = $numGlyphs - $numberOfHMetrics; + $w = intval(round($scale * $aw)); + if ($w == 0) { + $w = 65535; + } + for ($pos = 0; $pos < $diff; $pos++) { + $glyph = $pos + $numberOfHMetrics; + if (isset($glyphToChar[$glyph])) { + foreach ($glyphToChar[$glyph] as $char) { + if ($char != 0 && $char != 65535) { + if ($char < 196608) { + $this->charWidths[$char * 2] = chr($w >> 8); + $this->charWidths[$char * 2 + 1] = chr($w & 0xFF); + $nCharWidths++; + } + } + } + } + } + // NB 65535 is a set width of 0 + // First bytes define number of chars in font + $this->charWidths[0] = chr($nCharWidths >> 8); + $this->charWidths[1] = chr($nCharWidths & 0xFF); + } + + function getHMetric($numberOfHMetrics, $gid) + { + $start = $this->seek_table("hmtx"); + if ($gid < $numberOfHMetrics) { + $this->seek($start + ($gid * 4)); + $hm = fread($this->fh, 4); + } else { + $this->seek($start + (($numberOfHMetrics - 1) * 4)); + $hm = fread($this->fh, 2); + $this->seek($start + ($numberOfHMetrics * 2) + ($gid * 2)); + $hm .= fread($this->fh, 2); + } + + return $hm; + } + + function getLOCA($indexToLocFormat, $numGlyphs) + { + $start = $this->seek_table('loca'); + $this->glyphPos = []; + if ($indexToLocFormat == 0) { + $data = $this->get_chunk($start, ($numGlyphs * 2) + 2); + $arr = unpack("n*", $data); + for ($n = 0; $n <= $numGlyphs; $n++) { + $this->glyphPos[] = ($arr[$n + 1] * 2); + } + } else { + if ($indexToLocFormat == 1) { + $data = $this->get_chunk($start, ($numGlyphs * 4) + 4); + $arr = unpack("N*", $data); + for ($n = 0; $n <= $numGlyphs; $n++) { + $this->glyphPos[] = ($arr[$n + 1]); + } + } else { + throw new \Mpdf\MpdfException('Unknown location table format ' . $indexToLocFormat); + } + } + } + + // CMAP Format 4 + function getCMAP4($unicode_cmap_offset, &$glyphToChar, &$charToGlyph) + { + $this->maxUniChar = 0; + $this->seek($unicode_cmap_offset + 2); + $length = $this->read_ushort(); + $limit = $unicode_cmap_offset + $length; + $this->skip(2); + + $segCount = $this->read_ushort() / 2; + $this->skip(6); + $endCount = []; + for ($i = 0; $i < $segCount; $i++) { + $endCount[] = $this->read_ushort(); + } + $this->skip(2); + $startCount = []; + for ($i = 0; $i < $segCount; $i++) { + $startCount[] = $this->read_ushort(); + } + $idDelta = []; + for ($i = 0; $i < $segCount; $i++) { + $idDelta[] = $this->read_short(); + } // ???? was unsigned short + $idRangeOffset_start = $this->_pos; + $idRangeOffset = []; + for ($i = 0; $i < $segCount; $i++) { + $idRangeOffset[] = $this->read_ushort(); + } + + for ($n = 0; $n < $segCount; $n++) { + $endpoint = ($endCount[$n] + 1); + for ($unichar = $startCount[$n]; $unichar < $endpoint; $unichar++) { + if ($idRangeOffset[$n] == 0) { + $glyph = ($unichar + $idDelta[$n]) & 0xFFFF; + } else { + $offset = ($unichar - $startCount[$n]) * 2 + $idRangeOffset[$n]; + $offset = $idRangeOffset_start + 2 * $n + $offset; + if ($offset >= $limit) { + $glyph = 0; + } else { + $glyph = $this->get_ushort($offset); + if ($glyph != 0) { + $glyph = ($glyph + $idDelta[$n]) & 0xFFFF; + } + } + } + $charToGlyph[$unichar] = $glyph; + if ($unichar < 196608) { + $this->maxUniChar = max($unichar, $this->maxUniChar); + } + $glyphToChar[$glyph][] = $unichar; + } + } + } + + function formatUni($char) + { + $x = preg_replace('/^[0]*/', '', $char); + $x = str_pad($x, 4, '0', STR_PAD_LEFT); + $d = hexdec($x); + if (($d > 57343 && $d < 63744) || ($d > 122879 && $d < 126977)) { + $id = 'M'; + } // E000 - F8FF, 1E000-1F000 + else { + $id = 'U'; + } + + return $id . '+' . $x; + } + + function formatEntity($char, $allowjoining = false) + { + $char = preg_replace('/^[0]/', '', $char); + $x = '&#x' . $char . ';'; + if (strpos($this->GlyphClassMarks, $char) !== false) { + if (!$allowjoining) { + $x = '◌' . $x; + } + } + + return $x; + } + + function formatUniArr($arr) + { + $s = []; + foreach ($arr as $c) { + $x = preg_replace('/^[0]*/', '', $c); + $d = hexdec($x); + if (($d > 57343 && $d < 63744) || ($d > 122879 && $d < 126977)) { + $id = 'M'; + } // E000 - F8FF, 1E000-1F000 + else { + $id = 'U'; + } + $s[] = $id . '+' . str_pad($x, 4, '0', STR_PAD_LEFT); + } + + return implode(', ', $s); + } + + function formatEntityArr($arr) + { + $s = []; + foreach ($arr as $c) { + $c = preg_replace('/^[0]/', '', $c); + $x = '&#x' . $c . ';'; + if (strpos($this->GlyphClassMarks, $c) !== false) { + $x = '◌' . $x; + } + $s[] = $x; + } + + return implode(' ', $s); // ZWNJ? ‍ + } + + function formatClassArr($arr) + { + $s = []; + foreach ($arr as $c) { + $x = preg_replace('/^[0]*/', '', $c); + $d = hexdec($x); + if (($d > 57343 && $d < 63744) || ($d > 122879 && $d < 126977)) { + $id = 'M'; + } // E000 - F8FF, 1E000-1F000 + else { + $id = 'U'; + } + $s[] = $id . '+' . str_pad($x, 4, '0', STR_PAD_LEFT); + } + + return implode(', ', $s); + } + + function formatUniStr($str) + { + $s = []; + $arr = explode('|', $str); + foreach ($arr as $c) { + $x = preg_replace('/^[0]*/', '', $c); + $d = hexdec($x); + if (($d > 57343 && $d < 63744) || ($d > 122879 && $d < 126977)) { + $id = 'M'; + } // E000 - F8FF, 1E000-1F000 + else { + $id = 'U'; + } + $s[] = $id . '+' . str_pad($x, 4, '0', STR_PAD_LEFT); + } + + return implode(', ', $s); + } + + function formatEntityStr($str) + { + $s = []; + $arr = explode('|', $str); + foreach ($arr as $c) { + $c = preg_replace('/^[0]/', '', $c); + $x = '&#x' . $c . ';'; + if (strpos($this->GlyphClassMarks, $c) !== false) { + $x = '◌' . $x; + } + $s[] = $x; + } + + return implode(' ', $s); // ZWNJ? ‍ + } + + function formatEntityFirst($str) + { + $arr = explode('|', $str); + $char = preg_replace('/^[0]/', '', $arr[0]); + $x = '&#x' . $char . ';'; + if (strpos($this->GlyphClassMarks, $char) !== false) { + $x = '◌' . $x; + } + + return $x; + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Output/Destination.php b/src/bb-vendor/mpdf/mpdf/src/Output/Destination.php new file mode 100644 index 000000000..25b46d6a4 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Output/Destination.php @@ -0,0 +1,15 @@ +<?php + +namespace Mpdf\Output; + +class Destination +{ + + const FILE = 'F'; + + const DOWNLOAD = 'D'; + + const STRING_RETURN = 'S'; + + const INLINE = 'I'; +} diff --git a/src/bb-vendor/mpdf/mpdf/src/PageFormat.php b/src/bb-vendor/mpdf/mpdf/src/PageFormat.php new file mode 100644 index 000000000..57a534e07 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/PageFormat.php @@ -0,0 +1,83 @@ +<?php + +namespace Mpdf; + +class PageFormat +{ + + /** + * This method returns an array of width and height of given named format. + * + * Returned values are milimeters multiplied by scale factor of 72 / 25.4 + * + * @param string $name + * @return float[] Width and height of given format + */ + public static function getSizeFromName($name) + { + $format = strtoupper($name); + $formats = [ + '4A0' => [4767.87, 6740.79], + '2A0' => [3370.39, 4767.87], + 'A0' => [2383.94, 3370.39], + 'A1' => [1683.78, 2383.94], + 'A2' => [1190.55, 1683.78], + 'A3' => [841.89, 1190.55], + 'A4' => [595.28, 841.89], + 'A5' => [419.53, 595.28], + 'A6' => [297.64, 419.53], + 'A7' => [209.76, 297.64], + 'A8' => [147.40, 209.76], + 'A9' => [104.88, 147.40], + 'A10' => [73.70, 104.88], + 'B0' => [2834.65, 4008.19], + 'B1' => [2004.09, 2834.65], + 'B2' => [1417.32, 2004.09], + 'B3' => [1000.63, 1417.32], + 'B4' => [708.66, 1000.63], + 'B5' => [498.90, 708.66], + 'B6' => [354.33, 498.90], + 'B7' => [249.45, 354.33], + 'B8' => [175.75, 249.45], + 'B9' => [124.72, 175.75], + 'B10' => [87.87, 124.72], + 'C0' => [2599.37, 3676.54], + 'C1' => [1836.85, 2599.37], + 'C2' => [1298.27, 1836.85], + 'C3' => [918.43, 1298.27], + 'C4' => [649.13, 918.43], + 'C5' => [459.21, 649.13], + 'C6' => [323.15, 459.21], + 'C7' => [229.61, 323.15], + 'C8' => [161.57, 229.61], + 'C9' => [113.39, 161.57], + 'C10' => [79.37, 113.39], + 'RA0' => [2437.80, 3458.27], + 'RA1' => [1729.13, 2437.80], + 'RA2' => [1218.90, 1729.13], + 'RA3' => [864.57, 1218.90], + 'RA4' => [609.45, 864.57], + 'SRA0' => [2551.18, 3628.35], + 'SRA1' => [1814.17, 2551.18], + 'SRA2' => [1275.59, 1814.17], + 'SRA3' => [907.09, 1275.59], + 'SRA4' => [637.80, 907.09], + 'LETTER' => [612.00, 792.00], + 'LEGAL' => [612.00, 1008.00], + 'LEDGER' => [1224.00, 792.00], + 'TABLOID' => [792.00, 1224.00], + 'EXECUTIVE' => [521.86, 756.00], + 'FOLIO' => [612.00, 936.00], + 'B' => [362.83, 561.26], // 'B' format paperback size 128x198mm + 'A' => [314.65, 504.57], // 'A' format paperback size 111x178mm + 'DEMY' => [382.68, 612.28], // 'Demy' format paperback size 135x216mm + 'ROYAL' => [433.70, 663.30], // 'Royal' format paperback size 153x234mm + ]; + + if (!isset($formats[$format])) { + throw new \Mpdf\MpdfException(sprintf('Unknown page format %s', $format)); + } + + return $formats[$format]; + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Pdf/Protection.php b/src/bb-vendor/mpdf/mpdf/src/Pdf/Protection.php new file mode 100644 index 000000000..8a63da952 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Pdf/Protection.php @@ -0,0 +1,360 @@ +<?php + +namespace Mpdf\Pdf; + +use Mpdf\Pdf\Protection\UniqidGenerator; + +class Protection +{ + + /** + * @var string + */ + private $lastRc4Key; + + /** + * @var string + */ + private $lastRc4KeyC; + + /** + * @var bool + */ + private $useRC128Encryption; + + /** + * @var string + */ + private $encryptionKey; + + /** + * @var string + */ + private $padding; + + /** + * @var string + */ + private $uniqid; + + /** + * @var string + */ + private $oValue; + + /** + * @var string + */ + private $uValue; + + /** + * @var string + */ + private $pValue; + + /** + * @var int[] Array of permission => byte representation + */ + private $options; + + /** + * @var \Mpdf\Pdf\Protection\UniqidGenerator + */ + private $uniqidGenerator; + + public function __construct(UniqidGenerator $uniqidGenerator) + { + if (!function_exists('random_int') || !function_exists('random_bytes')) { + throw new \Mpdf\MpdfException( + 'Unable to set PDF file protection, CSPRNG Functions are not available. ' + . 'Use paragonie/random_compat polyfill or upgrade to PHP 7.' + ); + } + + $this->uniqidGenerator = $uniqidGenerator; + + $this->lastRc4Key = ''; + + $this->padding = "\x28\xBF\x4E\x5E\x4E\x75\x8A\x41\x64\x00\x4E\x56\xFF\xFA\x01\x08" . + "\x2E\x2E\x00\xB6\xD0\x68\x3E\x80\x2F\x0C\xA9\xFE\x64\x53\x69\x7A"; + + $this->useRC128Encryption = false; + + $this->options = [ + 'print' => 4, // bit 3 + 'modify' => 8, // bit 4 + 'copy' => 16, // bit 5 + 'annot-forms' => 32, // bit 6 + 'fill-forms' => 256, // bit 9 + 'extract' => 512, // bit 10 + 'assemble' => 1024, // bit 11 + 'print-highres' => 2048 // bit 12 + ]; + } + + /** + * @param array $permissions + * @param string $user_pass + * @param string $owner_pass + * @param int $length + * + * @return bool + */ + public function setProtection($permissions = [], $user_pass = '', $owner_pass = null, $length = 40) + { + if (is_string($permissions) && strlen($permissions) > 0) { + $permissions = [$permissions]; + } elseif (!is_array($permissions)) { + return false; + } + + $protection = $this->getProtectionBitsFromOptions($permissions); + + if ($length === 128) { + $this->useRC128Encryption = true; + } elseif ($length !== 40) { + throw new \Mpdf\MpdfException('PDF protection only allows lenghts of 40 or 128'); + } + + if ($owner_pass === null) { + $owner_pass = bin2hex(random_bytes(23)); + } + + $this->generateEncryptionKey($user_pass, $owner_pass, $protection); + + return true; + } + + /** + * Compute key depending on object number where the encrypted data is stored + * + * @param int $n + * + * @return string + */ + public function objectKey($n) + { + if ($this->useRC128Encryption) { + $len = 16; + } else { + $len = 10; + } + + return substr($this->md5toBinary($this->encryptionKey . pack('VXxx', $n)), 0, $len); + } + + /** + * RC4 is the standard encryption algorithm used in PDF format + * + * @param string $key + * @param string $text + * + * @return string + */ + public function rc4($key, $text) + { + if ($this->lastRc4Key != $key) { + $k = str_repeat($key, 256 / strlen($key) + 1); + $rc4 = range(0, 255); + $j = 0; + for ($i = 0; $i < 256; $i++) { + $t = $rc4[$i]; + $j = ($j + $t + ord($k[$i])) % 256; + $rc4[$i] = $rc4[$j]; + $rc4[$j] = $t; + } + $this->lastRc4Key = $key; + $this->lastRc4KeyC = $rc4; + } else { + $rc4 = $this->lastRc4KeyC; + } + + $len = strlen($text); + $a = 0; + $b = 0; + $out = ''; + for ($i = 0; $i < $len; $i++) { + $a = ($a + 1) % 256; + $t = $rc4[$a]; + $b = ($b + $t) % 256; + $rc4[$a] = $rc4[$b]; + $rc4[$b] = $t; + $k = $rc4[($rc4[$a] + $rc4[$b]) % 256]; + $out .= chr(ord($text[$i]) ^ $k); + } + + return $out; + } + + /** + * @return mixed + */ + public function getUseRC128Encryption() + { + return $this->useRC128Encryption; + } + + /** + * @return mixed + */ + public function getUniqid() + { + return $this->uniqid; + } + + /** + * @return mixed + */ + public function getOValue() + { + return $this->oValue; + } + + /** + * @return mixed + */ + public function getUValue() + { + return $this->uValue; + } + + /** + * @return mixed + */ + public function getPValue() + { + return $this->pValue; + } + + private function getProtectionBitsFromOptions($permissions) + { + // bit 31 = 1073741824 + // bit 32 = 2147483648 + // bits 13-31 = 2147479552 + // bits 13-32 = 4294963200 + 192 = 4294963392 + + $protection = 4294963392; // bits 7, 8, 13-32 + + foreach ($permissions as $permission) { + if (!isset($this->options[$permission])) { + throw new \Mpdf\MpdfException(sprintf('Invalid permission type "%s"', $permission)); + } + if ($this->options[$permission] > 32) { + $this->useRC128Encryption = true; + } + if (isset($this->options[$permission])) { + $protection += $this->options[$permission]; + } + } + + return $protection; + } + + private function oValue($user_pass, $owner_pass) + { + $tmp = $this->md5toBinary($owner_pass); + if ($this->useRC128Encryption) { + for ($i = 0; $i < 50; ++$i) { + $tmp = $this->md5toBinary($tmp); + } + } + if ($this->useRC128Encryption) { + $keybytelen = (128 / 8); + } else { + $keybytelen = (40 / 8); + } + $owner_rc4_key = substr($tmp, 0, $keybytelen); + $enc = $this->rc4($owner_rc4_key, $user_pass); + if ($this->useRC128Encryption) { + $len = strlen($owner_rc4_key); + for ($i = 1; $i <= 19; ++$i) { + $key = ''; + for ($j = 0; $j < $len; ++$j) { + $key .= chr(ord($owner_rc4_key[$j]) ^ $i); + } + $enc = $this->rc4($key, $enc); + } + } + + return $enc; + } + + private function uValue() + { + if ($this->useRC128Encryption) { + $tmp = $this->md5toBinary($this->padding . $this->hexToString($this->uniqid)); + $enc = $this->rc4($this->encryptionKey, $tmp); + $len = strlen($tmp); + for ($i = 1; $i <= 19; ++$i) { + $key = ''; + for ($j = 0; $j < $len; ++$j) { + $key .= chr(ord($this->encryptionKey[$j]) ^ $i); + } + $enc = $this->rc4($key, $enc); + } + $enc .= str_repeat("\x00", 16); + + return substr($enc, 0, 32); + } else { + return $this->rc4($this->encryptionKey, $this->padding); + } + } + + private function generateEncryptionKey($user_pass, $owner_pass, $protection) + { + // Pad passwords + $user_pass = substr($user_pass . $this->padding, 0, 32); + $owner_pass = substr($owner_pass . $this->padding, 0, 32); + + $this->oValue = $this->oValue($user_pass, $owner_pass); + + $this->uniqid = $this->uniqidGenerator->generate(); + + // Compute encyption key + if ($this->useRC128Encryption) { + $keybytelen = (128 / 8); + } else { + $keybytelen = (40 / 8); + } + + $prot = sprintf('%032b', $protection); + + $perms = chr(bindec(substr($prot, 24, 8))); + $perms .= chr(bindec(substr($prot, 16, 8))); + $perms .= chr(bindec(substr($prot, 8, 8))); + $perms .= chr(bindec(substr($prot, 0, 8))); + + $tmp = $this->md5toBinary($user_pass . $this->oValue . $perms . $this->hexToString($this->uniqid)); + + if ($this->useRC128Encryption) { + for ($i = 0; $i < 50; ++$i) { + $tmp = $this->md5toBinary(substr($tmp, 0, $keybytelen)); + } + } + + $this->encryptionKey = substr($tmp, 0, $keybytelen); + + $this->uValue = $this->uValue(); + $this->pValue = $protection; + } + + private function md5toBinary($string) + { + return pack('H*', md5($string)); + } + + private function hexToString($hs) + { + $s = ''; + $len = strlen($hs); + if (($len % 2) != 0) { + $hs .= '0'; + ++$len; + } + for ($i = 0; $i < $len; $i += 2) { + $s .= chr(hexdec($hs[$i] . $hs[($i + 1)])); + } + + return $s; + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Pdf/Protection/UniqidGenerator.php b/src/bb-vendor/mpdf/mpdf/src/Pdf/Protection/UniqidGenerator.php new file mode 100644 index 000000000..54753d451 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Pdf/Protection/UniqidGenerator.php @@ -0,0 +1,32 @@ +<?php + +namespace Mpdf\Pdf\Protection; + +class UniqidGenerator +{ + + public function __construct() + { + if (!function_exists('random_int') || !function_exists('random_bytes')) { + throw new \Mpdf\MpdfException( + 'Unable to set PDF file protection, CSPRNG Functions are not available. ' + . 'Use paragonie/random_compat polyfill or upgrade to PHP 7.' + ); + } + } + + /** + * @return string + */ + public function generate() + { + $chars = 'ABCDEF1234567890'; + $id = ''; + + for ($i = 0; $i < 32; $i++) { + $id .= $chars[random_int(0, 15)]; + } + + return md5($id); + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/RemoteContentFetcher.php b/src/bb-vendor/mpdf/mpdf/src/RemoteContentFetcher.php new file mode 100644 index 000000000..f1547ec55 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/RemoteContentFetcher.php @@ -0,0 +1,148 @@ +<?php + +namespace Mpdf; + +use Mpdf\Utils\Arrays; +use Psr\Log\LoggerInterface; +use Mpdf\Log\Context as LogContext; + +class RemoteContentFetcher implements \Psr\Log\LoggerAwareInterface +{ + + /** + * @var \Mpdf\Mpdf + */ + private $mpdf; + + /** + * @var \Psr\Log\LoggerInterface + */ + private $logger; + + public function __construct(Mpdf $mpdf, LoggerInterface $logger) + { + $this->mpdf = $mpdf; + $this->logger = $logger; + } + + public function getFileContentsByCurl($url) + { + $this->logger->debug(sprintf('Fetching (cURL) content of remote URL "%s"', $url), ['context' => LogContext::REMOTE_CONTENT]); + + $ch = curl_init($url); + + curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:13.0) Gecko/20100101 Firefox/13.0.1'); // mPDF 5.7.4 + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_NOBODY, 0); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->mpdf->curlTimeout); + + if ($this->mpdf->curlFollowLocation) { + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); + } + + if ($this->mpdf->curlAllowUnsafeSslRequests) { + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + } + + if (is_file($this->mpdf->curlCaCertificate)) { + curl_setopt($ch, CURLOPT_CAINFO, $this->mpdf->curlCaCertificate); + } + + if ($this->mpdf->curlProxy) { + curl_setopt($ch, CURLOPT_PROXY, $this->mpdf->curlProxy); + if ($this->mpdf->curlProxyAuth) { + curl_setopt($ch, CURLOPT_PROXYUSERPWD, $this->mpdf->curlProxyAuth); + } + } + + $data = curl_exec($ch); + + if (curl_error($ch)) { + $message = sprintf('cURL error: "%s"', curl_error($ch)); + $this->logger->error($message, ['context' => LogContext::REMOTE_CONTENT]); + + if ($this->mpdf->debug) { + throw new \Mpdf\MpdfException($message); + } + } + + $info = curl_getinfo($ch); + if (isset($info['http_code']) && $info['http_code'] !== 200) { + $message = sprintf('HTTP error: %d', $info['http_code']); + $this->logger->error($message, ['context' => LogContext::REMOTE_CONTENT]); + + if ($this->mpdf->debug) { + throw new \Mpdf\MpdfException($message); + } + } + + curl_close($ch); + + return $data; + } + + public function getFileContentsBySocket($url) + { + $this->logger->debug(sprintf('Fetching (socket) content of remote URL "%s"', $url), ['context' => LogContext::REMOTE_CONTENT]); + // mPDF 5.7.3 + + $timeout = 1; + $p = parse_url($url); + + $file = Arrays::get($p, 'path', ''); + $scheme = Arrays::get($p, 'scheme', ''); + $port = Arrays::get($p, 'port', 80); + $prefix = ''; + + if ($scheme === 'https') { + $prefix = 'ssl://'; + $port = Arrays::get($p, 'port', 443); + } + + $query = Arrays::get($p, 'query', null); + if ($query) { + $file .= '?' . $query; + } + + if (!($fh = @fsockopen($prefix . $p['host'], $port, $errno, $errstr, $timeout))) { + $this->logger->error(sprintf('Socket error "%s": "%s"', $errno, $errstr), ['context' => LogContext::REMOTE_CONTENT]); + return false; + } + + $getstring = 'GET ' . $file . " HTTP/1.0 \r\n" . + 'Host: ' . $p['host'] . " \r\n" . + "Connection: close\r\n\r\n"; + + fwrite($fh, $getstring); + + // Get rid of HTTP header + $s = fgets($fh, 1024); + if (!$s) { + return false; + } + + while (!feof($fh)) { + $s = fgets($fh, 1024); + if ($s === "\r\n") { + break; + } + } + + $data = ''; + + while (!feof($fh)) { + $data .= fgets($fh, 1024); + } + + fclose($fh); + + return $data; + } + + public function setLogger(LoggerInterface $logger) + { + $this->logger = $logger; + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/ServiceFactory.php b/src/bb-vendor/mpdf/mpdf/src/ServiceFactory.php new file mode 100644 index 000000000..f81e6f700 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/ServiceFactory.php @@ -0,0 +1,173 @@ +<?php + +namespace Mpdf; + +use Mpdf\Color\ColorConverter; +use Mpdf\Color\ColorModeConverter; +use Mpdf\Color\ColorSpaceRestrictor; + +use Mpdf\Fonts\FontCache; +use Mpdf\Fonts\FontFileFinder; + +use Mpdf\Image\ImageProcessor; + +use Mpdf\Pdf\Protection; +use Mpdf\Pdf\Protection\UniqidGenerator; + +use Mpdf\Writer\BaseWriter; +use Mpdf\Writer\BackgroundWriter; +use Mpdf\Writer\ColorWriter; +use Mpdf\Writer\BookmarkWriter; +use Mpdf\Writer\FontWriter; +use Mpdf\Writer\FormWriter; +use Mpdf\Writer\ImageWriter; +use Mpdf\Writer\JavaScriptWriter; +use Mpdf\Writer\MetadataWriter; +use Mpdf\Writer\OptionalContentWriter; +use Mpdf\Writer\PageWriter; + +use Mpdf\Writer\ResourceWriter; +use Psr\Log\LoggerInterface; + +class ServiceFactory +{ + + public function getServices( + Mpdf $mpdf, + LoggerInterface $logger, + $config, + $restrictColorSpace, + $languageToFont, + $scriptToLanguage, + $fontDescriptor, + $bmp, + $directWrite, + $wmf + ) { + $sizeConverter = new SizeConverter($mpdf->dpi, $mpdf->default_font_size, $mpdf, $logger); + + $colorModeConverter = new ColorModeConverter(); + $colorSpaceRestrictor = new ColorSpaceRestrictor( + $mpdf, + $colorModeConverter, + $restrictColorSpace + ); + $colorConverter = new ColorConverter($mpdf, $colorModeConverter, $colorSpaceRestrictor); + + $tableOfContents = new TableOfContents($mpdf, $sizeConverter); + + $cache = new Cache($config['tempDir']); + $fontCache = new FontCache(new Cache($config['tempDir'] . '/ttfontdata')); + + $fontFileFinder = new FontFileFinder($config['fontDir']); + + $cssManager = new CssManager($mpdf, $cache, $sizeConverter, $colorConverter); + + $otl = new Otl($mpdf, $fontCache); + + $protection = new Protection(new UniqidGenerator()); + + $writer = new BaseWriter($mpdf, $protection); + + $gradient = new Gradient($mpdf, $sizeConverter, $colorConverter, $writer); + + $formWriter = new FormWriter($mpdf, $writer); + + $form = new Form($mpdf, $otl, $colorConverter, $writer, $formWriter); + + $hyphenator = new Hyphenator($mpdf); + + $remoteContentFetcher = new RemoteContentFetcher($mpdf, $logger); + + $imageProcessor = new ImageProcessor( + $mpdf, + $otl, + $cssManager, + $sizeConverter, + $colorConverter, + $colorModeConverter, + $cache, + $languageToFont, + $scriptToLanguage, + $remoteContentFetcher, + $logger + ); + + $tag = new Tag( + $mpdf, + $cache, + $cssManager, + $form, + $otl, + $tableOfContents, + $sizeConverter, + $colorConverter, + $imageProcessor, + $languageToFont + ); + + $fontWriter = new FontWriter($mpdf, $writer, $fontCache, $fontDescriptor); + $metadataWriter = new MetadataWriter($mpdf, $writer, $form, $protection, $logger); + $imageWriter = new ImageWriter($mpdf, $writer); + $pageWriter = new PageWriter($mpdf, $form, $writer, $metadataWriter); + $bookmarkWriter = new BookmarkWriter($mpdf, $writer); + $optionalContentWriter = new OptionalContentWriter($mpdf, $writer); + $colorWriter = new ColorWriter($mpdf, $writer); + $backgroundWriter = new BackgroundWriter($mpdf, $writer); + $javaScriptWriter = new JavaScriptWriter($mpdf, $writer); + + $resourceWriter = new ResourceWriter( + $mpdf, + $writer, + $colorWriter, + $fontWriter, + $imageWriter, + $formWriter, + $optionalContentWriter, + $backgroundWriter, + $bookmarkWriter, + $metadataWriter, + $javaScriptWriter, + $logger + ); + + return [ + 'otl' => $otl, + 'bmp' => $bmp, + 'cache' => $cache, + 'cssManager' => $cssManager, + 'directWrite' => $directWrite, + 'fontCache' => $fontCache, + 'fontFileFinder' => $fontFileFinder, + 'form' => $form, + 'gradient' => $gradient, + 'tableOfContents' => $tableOfContents, + 'tag' => $tag, + 'wmf' => $wmf, + 'sizeConverter' => $sizeConverter, + 'colorConverter' => $colorConverter, + 'hyphenator' => $hyphenator, + 'remoteContentFetcher' => $remoteContentFetcher, + 'imageProcessor' => $imageProcessor, + 'protection' => $protection, + + 'languageToFont' => $languageToFont, + 'scriptToLanguage' => $scriptToLanguage, + + 'writer' => $writer, + 'fontWriter' => $fontWriter, + 'metadataWriter' => $metadataWriter, + 'imageWriter' => $imageWriter, + 'formWriter' => $formWriter, + 'pageWriter' => $pageWriter, + 'bookmarkWriter' => $bookmarkWriter, + 'optionalContentWriter' => $optionalContentWriter, + 'colorWriter' => $colorWriter, + 'backgroundWriter' => $backgroundWriter, + 'javaScriptWriter' => $javaScriptWriter, + + 'resourceWriter' => $resourceWriter + ]; + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Shaper/Indic.php b/src/bb-vendor/mpdf/mpdf/src/Shaper/Indic.php new file mode 100644 index 000000000..28e3001a8 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Shaper/Indic.php @@ -0,0 +1,1945 @@ +<?php + +namespace Mpdf\Shaper; + +use Mpdf\Ucdn; + +class Indic +{ + /* FROM hb-ot-shape-complex-indic-private.hh */ + + // indic_category + const OT_X = 0; + const OT_C = 1; + const OT_V = 2; + const OT_N = 3; + const OT_H = 4; + const OT_ZWNJ = 5; + const OT_ZWJ = 6; + const OT_M = 7; /* Matra or Dependent Vowel */ + const OT_SM = 8; + const OT_VD = 9; + const OT_A = 10; + const OT_NBSP = 11; + const OT_DOTTEDCIRCLE = 12; /* Not in the spec, but special in Uniscribe. /Very very/ special! */ + const OT_RS = 13; /* Register Shifter, used in Khmer OT spec */ + const OT_COENG = 14; + const OT_REPHA = 15; + + const OT_RA = 16; /* Not explicitly listed in the OT spec, but used in the grammar. */ + const OT_CM = 17; + + /* Visual positions in a syllable from left to right. */ + /* FROM hb-ot-shape-complex-indic-private.hh */ + + // indic_position + const POS_START = 0; + + const POS_RA_TO_BECOME_REPH = 1; + const POS_PRE_M = 2; + const POS_PRE_C = 3; + + const POS_BASE_C = 4; + const POS_AFTER_MAIN = 5; + + const POS_ABOVE_C = 6; + + const POS_BEFORE_SUB = 7; + const POS_BELOW_C = 8; + const POS_AFTER_SUB = 9; + + const POS_BEFORE_POST = 10; + const POS_POST_C = 11; + const POS_AFTER_POST = 12; + + const POS_FINAL_C = 13; + const POS_SMVD = 14; + + const POS_END = 15; + + /* + * Basic features. + * These features are applied in order, one at a time, after initial_reordering. + */ + + /* + * Must be in the same order as the indic_features array. Ones starting with _ are F_GLOBAL + * Ones without the _ are only applied where the mask says! + */ + + const _NUKT = 0; + const _AKHN = 1; + const RPHF = 2; + const _RKRF = 3; + const PREF = 4; + const BLWF = 5; + const HALF = 6; + const ABVF = 7; + const PSTF = 8; + const CFAR = 9; // Khmer only + const _VATU = 10; + const _CJCT = 11; + const INIT = 12; + + // Based on indic_category used to make string to find syllables + // OT_ to string character (using e.g. OT_C from INDIC) hb-ot-shape-complex-indic-private.hh + public static $indic_category_char = [ + 'x', + 'C', + 'V', + 'N', + 'H', + 'Z', + 'J', + 'M', + 'S', + 'v', + 'A', /* Spec gives Andutta U+0952 as OT_A. However, testing shows that Uniscribe + * treats U+0951..U+0952 all as OT_VD - see set_indic_properties */ + 's', + 'D', + 'F', /* Register shift Khmer only */ + 'G', /* Khmer only */ + 'r', /* 0D4E (dot reph) only one in Malayalam */ + 'R', + 'm', /* Consonant medial only used in Indic 0A75 in Gurmukhi (0A00..0A7F) : also in Lao, Myanmar, Tai Tham, Javanese & Cham */ + ]; + + public static function set_indic_properties(&$info, $scriptblock) + { + $u = $info['uni']; + $type = self::indic_get_categories($u); + $cat = ($type & 0x7F); + $pos = ($type >> 8); + + /* + * Re-assign category + */ + + if ($u == 0x17D1) { + $cat = self::OT_X; + } + + if ($cat == self::OT_X && self::in_range($u, 0x17CB, 0x17D3)) { /* Khmer Various signs */ + /* These are like Top Matras. */ + $cat = self::OT_M; + $pos = self::POS_ABOVE_C; + } + + if ($u == 0x17C6) { + $cat = self::OT_N; + } /* Khmer Bindu doesn't like to be repositioned. */ + + if ($u == 0x17D2) { + $cat = self::OT_COENG; + } /* Khmer coeng */ + + /* The spec says U+0952 is OT_A. However, testing shows that Uniscribe + * treats U+0951..U+0952 all as OT_VD. + * TESTS: + * U+092E,U+0947,U+0952 + * U+092E,U+0952,U+0947 + * U+092E,U+0947,U+0951 + * U+092E,U+0951,U+0947 + * */ + //if ($u == 0x0952) $cat = self::OT_A; + if (self::in_range($u, 0x0951, 0x0954)) { + $cat = self::OT_VD; + } + + if ($u == 0x200C) { + $cat = self::OT_ZWNJ; + } elseif ($u == 0x200D) { + $cat = self::OT_ZWJ; + } elseif ($u == 0x25CC) { + $cat = self::OT_DOTTEDCIRCLE; + } elseif ($u == 0x0A71) { + $cat = self::OT_SM; + } /* GURMUKHI ADDAK. More like consonant medial. like 0A75. */ + + if ($cat == self::OT_REPHA) { + /* There are two kinds of characters marked as Repha: + * - The ones that are GenCat=Mn are already positioned visually, ie. after base. (eg. Khmer) + * - The ones that are GenCat=Lo is encoded logically, ie. beginning of syllable. (eg. Malayalam) + * + * We recategorize the first kind to look like a Nukta and attached to the base directly. + */ + if ($info['general_category'] == Ucdn::UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK) { + $cat = self::OT_N; + } + } + + /* + * Re-assign position. + */ + + if ((self::FLAG($cat) & (self::FLAG(self::OT_C) | self::FLAG(self::OT_CM) | self::FLAG(self::OT_RA) | self::FLAG(self::OT_V) | self::FLAG(self::OT_NBSP) | self::FLAG(self::OT_DOTTEDCIRCLE)))) { // = CONSONANT_FLAGS like is_consonant + if ($scriptblock == Ucdn::SCRIPT_KHMER) { + $pos = self::POS_BELOW_C; + } /* Khmer differs from Indic here. */ + else { + $pos = self::POS_BASE_C; + } /* Will recategorize later based on font lookups. */ + + if (self::is_ra($u)) { + $cat = self::OT_RA; + } + } elseif ($cat == self::OT_M) { + $pos = self::matra_position($u, $pos); + } elseif ($cat == self::OT_SM || $cat == self::OT_VD) { + $pos = self::POS_SMVD; + } + + if ($u == 0x0B01) { + $pos = self::POS_BEFORE_SUB; + } /* Oriya Bindu is BeforeSub in the spec. */ + + $info['indic_category'] = $cat; + $info['indic_position'] = $pos; + } + + // syllable_type + const CONSONANT_SYLLABLE = 0; + const VOWEL_SYLLABLE = 1; + const STANDALONE_CLUSTER = 2; + const BROKEN_CLUSTER = 3; + const NON_INDIC_CLUSTER = 4; + + public static function set_syllables(&$o, $s, &$broken_syllables) + { + $ptr = 0; + $syllable_serial = 1; + $broken_syllables = false; + + while ($ptr < strlen($s)) { + $match = ''; + $syllable_length = 1; + $syllable_type = self::NON_INDIC_CLUSTER; + // CONSONANT_SYLLABLE Consonant syllable + // From OT spec: + if (preg_match('/^([CR]m*[N]?(H[ZJ]?|[ZJ]H))*[CR]m*[N]?[A]?(H[ZJ]?|[M]*[N]?[H]?)?[S]?[v]{0,2}/', substr($s, $ptr), $ma)) { + // From HarfBuzz: + //if (preg_match('/^r?([CR]J?(Z?[N]{0,2})?[ZJ]?H(J[N]?)?){0,4}[CR]J?(Z?[N]{0,2})?A?((([ZJ]?H(J[N]?)?)|HZ)|(HJ)?([ZJ]{0,3}M[N]?(H|JHJR)?){0,4})?(S[Z]?)?[v]{0,2}/', substr($s,$ptr), $ma)) { + $syllable_length = strlen($ma[0]); + $syllable_type = self::CONSONANT_SYLLABLE; + } // VOWEL_SYLLABLE Vowel-based syllable + // From OT spec: + elseif (preg_match('/^(RH|r)?V[N]?([ZJ]?H[CR]m*|J[CR]m*)?([M]*[N]?[H]?)?[S]?[v]{0,2}/', substr($s, $ptr), $ma)) { + // From HarfBuzz: + //else if (preg_match('/^(RH|r)?V(Z?[N]{0,2})?(J|([ZJ]?H(J[N]?)?[CR]J?(Z?[N]{0,2})?){0,4}((([ZJ]?H(J[N]?)?)|HZ)|(HJ)?([ZJ]{0,3}M[N]?(H|JHJR)?){0,4})?(S[Z]?)?[v]{0,2})/', substr($s,$ptr), $ma)) { + $syllable_length = strlen($ma[0]); + $syllable_type = self::VOWEL_SYLLABLE; + } /* Apply only if it's a word start. */ + // STANDALONE_CLUSTER Stand Alone syllable at start of word + // From OT spec: + elseif (($ptr == 0 || + $o[$ptr - 1]['general_category'] < Ucdn::UNICODE_GENERAL_CATEGORY_LOWERCASE_LETTER || + $o[$ptr - 1]['general_category'] > Ucdn::UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK + ) && (preg_match('/^(RH|r)?[sD][N]?([ZJ]?H[CR]m*)?([M]*[N]?[H]?)?[S]?[v]{0,2}/', substr($s, $ptr), $ma))) { + // From HarfBuzz: + // && (preg_match('/^(RH|r)?[sD](Z?[N]{0,2})?(([ZJ]?H(J[N]?)?)[CR]J?(Z?[N]{0,2})?){0,4}((([ZJ]?H(J[N]?)?)|HZ)|(HJ)?([ZJ]{0,3}M[N]?(H|JHJR)?){0,4})?(S[Z]?)?[v]{0,2}/', substr($s,$ptr), $ma)) { + $syllable_length = strlen($ma[0]); + $syllable_type = self::STANDALONE_CLUSTER; + } // BROKEN_CLUSTER syllable + elseif (preg_match('/^(RH|r)?[N]?([ZJ]?H[CR])?([M]*[N]?[H]?)?[S]?[v]{0,2}/', substr($s, $ptr), $ma)) { + // From HarfBuzz: + //else if (preg_match('/^(RH|r)?(Z?[N]{0,2})?(([ZJ]?H(J[N]?)?)[CR]J?(Z?[N]{0,2})?){0,4}((([ZJ]?H(J[N]?)?)|HZ)|(HJ)?([ZJ]{0,3}M[N]?(H|JHJR)?){0,4})(S[Z]?)?[v]{0,2}/', substr($s,$ptr), $ma)) { + if (strlen($ma[0])) { // May match blank + $syllable_length = strlen($ma[0]); + $syllable_type = self::BROKEN_CLUSTER; + $broken_syllables = true; + } + } + + for ($i = $ptr; $i < $ptr + $syllable_length; $i++) { + $o[$i]['syllable'] = ($syllable_serial << 4) | $syllable_type; + } + $ptr += $syllable_length; + $syllable_serial++; + if ($syllable_serial == 16) { + $syllable_serial = 1; + } + } + } + + public static function set_syllables_sinhala(&$o, $s, &$broken_syllables) + { + $ptr = 0; + $syllable_serial = 1; + $broken_syllables = false; + + while ($ptr < strlen($s)) { + $match = ''; + $syllable_length = 1; + $syllable_type = self::NON_INDIC_CLUSTER; + // CONSONANT_SYLLABLE Consonant syllable + // From OT spec: + if (preg_match('/^([CR]HJ|[CR]JH){0,8}[CR][HM]{0,3}[S]{0,1}/', substr($s, $ptr), $ma)) { + $syllable_length = strlen($ma[0]); + $syllable_type = self::CONSONANT_SYLLABLE; + } // VOWEL_SYLLABLE Vowel-based syllable + // From OT spec: + elseif (preg_match('/^V[S]{0,1}/', substr($s, $ptr), $ma)) { + $syllable_length = strlen($ma[0]); + $syllable_type = self::VOWEL_SYLLABLE; + } + + for ($i = $ptr; $i < $ptr + $syllable_length; $i++) { + $o[$i]['syllable'] = ($syllable_serial << 4) | $syllable_type; + } + $ptr += $syllable_length; + $syllable_serial++; + if ($syllable_serial == 16) { + $syllable_serial = 1; + } + } + } + + public static function set_syllables_khmer(&$o, $s, &$broken_syllables) + { + $ptr = 0; + $syllable_serial = 1; + $broken_syllables = false; + + while ($ptr < strlen($s)) { + $match = ''; + $syllable_length = 1; + $syllable_type = self::NON_INDIC_CLUSTER; + // CONSONANT_SYLLABLE Consonant syllable + if (preg_match('/^r?([CR]J?((Z?F)?[N]{0,2})?[ZJ]?G(JN?)?){0,4}[CR]J?((Z?F)?[N]{0,2})?A?((([ZJ]?G(JN?)?)|GZ)|(GJ)?([ZJ]{0,3}MN?(H|JHJR)?){0,4})?(G([CR]J?((Z?F)?[N]{0,2})?|V))?(SZ?)?[v]{0,2}/', substr($s, $ptr), $ma)) { + $syllable_length = strlen($ma[0]); + $syllable_type = self::CONSONANT_SYLLABLE; + } // VOWEL_SYLLABLE Vowel-based syllable + elseif (preg_match('/^(RH|r)?V((Z?F)?[N]{0,2})?(J|([ZJ]?G(JN?)?[CR]J?((Z?F)?[N]{0,2})?){0,4}((([ZJ]?G(JN?)?)|GZ)|(GJ)?([ZJ]{0,3}MN?(H|JHJR)?){0,4})?(G([CR]J?((Z?F)?[N]{0,2})?|V))?(SZ?)?[v]{0,2})/', substr($s, $ptr), $ma)) { + $syllable_length = strlen($ma[0]); + $syllable_type = self::VOWEL_SYLLABLE; + } // BROKEN_CLUSTER syllable + elseif (preg_match('/^(RH|r)?((Z?F)?[N]{0,2})?(([ZJ]?G(JN?)?)[CR]J?((Z?F)?[N]{0,2})?){0,4}((([ZJ]?G(JN?)?)|GZ)|(GJ)?([ZJ]{0,3}MN?(H|JHJR)?){0,4})(G([CR]J?((Z?F)?[N]{0,2})?|V))?(SZ?)?[v]{0,2}/', substr($s, $ptr), $ma)) { + if (strlen($ma[0])) { // May match blank + $syllable_length = strlen($ma[0]); + $syllable_type = self::BROKEN_CLUSTER; + $broken_syllables = true; + } + } + + for ($i = $ptr; $i < $ptr + $syllable_length; $i++) { + $o[$i]['syllable'] = ($syllable_serial << 4) | $syllable_type; + } + $ptr += $syllable_length; + $syllable_serial++; + if ($syllable_serial == 16) { + $syllable_serial = 1; + } + } + } + + public static function initial_reordering(&$info, $GSUBdata, $broken_syllables, $indic_config, $scriptblock, $is_old_spec, $dottedcircle) + { + + self::update_consonant_positions($info, $GSUBdata); + + if ($broken_syllables && $dottedcircle) { + self::insert_dotted_circles($info, $dottedcircle); + } + + $count = count($info); + if (!$count) { + return; + } + $last = 0; + $last_syllable = $info[0]['syllable']; + for ($i = 1; $i < $count; $i++) { + if ($last_syllable != $info[$i]['syllable']) { + self::initial_reordering_syllable($info, $GSUBdata, $indic_config, $scriptblock, $is_old_spec, $last, $i); + $last = $i; + $last_syllable = $info[$last]['syllable']; + } + } + self::initial_reordering_syllable($info, $GSUBdata, $indic_config, $scriptblock, $is_old_spec, $last, $count); + } + + public static function update_consonant_positions(&$info, $GSUBdata) + { + $count = count($info); + for ($i = 0; $i < $count; $i++) { + if ($info[$i]['indic_position'] == self::POS_BASE_C) { + $c = $info[$i]['uni']; + // If would substitute... + if (isset($GSUBdata['pref'][$c])) { + $info[$i]['indic_position'] = self::POS_POST_C; + } elseif (isset($GSUBdata['blwf'][$c])) { + $info[$i]['indic_position'] = self::POS_BELOW_C; + } elseif (isset($GSUBdata['pstf'][$c])) { + $info[$i]['indic_position'] = self::POS_POST_C; + } + } + } + } + + public static function insert_dotted_circles(&$info, $dottedcircle) + { + $idx = 0; + $last_syllable = 0; + while ($idx < count($info)) { + $syllable = $info[$idx]['syllable']; + $syllable_type = ($syllable & 0x0F); + if ($last_syllable != $syllable && $syllable_type == self::BROKEN_CLUSTER) { + $last_syllable = $syllable; + + $dottedcircle[0]['syllable'] = $info[$idx]['syllable']; + + /* Insert dottedcircle after possible Repha. */ + while ($idx < count($info) && $last_syllable == $info[$idx]['syllable'] && $info[$idx]['indic_category'] == self::OT_REPHA) { + $idx++; + } + array_splice($info, $idx, 0, $dottedcircle); + } else { + $idx++; + } + } + + // I am not sue how this code below got in here, since $idx should now be > count($info) and thus invalid. + // In case I am missing something(!) I'll leave a warning here for now: + if (isset($info[$idx])) { + throw new \Mpdf\MpdfException('Unexpected error occured in Indic processing'); + } + // In case of final bloken cluster... + //$syllable = $info[$idx]['syllable']; + //$syllable_type = ($syllable & 0x0F); + //if ($last_syllable != $syllable && $syllable_type == self::BROKEN_CLUSTER) { + // $dottedcircle[0]['syllable'] = $info[$idx]['syllable']; + // array_splice($info, $idx, 0, $dottedcircle); + //} + } + + /* Rules from: + * https://www.microsoft.com/typography/otfntdev/devanot/shaping.aspx */ + + public static function initial_reordering_syllable(&$info, $GSUBdata, $indic_config, $scriptblock, $is_old_spec, $start, $end) + { + /* vowel_syllable: We made the vowels look like consonants. So uses the consonant logic! */ + /* broken_cluster: We already inserted dotted-circles, so just call the standalone_cluster. */ + /* standalone_cluster: We treat NBSP/dotted-circle as if they are consonants, so we should just chain. */ + + $syllable_type = ($info[$start]['syllable'] & 0x0F); + if ($syllable_type == self::NON_INDIC_CLUSTER) { + return; + } + if ($syllable_type == self::BROKEN_CLUSTER || $syllable_type == self::STANDALONE_CLUSTER) { + //if ($uniscribe_bug_compatible) { + /* For dotted-circle, this is what Uniscribe does: + * If dotted-circle is the last glyph, it just does nothing. + * i.e. It doesn't form Reph. */ + if ($info[$end - 1]['indic_category'] == self::OT_DOTTEDCIRCLE) { + return; + } + } + + /* 1. Find base consonant: + * + * The shaping engine finds the base consonant of the syllable, using the + * following algorithm: starting from the end of the syllable, move backwards + * until a consonant is found that does not have a below-base or post-base + * form (post-base forms have to follow below-base forms), or that is not a + * pre-base reordering Ra, or arrive at the first consonant. The consonant + * stopped at will be the base. + * + * o If the syllable starts with Ra + Halant (in a script that has Reph) + * and has more than one consonant, Ra is excluded from candidates for + * base consonants. + */ + + $base = $end; + $has_reph = false; + $limit = $start; + + if ($scriptblock != Ucdn::SCRIPT_KHMER) { + /* -> If the syllable starts with Ra + Halant (in a script that has Reph) + * and has more than one consonant, Ra is excluded from candidates for + * base consonants. */ + if (count($GSUBdata['rphf']) /* ?? $indic_plan->mask_array[RPHF] */ && $start + 3 <= $end && + ( + ($indic_config[4] == self::REPH_MODE_IMPLICIT && !self::is_joiner($info[$start + 2])) || + ($indic_config[4] == self::REPH_MODE_EXPLICIT && $info[$start + 2]['indic_category'] == self::OT_ZWJ) + )) { + /* See if it matches the 'rphf' feature. */ + //$glyphs = array($info[$start]['uni'], $info[$start + 1]['uni']); + //if ($indic_plan->rphf->would_substitute ($glyphs, count($glyphs), true, face)) { + if (isset($GSUBdata['rphf'][$info[$start]['uni']]) && self::is_halant_or_coeng($info[$start + 1])) { + $limit += 2; + while ($limit < $end && self::is_joiner($info[$limit])) { + $limit++; + } + $base = $start; + $has_reph = true; + } + } elseif ($indic_config[4] == self::REPH_MODE_LOG_REPHA && $info[$start]['indic_category'] == self::OT_REPHA) { + $limit += 1; + while ($limit < $end && self::is_joiner($info[$limit])) { + $limit++; + } + $base = $start; + $has_reph = true; + } + } + + switch ($indic_config[2]) { // base_pos + case self::BASE_POS_LAST: + /* -> starting from the end of the syllable, move backwards */ + $i = $end; + $seen_below = false; + do { + $i--; + /* -> until a consonant is found */ + if (self::is_consonant($info[$i])) { + /* -> that does not have a below-base or post-base form + * (post-base forms have to follow below-base forms), */ + if ($info[$i]['indic_position'] != self::POS_BELOW_C && ($info[$i]['indic_position'] != self::POS_POST_C || $seen_below)) { + $base = $i; + break; + } + if ($info[$i]['indic_position'] == self::POS_BELOW_C) { + $seen_below = true; + } + + /* -> or that is not a pre-base reordering Ra, + * + * IMPLEMENTATION NOTES: + * + * Our pre-base reordering Ra's are marked POS_POST_C, so will be skipped + * by the logic above already. + */ + + /* -> or arrive at the first consonant. The consonant stopped at will + * be the base. */ + $base = $i; + } else { + /* A ZWJ after a Halant stops the base search, and requests an explicit + * half form. + * [A ZWJ before a Halant, requests a subjoined form instead, and hence + * search continues. This is particularly important for Bengali + * sequence Ra,H,Ya that should form Ya-Phalaa by subjoining Ya] */ + if ($start < $i && $info[$i]['indic_category'] == self::OT_ZWJ && $info[$i - 1]['indic_category'] == self::OT_H) { + if (!defined("OMIT_INDIC_FIX_1") || OMIT_INDIC_FIX_1 != 1) { + $base = $i; + } // INDIC_FIX_1 + break; + } + // ZKI8 + if ($start < $i && $info[$i]['indic_category'] == self::OT_ZWNJ) { + break; + } + } + } while ($i > $limit); + break; + + case self::BASE_POS_FIRST: + /* In scripts without half forms (eg. Khmer), the first consonant is always the base. */ + + if (!$has_reph) { + $base = $limit; + } + + /* Find the last base consonant that is not blocked by ZWJ. If there is + * a ZWJ right before a base consonant, that would request a subjoined form. */ + for ($i = $limit; $i < $end; $i++) { + if (self::is_consonant($info[$i]) && $info[$i]['indic_position'] == self::POS_BASE_C) { + if ($limit < $i && $info[$i - 1]['indic_category'] == self::OT_ZWJ) { + break; + } else { + $base = $i; + } + } + } + + /* Mark all subsequent consonants as below. */ + for ($i = $base + 1; $i < $end; $i++) { + if (self::is_consonant($info[$i]) && $info[$i]['indic_position'] == self::POS_BASE_C) { + $info[$i]['indic_position'] = self::POS_BELOW_C; + } + } + break; + //default: + //assert (false); + /* fallthrough */ + } + + /* -> If the syllable starts with Ra + Halant (in a script that has Reph) + * and has more than one consonant, Ra is excluded from candidates for + * base consonants. + * + * Only do this for unforced Reph. (ie. not for Ra,H,ZWJ. */ + if ($scriptblock != Ucdn::SCRIPT_KHMER) { + if ($has_reph && $base == $start && $limit - $base <= 2) { + /* Have no other consonant, so Reph is not formed and Ra becomes base. */ + $has_reph = false; + } + } + + /* 2. Decompose and reorder Matras: + * + * Each matra and any syllable modifier sign in the cluster are moved to the + * appropriate position relative to the consonant(s) in the cluster. The + * shaping engine decomposes two- or three-part matras into their constituent + * parts before any repositioning. Matra characters are classified by which + * consonant in a conjunct they have affinity for and are reordered to the + * following positions: + * + * o Before first half form in the syllable + * o After subjoined consonants + * o After post-form consonant + * o After main consonant (for above marks) + * + * IMPLEMENTATION NOTES: + * + * The normalize() routine has already decomposed matras for us, so we don't + * need to worry about that. + */ + + + /* 3. Reorder marks to canonical order: + * + * Adjacent nukta and halant or nukta and vedic sign are always repositioned + * if necessary, so that the nukta is first. + * + * IMPLEMENTATION NOTES: + * + * Use the combining Class from Unicode categories? to bubble_sort. + */ + + /* Reorder characters */ + + for ($i = $start; $i < $base; $i++) { + $info[$i]['indic_position'] = min(self::POS_PRE_C, $info[$i]['indic_position']); + } + + if ($base < $end) { + $info[$base]['indic_position'] = self::POS_BASE_C; + } + + /* Mark final consonants. A final consonant is one appearing after a matra, + * ? only in Khmer. */ + for ($i = $base + 1; $i < $end; $i++) { + if ($info[$i]['indic_category'] == self::OT_M) { + for ($j = $i + 1; $j < $end; $j++) { + if (self::is_consonant($info[$j])) { + $info[$j]['indic_position'] = self::POS_FINAL_C; + break; + } + } + break; + } + } + + /* Handle beginning Ra */ + if ($scriptblock != Ucdn::SCRIPT_KHMER) { + if ($has_reph) { + $info[$start]['indic_position'] = self::POS_RA_TO_BECOME_REPH; + } + } + + + /* For old-style Indic script tags, move the first post-base Halant after + * last consonant. Only do this if there is *not* a Halant after last + * consonant. Otherwise it becomes messy. */ + if ($is_old_spec) { + for ($i = $base + 1; $i < $end; $i++) { + if ($info[$i]['indic_category'] == self::OT_H) { + for ($j = $end - 1; $j > $i; $j--) { + if (self::is_consonant($info[$j]) || $info[$j]['indic_category'] == self::OT_H) { + break; + } + } + if ($info[$j]['indic_category'] != self::OT_H && $j > $i) { + /* Move Halant to after last consonant. */ + self::_move_info_pos($info, $i, $j + 1); + } + break; + } + } + } + + /* Attach misc marks to previous char to move with them. */ + $last_pos = self::POS_START; + for ($i = $start; $i < $end; $i++) { + if ((self::FLAG($info[$i]['indic_category']) & (self::FLAG(self::OT_ZWJ) | self::FLAG(self::OT_ZWNJ) | self::FLAG(self::OT_N) | self::FLAG(self::OT_RS) | self::FLAG(self::OT_H) | self::FLAG(self::OT_COENG) ))) { + $info[$i]['indic_position'] = $last_pos; + if ($info[$i]['indic_category'] == self::OT_H && $info[$i]['indic_position'] == self::POS_PRE_M) { + /* + * Uniscribe doesn't move the Halant with Left Matra. + * TEST: U+092B,U+093F,U+094DE + * We follow. This is important for the Sinhala + * U+0DDA split matra since it decomposes to U+0DD9,U+0DCA + * where U+0DD9 is a left matra and U+0DCA is the virama. + * We don't want to move the virama with the left matra. + * TEST: U+0D9A,U+0DDA + */ + for ($j = $i; $j > $start; $j--) { + if ($info[$j - 1]['indic_position'] != self::POS_PRE_M) { + $info[$i]['indic_position'] = $info[$j - 1]['indic_position']; + break; + } + } + } + } elseif ($info[$i]['indic_position'] != self::POS_SMVD) { + $last_pos = $info[$i]['indic_position']; + } + } + + /* Re-attach ZWJ, ZWNJ, and halant to next char, for after-base consonants. */ + $last_halant = $end; + for ($i = $base + 1; $i < $end; $i++) { + if (self::is_halant_or_coeng($info[$i])) { + $last_halant = $i; + } elseif (self::is_consonant($info[$i])) { + for ($j = $last_halant; $j < $i; $j++) { + if ($info[$j]['indic_position'] != self::POS_SMVD) { + $info[$j]['indic_position'] = $info[$i]['indic_position']; + } + } + } + } + + + if ($scriptblock == Ucdn::SCRIPT_KHMER) { + /* KHMER_FIX_2 */ + /* Move Coeng+RO (Halant,Ra) sequence before base consonant. */ + for ($i = $base + 1; $i < $end; $i++) { + if (self::is_halant_or_coeng($info[$i]) && self::is_ra($info[$i + 1]['uni'])) { + $info[$i]['indic_position'] = self::POS_PRE_C; + $info[$i + 1]['indic_position'] = self::POS_PRE_C; + break; + } + } + } + + + /* + if (!defined("OMIT_INDIC_FIX_2") || OMIT_INDIC_FIX_2 != 1) { + // INDIC_FIX_2 + $ZWNJ_found = false; + $POST_ZWNJ_c_found = false; + for ($i = $base + 1; $i < $end; $i++) { + if ($info[$i]['indic_category'] == self::OT_ZWNJ) { $ZWNJ_found = true; } + else if ($ZWNJ_found && $info[$i]['indic_category'] == self::OT_C) { $POST_ZWNJ_c_found = true; } + else if ($POST_ZWNJ_c_found && $info[$i]['indic_position'] == self::POS_BEFORE_SUB) { $info[$i]['indic_position'] = self::POS_AFTER_SUB; } + } + } + */ + + /* Setup masks now */ + for ($i = $start; $i < $end; $i++) { + $info[$i]['mask'] = 0; + } + + + if ($scriptblock == Ucdn::SCRIPT_KHMER) { + /* Find a Coeng+RO (Halant,Ra) sequence and mark it for pre-base processing. */ + $mask = self::FLAG(self::PREF); + for ($i = $base; $i < $end - 1; $i++) { /* KHMER_FIX_1 From $start (not base) */ + if (self::is_halant_or_coeng($info[$i]) && self::is_ra($info[$i + 1]['uni'])) { + $info[$i]['mask'] |= self::FLAG(self::PREF); + $info[$i + 1]['mask'] |= self::FLAG(self::PREF); + + /* Mark the subsequent stuff with 'cfar'. Used in Khmer. + * Read the feature spec. + * This allows distinguishing the following cases with MS Khmer fonts: + * U+1784,U+17D2,U+179A,U+17D2,U+1782 [C+Coeng+RO+Coeng+C] => Should activate CFAR + * U+1784,U+17D2,U+1782,U+17D2,U+179A [C+Coeng+C+Coeng+RO] => Should NOT activate CFAR + */ + for ($j = ($i + 2); $j < $end; $j++) { + $info[$j]['mask'] |= self::FLAG(self::CFAR); + } + + break; + } + } + } + + + + /* Sit tight, rock 'n roll! */ + self::bubble_sort($info, $start, $end - $start); + + /* Find base again */ + $base = $end; + for ($i = $start; $i < $end; $i++) { + if ($info[$i]['indic_position'] == self::POS_BASE_C) { + $base = $i; + break; + } + } + + if ($scriptblock != Ucdn::SCRIPT_KHMER) { + /* Reph */ + for ($i = $start; $i < $end; $i++) { + if ($info[$i]['indic_position'] == self::POS_RA_TO_BECOME_REPH) { + $info[$i]['mask'] |= self::FLAG(self::RPHF); + } + } + + /* Pre-base */ + $mask = self::FLAG(self::HALF); + for ($i = $start; $i < $base; $i++) { + $info[$i]['mask'] |= $mask; + } + } + + /* Post-base */ + $mask = (self::FLAG(self::BLWF) | self::FLAG(self::ABVF) | self::FLAG(self::PSTF)); + for ($i = $base + 1; $i < $end; $i++) { + $info[$i]['mask'] |= $mask; + } + + + if ($scriptblock != Ucdn::SCRIPT_KHMER) { + if (!defined("OMIT_INDIC_FIX_3") || OMIT_INDIC_FIX_3 != 1) { + /* INDIC_FIX_3 */ + /* Find a (pre-base) Consonant, Halant,Ra sequence and mark Halant|Ra for below-base BLWF processing. */ + // TEST CASE ক্র্ক in FreeSans versus Vrinda + if (($base - $start) >= 3) { + for ($i = $start; $i < ($base - 2); $i++) { + if (self::is_consonant($info[$i])) { + if (self::is_halant_or_coeng($info[$i + 1]) && self::is_ra($info[$i + 2]['uni'])) { + // If would substitute Halant+Ra...BLWF + if (isset($GSUBdata['blwf'][$info[$i + 2]['uni']])) { + $info[$i + 1]['mask'] |= self::FLAG(self::BLWF); + $info[$i + 2]['mask'] |= self::FLAG(self::BLWF); + } /* If would not substitute as blwf, mark Ra+Halant for RPHF using following Halant (if present) */ elseif (self::is_halant_or_coeng($info[$i + 3])) { + $info[$i + 2]['mask'] |= self::FLAG(self::RPHF); + $info[$i + 3]['mask'] |= self::FLAG(self::RPHF); + } + break; + } + } + } + } + } + } + + + + if ($is_old_spec && $scriptblock == Ucdn::SCRIPT_DEVANAGARI) { + /* Old-spec eye-lash Ra needs special handling. From the spec: + * "The feature 'below-base form' is applied to consonants + * having below-base forms and following the base consonant. + * The exception is vattu, which may appear below half forms + * as well as below the base glyph. The feature 'below-base + * form' will be applied to all such occurrences of Ra as well." + * + * Test case: U+0924,U+094D,U+0930,U+094d,U+0915 + * with Sanskrit 2003 font. + * + * However, note that Ra,Halant,ZWJ is the correct way to + * request eyelash form of Ra, so we wouldbn't inhibit it + * in that sequence. + * + * Test case: U+0924,U+094D,U+0930,U+094d,U+200D,U+0915 + */ + for ($i = $start; ($i + 1) < $base; $i++) { + if ($info[$i]['indic_category'] == self::OT_RA && $info[$i + 1]['indic_category'] == self::OT_H && + ($i + 2 == $base || $info[$i + 2]['indic_category'] != self::OT_ZWJ)) { + $info[$i]['mask'] |= self::FLAG(self::BLWF); + $info[$i + 1]['mask'] |= self::FLAG(self::BLWF); + } + } + } + + if ($scriptblock != Ucdn::SCRIPT_KHMER) { + if (count($GSUBdata['pref']) && $base + 2 < $end) { + /* Find a Halant,Ra sequence and mark it for pre-base processing. */ + for ($i = $base + 1; $i + 1 < $end; $i++) { + // If old_spec find Ra-Halant... + if ((isset($GSUBdata['pref'][$info[$i + 1]['uni']]) && self::is_halant_or_coeng($info[$i]) && self::is_ra($info[$i + 1]['uni']) ) || + ($is_old_spec && isset($GSUBdata['pref'][$info[$i]['uni']]) && self::is_halant_or_coeng($info[$i + 1]) && self::is_ra($info[$i]['uni']) ) + ) { + $info[$i++]['mask'] |= self::FLAG(self::PREF); + $info[$i++]['mask'] |= self::FLAG(self::PREF); + break; + } + } + } + } + + + /* Apply ZWJ/ZWNJ effects */ + for ($i = $start + 1; $i < $end; $i++) { + if (self::is_joiner($info[$i])) { + $non_joiner = ($info[$i]['indic_category'] == self::OT_ZWNJ); + $j = $i; + while ($j > $start) { + if (defined("OMIT_INDIC_FIX_4") && OMIT_INDIC_FIX_4 == 1) { + // INDIC_FIX_4 = do nothing - carry on // + // ZWNJ should block H C from forming blwf post-base - need to unmask backwards beyond first consonant arrived at // + if (!self::is_consonant($info[$j])) { + break; + } + } + $j--; + + /* ZWJ/ZWNJ should disable CJCT. They do that by simply + * being there, since we don't skip them for the CJCT + * feature (ie. F_MANUAL_ZWJ) */ + + /* A ZWNJ disables HALF. */ + if ($non_joiner) { + $info[$j]['mask'] &= ~(self::FLAG(self::HALF) | self::FLAG(self::BLWF)); + } + } + } + } + } + + public static function final_reordering(&$info, $GSUBdata, $indic_config, $scriptblock, $is_old_spec) + { + $count = count($info); + if (!$count) { + return; + } + $last = 0; + $last_syllable = $info[0]['syllable']; + for ($i = 1; $i < $count; $i++) { + if ($last_syllable != $info[$i]['syllable']) { + self::final_reordering_syllable($info, $GSUBdata, $indic_config, $scriptblock, $is_old_spec, $last, $i); + $last = $i; + $last_syllable = $info[$last]['syllable']; + } + } + self::final_reordering_syllable($info, $GSUBdata, $indic_config, $scriptblock, $is_old_spec, $last, $count); + } + + public static function final_reordering_syllable(&$info, $GSUBdata, $indic_config, $scriptblock, $is_old_spec, $start, $end) + { + + /* 4. Final reordering: + * + * After the localized forms and basic shaping forms GSUB features have been + * applied (see below), the shaping engine performs some final glyph + * reordering before applying all the remaining font features to the entire + * cluster. + */ + + /* Find base again */ + for ($base = $start; $base < $end; $base++) { + if ($info[$base]['indic_position'] >= self::POS_BASE_C) { + if ($start < $base && $info[$base]['indic_position'] > self::POS_BASE_C) { + $base--; + } + break; + } + } + if ($base == $end && $start < $base && $info[$base - 1]['indic_category'] != self::OT_ZWJ) { + $base--; + } + while ($start < $base && isset($info[$base]) && ($info[$base]['indic_category'] == self::OT_H || $info[$base]['indic_category'] == self::OT_N)) { + $base--; + } + + + /* o Reorder matras: + * + * If a pre-base matra character had been reordered before applying basic + * features, the glyph can be moved closer to the main consonant based on + * whether half-forms had been formed. Actual position for the matra is + * defined as "after last standalone halant glyph, after initial matra + * position and before the main consonant". If ZWJ or ZWNJ follow this + * halant, position is moved after it. + */ + + + if ($start + 1 < $end && $start < $base) { /* Otherwise there can't be any pre-base matra characters. */ + /* If we lost track of base, alas, position before last thingy. */ + $new_pos = ($base == $end) ? $base - 2 : $base - 1; + + /* Malayalam / Tamil do not have "half" forms or explicit virama forms. + * The glyphs formed by 'half' are Chillus or ligated explicit viramas. + * We want to position matra after them. + */ + if ($scriptblock != Ucdn::SCRIPT_MALAYALAM && $scriptblock != Ucdn::SCRIPT_TAMIL) { + while ($new_pos > $start && !(self::is_one_of($info[$new_pos], (self::FLAG(self::OT_M) | self::FLAG(self::OT_H) | self::FLAG(self::OT_COENG))))) { + $new_pos--; + } + + /* If we found no Halant we are done. + * Otherwise only proceed if the Halant does + * not belong to the Matra itself! */ + if (self::is_halant_or_coeng($info[$new_pos]) && $info[$new_pos]['indic_position'] != self::POS_PRE_M) { + /* -> If ZWJ or ZWNJ follow this halant, position is moved after it. */ + if ($new_pos + 1 < $end && self::is_joiner($info[$new_pos + 1])) { + $new_pos++; + } + } else { + $new_pos = $start; + } /* No move. */ + } + + if ($start < $new_pos && $info[$new_pos]['indic_position'] != self::POS_PRE_M) { + /* Now go see if there's actually any matras... */ + for ($i = $new_pos; $i > $start; $i--) { + if ($info[$i - 1]['indic_position'] == self::POS_PRE_M) { + $old_pos = $i - 1; + //memmove (&info[$old_pos], &info[$old_pos + 1], ($new_pos - $old_pos) * sizeof ($info[0])); + self::_move_info_pos($info, $old_pos, $new_pos + 1); + + if ($old_pos < $base && $base <= $new_pos) { /* Shouldn't actually happen. */ + $base--; + } + $new_pos--; + } + } + } + } + + + /* o Reorder reph: + * + * Reph's original position is always at the beginning of the syllable, + * (i.e. it is not reordered at the character reordering stage). However, + * it will be reordered according to the basic-forms shaping results. + * Possible positions for reph, depending on the script, are; after main, + * before post-base consonant forms, and after post-base consonant forms. + */ + + /* If there's anything after the Ra that has the REPH pos, it ought to be halant. + * Which means that the font has failed to ligate the Reph. In which case, we + * shouldn't move. */ + if ($start + 1 < $end && + $info[$start]['indic_position'] == self::POS_RA_TO_BECOME_REPH && $info[$start + 1]['indic_position'] != self::POS_RA_TO_BECOME_REPH) { + $reph_pos = $indic_config[3]; + $skip_to_reph_step_5 = false; + $skip_to_reph_move = false; + + /* 1. If reph should be positioned after post-base consonant forms, + * proceed to step 5. + */ + if ($reph_pos == self::REPH_POS_AFTER_POST) { + $skip_to_reph_step_5 = true; + } + + /* 2. If the reph repositioning class is not after post-base: target + * position is after the first explicit halant glyph between the + * first post-reph consonant and last main consonant. If ZWJ or ZWNJ + * are following this halant, position is moved after it. If such + * position is found, this is the target position. Otherwise, + * proceed to the next step. + * + * Note: in old-implementation fonts, where classifications were + * fixed in shaping engine, there was no case where reph position + * will be found on this step. + */ + + if (!$skip_to_reph_step_5) { + $new_reph_pos = $start + 1; + + while ($new_reph_pos < $base && !self::is_halant_or_coeng($info[$new_reph_pos])) { + $new_reph_pos++; + } + + if ($new_reph_pos < $base && self::is_halant_or_coeng($info[$new_reph_pos])) { + /* ->If ZWJ or ZWNJ are following this halant, position is moved after it. */ + if ($new_reph_pos + 1 < $base && self::is_joiner($info[$new_reph_pos + 1])) { + $new_reph_pos++; + } + $skip_to_reph_move = true; + } + } + + /* 3. If reph should be repositioned after the main consonant: find the + * first consonant not ligated with main, or find the first + * consonant that is not a potential pre-base reordering Ra. + */ + if ($reph_pos == self::REPH_POS_AFTER_MAIN && !$skip_to_reph_move && !$skip_to_reph_step_5) { + $new_reph_pos = $base; + /* XXX Skip potential pre-base reordering Ra. */ + while ($new_reph_pos + 1 < $end && $info[$new_reph_pos + 1]['indic_position'] <= self::POS_AFTER_MAIN) { + $new_reph_pos++; + } + if ($new_reph_pos < $end) { + $skip_to_reph_move = true; + } + } + + /* 4. If reph should be positioned before post-base consonant, find + * first post-base classified consonant not ligated with main. If no + * consonant is found, the target position should be before the + * first matra, syllable modifier sign or vedic sign. + */ + /* This is our take on what step 4 is trying to say (and failing, BADLY). */ + if ($reph_pos == self::REPH_POS_AFTER_SUB && !$skip_to_reph_move && !$skip_to_reph_step_5) { + $new_reph_pos = $base; + while ($new_reph_pos < $end && isset($info[$new_reph_pos + 1]['indic_position']) && + !( self::FLAG($info[$new_reph_pos + 1]['indic_position']) & (self::FLAG(self::POS_POST_C) | self::FLAG(self::POS_AFTER_POST) | self::FLAG(self::POS_SMVD)))) { + $new_reph_pos++; + } + if ($new_reph_pos < $end) { + $skip_to_reph_move = true; + } + } + + /* 5. If no consonant is found in steps 3 or 4, move reph to a position + * immediately before the first post-base matra, syllable modifier + * sign or vedic sign that has a reordering class after the intended + * reph position. For example, if the reordering position for reph + * is post-main, it will skip above-base matras that also have a + * post-main position. + */ + if (!$skip_to_reph_move) { + /* Copied from step 2. */ + $new_reph_pos = $start + 1; + while ($new_reph_pos < $base && !self::is_halant_or_coeng($info[$new_reph_pos])) { + $new_reph_pos++; + } + + if ($new_reph_pos < $base && self::is_halant_or_coeng($info[$new_reph_pos])) { + /* ->If ZWJ or ZWNJ are following this halant, position is moved after it. */ + if ($new_reph_pos + 1 < $base && self::is_joiner($info[$new_reph_pos + 1])) { + $new_reph_pos++; + } + $skip_to_reph_move = true; + } + } + + + /* 6. Otherwise, reorder reph to the end of the syllable. + */ + if (!$skip_to_reph_move) { + $new_reph_pos = $end - 1; + while ($new_reph_pos > $start && $info[$new_reph_pos]['indic_position'] == self::POS_SMVD) { + $new_reph_pos--; + } + + /* + * If the Reph is to be ending up after a Matra,Halant sequence, + * position it before that Halant so it can interact with the Matra. + * However, if it's a plain Consonant,Halant we shouldn't do that. + * Uniscribe doesn't do this. + * TEST: U+0930,U+094D,U+0915,U+094B,U+094D + */ + //if (!$hb_options.uniscribe_bug_compatible && self::is_halant_or_coeng($info[$new_reph_pos])) { + if (self::is_halant_or_coeng($info[$new_reph_pos])) { + for ($i = $base + 1; $i < $new_reph_pos; $i++) { + if ($info[$i]['indic_category'] == self::OT_M) { + /* Ok, got it. */ + $new_reph_pos--; + } + } + } + } + + + /* Move */ + self::_move_info_pos($info, $start, $new_reph_pos + 1); + + if ($start < $base && $base <= $new_reph_pos) { + $base--; + } + } + + + /* o Reorder pre-base reordering consonants: + * + * If a pre-base reordering consonant is found, reorder it according to + * the following rules: + */ + + + if (count($GSUBdata['pref']) && $base + 1 < $end) { /* Otherwise there can't be any pre-base reordering Ra. */ + for ($i = $base + 1; $i < $end; $i++) { + if ($info[$i]['mask'] & self::FLAG(self::PREF)) { + /* 1. Only reorder a glyph produced by substitution during application + * of the <pref> feature. (Note that a font may shape a Ra consonant with + * the feature generally but block it in certain contexts.) + */ + // ??? Need to TEST if actual substitution has occurred + if ($i + 1 == $end || ($info[$i + 1]['mask'] & self::FLAG(self::PREF)) == 0) { + /* + * 2. Try to find a target position the same way as for pre-base matra. + * If it is found, reorder pre-base consonant glyph. + * + * 3. If position is not found, reorder immediately before main + * consonant. + */ + $new_pos = $base; + /* Malayalam / Tamil do not have "half" forms or explicit virama forms. + * The glyphs formed by 'half' are Chillus or ligated explicit viramas. + * We want to position matra after them. + */ + if ($scriptblock != Ucdn::SCRIPT_MALAYALAM && $scriptblock != Ucdn::SCRIPT_TAMIL) { + while ($new_pos > $start && + !(self::is_one_of($info[$new_pos - 1], self::FLAG(self::OT_M) | self::FLAG(self::OT_H) | self::FLAG(self::OT_COENG)))) { + $new_pos--; + } + + /* In Khmer coeng model, a V,Ra can go *after* matras. If it goes after a + * split matra, it should be reordered to *before* the left part of such matra. */ + if ($new_pos > $start && $info[$new_pos - 1]['indic_category'] == self::OT_M) { + $old_pos = $i; + for ($i = $base + 1; $i < $old_pos; $i++) { + if ($info[$i]['indic_category'] == self::OT_M) { + $new_pos--; + break; + } + } + } + } + + if ($new_pos > $start && self::is_halant_or_coeng($info[$new_pos - 1])) { + /* -> If ZWJ or ZWNJ follow this halant, position is moved after it. */ + if ($new_pos < $end && self::is_joiner($info[$new_pos])) { + $new_pos++; + } + } + + $old_pos = $i; + self::_move_info_pos($info, $old_pos, $new_pos); + + if ($new_pos <= $base && $base < $old_pos) { + $base++; + } + } + + break; + } + } + } + + + /* Apply 'init' to the Left Matra if it's a word start. */ + if ($info[$start]['indic_position'] == self::POS_PRE_M && + ($start == 0 || + ($info[$start - 1]['general_category'] < Ucdn::UNICODE_GENERAL_CATEGORY_FORMAT || $info[$start - 1]['general_category'] > Ucdn::UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK) + )) { + $info[$start]['mask'] |= self::FLAG(self::INIT); + } + + + /* + * Finish off and go home! + */ + } + + public static function _move_info_pos(&$info, $from, $to) + { + $t = []; + $t[0] = $info[$from]; + if ($from > $to) { + array_splice($info, $from, 1); + array_splice($info, $to, 0, $t); + } else { + array_splice($info, $to, 0, $t); + array_splice($info, $from, 1); + } + } + + public static $ra_chars = [ + 0x0930 => 1, /* Devanagari */ + 0x09B0 => 1, /* Bengali */ + 0x09F0 => 1, /* Bengali (Assamese) */ + 0x0A30 => 1, /* Gurmukhi */ /* No Reph */ + 0x0AB0 => 1, /* Gujarati */ + 0x0B30 => 1, /* Oriya */ + 0x0BB0 => 1, /* Tamil */ /* No Reph */ + 0x0C30 => 1, /* Telugu */ /* Reph formed only with ZWJ */ + 0x0CB0 => 1, /* Kannada */ + 0x0D30 => 1, /* Malayalam */ /* No Reph, Logical Repha */ + 0x0DBB => 1, /* Sinhala */ /* Reph formed only with ZWJ */ + 0x179A => 1, /* Khmer */ /* No Reph, Visual Repha */ + ]; + + public static function is_ra($u) + { + return isset(self::$ra_chars[$u]); + } + + public static function is_one_of($info, $flags) + { + if (isset($info['is_ligature']) && $info['is_ligature']) { + return false; + } /* If it ligated, all bets are off. */ + return !!(self::FLAG($info['indic_category']) & $flags); + } + + public static function is_joiner($info) + { + return self::is_one_of($info, (self::FLAG(self::OT_ZWJ) | self::FLAG(self::OT_ZWNJ))); + } + + /* Vowels and placeholders treated as if they were consonants. */ + + public static function is_consonant($info) + { + return self::is_one_of($info, (self::FLAG(self::OT_C) | self::FLAG(self::OT_CM) | self::FLAG(self::OT_RA) | self::FLAG(self::OT_V) | self::FLAG(self::OT_NBSP) | self::FLAG(self::OT_DOTTEDCIRCLE))); + } + + public static function is_halant_or_coeng($info) + { + return self::is_one_of($info, (self::FLAG(self::OT_H) | self::FLAG(self::OT_COENG))); + } + + // From hb-private.hh + public static function in_range($u, $lo, $hi) + { + if ((($lo ^ $hi) & $lo) == 0 && (($lo ^ $hi) & $hi) == ($lo ^ $hi) && (($lo ^ $hi) & (($lo ^ $hi) + 1)) == 0) { + return ($u & ~($lo ^ $hi)) == $lo; + } else { + return $lo <= $u && $u <= $hi; + } + } + + // From hb-private.hh + public static function FLAG($x) + { + return (1 << ($x)); + } + + // BELOW from hb-ot-shape-complex-indic.cc + + /* + * Indic configurations. + */ + + // base_position + const BASE_POS_FIRST = 0; + const BASE_POS_LAST = 1; + + // reph_position + const REPH_POS_DEFAULT = 10; // POS_BEFORE_POST, + + const REPH_POS_AFTER_MAIN = 5; // POS_AFTER_MAIN, + + const REPH_POS_BEFORE_SUB = 7; // POS_BEFORE_SUB, + const REPH_POS_AFTER_SUB = 9; // POS_AFTER_SUB, + const REPH_POS_BEFORE_POST = 10; // POS_BEFORE_POST, + const REPH_POS_AFTER_POST = 12; // POS_AFTER_POST + + // reph_mode + const REPH_MODE_IMPLICIT = 0; /* Reph formed out of initial Ra,H sequence. */ + const REPH_MODE_EXPLICIT = 1; /* Reph formed out of initial Ra,H,ZWJ sequence. */ + const REPH_MODE_VIS_REPHA = 2; /* Encoded Repha character, no reordering needed. */ + const REPH_MODE_LOG_REPHA = 3; /* Encoded Repha character, needs reordering. */ + + /* + struct of indic_configs{ + KEY - script; + 0 - has_old_spec; + 1 - virama; + 2 - base_pos; + 3 - reph_pos; + 4 - reph_mode; + }; + */ + + public static $indic_configs = [/* index is SCRIPT_number from UCDN */ + 9 => [true, 0x094D, 1, 10, 0], + 10 => [true, 0x09CD, 1, 9, 0], + 11 => [true, 0x0A4D, 1, 7, 0], + 12 => [true, 0x0ACD, 1, 10, 0], + 13 => [true, 0x0B4D, 1, 5, 0], + 14 => [true, 0x0BCD, 1, 12, 0], + 15 => [true, 0x0C4D, 1, 12, 1], + 16 => [true, 0x0CCD, 1, 12, 0], + 17 => [true, 0x0D4D, 1, 5, 3], + 18 => [false, 0x0DCA, 0, 5, 1], /* Sinhala */ + 30 => [false, 0x17D2, 0, 10, 2], /* Khmer */ + 84 => [false, 0xA9C0, 1, 10, 0], /* Javanese */ + ]; + + + + /* + + // from "hb-ot-shape-complex-indic-table.cc" + + + const ISC_A = 0; // INDIC_SYLLABIC_CATEGORY_AVAGRAHA Avagraha + const ISC_Bi = 8; // INDIC_SYLLABIC_CATEGORY_BINDU Bindu + const ISC_C = 1; // INDIC_SYLLABIC_CATEGORY_CONSONANT Consonant + const ISC_CD = 1; // INDIC_SYLLABIC_CATEGORY_CONSONANT_DEAD Consonant_Dead + const ISC_CF = 17; // INDIC_SYLLABIC_CATEGORY_CONSONANT_FINAL Consonant_Final + const ISC_CHL = 1; // INDIC_SYLLABIC_CATEGORY_CONSONANT_HEAD_LETTER Consonant_Head_Letter + const ISC_CM = 17; // INDIC_SYLLABIC_CATEGORY_CONSONANT_MEDIAL Consonant_Medial + const ISC_CP = 11; // INDIC_SYLLABIC_CATEGORY_CONSONANT_PLACEHOLDER Consonant_Placeholder + const ISC_CR = 15; // INDIC_SYLLABIC_CATEGORY_CONSONANT_REPHA Consonant_Repha + const ISC_CS = 1; // INDIC_SYLLABIC_CATEGORY_CONSONANT_SUBJOINED Consonant_Subjoined + const ISC_ML = 0; // INDIC_SYLLABIC_CATEGORY_MODIFYING_LETTER Modifying_Letter + const ISC_N = 3; // INDIC_SYLLABIC_CATEGORY_NUKTA Nukta + const ISC_x = 0; // INDIC_SYLLABIC_CATEGORY_OTHER Other + const ISC_RS = 13; // INDIC_SYLLABIC_CATEGORY_REGISTER_SHIFTER Register_Shifter + const ISC_TL = 0; // INDIC_SYLLABIC_CATEGORY_TONE_LETTER Tone_Letter + const ISC_TM = 3; // INDIC_SYLLABIC_CATEGORY_TONE_MARK Tone_Mark + const ISC_V = 4; // INDIC_SYLLABIC_CATEGORY_VIRAMA Virama + const ISC_Vs = 8; // INDIC_SYLLABIC_CATEGORY_VISARGA Visarga + const ISC_Vo = 2; // INDIC_SYLLABIC_CATEGORY_VOWEL Vowel + const ISC_M = 7; // INDIC_SYLLABIC_CATEGORY_VOWEL_DEPENDENT Vowel_Dependent + const ISC_VI = 2; // INDIC_SYLLABIC_CATEGORY_VOWEL_INDEPENDENT Vowel_Independent + + const IMC_B = 8; // INDIC_MATRA_CATEGORY_BOTTOM Bottom + const IMC_BR = 11; // INDIC_MATRA_CATEGORY_BOTTOM_AND_RIGHT Bottom_And_Right + const IMC_I = 15; // INDIC_MATRA_CATEGORY_INVISIBLE Invisible + const IMC_L = 3; // INDIC_MATRA_CATEGORY_LEFT Left + const IMC_LR = 11; // INDIC_MATRA_CATEGORY_LEFT_AND_RIGHT Left_And_Right + const IMC_x = 15; // INDIC_MATRA_CATEGORY_NOT_APPLICABLE Not_Applicable + const IMC_O = 5; // INDIC_MATRA_CATEGORY_OVERSTRUCK Overstruck + const IMC_R = 11; // INDIC_MATRA_CATEGORY_RIGHT Right + const IMC_T = 6; // INDIC_MATRA_CATEGORY_TOP Top + const IMC_TB = 8; // INDIC_MATRA_CATEGORY_TOP_AND_BOTTOM Top_And_Bottom + const IMC_TBR = 11; // INDIC_MATRA_CATEGORY_TOP_AND_BOTTOM_AND_RIGHT Top_And_Bottom_And_Right + const IMC_TL = 6; // INDIC_MATRA_CATEGORY_TOP_AND_LEFT Top_And_Left + const IMC_TLR = 11; // INDIC_MATRA_CATEGORY_TOP_AND_LEFT_AND_RIGHT Top_And_Left_And_Right + const IMC_TR = 11; // INDIC_MATRA_CATEGORY_TOP_AND_RIGHT Top_And_Right + const IMC_VOL = 2; // INDIC_MATRA_CATEGORY_VISUAL_ORDER_LEFT Visual_Order_Left + + If in original table = _(C,x), that = ISC_C,IMC_x + Value is IMC_x << 8 (or IMC_x * 256) = 3840 + plus ISC_C = 1, so = 3841 + + */ + + public static $indic_table = [ + /* Devanagari (0900..097F) */ + + /* 0900 */ 3848, 3848, 3848, 3848, 3842, 3842, 3842, 3842, + /* 0908 */ 3842, 3842, 3842, 3842, 3842, 3842, 3842, 3842, + /* 0910 */ 3842, 3842, 3842, 3842, 3842, 3841, 3841, 3841, + /* 0918 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0920 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0928 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0930 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0938 */ 3841, 3841, 1543, 2823, 3843, 3840, 2823, 775, + /* 0940 */ 2823, 2055, 2055, 2055, 2055, 1543, 1543, 1543, + /* 0948 */ 1543, 2823, 2823, 2823, 2823, 2052, 775, 2823, + /* 0950 */ 3840, 3840, 3840, 3840, 3840, 1543, 2055, 2055, + /* 0958 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0960 */ 3842, 3842, 2055, 2055, 3840, 3840, 3840, 3840, + /* 0968 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 0970 */ 3840, 3840, 3842, 3842, 3842, 3842, 3842, 3842, + /* 0978 */ 3840, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* Bengali (0980..09FF) */ + + /* 0980 */ 3840, 3848, 3848, 3848, 3840, 3842, 3842, 3842, + /* 0988 */ 3842, 3842, 3842, 3842, 3842, 3840, 3840, 3842, + /* 0990 */ 3842, 3840, 3840, 3842, 3842, 3841, 3841, 3841, + /* 0998 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 09A0 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 09A8 */ 3841, 3840, 3841, 3841, 3841, 3841, 3841, 3841, + /* 09B0 */ 3841, 3840, 3841, 3840, 3840, 3840, 3841, 3841, + /* 09B8 */ 3841, 3841, 3840, 3840, 3843, 3840, 2823, 775, + /* 09C0 */ 2823, 2055, 2055, 2055, 2055, 3840, 3840, 775, + /* 09C8 */ 775, 3840, 3840, 2823, 2823, 2052, 3841, 3840, + /* 09D0 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 2823, + /* 09D8 */ 3840, 3840, 3840, 3840, 3841, 3841, 3840, 3841, + /* 09E0 */ 3842, 3842, 2055, 2055, 3840, 3840, 3840, 3840, + /* 09E8 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 09F0 */ 3841, 3841, 3840, 3840, 3840, 3840, 3840, 3840, + /* 09F8 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* Gurmukhi (0A00..0A7F) */ + + /* 0A00 */ 3840, 3848, 3848, 3848, 3840, 3842, 3842, 3842, + /* 0A08 */ 3842, 3842, 3842, 3840, 3840, 3840, 3840, 3842, + /* 0A10 */ 3842, 3840, 3840, 3842, 3842, 3841, 3841, 3841, + /* 0A18 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0A20 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0A28 */ 3841, 3840, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0A30 */ 3841, 3840, 3841, 3841, 3840, 3841, 3841, 3840, + /* 0A38 */ 3841, 3841, 3840, 3840, 3843, 3840, 2823, 775, + /* 0A40 */ 2823, 2055, 2055, 3840, 3840, 3840, 3840, 1543, + /* 0A48 */ 1543, 3840, 3840, 1543, 1543, 2052, 3840, 3840, + /* 0A50 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 0A58 */ 3840, 3841, 3841, 3841, 3841, 3840, 3841, 3840, + /* 0A60 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 0A68 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 0A70 */ 3848, 3840, 13841, 13841, 3840, 3857, 3840, 3840, + /* 0A78 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* Gujarati (0A80..0AFF) */ + + /* 0A80 */ 3840, 3848, 3848, 3848, 3840, 3842, 3842, 3842, + /* 0A88 */ 3842, 3842, 3842, 3842, 3842, 3842, 3840, 3842, + /* 0A90 */ 3842, 3842, 3840, 3842, 3842, 3841, 3841, 3841, + /* 0A98 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0AA0 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0AA8 */ 3841, 3840, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0AB0 */ 3841, 3840, 3841, 3841, 3840, 3841, 3841, 3841, + /* 0AB8 */ 3841, 3841, 3840, 3840, 3843, 3840, 2823, 775, + /* 0AC0 */ 2823, 2055, 2055, 2055, 2055, 1543, 3840, 1543, + /* 0AC8 */ 1543, 2823, 3840, 2823, 2823, 2052, 3840, 3840, + /* 0AD0 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 0AD8 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 0AE0 */ 3842, 3842, 2055, 2055, 3840, 3840, 3840, 3840, + /* 0AE8 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 0AF0 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 0AF8 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* Oriya (0B00..0B7F) */ + + /* 0B00 */ 3840, 3848, 3848, 3848, 3840, 3842, 3842, 3842, + /* 0B08 */ 3842, 3842, 3842, 3842, 3842, 3840, 3840, 3842, + /* 0B10 */ 3842, 3840, 3840, 3842, 3842, 3841, 3841, 3841, + /* 0B18 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0B20 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0B28 */ 3841, 3840, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0B30 */ 3841, 3840, 3841, 3841, 3840, 3841, 3841, 3841, + /* 0B38 */ 3841, 3841, 3840, 3840, 3843, 3840, 2823, 1543, + /* 0B40 */ 2823, 2055, 2055, 2055, 2055, 3840, 3840, 775, + /* 0B48 */ 1543, 3840, 3840, 2823, 2823, 2052, 3840, 3840, + /* 0B50 */ 3840, 3840, 3840, 3840, 3840, 3840, 1543, 2823, + /* 0B58 */ 3840, 3840, 3840, 3840, 3841, 3841, 3840, 3841, + /* 0B60 */ 3842, 3842, 2055, 2055, 3840, 3840, 3840, 3840, + /* 0B68 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 0B70 */ 3840, 3841, 3840, 3840, 3840, 3840, 3840, 3840, + /* 0B78 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* Tamil (0B80..0BFF) */ + + /* 0B80 */ 3840, 3840, 3848, 3840, 3840, 3842, 3842, 3842, + /* 0B88 */ 3842, 3842, 3842, 3840, 3840, 3840, 3842, 3842, + /* 0B90 */ 3842, 3840, 3842, 3842, 3842, 3841, 3840, 3840, + /* 0B98 */ 3840, 3841, 3841, 3840, 3841, 3840, 3841, 3841, + /* 0BA0 */ 3840, 3840, 3840, 3841, 3841, 3840, 3840, 3840, + /* 0BA8 */ 3841, 3841, 3841, 3840, 3840, 3840, 3841, 3841, + /* 0BB0 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0BB8 */ 3841, 3841, 3840, 3840, 3840, 3840, 2823, 2823, + /* 0BC0 */ 1543, 2055, 2055, 3840, 3840, 3840, 775, 775, + /* 0BC8 */ 775, 3840, 2823, 2823, 2823, 1540, 3840, 3840, + /* 0BD0 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 2823, + /* 0BD8 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 0BE0 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 0BE8 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 0BF0 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 0BF8 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* Telugu (0C00..0C7F) */ + + /* 0C00 */ 3840, 3848, 3848, 3848, 3840, 3842, 3842, 3842, + /* 0C08 */ 3842, 3842, 3842, 3842, 3842, 3840, 3842, 3842, + /* 0C10 */ 3842, 3840, 3842, 3842, 3842, 3841, 3841, 3841, + /* 0C18 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0C20 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0C28 */ 3841, 3840, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0C30 */ 3841, 3841, 3841, 3841, 3840, 3841, 3841, 3841, + /* 0C38 */ 3841, 3841, 3840, 3840, 3840, 3840, 1543, 1543, + /* 0C40 */ 1543, 2823, 2823, 2823, 2823, 3840, 1543, 1543, + /* 0C48 */ 2055, 3840, 1543, 1543, 1543, 1540, 3840, 3840, + /* 0C50 */ 3840, 3840, 3840, 3840, 3840, 1543, 2055, 3840, + /* 0C58 */ 3841, 3841, 3840, 3840, 3840, 3840, 3840, 3840, + /* 0C60 */ 3842, 3842, 2055, 2055, 3840, 3840, 3840, 3840, + /* 0C68 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 0C70 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 0C78 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* Kannada (0C80..0CFF) */ + + /* 0C80 */ 3840, 3840, 3848, 3848, 3840, 3842, 3842, 3842, + /* 0C88 */ 3842, 3842, 3842, 3842, 3842, 3840, 3842, 3842, + /* 0C90 */ 3842, 3840, 3842, 3842, 3842, 3841, 3841, 3841, + /* 0C98 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0CA0 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0CA8 */ 3841, 3840, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0CB0 */ 3841, 3841, 3841, 3841, 3840, 3841, 3841, 3841, + /* 0CB8 */ 3841, 3841, 3840, 3840, 3843, 3840, 2823, 1543, + /* 0CC0 */ 2823, 2823, 2823, 2823, 2823, 3840, 1543, 2823, + /* 0CC8 */ 2823, 3840, 2823, 2823, 1543, 1540, 3840, 3840, + /* 0CD0 */ 3840, 3840, 3840, 3840, 3840, 2823, 2823, 3840, + /* 0CD8 */ 3840, 3840, 3840, 3840, 3840, 3840, 3841, 3840, + /* 0CE0 */ 3842, 3842, 2055, 2055, 3840, 3840, 3840, 3840, + /* 0CE8 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 0CF0 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 0CF8 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* Malayalam (0D00..0D7F) */ + + /* 0D00 */ 3840, 3840, 3848, 3848, 3840, 3842, 3842, 3842, + /* 0D08 */ 3842, 3842, 3842, 3842, 3842, 3840, 3842, 3842, + /* 0D10 */ 3842, 3840, 3842, 3842, 3842, 3841, 3841, 3841, + /* 0D18 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0D20 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0D28 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0D30 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0D38 */ 3841, 3841, 3841, 3840, 3840, 3840, 2823, 2823, + /* 0D40 */ 2823, 2823, 2823, 2055, 2055, 3840, 775, 775, + /* 0D48 */ 775, 3840, 2823, 2823, 2823, 1540, 3855, 3840, + /* 0D50 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 2823, + /* 0D58 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 0D60 */ 3842, 3842, 2055, 2055, 3840, 3840, 3840, 3840, + /* 0D68 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 0D70 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 0D78 */ 3840, 3840, 3841, 3841, 3841, 3841, 3841, 3841, + /* Sinhala (0D80..0DFF) */ + + /* 0D80 */ 3840, 3840, 3848, 3848, 3840, 3842, 3842, 3842, + /* 0D88 */ 3842, 3842, 3842, 3842, 3842, 3842, 3842, 3842, + /* 0D90 */ 3842, 3842, 3842, 3842, 3842, 3842, 3842, 3840, + /* 0D98 */ 3840, 3840, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0DA0 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0DA8 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 0DB0 */ 3841, 3841, 3840, 3841, 3841, 3841, 3841, 3841, + /* 0DB8 */ 3841, 3841, 3841, 3841, 3840, 3841, 3840, 3840, + /* 0DC0 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3840, + /* 0DC8 */ 3840, 3840, 1540, 3840, 3840, 3840, 3840, 2823, + /* 0DD0 */ 2823, 2823, 1543, 1543, 2055, 3840, 2055, 3840, + /* 0DD8 */ 2823, 775, 1543, 775, 2823, 2823, 2823, 2823, + /* 0DE0 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 0DE8 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 0DF0 */ 3840, 3840, 2823, 2823, 3840, 3840, 3840, 3840, + /* 0DF8 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* Vedic Extensions (1CD0..1CFF) */ + + /* 1CD0 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 1CD8 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 1CE0 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 1CE8 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 1CF0 */ 3840, 3840, 3848, 3848, 3840, 3840, 3840, 3840, + /* 1CF8 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + ]; + + public static $khmer_table = [ + /* Khmer (1780..17FF) */ + + /* 1780 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 1788 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 1790 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 1798 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 17A0 */ 3841, 3841, 3841, 3842, 3842, 3842, 3842, 3842, + /* 17A8 */ 3842, 3842, 3842, 3842, 3842, 3842, 3842, 3842, + /* 17B0 */ 3842, 3842, 3842, 3842, 3840, 3840, 2823, 1543, + /* 17B8 */ 1543, 1543, 1543, 2055, 2055, 2055, 1543, 2823, + /* 17C0 */ 2823, 775, 775, 775, 2823, 2823, 3848, 3848, + /* 17C8 */ 2823, 3853, 3853, 3840, 3855, 3840, 3840, 3840, + /* 17D0 */ 3840, 1540, 3844, 3840, 3840, 3840, 3840, 3840, + /* 17D8 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 17E0 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 17E8 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 17F0 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 17F8 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + ]; + + // from "hb-ot-shape-complex-indic-table.cc" + public static function indic_get_categories($u) + { + if (0x0900 <= $u && $u <= 0x0DFF) { + return self::$indic_table[$u - 0x0900 + 0]; // offset 0 for Most "indic" + } + if (0x1CD0 <= $u && $u <= 0x1D00) { + return self::$indic_table[$u - 0x1CD0 + 1152]; // offset for Vedic extensions + } + if (0x1780 <= $u && $u <= 0x17FF) { + return self::$khmer_table[$u - 0x1780]; // Khmer + } + if ($u == 0x00A0) { + return 3851; // (ISC_CP | (IMC_x << 8)) + } + if ($u == 0x25CC) { + return 3851; // (ISC_CP | (IMC_x << 8)) + } + return 3840; // (ISC_x | (IMC_x << 8)) + } + + // BELOW from hb-ot-shape-complex-indic.cc + /* + * Indic shaper. + */ + + public static function IN_HALF_BLOCK($u, $Base) + { + return (($u & ~0x7F) == $Base); + } + + public static function IS_DEVA($u) + { + return self::IN_HALF_BLOCK($u, 0x0900); + } + + public static function IS_BENG($u) + { + return self::IN_HALF_BLOCK($u, 0x0980); + } + + public static function IS_GURU($u) + { + return self::IN_HALF_BLOCK($u, 0x0A00); + } + + public static function IS_GUJR($u) + { + return self::IN_HALF_BLOCK($u, 0x0A80); + } + + public static function IS_ORYA($u) + { + return self::IN_HALF_BLOCK($u, 0x0B00); + } + + public static function IS_TAML($u) + { + return self::IN_HALF_BLOCK($u, 0x0B80); + } + + public static function IS_TELU($u) + { + return self::IN_HALF_BLOCK($u, 0x0C00); + } + + public static function IS_KNDA($u) + { + return self::IN_HALF_BLOCK($u, 0x0C80); + } + + public static function IS_MLYM($u) + { + return self::IN_HALF_BLOCK($u, 0x0D00); + } + + public static function IS_SINH($u) + { + return self::IN_HALF_BLOCK($u, 0x0D80); + } + + public static function IS_KHMR($u) + { + return self::IN_HALF_BLOCK($u, 0x1780); + } + + public static function MATRA_POS_LEFT($u) + { + return self::POS_PRE_M; + } + + public static function MATRA_POS_RIGHT($u) + { + return + (self::IS_DEVA($u) ? self::POS_AFTER_SUB : + (self::IS_BENG($u) ? self::POS_AFTER_POST : + (self::IS_GURU($u) ? self::POS_AFTER_POST : + (self::IS_GUJR($u) ? self::POS_AFTER_POST : + (self::IS_ORYA($u) ? self::POS_AFTER_POST : + (self::IS_TAML($u) ? self::POS_AFTER_POST : + (self::IS_TELU($u) ? ($u <= 0x0C42 ? self::POS_BEFORE_SUB : self::POS_AFTER_SUB) : + (self::IS_KNDA($u) ? ($u < 0x0CC3 || $u > 0xCD6 ? self::POS_BEFORE_SUB : self::POS_AFTER_SUB) : + (self::IS_MLYM($u) ? self::POS_AFTER_POST : + (self::IS_SINH($u) ? self::POS_AFTER_SUB : + (self::IS_KHMR($u) ? self::POS_AFTER_POST : + self::POS_AFTER_SUB))))))))))); /* default */ + } + + public static function MATRA_POS_TOP($u) + { + return /* BENG and MLYM don't have top matras. */ + (self::IS_DEVA($u) ? self::POS_AFTER_SUB : + (self::IS_GURU($u) ? self::POS_AFTER_POST : /* Deviate from spec */ + (self::IS_GUJR($u) ? self::POS_AFTER_SUB : + (self::IS_ORYA($u) ? self::POS_AFTER_MAIN : + (self::IS_TAML($u) ? self::POS_AFTER_SUB : + (self::IS_TELU($u) ? self::POS_BEFORE_SUB : + (self::IS_KNDA($u) ? self::POS_BEFORE_SUB : + (self::IS_SINH($u) ? self::POS_AFTER_SUB : + (self::IS_KHMR($u) ? self::POS_AFTER_POST : + self::POS_AFTER_SUB))))))))); /* default */ + } + + public static function MATRA_POS_BOTTOM($u) + { + return + (self::IS_DEVA($u) ? self::POS_AFTER_SUB : + (self::IS_BENG($u) ? self::POS_AFTER_SUB : + (self::IS_GURU($u) ? self::POS_AFTER_POST : + (self::IS_GUJR($u) ? self::POS_AFTER_POST : + (self::IS_ORYA($u) ? self::POS_AFTER_SUB : + (self::IS_TAML($u) ? self::POS_AFTER_POST : + (self::IS_TELU($u) ? self::POS_BEFORE_SUB : + (self::IS_KNDA($u) ? self::POS_BEFORE_SUB : + (self::IS_MLYM($u) ? self::POS_AFTER_POST : + (self::IS_SINH($u) ? self::POS_AFTER_SUB : + (self::IS_KHMR($u) ? self::POS_AFTER_POST : + self::POS_AFTER_SUB))))))))))); /* default */ + } + + public static function matra_position($u, $side) + { + switch ($side) { + case self::POS_PRE_C: + return self::MATRA_POS_LEFT($u); + case self::POS_POST_C: + return self::MATRA_POS_RIGHT($u); + case self::POS_ABOVE_C: + return self::MATRA_POS_TOP($u); + case self::POS_BELOW_C: + return self::MATRA_POS_BOTTOM($u); + } + return $side; + } + + // vowel matras that have to be split into two parts. + // From Harfbuzz (old) + // New HarfBuzz uses /src/hb-ucdn/ucdn.c and unicodedata_db.h for full method of decomposition for all characters + // Should always fully decompose and then recompose back, but we will just do the split matras + public static function decompose_indic($ab) + { + $sub = []; + switch ($ab) { + /* + * Decompose split matras. + */ + /* bengali */ + case 0x9cb: + $sub[0] = 0x9c7; + $sub[1] = 0x9be; + return $sub; + case 0x9cc: + $sub[0] = 0x9c7; + $sub[1] = 0x9d7; + return $sub; + /* oriya */ + case 0xb48: + $sub[0] = 0xb47; + $sub[1] = 0xb56; + return $sub; + case 0xb4b: + $sub[0] = 0xb47; + $sub[1] = 0xb3e; + return $sub; + case 0xb4c: + $sub[0] = 0xb47; + $sub[1] = 0xb57; + return $sub; + /* tamil */ + case 0xbca: + $sub[0] = 0xbc6; + $sub[1] = 0xbbe; + return $sub; + case 0xbcb: + $sub[0] = 0xbc7; + $sub[1] = 0xbbe; + return $sub; + case 0xbcc: + $sub[0] = 0xbc6; + $sub[1] = 0xbd7; + return $sub; + /* telugu */ + case 0xc48: + $sub[0] = 0xc46; + $sub[1] = 0xc56; + return $sub; + /* kannada */ + case 0xcc0: + $sub[0] = 0xcbf; + $sub[1] = 0xcd5; + return $sub; + case 0xcc7: + $sub[0] = 0xcc6; + $sub[1] = 0xcd5; + return $sub; + case 0xcc8: + $sub[0] = 0xcc6; + $sub[1] = 0xcd6; + return $sub; + case 0xcca: + $sub[0] = 0xcc6; + $sub[1] = 0xcc2; + return $sub; + case 0xccb: + $sub[0] = 0xcc6; + $sub[1] = 0xcc2; + $sub[2] = 0xcd5; + return $sub; + /* malayalam */ + case 0xd4a: + $sub[0] = 0xd46; + $sub[1] = 0xd3e; + return $sub; + case 0xd4b: + $sub[0] = 0xd47; + $sub[1] = 0xd3e; + return $sub; + case 0xd4c: + $sub[0] = 0xd46; + $sub[1] = 0xd57; + return $sub; + /* sinhala */ + // NB Some fonts break with these Sinhala decomps (although this is Uniscribe spec) + // Can check if character would be substituted by pstf and only decompose if true + // e.g. if (isset($GSUBdata['pstf'][$ab])) - would need to pass $GSUBdata as parameter to this function + case 0xdda: + $sub[0] = 0xdd9; + $sub[1] = 0xdca; + return $sub; + case 0xddc: + $sub[0] = 0xdd9; + $sub[1] = 0xdcf; + return $sub; + case 0xddd: + $sub[0] = 0xdd9; + $sub[1] = 0xdcf; + $sub[2] = 0xdca; + return $sub; + case 0xdde: + $sub[0] = 0xdd9; + $sub[1] = 0xddf; + return $sub; + /* khmer */ + case 0x17be: + $sub[0] = 0x17c1; + $sub[1] = 0x17be; + return $sub; + case 0x17bf: + $sub[0] = 0x17c1; + $sub[1] = 0x17bf; + return $sub; + case 0x17c0: + $sub[0] = 0x17c1; + $sub[1] = 0x17c0; + return $sub; + + case 0x17c4: + $sub[0] = 0x17c1; + $sub[1] = 0x17c4; + return $sub; + case 0x17c5: + $sub[0] = 0x17c1; + $sub[1] = 0x17c5; + return $sub; + /* tibetan - included here although does not use Inidc shaper in other ways */ + case 0xf73: + $sub[0] = 0xf71; + $sub[1] = 0xf72; + return $sub; + case 0xf75: + $sub[0] = 0xf71; + $sub[1] = 0xf74; + return $sub; + case 0xf76: + $sub[0] = 0xfb2; + $sub[1] = 0xf80; + return $sub; + case 0xf77: + $sub[0] = 0xfb2; + $sub[1] = 0xf81; + return $sub; + case 0xf78: + $sub[0] = 0xfb3; + $sub[1] = 0xf80; + return $sub; + case 0xf79: + $sub[0] = 0xfb3; + $sub[1] = 0xf71; + $sub[2] = 0xf80; + return $sub; + case 0xf81: + $sub[0] = 0xf71; + $sub[1] = 0xf80; + return $sub; + } + return false; + } + + public static function bubble_sort(&$arr, $start, $len) + { + if ($len < 2) { + return; + } + $k = $start + $len - 2; + while ($k >= $start) { + for ($j = $start; $j <= $k; $j++) { + if ($arr[$j]['indic_position'] > $arr[$j + 1]['indic_position']) { + $t = $arr[$j]; + $arr[$j] = $arr[$j + 1]; + $arr[$j + 1] = $t; + } + } + $k--; + } + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Shaper/Myanmar.php b/src/bb-vendor/mpdf/mpdf/src/Shaper/Myanmar.php new file mode 100644 index 000000000..9a68edacf --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Shaper/Myanmar.php @@ -0,0 +1,543 @@ +<?php + +namespace Mpdf\Shaper; + +class Myanmar +{ + /* FROM hb-ot-shape-complex-indic-private.hh */ + + // indic_category + const OT_X = 0; + const OT_C = 1; + const OT_V = 2; + const OT_N = 3; + const OT_H = 4; + const OT_ZWNJ = 5; + const OT_ZWJ = 6; + const OT_M = 7; /* Matra or Dependent Vowel */ + const OT_SM = 8; + const OT_VD = 9; + const OT_A = 10; + const OT_NBSP = 11; + const OT_DOTTEDCIRCLE = 12; /* Not in the spec, but special in Uniscribe. /Very very/ special! */ + const OT_RS = 13; /* Register Shifter, used in Khmer OT spec */ + const OT_COENG = 14; + const OT_REPHA = 15; + const OT_RA = 16; /* Not explicitly listed in the OT spec, but used in the grammar. */ + const OT_CM = 17; + + /* FROM hb-ot-shape-complex-myanmar.hh */ + + // myanmar_category + const OT_DB = 3; // same as Indic::OT_N; /* Dot below */ + const OT_GB = 12; // same as Indic::OT_DOTTEDCIRCLE; + const OT_AS = 18; /* Asat */ + const OT_D = 19; /* Digits except zero */ + const OT_D0 = 20; /* Digit zero */ + const OT_MH = 21; /* Various consonant medial types */ + const OT_MR = 22; /* Various consonant medial types */ + const OT_MW = 23; /* Various consonant medial types */ + const OT_MY = 24; /* Various consonant medial types */ + const OT_PT = 25; /* Pwo and other tones */ + + const OT_VABV = 26; + const OT_VBLW = 27; + const OT_VPRE = 28; + const OT_VPST = 29; + const OT_VS = 30; /* Variation selectors */ + + /* Visual positions in a syllable from left to right. */ + /* FROM hb-ot-shape-complex-myanmar-private.hh */ + + // myanmar_position + const POS_START = 0; + + const POS_RA_TO_BECOME_REPH = 1; + const POS_PRE_M = 2; + const POS_PRE_C = 3; + + const POS_BASE_C = 4; + const POS_AFTER_MAIN = 5; + + const POS_ABOVE_C = 6; + + const POS_BEFORE_SUB = 7; + const POS_BELOW_C = 8; + const POS_AFTER_SUB = 9; + + const POS_BEFORE_POST = 10; + const POS_POST_C = 11; + const POS_AFTER_POST = 12; + + const POS_FINAL_C = 13; + const POS_SMVD = 14; + + const POS_END = 15; + + // Based on myanmar_category used to make string to find syllables + // OT_ to string character (using e.g. OT_C from MYANMAR) hb-ot-shape-complex-myanmar-private.hh + public static $myanmar_category_char = [ + 'x', + 'C', + 'V', + 'N', + 'H', + 'Z', + 'J', + 'x', + 'S', + 'x', + 'A', + 'x', + 'D', + 'x', + 'x', + 'x', + 'R', + 'x', + 'a', /* As Asat */ + 'd', /* Digits except zero */ + 'o', /* Digit zero */ + 'k', /* Medial types */ + 'l', /* Medial types */ + 'm', /* Medial types */ + 'n', /* Medial types */ + 'p', /* Pwo and other tones */ + 'v', /* Vowel aboVe */ + 'b', /* Vowel Below */ + 'e', /* Vowel prE */ + 't', /* Vowel posT */ + 's', /* variation Selector */ + ]; + + public static function set_myanmar_properties(&$info) + { + $u = $info['uni']; + $type = self::myanmar_get_categories($u); + $cat = ($type & 0x7F); + $pos = ($type >> 8); + /* + * Re-assign category + * http://www.microsoft.com/typography/OpenTypeDev/myanmar/intro.htm#analyze + */ + if (self::in_range($u, 0xFE00, 0xFE0F)) { + $cat = self::OT_VS; + } elseif ($u == 0x200C) { + $cat = self::OT_ZWNJ; + } elseif ($u == 0x200D) { + $cat = self::OT_ZWJ; + } + + switch ($u) { + case 0x002D: + case 0x00A0: + case 0x00D7: + case 0x2012: + case 0x2013: + case 0x2014: + case 0x2015: + case 0x2022: + case 0x25CC: + case 0x25FB: + case 0x25FC: + case 0x25FD: + case 0x25FE: + $cat = self::OT_GB; + break; + + case 0x1004: + case 0x101B: + case 0x105A: + $cat = self::OT_RA; + break; + + case 0x1032: + case 0x1036: + $cat = self::OT_A; + break; + + case 0x103A: + $cat = self::OT_AS; + break; + + case 0x1041: + case 0x1042: + case 0x1043: + case 0x1044: + case 0x1045: + case 0x1046: + case 0x1047: + case 0x1048: + case 0x1049: + case 0x1090: + case 0x1091: + case 0x1092: + case 0x1093: + case 0x1094: + case 0x1095: + case 0x1096: + case 0x1097: + case 0x1098: + case 0x1099: + $cat = self::OT_D; + break; + + case 0x1040: + $cat = self::OT_D; /* XXX The spec says D0, but Uniscribe doesn't seem to do. */ + break; + + case 0x103E: + case 0x1060: + $cat = self::OT_MH; + break; + + case 0x103C: + $cat = self::OT_MR; + break; + + case 0x103D: + case 0x1082: + $cat = self::OT_MW; + break; + + case 0x103B: + case 0x105E: + case 0x105F: + $cat = self::OT_MY; + break; + + case 0x1063: + case 0x1064: + case 0x1069: + case 0x106A: + case 0x106B: + case 0x106C: + case 0x106D: + case 0xAA7B: + $cat = self::OT_PT; + break; + + case 0x1038: + case 0x1087: + case 0x1088: + case 0x1089: + case 0x108A: + case 0x108B: + case 0x108C: + case 0x108D: + case 0x108F: + case 0x109A: + case 0x109B: + case 0x109C: + $cat = self::OT_SM; + break; + } + + if ($cat == self::OT_M) { + switch ($pos) { + case self::POS_PRE_C: + $cat = self::OT_VPRE; + $pos = self::POS_PRE_M; + break; + case self::POS_ABOVE_C: + $cat = self::OT_VABV; + break; + case self::POS_BELOW_C: + $cat = self::OT_VBLW; + break; + case self::POS_POST_C: + $cat = self::OT_VPST; + break; + } + } + $info['myanmar_category'] = $cat; + $info['myanmar_position'] = $pos; + } + + // syllable_type + const CONSONANT_SYLLABLE = 0; + const BROKEN_CLUSTER = 3; + const NON_MYANMAR_CLUSTER = 4; + + public static function set_syllables(&$o, $s, &$broken_syllables) + { + $ptr = 0; + $syllable_serial = 1; + $broken_syllables = false; + + while ($ptr < strlen($s)) { + $match = ''; + $syllable_length = 1; + $syllable_type = self::NON_MYANMAR_CLUSTER; + // CONSONANT_SYLLABLE Consonant syllable + // From OT spec: + if (preg_match('/^(RaH)?([C|R]|V|d|D)[s]?(H([C|R|V])[s]?)*(H|[a]*[n]?[l]?((m[k]?|k)[a]?)?[e]*[v]*[b]*[A]*(N[a]?)?(t[k]?[a]*[v]*[A]*(N[a]?)?)*(p[A]*(N[a]?)?)*S*[J|Z]?)/', substr($s, $ptr), $ma)) { + $syllable_length = strlen($ma[0]); + $syllable_type = self::CONSONANT_SYLLABLE; + } // BROKEN_CLUSTER syllable + elseif (preg_match('/^(RaH)?s?(H|[a]*[n]?[l]?((m[k]?|k)[a]?)?[e]*[v]*[b]*[A]*(N[a]?)?(t[k]?[a]*[v]*[A]*(N[a]?)?)*(p[A]*(N[a]?)?)*S*[J|Z]?)/', substr($s, $ptr), $ma)) { + if (strlen($ma[0])) { // May match blank + $syllable_length = strlen($ma[0]); + $syllable_type = self::BROKEN_CLUSTER; + $broken_syllables = true; + } + } + for ($i = $ptr; $i < $ptr + $syllable_length; $i++) { + $o[$i]['syllable'] = ($syllable_serial << 4) | $syllable_type; + } + $ptr += $syllable_length; + $syllable_serial++; + if ($syllable_serial == 16) { + $syllable_serial = 1; + } + } + } + + public static function reordering(&$info, $GSUBdata, $broken_syllables, $dottedcircle) + { + if ($broken_syllables && $dottedcircle) { + self::insert_dotted_circles($info, $dottedcircle); + } + $count = count($info); + if (!$count) { + return; + } + $last = 0; + $last_syllable = $info[0]['syllable']; + for ($i = 1; $i < $count; $i++) { + if ($last_syllable != $info[$i]['syllable']) { + self::reordering_syllable($info, $GSUBdata, $last, $i); + $last = $i; + $last_syllable = $info[$last]['syllable']; + } + } + self::reordering_syllable($info, $GSUBdata, $last, $count); + } + + public static function insert_dotted_circles(&$info, $dottedcircle) + { + $idx = 0; + $last_syllable = 0; + while ($idx < count($info)) { + $syllable = $info[$idx]['syllable']; + $syllable_type = ($syllable & 0x0F); + if ($last_syllable != $syllable && $syllable_type == self::BROKEN_CLUSTER) { + $last_syllable = $syllable; + $dottedcircle[0]['syllable'] = $info[$idx]['syllable']; + array_splice($info, $idx, 0, $dottedcircle); + } else { + $idx++; + } + } + // In case of final bloken cluster... + $syllable = $info[$idx]['syllable']; + $syllable_type = ($syllable & 0x0F); + if ($last_syllable != $syllable && $syllable_type == self::BROKEN_CLUSTER) { + $dottedcircle[0]['syllable'] = $info[$idx]['syllable']; + array_splice($info, $idx, 0, $dottedcircle); + } + } + + /* Rules from: + * https://www.microsoft.com/typography/otfntdev/devanot/shaping.aspx */ + + public static function reordering_syllable(&$info, $GSUBdata, $start, $end) + { + /* vowel_syllable: We made the vowels look like consonants. So uses the consonant logic! */ + /* broken_cluster: We already inserted dotted-circles, so just call the standalone_cluster. */ + + $syllable_type = ($info[$start]['syllable'] & 0x0F); + if ($syllable_type == self::NON_MYANMAR_CLUSTER) { + return; + } + if ($syllable_type == self::BROKEN_CLUSTER) { + //if ($uniscribe_bug_compatible) { + /* For dotted-circle, this is what Uniscribe does: + * If dotted-circle is the last glyph, it just does nothing. + * i.e. It doesn't form Reph. */ + if ($info[$end - 1]['myanmar_category'] == self::OT_DOTTEDCIRCLE) { + return; + } + } + + $base = $end; + $has_reph = false; + $limit = $start; + + if (($start + 3 <= $end) && + $info[$start]['myanmar_category'] == self::OT_RA && + $info[$start + 1]['myanmar_category'] == self::OT_AS && + $info[$start + 2]['myanmar_category'] == self::OT_H) { + $limit += 3; + $base = $start; + $has_reph = true; + } + + if (!$has_reph) { + $base = $limit; + } + + for ($i = $limit; $i < $end; $i++) { + if (self::is_consonant($info[$i])) { + $base = $i; + break; + } + } + + + /* Reorder! */ + $i = $start; + for (; $i < $start + ($has_reph ? 3 : 0); $i++) { + $info[$i]['myanmar_position'] = self::POS_AFTER_MAIN; + } + for (; $i < $base; $i++) { + $info[$i]['myanmar_position'] = self::POS_PRE_C; + } + if ($i < $end) { + $info[$i]['myanmar_position'] = self::POS_BASE_C; + $i++; + } + $pos = self::POS_AFTER_MAIN; + /* The following loop may be ugly, but it implements all of + * Myanmar reordering! */ + for (; $i < $end; $i++) { + if ($info[$i]['myanmar_category'] == self::OT_MR) { /* Pre-base reordering */ + $info[$i]['myanmar_position'] = self::POS_PRE_C; + continue; + } + if ($info[$i]['myanmar_position'] < self::POS_BASE_C) { /* Left matra */ + continue; + } + + if ($pos == self::POS_AFTER_MAIN && $info[$i]['myanmar_category'] == self::OT_VBLW) { + $pos = self::POS_BELOW_C; + $info[$i]['myanmar_position'] = $pos; + continue; + } + + if ($pos == self::POS_BELOW_C && $info[$i]['myanmar_category'] == self::OT_A) { + $info[$i]['myanmar_position'] = self::POS_BEFORE_SUB; + continue; + } + if ($pos == self::POS_BELOW_C && $info[$i]['myanmar_category'] == self::OT_VBLW) { + $info[$i]['myanmar_position'] = $pos; + continue; + } + if ($pos == self::POS_BELOW_C && $info[$i]['myanmar_category'] != self::OT_A) { + $pos = self::POS_AFTER_SUB; + $info[$i]['myanmar_position'] = $pos; + continue; + } + $info[$i]['myanmar_position'] = $pos; + } + + + /* Sit tight, rock 'n roll! */ + self::bubble_sort($info, $start, $end - $start); + } + + public static function is_one_of($info, $flags) + { + if (isset($info['is_ligature']) && $info['is_ligature']) { + return false; + } /* If it ligated, all bets are off. */ + return !!(self::FLAG($info['myanmar_category']) & $flags); + } + + /* Vowels and placeholders treated as if they were consonants. */ + + public static function is_consonant($info) + { + return self::is_one_of($info, (self::FLAG(self::OT_C) | self::FLAG(self::OT_CM) | self::FLAG(self::OT_RA) | self::FLAG(self::OT_V) | self::FLAG(self::OT_NBSP) | self::FLAG(self::OT_GB))); + } + +// From hb-private.hh + public static function in_range($u, $lo, $hi) + { + if ((($lo ^ $hi) & $lo) == 0 && (($lo ^ $hi) & $hi) == ($lo ^ $hi) && (($lo ^ $hi) & (($lo ^ $hi) + 1)) == 0) { + return ($u & ~($lo ^ $hi)) == $lo; + } else { + return $lo <= $u && $u <= $hi; + } + } + + // From hb-private.hh + public static function FLAG($x) + { + return (1 << ($x)); + } + + public static function FLAG_RANGE($x, $y) + { + return self::FLAG($y + 1) - self::FLAG($x); + } + + // BELOW from hb-ot-shape-complex-indic.cc + // see INDIC for details + public static $myanmar_table = [ + /* Myanmar (1000..109F) */ + + /* 1000 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 1008 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 1010 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 1018 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 1020 */ 3841, 3842, 3842, 3842, 3842, 3842, 3842, 3842, + /* 1028 */ 3842, 3842, 3842, 2823, 2823, 1543, 1543, 2055, + /* 1030 */ 2055, 775, 1543, 1543, 1543, 1543, 3848, 3843, + /* 1038 */ 3848, 3844, 1540, 3857, 3857, 3857, 3857, 3841, + /* 1040 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 1048 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 1050 */ 3841, 3841, 3842, 3842, 3842, 3842, 2823, 2823, + /* 1058 */ 2055, 2055, 3841, 3841, 3841, 3841, 3857, 3857, + /* 1060 */ 3857, 3841, 2823, 3843, 3843, 3841, 3841, 2823, + /* 1068 */ 2823, 3843, 3843, 3843, 3843, 3843, 3841, 3841, + /* 1070 */ 3841, 1543, 1543, 1543, 1543, 3841, 3841, 3841, + /* 1078 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 1080 */ 3841, 3841, 3857, 2823, 775, 1543, 1543, 3843, + /* 1088 */ 3843, 3843, 3843, 3843, 3843, 3843, 3841, 3843, + /* 1090 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 1098 */ 3840, 3840, 3843, 3843, 2823, 1543, 3840, 3840, + /* Myanmar Extended-A (AA60..AA7F) */ + + /* AA60 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* AA68 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* AA70 */ 3840, 3841, 3841, 3841, 3840, 3840, 3840, 3840, + /* AA78 */ 3840, 3840, 3841, 3843, 3840, 3840, 3840, 3840, + ]; + + // from "hb-ot-shape-complex-indic-table.cc" + public static function myanmar_get_categories($u) + { + if (0x1000 <= $u && $u <= 0x109F) { + return self::$myanmar_table[$u - 0x1000 + 0]; // offset 0 for Most "myanmar" + } + if (0xAA60 <= $u && $u <= 0xAA7F) { + return self::$myanmar_table[$u - 0xAA60 + 160]; // offset for extensions + } + if ($u == 0x00A0) { + return 3851; // (ISC_CP | (IMC_x << 8)) + } + if ($u == 0x25CC) { + return 3851; // (ISC_CP | (IMC_x << 8)) + } + return 3840; // (ISC_x | (IMC_x << 8)) + } + + public static function bubble_sort(&$arr, $start, $len) + { + if ($len < 2) { + return; + } + $k = $start + $len - 2; + while ($k >= $start) { + for ($j = $start; $j <= $k; $j++) { + if ($arr[$j]['myanmar_position'] > $arr[$j + 1]['myanmar_position']) { + $t = $arr[$j]; + $arr[$j] = $arr[$j + 1]; + $arr[$j + 1] = $t; + } + } + $k--; + } + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Shaper/Sea.php b/src/bb-vendor/mpdf/mpdf/src/Shaper/Sea.php new file mode 100644 index 000000000..40adaccfa --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Shaper/Sea.php @@ -0,0 +1,397 @@ +<?php + +namespace Mpdf\Shaper; + +class Sea +{ + // South East Asian shaper + // sea_category + const OT_X = 0; + + const OT_C = 1; + + const OT_IV = 2; # Independent Vowel + + const OT_T = 3; # Tone Marks + + const OT_H = 4; # Halant + + const OT_A = 10; # Anusvara + + const OT_GB = 12; # Generic Base (OT_DOTTEDCIRCLE in Indic) + + const OT_CM = 17; # Consonant Medial + + const OT_MR = 22; # Medial Ra + + const OT_VABV = 26; + + const OT_VBLW = 27; + + const OT_VPRE = 28; + + const OT_VPST = 29; + + // ? From Indic categories + const OT_ZWNJ = 5; + + const OT_ZWJ = 6; + + const OT_M = 7; + + const OT_SM = 8; + + const OT_VD = 9; + + const OT_NBSP = 11; + + const OT_RS = 13; + + const OT_COENG = 14; + + const OT_REPHA = 15; + + const OT_RA = 16; + + /* Visual positions in a syllable from left to right. */ + // sea_position + const POS_START = 0; + + const POS_RA_TO_BECOME_REPH = 1; + + const POS_PRE_M = 2; + + const POS_PRE_C = 3; + + const POS_BASE_C = 4; + + const POS_AFTER_MAIN = 5; + + const POS_ABOVE_C = 6; + + const POS_BEFORE_SUB = 7; + + const POS_BELOW_C = 8; + + const POS_AFTER_SUB = 9; + + const POS_BEFORE_POST = 10; + + const POS_POST_C = 11; + + const POS_AFTER_POST = 12; + + const POS_FINAL_C = 13; + + const POS_SMVD = 14; + + const POS_END = 15; + + // Based on sea_category used to make string to find syllables + // OT_ to string character (using e.g. OT_C from INDIC) hb-ot-shape-complex-sea-private.hh + public static $sea_category_char = [ + 'x', + 'C', + 'V', + 'T', + 'H', + 'x', + 'x', + 'x', + 'x', + 'x', + 'A', + 'x', + 'G', + 'x', + 'x', + 'x', + 'x', + 'M', + 'x', + 'x', + 'x', + 'x', + 'R', + 'x', + 'x', + 'x', + 'a', + 'b', + 'p', + 't', + ]; + + public static function set_sea_properties(&$info, $scriptblock) + { + $u = $info['uni']; + $type = self::sea_get_categories($u); + $cat = ($type & 0x7F); + $pos = ($type >> 8); + + /* + * Re-assign category + */ + // Medial Ra + if ($u == 0x1A55 || $u == 0xAA34) { + $cat = self::OT_MR; + } + + /* + * Re-assign position. + */ + if ($cat == self::OT_M) { // definitely "OT_M" in HarfBuzz - although this does not seem to have been defined ? should be OT_MR + switch ($pos) { + case self::POS_PRE_C: + $cat = self::OT_VPRE; + break; + case self::POS_ABOVE_C: + $cat = self::OT_VABV; + break; + case self::POS_BELOW_C: + $cat = self::OT_VBLW; + break; + case self::POS_POST_C: + $cat = self::OT_VPST; + break; + } + } + + $info['sea_category'] = $cat; + $info['sea_position'] = $pos; + } + + // syllable_type + const CONSONANT_SYLLABLE = 0; + + const BROKEN_CLUSTER = 1; + + const NON_SEA_CLUSTER = 2; + + public static function set_syllables(&$o, $s, &$broken_syllables) + { + $ptr = 0; + $syllable_serial = 1; + $broken_syllables = false; + while ($ptr < strlen($s)) { + $match = ''; + $syllable_length = 1; + $syllable_type = self::NON_SEA_CLUSTER; + + // CONSONANT_SYLLABLE Consonant syllable + if (preg_match('/^(C|V|G)(p|a|b|t|HC|M|R|T|A)*/', substr($s, $ptr), $ma)) { + $syllable_length = strlen($ma[0]); + $syllable_type = self::CONSONANT_SYLLABLE; + } // BROKEN_CLUSTER syllable + elseif (preg_match('/^(p|a|b|t|HC|M|R|T|A)+/', substr($s, $ptr), $ma)) { + $syllable_length = strlen($ma[0]); + $syllable_type = self::BROKEN_CLUSTER; + $broken_syllables = true; + } + + for ($i = $ptr; $i < $ptr + $syllable_length; $i++) { + $o[$i]['syllable'] = ($syllable_serial << 4) | $syllable_type; + } + $ptr += $syllable_length; + $syllable_serial++; + if ($syllable_serial == 16) { + $syllable_serial = 1; + } + } + } + + public static function initial_reordering(&$info, $GSUBdata, $broken_syllables, $scriptblock, $dottedcircle) + { + + if ($broken_syllables && $dottedcircle) { + self::insert_dotted_circles($info, $dottedcircle); + } + + $count = count($info); + if (!$count) { + return; + } + $last = 0; + $last_syllable = $info[0]['syllable']; + for ($i = 1; $i < $count; $i++) { + if ($last_syllable != $info[$i]['syllable']) { + self::initial_reordering_syllable($info, $GSUBdata, $scriptblock, $last, $i); + $last = $i; + $last_syllable = $info[$last]['syllable']; + } + } + self::initial_reordering_syllable($info, $GSUBdata, $scriptblock, $last, $count); + } + + public static function insert_dotted_circles(&$info, $dottedcircle) + { + $idx = 0; + $last_syllable = 0; + while ($idx < count($info)) { + $syllable = $info[$idx]['syllable']; + $syllable_type = ($syllable & 0x0F); + if ($last_syllable != $syllable && $syllable_type == self::BROKEN_CLUSTER) { + $last_syllable = $syllable; + $dottedcircle[0]['syllable'] = $info[$idx]['syllable']; + array_splice($info, $idx, 0, $dottedcircle); + } else { + $idx++; + } + } + } + + public static function initial_reordering_syllable(&$info, $GSUBdata, $scriptblock, $start, $end) + { + /* broken_cluster: We already inserted dotted-circles, so just call the standalone_cluster. */ + + $syllable_type = ($info[$start]['syllable'] & 0x0F); + if ($syllable_type == self::NON_SEA_CLUSTER) { + return; + } + if ($syllable_type == self::BROKEN_CLUSTER) { + /* For dotted-circle, this is what Uniscribe does: + * If dotted-circle is the last glyph, it just does nothing. */ + if ($info[$end - 1]['sea_category'] == self::OT_GB) { + return; + } + } + + $base = $start; + $i = $start; + for (; $i < $base; $i++) { + $info[$i]['sea_position'] = self::POS_PRE_C; + } + if ($i < $end) { + $info[$i]['sea_position'] = self::POS_BASE_C; + $i++; + } + for (; $i < $end; $i++) { + if (isset($info[$i]['sea_category']) && $info[$i]['sea_category'] == self::OT_MR) { /* Pre-base reordering */ + $info[$i]['sea_position'] = self::POS_PRE_C; + continue; + } + if (isset($info[$i]['sea_category']) && $info[$i]['sea_category'] == self::OT_VPRE) { /* Left matra */ + $info[$i]['sea_position'] = self::POS_PRE_M; + continue; + } + $info[$i]['sea_position'] = self::POS_AFTER_MAIN; + } + + /* Sit tight, rock 'n roll! */ + self::bubble_sort($info, $start, $end - $start); + } + + public static function final_reordering(&$info, $GSUBdata, $scriptblock) + { + $count = count($info); + if (!$count) { + return; + } + $last = 0; + $last_syllable = $info[0]['syllable']; + for ($i = 1; $i < $count; $i++) { + if ($last_syllable != $info[$i]['syllable']) { + self::final_reordering_syllable($info, $GSUBdata, $scriptblock, $last, $i); + $last = $i; + $last_syllable = $info[$last]['syllable']; + } + } + self::final_reordering_syllable($info, $GSUBdata, $scriptblock, $last, $count); + } + + public static function final_reordering_syllable(&$info, $GSUBdata, $scriptblock, $start, $end) + { + /* + * Nothing to do here at present! + */ + } + + public static $sea_table = [ + /* New Tai Lue (1980..19DF) */ + + /* 1980 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 1988 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 1990 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 1998 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 19A0 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 19A8 */ 3841, 3841, 3841, 3841, 3840, 3840, 3840, 3840, + /* 19B0 */ 2823, 2823, 2823, 2823, 2823, 775, 775, 775, + /* 19B8 */ 2823, 2823, 775, 2823, 2823, 2823, 2823, 2823, + /* 19C0 */ 2823, 3857, 3857, 3857, 3857, 3857, 3857, 3857, + /* 19C8 */ 3843, 3843, 3840, 3840, 3840, 3840, 3840, 3840, + /* 19D0 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 19D8 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* Tai Tham (1A20..1AAF) */ + + /* 1A20 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 1A28 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 1A30 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 1A38 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 1A40 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* 1A48 */ 3841, 3841, 3841, 3841, 3841, 3842, 3842, 3842, + /* 1A50 */ 3842, 3842, 3842, 3841, 3841, 3857, 3857, 3857, + /* 1A58 */ 3857, 3857, 3857, 3857, 3857, 3857, 3857, 3840, + /* 1A60 */ 3844, 2823, 1543, 2823, 2823, 1543, 1543, 1543, + /* 1A68 */ 1543, 2055, 2055, 1543, 2055, 2823, 775, 775, + /* 1A70 */ 775, 775, 775, 1543, 1543, 3843, 3843, 3843, + /* 1A78 */ 3843, 3843, 3840, 3840, 3840, 3840, 3840, 3840, + /* 1A80 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 1A88 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 1A90 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 1A98 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 1AA0 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* 1AA8 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* Cham (AA00..AA5F) */ + + /* AA00 */ 3842, 3842, 3842, 3842, 3842, 3842, 3841, 3841, + /* AA08 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* AA10 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* AA18 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* AA20 */ 3841, 3841, 3841, 3841, 3841, 3841, 3841, 3841, + /* AA28 */ 3841, 1543, 1543, 1543, 1543, 2055, 1543, 775, + /* AA30 */ 775, 1543, 2055, 3857, 3857, 3857, 3857, 3840, + /* AA38 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* AA40 */ 3857, 3857, 3857, 3857, 3857, 3857, 3857, 3857, + /* AA48 */ 3857, 3857, 3857, 3857, 3857, 3857, 3840, 3840, + /* AA50 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + /* AA58 */ 3840, 3840, 3840, 3840, 3840, 3840, 3840, 3840, + ]; + + public static function sea_get_categories($u) + { + if (0x1980 <= $u && $u <= 0x19DF) { + return self::$sea_table[$u - 0x1980]; // offset 0 for New Tai Lue + } + if (0x1A20 <= $u && $u <= 0x1AAF) { + return self::$sea_table[$u - 0x1A20 + 96]; // offset for Tai Tham + } + if (0xAA00 <= $u && $u <= 0xAA5F) { + return self::$sea_table[$u - 0xAA00 + 96 + 144]; // Cham + } + if ($u == 0x00A0) { + return 3851; // (ISC_CP | (IMC_x << 8)) + } + if ($u == 0x25CC) { + return 3851; // (ISC_CP | (IMC_x << 8)) + } + return 3840; // (ISC_x | (IMC_x << 8)) + } + + public static function bubble_sort(&$arr, $start, $len) + { + if ($len < 2) { + return; + } + $k = $start + $len - 2; + while ($k >= $start) { + for ($j = $start; $j <= $k; $j++) { + if ($arr[$j]['sea_position'] > $arr[$j + 1]['sea_position']) { + $t = $arr[$j]; + $arr[$j] = $arr[$j + 1]; + $arr[$j + 1] = $t; + } + } + $k--; + } + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/SizeConverter.php b/src/bb-vendor/mpdf/mpdf/src/SizeConverter.php new file mode 100644 index 000000000..9ec93fd2a --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/SizeConverter.php @@ -0,0 +1,161 @@ +<?php + +namespace Mpdf; + +use Psr\Log\LoggerInterface; +use Mpdf\Log\Context as LogContext; + +class SizeConverter implements \Psr\Log\LoggerAwareInterface +{ + + private $dpi; + + private $defaultFontSize; + + /** + * @var \Mpdf\Mpdf + */ + private $mpdf; + + /** + * @var \Psr\Log\LoggerInterface + */ + private $logger; + + public function __construct($dpi, $defaultFontSize, Mpdf $mpdf, LoggerInterface $logger) + { + $this->dpi = $dpi; + $this->defaultFontSize = $defaultFontSize; + $this->mpdf = $mpdf; + $this->logger = $logger; + } + + public function setLogger(LoggerInterface $logger) + { + $this->logger = $logger; + } + + /** + * Depends of maxsize value to make % work properly. Usually maxsize == pagewidth + * For text $maxsize = $fontsize + * Setting e.g. margin % will use maxsize (pagewidth) and em will use fontsize + * + * @param mixed $size + * @param mixed $maxsize + * @param mixed $fontsize + * @param mixed $usefontsize Set false for e.g. margins - will ignore fontsize for % values + * + * @return float Final size in mm + */ + public function convert($size = 5, $maxsize = 0, $fontsize = false, $usefontsize = true) + { + $size = trim(strtolower($size)); + $res = preg_match('/^(?P<size>[-0-9.,]+([eE]\-?[0-9]+)?)?(?P<unit>[%a-z-]+)?$/', $size, $parts); + if (!$res) { + // ignore definition + $this->logger->warning(sprintf('Invalid size representation "%s"', $size), ['context' => LogContext::CSS_SIZE_CONVERSION]); + } + + $unit = !empty($parts['unit']) ? $parts['unit'] : null; + $size = !empty($parts['size']) ? (float) $parts['size'] : 0.0; + + switch ($unit) { + case 'mm': + // do nothing + break; + + case 'cm': + $size *= 10; + break; + + case 'pt': + $size *= 1 / Mpdf::SCALE; + break; + + case 'rem': + $size *= $this->mpdf->default_font_size / Mpdf::SCALE; + break; + + case '%': + if ($fontsize && $usefontsize) { + $size *= $fontsize / 100; + } else { + $size *= $maxsize / 100; + } + break; + + case 'in': + // mm in an inch + $size *= 25.4; + break; + + case 'pc': + // PostScript picas + $size *= 38.1 / 9; + break; + + case 'ex': + // Approximates "ex" as half of font height + $size *= $this->multiplyFontSize($fontsize, $maxsize, 0.5); + break; + + case 'em': + $size *= $this->multiplyFontSize($fontsize, $maxsize, 1); + break; + + case 'thin': + $size = 1 * (25.4 / $this->dpi); + break; + + case 'medium': + $size = 3 * (25.4 / $this->dpi); + // Commented-out dead code from legacy method + // $size *= $this->multiplyFontSize($fontsize, $maxsize, 1); + break; + + case 'thick': + $size = 5 * (25.4 / $this->dpi); // 5 pixel width for table borders + break; + + case 'xx-small': + $size *= $this->multiplyFontSize($fontsize, $maxsize, 0.7); + break; + + case 'x-small': + $size *= $this->multiplyFontSize($fontsize, $maxsize, 0.77); + break; + + case 'small': + $size *= $this->multiplyFontSize($fontsize, $maxsize, 0.86); + break; + + case 'large': + $size *= $this->multiplyFontSize($fontsize, $maxsize, 1.2); + break; + + case 'x-large': + $size *= $this->multiplyFontSize($fontsize, $maxsize, 1.5); + break; + + case 'xx-large': + $size *= $this->multiplyFontSize($fontsize, $maxsize, 2); + break; + + case 'px': + default: + $size *= (25.4 / $this->dpi); + break; + } + + return $size; + } + + private function multiplyFontSize($fontsize, $maxsize, $ratio) + { + if ($fontsize) { + return $fontsize * $ratio; + } + + return $maxsize * $ratio; + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Strict.php b/src/bb-vendor/mpdf/mpdf/src/Strict.php new file mode 100644 index 000000000..bab863db7 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Strict.php @@ -0,0 +1,67 @@ +<?php + +namespace Mpdf; + +trait Strict +{ + + /** + * @param string $name method name + * @param array $args arguments + */ + public function __call($name, $args) + { + $class = method_exists($this, $name) ? 'parent' : get_class($this); + throw new \Mpdf\MpdfException("Call to undefined method $class::$name()"); + } + + /** + * @param string $name lowercase method name + * @param array $args arguments + */ + public static function __callStatic($name, $args) + { + $class = get_called_class(); + throw new \Mpdf\MpdfException("Call to undefined static function $class::$name()"); + } + + /** + * @param string $name property name + */ + public function &__get($name) + { + $class = get_class($this); + throw new \Mpdf\MpdfException("Cannot read an undeclared property $class::\$$name"); + } + + /** + * @param string $name property name + * @param mixed $value property value + */ + public function __set($name, $value) + { + $class = get_class($this); + throw new \Mpdf\MpdfException("Cannot write to an undeclared property $class::\$$name"); + } + + /** + * @param string $name property name + * @throws \Kdyby\StrictObjects\\Mpdf\MpdfException + */ + public function __isset($name) + { + $class = get_class($this); + throw new \Mpdf\MpdfException("Cannot read an undeclared property $class::\$$name"); + } + + /** + * @param string $name property name + * @throws \Kdyby\StrictObjects\\Mpdf\MpdfException + */ + public function __unset($name) + { + $class = get_class($this); + throw new \Mpdf\MpdfException("Cannot unset the property $class::\$$name."); + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/TTFontFile.php b/src/bb-vendor/mpdf/mpdf/src/TTFontFile.php new file mode 100644 index 000000000..0834ff0c5 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/TTFontFile.php @@ -0,0 +1,4947 @@ +<?php + +namespace Mpdf; + +use Mpdf\Fonts\FontCache; +use Mpdf\Fonts\GlyphOperator; + +// NOTE*** If you change the defined constants below, be sure to delete all temporary font data files in /ttfontdata/ +// to force mPDF to regenerate cached font files. +if (!defined('_OTL_OLD_SPEC_COMPAT_2')) { + define('_OTL_OLD_SPEC_COMPAT_2', true); +} + +// Define the value used in the "head" table of a created TTF file +// 0x74727565 "true" for Mac +// 0x00010000 for Windows +// Either seems to work for a font embedded in a PDF file +// when read by Adobe Reader on a Windows PC(!) +if (!defined('_TTF_MAC_HEADER')) { + define('_TTF_MAC_HEADER', false); +} + +// Recalculate correct metadata/profiles when making subset fonts (not SIP/SMP) +// e.g. xMin, xMax, maxNContours +if (!defined('_RECALC_PROFILE')) { + define('_RECALC_PROFILE', false); +} + +// mPDF 5.7.1 +if (!function_exists('\Mpdf\unicode_hex')) { + function unicode_hex($unicode_dec) + { + return sprintf("%05s", strtoupper(dechex($unicode_dec))); + } +} + +/** + * TTFontFile class + * + * This class is based on The ReportLab Open Source PDF library + * written in Python - http://www.reportlab.com/software/opensource/ + * together with ideas from the OpenOffice source code and others. + * This header must be retained in any redistribution or + * modification of the file. + * + * @author Ian Back <ianb@bpm1.com> + * @license LGPL + */ +class TTFontFile +{ + + use Strict; + + private $fontCache; + + private $fontDescriptor; + + var $GPOSFeatures; + + var $GPOSLookups; + + var $GPOSScriptLang; + + var $MarkAttachmentType; + + var $MarkGlyphSets; + + var $GlyphClassMarks; + + var $GlyphClassLigatures; + + var $GlyphClassBases; + + var $GlyphClassComponents; + + var $GSUBScriptLang; + + var $rtlPUAstr; + + var $fontkey; + + var $useOTL; + + var $maxUni; + + var $sFamilyClass; + + var $sFamilySubClass; + + var $sipset; + + var $smpset; + + var $_pos; + + var $numTables; + + var $searchRange; + + var $entrySelector; + + var $rangeShift; + + var $tables; + + var $otables; + + var $filename; + + var $fh; + + var $glyphPos; + + var $charToGlyph; + + var $ascent; + + var $descent; + + var $lineGap; + + var $hheaascent; + + var $hheadescent; + + var $hhealineGap; + + var $advanceWidthMax; + + var $typoAscender; + + var $typoDescender; + + var $typoLineGap; + + var $usWinAscent; + + var $usWinDescent; + + var $strikeoutSize; + + var $strikeoutPosition; + + var $name; + + var $familyName; + + var $styleName; + + var $fullName; + + var $uniqueFontID; + + var $unitsPerEm; + + var $bbox; + + var $capHeight; + + var $xHeight; + + var $stemV; + + var $italicAngle; + + var $flags; + + var $underlinePosition; + + var $underlineThickness; + + var $charWidths; + + var $defaultWidth; + + var $maxStrLenRead; + + var $numTTCFonts; + + var $TTCFonts; + + var $maxUniChar; + + var $kerninfo; + + var $haskernGPOS; + + var $hassmallcapsGSUB; + + var $codeToGlyph; + + var $glyphdata; + + var $LuCoverage; + + public $panose; + + public $version; + + public $fontRevision; + + public $restrictedUse; + + public $glyphIDtoUni; + + public $glyphToChar; + + public $GSUBFeatures; + + public $GSUBLookups; + + public $GSLuCoverage; + + public function __construct(FontCache $fontCache, $fontDescriptor) + { + $this->fontCache = $fontCache; + $this->fontDescriptor = $fontDescriptor; + + // Maximum size of glyf table to read in as string (otherwise reads each glyph from file) + $this->maxStrLenRead = 200000; + } + + public function getMetrics($file, $fontkey, $TTCfontID = 0, $debug = false, $BMPonly = false, $useOTL = 0) + { + $this->useOTL = $useOTL; + $this->fontkey = $fontkey; + $this->filename = $file; + $this->fh = fopen($file, 'rb'); + + if (!$this->fh) { + throw new \Mpdf\MpdfException(sprintf('Unable to open font file "%s"', $file)); + } + + $this->_pos = 0; + $this->charWidths = ''; + $this->glyphPos = []; + $this->charToGlyph = []; + $this->tables = []; + $this->otables = []; + $this->kerninfo = []; + $this->haskernGPOS = []; + $this->hassmallcapsGSUB = []; + $this->ascent = 0; + $this->descent = 0; + $this->lineGap = 0; + $this->hheaascent = 0; + $this->hheadescent = 0; + $this->hhealineGap = 0; + $this->xHeight = 0; + $this->capHeight = 0; + $this->panose = []; + $this->sFamilyClass = 0; + $this->sFamilySubClass = 0; + $this->typoAscender = 0; + $this->typoDescender = 0; + $this->typoLineGap = 0; + $this->usWinAscent = 0; + $this->usWinDescent = 0; + $this->advanceWidthMax = 0; + $this->strikeoutSize = 0; + $this->strikeoutPosition = 0; + $this->numTTCFonts = 0; + $this->TTCFonts = []; + $this->version = $version = $this->read_ulong(); + $this->panose = []; + + if ($version === 0x4F54544F) { + throw new \Mpdf\MpdfException('Postscript outlines are not supported'); + } + + if ($version === 0x74746366 && !$TTCfontID) { + throw new \Mpdf\MpdfException(sprintf('TTCfontID for a TrueType Collection is not defined in mPDF "fontdata" configuration (%s)', $file)); + } + + if (!in_array($version, [0x00010000, 0x74727565], true) && !$TTCfontID) { + throw new \Mpdf\MpdfException(sprintf('Not a TrueType font: version=%s)', $version)); + } + + if ($TTCfontID > 0) { + $this->version = $version = $this->read_ulong(); // TTC Header version now + if (!in_array($version, [0x00010000, 0x00020000], true)) { + throw new \Mpdf\MpdfException(sprintf('Error parsing TrueType Collection: version=%s - (%s)', $version, $file)); + } + $this->numTTCFonts = $this->read_ulong(); + for ($i = 1; $i <= $this->numTTCFonts; $i++) { + $this->TTCFonts[$i]['offset'] = $this->read_ulong(); + } + $this->seek($this->TTCFonts[$TTCfontID]['offset']); + $this->version = $version = $this->read_ulong(); // TTFont version again now + } + + $this->readTableDirectory($debug); + $this->extractInfo($debug, $BMPonly, $useOTL); + + fclose($this->fh); + } + + function readTableDirectory($debug = false) + { + $this->numTables = $this->read_ushort(); + $this->searchRange = $this->read_ushort(); + $this->entrySelector = $this->read_ushort(); + $this->rangeShift = $this->read_ushort(); + $this->tables = []; + + for ($i = 0; $i < $this->numTables; $i++) { + $record = []; + $record['tag'] = $this->read_tag(); + $record['checksum'] = [$this->read_ushort(), $this->read_ushort()]; + $record['offset'] = $this->read_ulong(); + $record['length'] = $this->read_ulong(); + $this->tables[$record['tag']] = $record; + } + + if ($debug) { + $this->checksumTables(); + } + } + + function checksumTables() + { + // Check the checksums for all tables + foreach ($this->tables as $t) { + if ($t['length'] > 0 && $t['length'] < $this->maxStrLenRead) { // 1.02 + $table = $this->get_chunk($t['offset'], $t['length']); + $checksum = $this->calcChecksum($table); + if ($t['tag'] === 'head') { + $up = unpack('n*', substr($table, 8, 4)); + $adjustment[0] = $up[1]; + $adjustment[1] = $up[2]; + $checksum = $this->sub32($checksum, $adjustment); + } + $xchecksum = $t['checksum']; + if ($xchecksum != $checksum) { + throw new \Mpdf\MpdfException(sprintf('TTF file "%s": invalid checksum %s table: %s (expected %s)', $this->filename, dechex($checksum[0]) . dechex($checksum[1]), $t['tag'], dechex($xchecksum[0]) . dechex($xchecksum[1]))); + } + } + } + } + + function sub32($x, $y) + { + $xlo = $x[1]; + $xhi = $x[0]; + $ylo = $y[1]; + $yhi = $y[0]; + + if ($ylo > $xlo) { + $xlo += 1 << 16; + ++$yhi; + } + $reslo = $xlo - $ylo; + if ($yhi > $xhi) { + $xhi += 1 << 16; + } + $reshi = $xhi - $yhi; + $reshi &= 0xFFFF; + + return [$reshi, $reslo]; + } + + function calcChecksum($data) + { + if (strlen($data) % 4) { + $data .= str_repeat("\0", 4 - (strlen($data) % 4)); + } + + $len = strlen($data); + $hi = 0x0000; + $lo = 0x0000; + + for ($i = 0; $i < $len; $i += 4) { + $hi += (ord($data[$i]) << 8) + ord($data[$i + 1]); + $lo += (ord($data[$i + 2]) << 8) + ord($data[$i + 3]); + $hi += ($lo >> 16) & 0xFFFF; + $lo &= 0xFFFF; + } + + $hi &= 0xFFFF; + + return [$hi, $lo]; + } + + function get_table_pos($tag) + { + if (!isset($this->tables[$tag])) { + return [0, 0]; + } + $offset = $this->tables[$tag]['offset']; + $length = $this->tables[$tag]['length']; + + return [$offset, $length]; + } + + function seek($pos) + { + $this->_pos = $pos; + fseek($this->fh, $this->_pos); + } + + function skip($delta) + { + $this->_pos = $this->_pos + $delta; + fseek($this->fh, $delta, SEEK_CUR); + } + + function seek_table($tag, $offset_in_table = 0) + { + $tpos = $this->get_table_pos($tag); + $this->_pos = $tpos[0] + $offset_in_table; + fseek($this->fh, $this->_pos); + + return $this->_pos; + } + + function read_tag() + { + $this->_pos += 4; + + return fread($this->fh, 4); + } + + function read_short() + { + $this->_pos += 2; + $s = fread($this->fh, 2); + $a = (ord($s[0]) << 8) + ord($s[1]); + if ($a & (1 << 15)) { + $a = ($a - (1 << 16)); + } + + return $a; + } + + function unpack_short($s) + { + $a = (ord($s[0]) << 8) + ord($s[1]); + if ($a & (1 << 15)) { + $a = ($a - (1 << 16)); + } + + return $a; + } + + function read_ushort() + { + $this->_pos += 2; + $s = fread($this->fh, 2); + + return (ord($s[0]) << 8) + ord($s[1]); + } + + function read_ulong() + { + $this->_pos += 4; + $s = fread($this->fh, 4); + + // if large uInt32 as an integer, PHP converts it to -ve + return (ord($s[0]) * 16777216) + (ord($s[1]) << 16) + (ord($s[2]) << 8) + ord($s[3]); // 16777216 = 1<<24 + } + + function get_ushort($pos) + { + fseek($this->fh, $pos); + $s = fread($this->fh, 2); + + return (ord($s[0]) << 8) + ord($s[1]); + } + + function get_ulong($pos) + { + fseek($this->fh, $pos); + $s = fread($this->fh, 4); + + // iF large uInt32 as an integer, PHP converts it to -ve + return (ord($s[0]) * 16777216) + (ord($s[1]) << 16) + (ord($s[2]) << 8) + ord($s[3]); // 16777216 = 1<<24 + } + + function pack_short($val) + { + if ($val < 0) { + $val = abs($val); + $val = ~$val; + ++$val; + } + + return pack('n', $val); + } + + function splice($stream, $offset, $value) + { + return substr($stream, 0, $offset) . $value . substr($stream, $offset + strlen($value)); + } + + function _set_ushort($stream, $offset, $value) + { + $up = pack("n", $value); + + return $this->splice($stream, $offset, $up); + } + + function _set_short($stream, $offset, $val) + { + if ($val < 0) { + $val = abs($val); + $val = ~$val; + $val += 1; + } + $up = pack("n", $val); + + return $this->splice($stream, $offset, $up); + } + + function get_chunk($pos, $length) + { + fseek($this->fh, $pos); + if ($length < 1) { + return ''; + } + + return (fread($this->fh, $length)); + } + + function get_table($tag) + { + list($pos, $length) = $this->get_table_pos($tag); + if ($length == 0) { + return ''; + } + fseek($this->fh, $pos); + + return (fread($this->fh, $length)); + } + + function add($tag, $data) + { + if ($tag === 'head') { + $data = $this->splice($data, 8, "\0\0\0\0"); + } + $this->otables[$tag] = $data; + } + + function getCTG($file, $TTCfontID = 0, $debug = false, $useOTL = false) + { + // Only called if font is not to be used as embedded subset i.e. NOT called for SIP/SMP fonts + $this->useOTL = $useOTL; // mPDF 5.7.1 + $this->filename = $file; + $this->fh = fopen($file, 'rb'); + + if (!$this->fh) { + throw new \Mpdf\MpdfException(sprintf('Unable to open file "%s"', $file)); + } + + $this->_pos = 0; + $this->charWidths = ''; + $this->glyphPos = []; + $this->charToGlyph = []; + $this->tables = []; + $this->numTTCFonts = 0; + $this->TTCFonts = []; + $this->skip(4); + + if ($TTCfontID > 0) { + $this->version = $version = $this->read_ulong(); // TTC Header version now + if (!in_array($version, [0x00010000, 0x00020000], true)) { + throw new \Mpdf\MpdfException(sprintf("Error parsing TrueType Collection: version=%s (%s)", $version, $file)); + } + $this->numTTCFonts = $this->read_ulong(); + for ($i = 1; $i <= $this->numTTCFonts; $i++) { + $this->TTCFonts[$i]['offset'] = $this->read_ulong(); + } + $this->seek($this->TTCFonts[$TTCfontID]['offset']); + $this->version = $version = $this->read_ulong(); // TTFont version again now + } + $this->readTableDirectory($debug); + + // cmap - Character to glyph index mapping table + $cmap_offset = $this->seek_table('cmap'); + $this->skip(2); + $cmapTableCount = $this->read_ushort(); + $unicode_cmap_offset = 0; + for ($i = 0; $i < $cmapTableCount; $i++) { + $platformID = $this->read_ushort(); + $encodingID = $this->read_ushort(); + $offset = $this->read_ulong(); + $save_pos = $this->_pos; + if ($platformID == 3 && $encodingID == 1) { // Microsoft, Unicode + $format = $this->get_ushort($cmap_offset + $offset); + if ($format == 4) { + $unicode_cmap_offset = $cmap_offset + $offset; + break; + } + } elseif ($platformID == 0) { // Unicode -- assume all encodings are compatible + $format = $this->get_ushort($cmap_offset + $offset); + if ($format == 4) { + $unicode_cmap_offset = $cmap_offset + $offset; + break; + } + } + $this->seek($save_pos); + } + + $glyphToChar = []; + $charToGlyph = []; + $this->getCMAP4($unicode_cmap_offset, $glyphToChar, $charToGlyph); + + // Map Unmapped glyphs - from $numGlyphs + if ($useOTL) { + $this->seek_table("maxp"); + $this->skip(4); + $numGlyphs = $this->read_ushort(); + $bctr = 0xE000; + for ($gid = 1; $gid < $numGlyphs; $gid++) { + if (!isset($glyphToChar[$gid])) { + while (isset($charToGlyph[$bctr])) { + $bctr++; + } // Avoid overwriting a glyph already mapped in PUA + if ($bctr > 0xF8FF) { + throw new \Mpdf\MpdfException(sprintf('Font "%s" cannot map all included glyphs into Private Use Area U+E000-U+F8FF; cannot use useOTL on this font', $file)); + } + $glyphToChar[$gid][] = $bctr; + $charToGlyph[$bctr] = $gid; + $bctr++; + } + } + } + + fclose($this->fh); + + return $charToGlyph; + } + + function getTTCFonts($file) + { + $this->filename = $file; + + $this->fh = fopen($file, 'rb'); + if (!$this->fh) { + throw new \Mpdf\MpdfException(sprintf('Unable to open file "%s"', $file)); + } + + $this->numTTCFonts = 0; + $this->TTCFonts = []; + $this->version = $version = $this->read_ulong(); + if ($version === 0x74746366) { + $this->version = $version = $this->read_ulong(); // TTC Header version now + if (!in_array($version, [0x00010000, 0x00020000], true)) { + throw new \Mpdf\MpdfException(sprintf("Error parsing TrueType Collection: version=%s (%s)", $version, $file)); + } + } else { + throw new \Mpdf\MpdfException(sprintf("Not a TrueType Collection: version=%s (%s)", $version, $file)); + } + + $this->numTTCFonts = $this->read_ulong(); + for ($i = 1; $i <= $this->numTTCFonts; $i++) { + $this->TTCFonts[$i]['offset'] = $this->read_ulong(); + } + } + + function extractInfo($debug = false, $BMPonly = false, $useOTL = 0) + { + // Values are all set to 0 or blank at start of getMetrics + // name - Naming table + $name_offset = $this->seek_table("name"); + $format = $this->read_ushort(); + if ($format != 0 && $format != 1) { + throw new \Mpdf\MpdfException("Unknown name table format " . $format); + } + + $numRecords = $this->read_ushort(); + $string_data_offset = $name_offset + $this->read_ushort(); + $names = [1 => '', 2 => '', 3 => '', 4 => '', 6 => '']; + $K = array_keys($names); + $nameCount = count($names); + + for ($i = 0; $i < $numRecords; $i++) { + + $platformId = $this->read_ushort(); + $encodingId = $this->read_ushort(); + $languageId = $this->read_ushort(); + $nameId = $this->read_ushort(); + $length = $this->read_ushort(); + $offset = $this->read_ushort(); + + if (!in_array($nameId, $K)) { + continue; + } + + $N = ''; + if ($platformId == 3 && $encodingId == 1 && $languageId == 0x409) { // Microsoft, Unicode, US English, PS Name + $opos = $this->_pos; + $this->seek($string_data_offset + $offset); + if ($length % 2 != 0) { + throw new \Mpdf\MpdfException("PostScript name is UTF-16BE string of odd length"); + } + $length /= 2; + $N = ''; + while ($length > 0) { + $char = $this->read_ushort(); + $N .= (chr($char)); + $length -= 1; + } + $this->_pos = $opos; + $this->seek($opos); + } elseif ($platformId == 1 && $encodingId == 0 && $languageId == 0) { // Macintosh, Roman, English, PS Name + $opos = $this->_pos; + $N = $this->get_chunk($string_data_offset + $offset, $length); + $this->_pos = $opos; + $this->seek($opos); + } + if ($N && $names[$nameId] == '') { + $names[$nameId] = $N; + $nameCount -= 1; + if ($nameCount == 0) { + break; + } + } + } + + if ($names[6]) { + $psName = $names[6]; + } elseif ($names[4]) { + $psName = preg_replace('/ /', '-', $names[4]); + } elseif ($names[1]) { + $psName = preg_replace('/ /', '-', $names[1]); + } else { + $psName = ''; + } + + if (!$psName) { + throw new \Mpdf\MpdfException("Could not find PostScript font name: " . $this->filename); + } + + // CHECK IF psName valid (PadaukBook contains illegal characters in Name ID 6 i.e. Postscript Name) + $psNameInvalid = false; + $nameLength = strlen($psName); + for ($i = 0; $i < $nameLength; $i++) { + $c = $psName[$i]; + $oc = ord($c); + if ($oc > 126 || strpos(' [](){}<>/%', $c) !== false) { + //throw new \Mpdf\MpdfException("psName=".$psName." contains invalid character ".$c." ie U+".ord(c)); + $psNameInvalid = true; + break; + } + } + + if ($psNameInvalid && $names[4]) { + $psName = preg_replace('/ /', '-', $names[4]); + } + + $this->name = $psName; + if ($names[1]) { + $this->familyName = $names[1]; + } else { + $this->familyName = $psName; + } + if ($names[2]) { + $this->styleName = $names[2]; + } else { + $this->styleName = 'Regular'; + } + if ($names[4]) { + $this->fullName = $names[4]; + } else { + $this->fullName = $psName; + } + if ($names[3]) { + $this->uniqueFontID = $names[3]; + } else { + $this->uniqueFontID = $psName; + } + + if (!$psNameInvalid && $names[6]) { + $this->fullName = $names[6]; + } + + // head - Font header table + $this->seek_table('head'); + if ($debug) { + $ver_maj = $this->read_ushort(); + $ver_min = $this->read_ushort(); + if ($ver_maj != 1) { + throw new \Mpdf\MpdfException('Unknown head table version ' . $ver_maj . '.' . $ver_min); + } + $this->fontRevision = $this->read_ushort() . $this->read_ushort(); + + $this->skip(4); + $magic = $this->read_ulong(); + if ($magic !== 0x5F0F3CF5) { + throw new \Mpdf\MpdfException('Invalid head table magic ' . $magic); + } + $this->skip(2); + } else { + $this->skip(18); + } + $this->unitsPerEm = $unitsPerEm = $this->read_ushort(); + $scale = 1000 / $unitsPerEm; + $this->skip(16); + $xMin = $this->read_short(); + $yMin = $this->read_short(); + $xMax = $this->read_short(); + $yMax = $this->read_short(); + $this->bbox = [($xMin * $scale), ($yMin * $scale), ($xMax * $scale), ($yMax * $scale)]; + + $this->skip(3 * 2); + $indexToLocFormat = $this->read_ushort(); + $glyphDataFormat = $this->read_ushort(); + if ($glyphDataFormat != 0) { + throw new \Mpdf\MpdfException(sprintf('Unknown glyph data format %s', $glyphDataFormat)); + } + + // hhea metrics table + if (isset($this->tables["hhea"])) { + $this->seek_table("hhea"); + $this->skip(4); + $hheaAscender = $this->read_short(); + $hheaDescender = $this->read_short(); + $hheaLineGap = $this->read_short(); + $hheaAdvanceWidthMax = $this->read_ushort(); + $this->hheaascent = ($hheaAscender * $scale); + $this->hheadescent = ($hheaDescender * $scale); + $this->hhealineGap = ($hheaLineGap * $scale); + $this->advanceWidthMax = ($hheaAdvanceWidthMax * $scale); + } + + // OS/2 - OS/2 and Windows metrics table + $use_typo_metrics = false; + if (isset($this->tables["OS/2"])) { + $this->seek_table("OS/2"); + $version = $this->read_ushort(); + $this->skip(2); + $usWeightClass = $this->read_ushort(); + $this->skip(2); + $fsType = $this->read_ushort(); + if ($fsType == 0x0002 || ($fsType & 0x0300) != 0) { + $this->restrictedUse = true; + } + + $this->skip(16); + $yStrikeoutSize = $this->read_short(); + $yStrikeoutPosition = $this->read_short(); + $this->strikeoutSize = ($yStrikeoutSize * $scale); + $this->strikeoutPosition = ($yStrikeoutPosition * $scale); + + $sF = $this->read_short(); + $this->sFamilyClass = ($sF >> 8); + $this->sFamilySubClass = ($sF & 0xFF); + $this->_pos += 10; //PANOSE = 10 byte length + $panose = fread($this->fh, 10); + $this->panose = []; + $panoseLenght = strlen($panose); + for ($p = 0; $p < $panoseLenght; $p++) { + $this->panose[] = ord($panose[$p]); + } + + $this->skip(20); + $fsSelection = $this->read_ushort(); + $use_typo_metrics = (($fsSelection & 0x80) === 0x80); // bit#7 = USE_TYPO_METRICS + $this->skip(4); + + $sTypoAscender = $this->read_short(); + $sTypoDescender = $this->read_short(); + $sTypoLineGap = $this->read_short(); + + if ($sTypoAscender) { + $this->typoAscender = ($sTypoAscender * $scale); + } + if ($sTypoDescender) { + $this->typoDescender = ($sTypoDescender * $scale); + } + if ($sTypoLineGap) { + $this->typoLineGap = ($sTypoLineGap * $scale); + } + + $usWinAscent = $this->read_ushort(); + $usWinDescent = $this->read_ushort(); + if ($usWinAscent) { + $this->usWinAscent = ($usWinAscent * $scale); + } + if ($usWinDescent) { + $this->usWinDescent = ($usWinDescent * $scale); + } + + if ($version > 1) { + $this->skip(8); + $sxHeight = $this->read_short(); + $this->xHeight = ($sxHeight * $scale); + $sCapHeight = $this->read_short(); + $this->capHeight = ($sCapHeight * $scale); + } + } else { + $usWeightClass = 400; + } + $this->stemV = 50 + (int) (($usWeightClass / 65.0) ** 2); + + // FONT DESCRIPTOR METRICS + if ($this->fontDescriptor === 'winTypo') { + $this->ascent = $this->typoAscender; + $this->descent = $this->typoDescender; + $this->lineGap = $this->typoLineGap; + } elseif ($this->fontDescriptor === 'mac') { + $this->ascent = $this->hheaascent; + $this->descent = $this->hheadescent; + $this->lineGap = $this->hhealineGap; + } else { // $this->fontDescriptor === 'win' + $this->ascent = $this->usWinAscent; + $this->descent = -$this->usWinDescent; + $this->lineGap = 0; + + // Special case - if either the winAscent or winDescent are greater than the + // font bounding box yMin yMax, then reduce them accordingly. + // This works with Myanmar Text (Windows 8 version) to give a + // line-height normal that is equivalent to that produced in browsers. + // Also Khmer OS = compatible with MSWord, Wordpad and browser. + if ($this->ascent > $this->bbox[3]) { + $this->ascent = $this->bbox[3]; + } + + if ($this->descent < $this->bbox[1]) { + $this->descent = $this->bbox[1]; + } + + // Override case - if the USE_TYPO_METRICS bit is set on OS/2 fsSelection + // this is telling the font to use the sTypo values and not the usWinAscent values. + // This works as a fix with Cambria Math to give a normal line-height; + // at present, this is the only font I have found with this bit set; + // although note that MS WordPad and windows FF browser uses the big line-height from winAscent + // but Word 2007 get it right + if ($use_typo_metrics && $this->typoAscender) { + $this->ascent = $this->typoAscender; + $this->descent = $this->typoDescender; + $this->lineGap = $this->typoLineGap; + } + } + + // post - PostScript table + $this->seek_table('post'); + if ($debug) { + $ver_maj = $this->read_ushort(); + if ($ver_maj < 1 || $ver_maj > 4) { + throw new \Mpdf\MpdfException(sprintf('Unknown post table version %s', $ver_maj)); + } + } else { + $this->skip(4); + } + + $this->italicAngle = $this->read_short() + $this->read_ushort() / 65536.0; + $this->underlinePosition = $this->read_short() * $scale; + $this->underlineThickness = $this->read_short() * $scale; + $isFixedPitch = $this->read_ulong(); + + $this->flags = 4; + + if ($this->italicAngle != 0) { + $this->flags |= 64; + } + if ($usWeightClass >= 600) { + $this->flags |= 262144; + } + if ($isFixedPitch) { + $this->flags |= 1; + } + + // hhea - Horizontal header table + $this->seek_table('hhea'); + if ($debug) { + $ver_maj = $this->read_ushort(); + if ($ver_maj != 1) { + throw new \Mpdf\MpdfException(sprintf('Unknown hhea table version %s', $ver_maj)); + } + $this->skip(28); + } else { + $this->skip(32); + } + + $metricDataFormat = $this->read_ushort(); + + if ($metricDataFormat != 0) { + throw new \Mpdf\MpdfException(sprintf('Unknown horizontal metric data format "%s"', $metricDataFormat)); + } + + $numberOfHMetrics = $this->read_ushort(); + + if ($numberOfHMetrics == 0) { + throw new \Mpdf\MpdfException('Number of horizontal metrics is 0'); + } + + // maxp - Maximum profile table + $this->seek_table('maxp'); + if ($debug) { + $ver_maj = $this->read_ushort(); + if ($ver_maj != 1) { + throw new \Mpdf\MpdfException(sprintf('Unknown maxp table version ', $ver_maj)); + } + } else { + $this->skip(4); + } + $numGlyphs = $this->read_ushort(); + + // cmap - Character to glyph index mapping table + $cmap_offset = $this->seek_table('cmap'); + $this->skip(2); + $cmapTableCount = $this->read_ushort(); + $unicode_cmap_offset = 0; + for ($i = 0; $i < $cmapTableCount; $i++) { + $platformID = $this->read_ushort(); + $encodingID = $this->read_ushort(); + $offset = $this->read_ulong(); + $save_pos = $this->_pos; + if (($platformID == 3 && $encodingID == 1) || $platformID == 0) { // Microsoft, Unicode + $format = $this->get_ushort($cmap_offset + $offset); + if ($format == 4) { + if (!$unicode_cmap_offset) { + $unicode_cmap_offset = $cmap_offset + $offset; + } + if ($BMPonly) { + break; + } + } + } elseif ((($platformID == 3 && $encodingID == 10) || $platformID == 0) && !$BMPonly) { // Microsoft, Unicode Format 12 table HKCS + $format = $this->get_ushort($cmap_offset + $offset); + if ($format == 12) { + $unicode_cmap_offset = $cmap_offset + $offset; + break; + } + } + $this->seek($save_pos); + } + + if (!$unicode_cmap_offset) { + throw new \Mpdf\MpdfException(sprintf('Font "%s" does not have cmap for Unicode (platform 3, encoding 1, format 4, or platform 0, any encoding, format 4)', $this->filename)); + } + + $sipset = false; + $smpset = false; + + $this->rtlPUAstr = ''; + $this->GSUBScriptLang = []; + $this->GSUBFeatures = []; + $this->GSUBLookups = []; + $this->GPOSScriptLang = []; + $this->GPOSFeatures = []; + $this->GPOSLookups = []; + $this->glyphIDtoUni = ''; + + // Format 12 CMAP does characters above Unicode BMP i.e. some HKCS characters U+20000 and above + if ($format == 12 && !$BMPonly) { + $this->maxUniChar = 0; + $this->seek($unicode_cmap_offset + 4); + $length = $this->read_ulong(); + $limit = $unicode_cmap_offset + $length; + $this->skip(4); + + $nGroups = $this->read_ulong(); + + $glyphToChar = []; + $charToGlyph = []; + for ($i = 0; $i < $nGroups; $i++) { + $startCharCode = $this->read_ulong(); + $endCharCode = $this->read_ulong(); + $startGlyphCode = $this->read_ulong(); + // ZZZ98 + if ($endCharCode > 0x20000 && $endCharCode < 0x2FFFF) { + $sipset = true; + } elseif ($endCharCode > 0x10000 && $endCharCode < 0x1FFFF) { + $smpset = true; + } + $offset = 0; + for ($unichar = $startCharCode; $unichar <= $endCharCode; $unichar++) { + $glyph = $startGlyphCode + $offset; + $offset++; + // ZZZ98 + if ($unichar < 0x30000) { + $charToGlyph[$unichar] = $glyph; + $this->maxUniChar = max($unichar, $this->maxUniChar); + $glyphToChar[$glyph][] = $unichar; + } + } + } + } else { + $glyphToChar = []; + $charToGlyph = []; + $this->getCMAP4($unicode_cmap_offset, $glyphToChar, $charToGlyph); + } + $this->sipset = $sipset; + $this->smpset = $smpset; + + // Map Unmapped glyphs (or glyphs mapped to upper PUA U+F00000 onwards i.e. > U+2FFFF) - from $numGlyphs + if ($this->useOTL) { + + $bctr = 0xE000; + + for ($gid = 1; $gid < $numGlyphs; $gid++) { + + if (!isset($glyphToChar[$gid])) { + + while (isset($charToGlyph[$bctr])) { + $bctr++; + } + + // Avoid overwriting a glyph already mapped in PUA + // ZZZ98 + if (($bctr > 0xF8FF) && ($bctr < 0x2CEB0)) { + if (!$BMPonly) { + $bctr = 0x2CEB0; // Use unassigned area 0x2CEB0 to 0x2F7FF (space for 10,000 characters) + $this->sipset = $sipset = true; // forces subsetting; also ensure charwidths are saved + while (isset($charToGlyph[$bctr])) { + $bctr++; + } + } else { + throw new \Mpdf\MpdfException(sprintf('The font "%s" does not have enough space to map all (unmapped) included glyphs into Private Use Area U+E000-U+F8FF', $names[1])); + } + } + + $glyphToChar[$gid][] = $bctr; + $charToGlyph[$bctr] = $gid; + $this->maxUniChar = max($bctr, $this->maxUniChar); + $bctr++; + } + } + } + + $this->glyphToChar = $glyphToChar; + + $this->GSUBScriptLang = []; + $this->rtlPUAstr = ''; + if ($useOTL) { + $this->_getGDEFtables(); + list($this->GSUBScriptLang, $this->GSUBFeatures, $this->GSUBLookups, $this->rtlPUAstr) = $this->_getGSUBtables(); + list($this->GPOSScriptLang, $this->GPOSFeatures, $this->GPOSLookups) = $this->_getGPOStables(); + $this->glyphIDtoUni = str_pad('', 256 * 256 * 3, "\x00"); + foreach ($glyphToChar as $gid => $arr) { + if (isset($glyphToChar[$gid][0])) { + $char = $glyphToChar[$gid][0]; + + if ($char != 0 && $char != 65535) { + $this->glyphIDtoUni[$gid * 3] = chr($char >> 16); + $this->glyphIDtoUni[$gid * 3 + 1] = chr(($char >> 8) & 0xFF); + $this->glyphIDtoUni[$gid * 3 + 2] = chr($char & 0xFF); + } + } + } + } + + // if xHeight and/or CapHeight are not available from OS/2 (e.g. eraly versions) + // Calculate from yMax of 'x' or 'H' Glyphs... + if ($this->xHeight == 0) { + if (isset($charToGlyph[0x78])) { + $gidx = $charToGlyph[0x78]; // U+0078 (LATIN SMALL LETTER X) + $start = $this->seek_table('loca'); + if ($indexToLocFormat == 0) { + $this->skip($gidx * 2); + $locax = $this->read_ushort() * 2; + } elseif ($indexToLocFormat == 1) { + $this->skip($gidx * 4); + $locax = $this->read_ulong(); + } + $start = $this->seek_table('glyf'); + $this->skip($locax); + $this->skip(8); + $yMaxx = $this->read_short(); + $this->xHeight = $yMaxx * $scale; + } + } + + if ($this->capHeight == 0) { + if (isset($charToGlyph[0x48])) { + $gidH = $charToGlyph[0x48]; // U+0048 (LATIN CAPITAL LETTER H) + $start = $this->seek_table('loca'); + if ($indexToLocFormat == 0) { + $this->skip($gidH * 2); + $locaH = $this->read_ushort() * 2; + } elseif ($indexToLocFormat == 1) { + $this->skip($gidH * 4); + $locaH = $this->read_ulong(); + } + $start = $this->seek_table('glyf'); + $this->skip($locaH); + $this->skip(8); + $yMaxH = $this->read_short(); + $this->capHeight = $yMaxH * $scale; + } else { + $this->capHeight = $this->ascent; + } + // final default is to set it = to Ascent + } + + // hmtx - Horizontal metrics table + $this->getHMTX($numberOfHMetrics, $numGlyphs, $glyphToChar, $scale); + + // kern - Kerning pair table + // Recognises old form of Kerning table - as required by Windows - Format 0 only + $kern_offset = $this->seek_table("kern"); + $version = $this->read_ushort(); + $nTables = $this->read_ushort(); + + // subtable header + $sversion = $this->read_ushort(); + $slength = $this->read_ushort(); + $scoverage = $this->read_ushort(); + $format = $scoverage >> 8; + if ($kern_offset && $version == 0 && $format == 0) { + // Format 0 + $nPairs = $this->read_ushort(); + $this->skip(6); + for ($i = 0; $i < $nPairs; $i++) { + $left = $this->read_ushort(); + $right = $this->read_ushort(); + $val = $this->read_short(); + if (isset($glyphToChar[$left]) && count($glyphToChar[$left]) == 1 && isset($glyphToChar[$right]) && count($glyphToChar[$right]) == 1) { + if ($left != 32 && $right != 32) { + $this->kerninfo[$glyphToChar[$left][0]][$glyphToChar[$right][0]] = intval($val * $scale); + } + } + } + } + } + + function _getGDEFtables() + { + // http://www.microsoft.com/typography/otspec/gdef.htm + if (isset($this->tables["GDEF"])) { + $gdef_offset = $this->seek_table("GDEF"); + + // ULONG Version of the GDEF table-currently 0x00010000 + $ver_maj = $this->read_ushort(); + $ver_min = $this->read_ushort(); + $GlyphClassDef_offset = $this->read_ushort(); + $AttachList_offset = $this->read_ushort(); + $LigCaretList_offset = $this->read_ushort(); + $MarkAttachClassDef_offset = $this->read_ushort(); + + // Version 0x00010002 of GDEF header contains additional Offset to a list defining mark glyph set definitions (MarkGlyphSetDef) + if ($ver_min == 2) { + $MarkGlyphSetsDef_offset = $this->read_ushort(); + } + + // GlyphClassDef + if ($GlyphClassDef_offset) { + + $this->seek($gdef_offset + $GlyphClassDef_offset); + // 1 Base glyph (single character, spacing glyph) + // 2 Ligature glyph (multiple character, spacing glyph) + // 3 Mark glyph (non-spacing combining glyph) + // 4 Component glyph (part of single character, spacing glyph) + $GlyphByClass = $this->_getClassDefinitionTable(); + } else { + $GlyphByClass = []; + } + + if (isset($GlyphByClass[1]) && count($GlyphByClass[1]) > 0) { + $this->GlyphClassBases = ' ' . implode('| ', $GlyphByClass[1]); + } else { + $this->GlyphClassBases = ''; + } + if (isset($GlyphByClass[2]) && count($GlyphByClass[2]) > 0) { + $this->GlyphClassLigatures = ' ' . implode('| ', $GlyphByClass[2]); + } else { + $this->GlyphClassLigatures = ''; + } + if (isset($GlyphByClass[3]) && count($GlyphByClass[3]) > 0) { + $this->GlyphClassMarks = ' ' . implode('| ', $GlyphByClass[3]); + } else { + $this->GlyphClassMarks = ''; + } + if (isset($GlyphByClass[4]) && count($GlyphByClass[4]) > 0) { + $this->GlyphClassComponents = ' ' . implode('| ', $GlyphByClass[4]); + } else { + $this->GlyphClassComponents = ''; + } + + if (isset($GlyphByClass[3]) && count($GlyphByClass[3]) > 0) { + $Marks = $GlyphByClass[3]; + } else { // to use for MarkAttachmentType + $Marks = []; + } + + /* Required for GPOS + // Attachment List + if ($AttachList_offset) { + $this->seek($gdef_offset+$AttachList_offset ); + } + The Attachment Point List table (AttachmentList) identifies all the attachment points defined in the GPOS table and their associated glyphs so a client can quickly access coordinates for each glyph's attachment points. As a result, the client can cache coordinates for attachment points along with glyph bitmaps and avoid recalculating the attachment points each time it displays a glyph. Without this table, processing speed would be slower because the client would have to decode the GPOS lookups that define attachment points and compile the points in a list. + + The Attachment List table (AttachList) may be used to cache attachment point coordinates along with glyph bitmaps. + + The table consists of an offset to a Coverage table (Coverage) listing all glyphs that define attachment points in the GPOS table, a count of the glyphs with attachment points (GlyphCount), and an array of offsets to AttachPoint tables (AttachPoint). The array lists the AttachPoint tables, one for each glyph in the Coverage table, in the same order as the Coverage Index. + AttachList table + Type Name Description + Offset Coverage Offset to Coverage table - from beginning of AttachList table + uint16 GlyphCount Number of glyphs with attachment points + Offset AttachPoint[GlyphCount] Array of offsets to AttachPoint tables-from beginning of AttachList table-in Coverage Index order + + An AttachPoint table consists of a count of the attachment points on a single glyph (PointCount) and an array of contour indices of those points (PointIndex), listed in increasing numerical order. + + AttachPoint table + Type Name Description + uint16 PointCount Number of attachment points on this glyph + uint16 PointIndex[PointCount] Array of contour point indices -in increasing numerical order + + See Example 3 - http://www.microsoft.com/typography/otspec/gdef.htm + */ + + // Ligature Caret List + // The Ligature Caret List table (LigCaretList) defines caret positions for all the ligatures in a font. + // Not required for mDPF + // MarkAttachmentType + if ($MarkAttachClassDef_offset) { + $this->seek($gdef_offset + $MarkAttachClassDef_offset); + $MarkAttachmentTypes = $this->_getClassDefinitionTable(); + foreach ($MarkAttachmentTypes as $class => $glyphs) { + if (is_array($Marks) && count($Marks)) { + $mat = array_diff($Marks, $MarkAttachmentTypes[$class]); + sort($mat, SORT_STRING); + } else { + $mat = []; + } + + $this->MarkAttachmentType[$class] = ' ' . implode('| ', $mat); + } + } else { + $this->MarkAttachmentType = []; + } + + // MarkGlyphSets only in Version 0x00010002 of GDEF + if ($ver_min == 2 && $MarkGlyphSetsDef_offset) { + $this->seek($gdef_offset + $MarkGlyphSetsDef_offset); + $MarkSetTableFormat = $this->read_ushort(); + $MarkSetCount = $this->read_ushort(); + $MarkSetOffset = []; + for ($i = 0; $i < $MarkSetCount; $i++) { + $MarkSetOffset[] = $this->read_ulong(); + } + for ($i = 0; $i < $MarkSetCount; $i++) { + $this->seek($MarkSetOffset[$i]); + $glyphs = $this->_getCoverage(); + $this->MarkGlyphSets[$i] = ' ' . implode('| ', $glyphs); + } + } else { + $this->MarkGlyphSets = []; + } + } else { + throw new \Mpdf\MpdfException(sprintf('Unable to set font "%s" to use OTL as it does not include OTL tables (or at least not a GDEF table).', $this->filename)); + } + + $GSUB_offset = 0; + $GPOS_offset = 0; + $GSUB_length = 0; + + $s = ''; + + if (isset($this->tables['GSUB'])) { + $GSUB_offset = $this->seek_table('GSUB'); + $GSUB_length = $this->tables['GSUB']['length']; + $s .= fread($this->fh, $this->tables['GSUB']['length']); + } + + if (isset($this->tables['GPOS'])) { + $GPOS_offset = $this->seek_table('GPOS'); + $s .= fread($this->fh, $this->tables['GPOS']['length']); + } + + if ($s) { + $this->fontCache->write($this->fontkey . '.GSUBGPOStables.dat', $s); + } + + $font = [ + 'GSUB_offset' => $GSUB_offset, + 'GPOS_offset' => $GPOS_offset, + 'GSUB_length' => $GSUB_length, + 'GlyphClassBases' => $this->GlyphClassBases, + 'GlyphClassMarks' => $this->GlyphClassMarks, + 'GlyphClassLigatures' => $this->GlyphClassLigatures, + 'GlyphClassComponents' => $this->GlyphClassComponents, + 'MarkGlyphSets' => $this->MarkGlyphSets, + 'MarkAttachmentType' => $this->MarkAttachmentType, + ]; + + $this->fontCache->jsonWrite($this->fontkey . '.GDEFdata.json', $font); + } + + function _getClassDefinitionTable() + { + // NB Any glyph not included in the range of covered GlyphIDs automatically belongs to Class 0. This is not returned by this function + $ClassFormat = $this->read_ushort(); + $GlyphByClass = []; + + if ($ClassFormat == 1) { + $StartGlyph = $this->read_ushort(); + $GlyphCount = $this->read_ushort(); + for ($i = 0; $i < $GlyphCount; $i++) { + $gid = $StartGlyph + $i; + $class = $this->read_ushort(); + // Several fonts (mainly dejavu.../Freeserif etc) have a MarkAttachClassDef Format 1, where StartGlyph is 0 and GlyphCount is 1 + // This doesn't seem to do anything useful? + // Freeserif does not have $this->glyphToChar[0] allocated and would throw an error, so check if isset: + if (isset($this->glyphToChar[$gid][0])) { + $GlyphByClass[$class][] = unicode_hex($this->glyphToChar[$gid][0]); + } + } + } elseif ($ClassFormat == 2) { + $tableCount = $this->read_ushort(); + for ($i = 0; $i < $tableCount; $i++) { + $startGlyphID = $this->read_ushort(); + $endGlyphID = $this->read_ushort(); + $class = $this->read_ushort(); + for ($gid = $startGlyphID; $gid <= $endGlyphID; $gid++) { + if (isset($this->glyphToChar[$gid][0])) { + $GlyphByClass[$class][] = unicode_hex($this->glyphToChar[$gid][0]); + } + } + } + } + foreach ($GlyphByClass as $class => $glyphs) { + sort($GlyphByClass[$class], SORT_STRING); // SORT makes it easier to read in development ? order not important ??? + } + ksort($GlyphByClass); + + return $GlyphByClass; + } + + /** + * GSUB - Glyph Substitution + */ + function _getGSUBtables() + { + if (!isset($this->tables['GSUB'])) { + return [[], [], [], '']; + } + + $ffeats = []; + $gsub_offset = $this->seek_table('GSUB'); + $this->skip(4); + $ScriptList_offset = $gsub_offset + $this->read_ushort(); + $FeatureList_offset = $gsub_offset + $this->read_ushort(); + $LookupList_offset = $gsub_offset + $this->read_ushort(); + + // ScriptList + $this->seek($ScriptList_offset); + $ScriptCount = $this->read_ushort(); + for ($i = 0; $i < $ScriptCount; $i++) { + $ScriptTag = $this->read_tag(); // = "beng", "deva" etc. + $ScriptTableOffset = $this->read_ushort(); + $ffeats[$ScriptTag] = $ScriptList_offset + $ScriptTableOffset; + } + + // Script Table + foreach ($ffeats as $t => $o) { + $ls = []; + $this->seek($o); + $DefLangSys_offset = $this->read_ushort(); + if ($DefLangSys_offset > 0) { + $ls['DFLT'] = $DefLangSys_offset + $o; + } + $LangSysCount = $this->read_ushort(); + for ($i = 0; $i < $LangSysCount; $i++) { + $LangTag = $this->read_tag(); // = + $LangTableOffset = $this->read_ushort(); + $ls[$LangTag] = $o + $LangTableOffset; + } + $ffeats[$t] = $ls; + } + + // Get FeatureIndexList + // LangSys Table - from first listed langsys + foreach ($ffeats as $st => $scripts) { + foreach ($scripts as $t => $o) { + $FeatureIndex = []; + $langsystable_offset = $o; + $this->seek($langsystable_offset); + $LookUpOrder = $this->read_ushort(); //==NULL + $ReqFeatureIndex = $this->read_ushort(); + if ($ReqFeatureIndex != 0xFFFF) { + $FeatureIndex[] = $ReqFeatureIndex; + } + $FeatureCount = $this->read_ushort(); + for ($i = 0; $i < $FeatureCount; $i++) { + $FeatureIndex[] = $this->read_ushort(); // = index of feature + } + $ffeats[$st][$t] = $FeatureIndex; + } + } + + // Feauture List => LookupListIndex es + $this->seek($FeatureList_offset); + $FeatureCount = $this->read_ushort(); + $Feature = []; + + for ($i = 0; $i < $FeatureCount; $i++) { + $tag = $this->read_tag(); + if ($tag == 'smcp') { + $this->hassmallcapsGSUB = true; + } + $Feature[$i] = ['tag' => $tag]; + $Feature[$i]['offset'] = $FeatureList_offset + $this->read_ushort(); + } + + for ($i = 0; $i < $FeatureCount; $i++) { + $this->seek($Feature[$i]['offset']); + $this->read_ushort(); // null [FeatureParams] + $Feature[$i]['LookupCount'] = $Lookupcount = $this->read_ushort(); + $Feature[$i]['LookupListIndex'] = []; + for ($c = 0; $c < $Lookupcount; $c++) { + $Feature[$i]['LookupListIndex'][] = $this->read_ushort(); + } + } + + foreach ($ffeats as $st => $scripts) { + foreach ($scripts as $t => $o) { + $FeatureIndex = $ffeats[$st][$t]; + foreach ($FeatureIndex as $k => $fi) { + $ffeats[$st][$t][$k] = $Feature[$fi]; + } + } + } + + $gsub = []; + $GSUBScriptLang = []; + foreach ($ffeats as $st => $scripts) { + foreach ($scripts as $t => $langsys) { + $lg = []; + foreach ($langsys as $ft) { + $lg[$ft['LookupListIndex'][0]] = $ft; + } + // list of Lookups in order they need to be run i.e. order listed in Lookup table + ksort($lg); + foreach ($lg as $ft) { + $gsub[$st][$t][$ft['tag']] = $ft['LookupListIndex']; + } + if (!isset($GSUBScriptLang[$st])) { + $GSUBScriptLang[$st] = ''; + } + $GSUBScriptLang[$st] .= $t . ' '; + } + } + + // Get metadata and offsets for whole Lookup List table + $this->seek($LookupList_offset); + $LookupCount = $this->read_ushort(); + $GSLookup = []; + $Offsets = []; + $SubtableCount = []; + + for ($i = 0; $i < $LookupCount; $i++) { + $Offsets[$i] = $LookupList_offset + $this->read_ushort(); + } + + for ($i = 0; $i < $LookupCount; $i++) { + + $this->seek($Offsets[$i]); + + $GSLookup[$i]['Type'] = $this->read_ushort(); + $GSLookup[$i]['Flag'] = $flag = $this->read_ushort(); + $GSLookup[$i]['SubtableCount'] = $SubtableCount[$i] = $this->read_ushort(); + + for ($c = 0; $c < $SubtableCount[$i]; $c++) { + $GSLookup[$i]['Subtables'][$c] = $Offsets[$i] + $this->read_ushort(); + } + + // MarkFilteringSet = Index (base 0) into GDEF mark glyph sets structure + if (($flag & 0x0010) == 0x0010) { + $GSLookup[$i]['MarkFilteringSet'] = $this->read_ushort(); + } else { + $GSLookup[$i]['MarkFilteringSet'] = ''; + } + + // Lookup Type 7: Extension + if ($GSLookup[$i]['Type'] == 7) { + // Overwrites new offset (32-bit) for each subtable, and a new lookup Type + for ($c = 0; $c < $SubtableCount[$i]; $c++) { + $this->seek($GSLookup[$i]['Subtables'][$c]); + $ExtensionPosFormat = $this->read_ushort(); + $type = $this->read_ushort(); + $ext_offset = $this->read_ulong(); + $GSLookup[$i]['Subtables'][$c] = $GSLookup[$i]['Subtables'][$c] + $ext_offset; + } + $GSLookup[$i]['Type'] = $type; + } + } + + // Process Whole LookupList - Get LuCoverage = Lookup coverage just for first glyph + $this->GSLuCoverage = []; + for ($i = 0; $i < $LookupCount; $i++) { + for ($c = 0; $c < $GSLookup[$i]['SubtableCount']; $c++) { + $this->seek($GSLookup[$i]['Subtables'][$c]); + $PosFormat = $this->read_ushort(); + + if ($GSLookup[$i]['Type'] == 5 && $PosFormat == 3) { + $this->skip(4); + } elseif ($GSLookup[$i]['Type'] == 6 && $PosFormat == 3) { + $BacktrackGlyphCount = $this->read_ushort(); + $this->skip(2 * $BacktrackGlyphCount + 2); + } + + // NB Coverage only looks at glyphs for position 1 (i.e. 5.3 and 6.3) // NEEDS TO READ ALL ******************** + $Coverage = $GSLookup[$i]['Subtables'][$c] + $this->read_ushort(); + $this->seek($Coverage); + $glyphs = $this->_getCoverage(false, 2); + $this->GSLuCoverage[$i][$c] = $glyphs; + } + } + + // $this->GSLuCoverage and $GSLookup + $this->fontCache->jsonWrite($this->fontkey . '.GSUBdata.json', $this->GSLuCoverage); + + // Now repeats as original to get Substitution rules + // Get metadata and offsets for whole Lookup List table + $this->seek($LookupList_offset); + $LookupCount = $this->read_ushort(); + $Lookup = []; + + for ($i = 0; $i < $LookupCount; $i++) { + $Lookup[$i]['offset'] = $LookupList_offset + $this->read_ushort(); + } + + for ($i = 0; $i < $LookupCount; $i++) { + $this->seek($Lookup[$i]['offset']); + $Lookup[$i]['Type'] = $this->read_ushort(); + $Lookup[$i]['Flag'] = $flag = $this->read_ushort(); + $Lookup[$i]['SubtableCount'] = $this->read_ushort(); + for ($c = 0; $c < $Lookup[$i]['SubtableCount']; $c++) { + $Lookup[$i]['Subtable'][$c]['Offset'] = $Lookup[$i]['offset'] + $this->read_ushort(); + } + // MarkFilteringSet = Index (base 0) into GDEF mark glyph sets structure + if (($flag & 0x0010) == 0x0010) { + $Lookup[$i]['MarkFilteringSet'] = $this->read_ushort(); + } else { + $Lookup[$i]['MarkFilteringSet'] = ''; + } + + // Lookup Type 7: Extension + if ($Lookup[$i]['Type'] == 7) { + // Overwrites new offset (32-bit) for each subtable, and a new lookup Type + for ($c = 0; $c < $Lookup[$i]['SubtableCount']; $c++) { + $this->seek($Lookup[$i]['Subtable'][$c]['Offset']); + $ExtensionPosFormat = $this->read_ushort(); + $type = $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['Offset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ulong(); + } + $Lookup[$i]['Type'] = $type; + } + } + + // Process (1) Whole LookupList + for ($i = 0; $i < $LookupCount; $i++) { + for ($c = 0; $c < $Lookup[$i]['SubtableCount']; $c++) { + $this->seek($Lookup[$i]['Subtable'][$c]['Offset']); + $SubstFormat = $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['Format'] = $SubstFormat; + + /* + Lookup['Type'] Enumeration table for glyph substitution + Value Type Description + 1 Single Replace one glyph with one glyph + 2 Multiple Replace one glyph with more than one glyph + 3 Alternate Replace one glyph with one of many glyphs + 4 Ligature Replace multiple glyphs with one glyph + 5 Context Replace one or more glyphs in context + 6 Chaining Context Replace one or more glyphs in chained context + 7 Extension Substitution Extension mechanism for other substitutions (i.e. this excludes the Extension type substitution itself) + 8 Reverse chaining context single Applied in reverse order, replace single glyph in chaining context + */ + + // LookupType 1: Single Substitution Subtable + if ($Lookup[$i]['Type'] == 1) { + $Lookup[$i]['Subtable'][$c]['CoverageTableOffset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + if ($SubstFormat == 1) { // Calculated output glyph indices + $Lookup[$i]['Subtable'][$c]['DeltaGlyphID'] = $this->read_short(); + } elseif ($SubstFormat == 2) { // Specified output glyph indices + $GlyphCount = $this->read_ushort(); + for ($g = 0; $g < $GlyphCount; $g++) { + $Lookup[$i]['Subtable'][$c]['Glyphs'][] = $this->read_ushort(); + } + } + } // LookupType 2: Multiple Substitution Subtable + elseif ($Lookup[$i]['Type'] == 2) { + $Lookup[$i]['Subtable'][$c]['CoverageTableOffset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['SequenceCount'] = $SequenceCount = $this->read_short(); + for ($s = 0; $s < $SequenceCount; $s++) { + $Lookup[$i]['Subtable'][$c]['Sequences'][$s]['Offset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_short(); + } + for ($s = 0; $s < $SequenceCount; $s++) { + // Sequence Tables + $this->seek($Lookup[$i]['Subtable'][$c]['Sequences'][$s]['Offset']); + $Lookup[$i]['Subtable'][$c]['Sequences'][$s]['GlyphCount'] = $this->read_short(); + for ($g = 0; $g < $Lookup[$i]['Subtable'][$c]['Sequences'][$s]['GlyphCount']; $g++) { + $Lookup[$i]['Subtable'][$c]['Sequences'][$s]['SubstituteGlyphID'][] = $this->read_ushort(); + } + } + } // LookupType 3: Alternate Forms + elseif ($Lookup[$i]['Type'] == 3) { + $Lookup[$i]['Subtable'][$c]['CoverageTableOffset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['AlternateSetCount'] = $AlternateSetCount = $this->read_short(); + for ($s = 0; $s < $AlternateSetCount; $s++) { + $Lookup[$i]['Subtable'][$c]['AlternateSets'][$s]['Offset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_short(); + } + + for ($s = 0; $s < $AlternateSetCount; $s++) { + // AlternateSet Tables + $this->seek($Lookup[$i]['Subtable'][$c]['AlternateSets'][$s]['Offset']); + $Lookup[$i]['Subtable'][$c]['AlternateSets'][$s]['GlyphCount'] = $this->read_short(); + for ($g = 0; $g < $Lookup[$i]['Subtable'][$c]['AlternateSets'][$s]['GlyphCount']; $g++) { + $Lookup[$i]['Subtable'][$c]['AlternateSets'][$s]['SubstituteGlyphID'][] = $this->read_ushort(); + } + } + } // LookupType 4: Ligature Substitution Subtable + elseif ($Lookup[$i]['Type'] == 4) { + $Lookup[$i]['Subtable'][$c]['CoverageTableOffset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['LigSetCount'] = $LigSetCount = $this->read_short(); + for ($s = 0; $s < $LigSetCount; $s++) { + $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['Offset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_short(); + } + for ($s = 0; $s < $LigSetCount; $s++) { + // LigatureSet Tables + $this->seek($Lookup[$i]['Subtable'][$c]['LigSet'][$s]['Offset']); + $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['LigCount'] = $this->read_short(); + for ($g = 0; $g < $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['LigCount']; $g++) { + $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['LigatureOffset'][$g] = $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['Offset'] + $this->read_ushort(); + } + } + for ($s = 0; $s < $LigSetCount; $s++) { + for ($g = 0; $g < $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['LigCount']; $g++) { + // Ligature tables + $this->seek($Lookup[$i]['Subtable'][$c]['LigSet'][$s]['LigatureOffset'][$g]); + $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['Ligature'][$g]['LigGlyph'] = $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['Ligature'][$g]['CompCount'] = $this->read_ushort(); + for ($l = 1; $l < $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['Ligature'][$g]['CompCount']; $l++) { + $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['Ligature'][$g]['GlyphID'][$l] = $this->read_ushort(); + } + } + } + } // LookupType 5: Contextual Substitution Subtable + elseif ($Lookup[$i]['Type'] == 5) { + // Format 1: Context Substitution + if ($SubstFormat == 1) { + $Lookup[$i]['Subtable'][$c]['CoverageTableOffset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['SubRuleSetCount'] = $SubRuleSetCount = $this->read_short(); + for ($s = 0; $s < $SubRuleSetCount; $s++) { + $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['Offset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_short(); + } + for ($s = 0; $s < $SubRuleSetCount; $s++) { + // SubRuleSet Tables + $this->seek($Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['Offset']); + $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRuleCount'] = $this->read_short(); + for ($g = 0; $g < $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRuleCount']; $g++) { + $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRuleOffset'][$g] = $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['Offset'] + $this->read_ushort(); + } + } + for ($s = 0; $s < $SubRuleSetCount; $s++) { + // SubRule Tables + for ($g = 0; $g < $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRuleCount']; $g++) { + // Ligature tables + $this->seek($Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRuleOffset'][$g]); + + $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRule'][$g]['GlyphCount'] = $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRule'][$g]['SubstCount'] = $this->read_ushort(); + // "Input"::[GlyphCount - 1]::Array of input GlyphIDs-start with second glyph + for ($l = 1; $l < $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRule'][$g]['GlyphCount']; $l++) { + $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRule'][$g]['Input'][$l] = $this->read_ushort(); + } + // "SubstLookupRecord"::[SubstCount]::Array of SubstLookupRecords-in design order + for ($l = 0; $l < $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRule'][$g]['SubstCount']; $l++) { + $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRule'][$g]['SubstLookupRecord'][$l]['SequenceIndex'] = $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRule'][$g]['SubstLookupRecord'][$l]['LookupListIndex'] = $this->read_ushort(); + } + } + } + } // Format 2: Class-based Context Glyph Substitution + elseif ($SubstFormat == 2) { + $Lookup[$i]['Subtable'][$c]['CoverageTableOffset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['ClassDefOffset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['SubClassSetCnt'] = $this->read_ushort(); + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['SubClassSetCnt']; $b++) { + $offset = $this->read_ushort(); + if ($offset == 0x0000) { + $Lookup[$i]['Subtable'][$c]['SubClassSetOffset'][] = 0; + } else { + $Lookup[$i]['Subtable'][$c]['SubClassSetOffset'][] = $Lookup[$i]['Subtable'][$c]['Offset'] + $offset; + } + } + } else { + throw new \Mpdf\MpdfException("GPOS Lookup Type " . $Lookup[$i]['Type'] . ", Format " . $SubstFormat . " not supported (ttfontsuni.php)."); + } + } // LookupType 6: Chaining Contextual Substitution Subtable + elseif ($Lookup[$i]['Type'] == 6) { + // Format 1: Simple Chaining Context Glyph Substitution p255 + if ($SubstFormat == 1) { + $Lookup[$i]['Subtable'][$c]['CoverageTableOffset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['ChainSubRuleSetCount'] = $this->read_ushort(); + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['ChainSubRuleSetCount']; $b++) { + $Lookup[$i]['Subtable'][$c]['ChainSubRuleSetOffset'][] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + } + } // Format 2: Class-based Chaining Context Glyph Substitution p257 + elseif ($SubstFormat == 2) { + $Lookup[$i]['Subtable'][$c]['CoverageTableOffset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['BacktrackClassDefOffset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['InputClassDefOffset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['LookaheadClassDefOffset'] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['ChainSubClassSetCnt'] = $this->read_ushort(); + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['ChainSubClassSetCnt']; $b++) { + $offset = $this->read_ushort(); + if ($offset == 0x0000) { + $Lookup[$i]['Subtable'][$c]['ChainSubClassSetOffset'][] = $offset; + } else { + $Lookup[$i]['Subtable'][$c]['ChainSubClassSetOffset'][] = $Lookup[$i]['Subtable'][$c]['Offset'] + $offset; + } + } + } // Format 3: Coverage-based Chaining Context Glyph Substitution p259 + elseif ($SubstFormat == 3) { + $Lookup[$i]['Subtable'][$c]['BacktrackGlyphCount'] = $this->read_ushort(); + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['BacktrackGlyphCount']; $b++) { + $Lookup[$i]['Subtable'][$c]['CoverageBacktrack'][] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + } + $Lookup[$i]['Subtable'][$c]['InputGlyphCount'] = $this->read_ushort(); + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['InputGlyphCount']; $b++) { + $Lookup[$i]['Subtable'][$c]['CoverageInput'][] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + } + $Lookup[$i]['Subtable'][$c]['LookaheadGlyphCount'] = $this->read_ushort(); + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['LookaheadGlyphCount']; $b++) { + $Lookup[$i]['Subtable'][$c]['CoverageLookahead'][] = $Lookup[$i]['Subtable'][$c]['Offset'] + $this->read_ushort(); + } + $Lookup[$i]['Subtable'][$c]['SubstCount'] = $this->read_ushort(); + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['SubstCount']; $b++) { + $Lookup[$i]['Subtable'][$c]['SubstLookupRecord'][$b]['SequenceIndex'] = $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['SubstLookupRecord'][$b]['LookupListIndex'] = $this->read_ushort(); + // Substitution Lookup Record + // All contextual substitution subtables specify the substitution data in a Substitution Lookup Record + // (SubstLookupRecord). Each record contains a SequenceIndex, which indicates the position where the substitution + // will occur in the glyph sequence. In addition, a LookupListIndex identifies the lookup to be applied at the + // glyph position specified by the SequenceIndex. + } + } + } else { + throw new \Mpdf\MpdfException(sprintf('Lookup Type "%s" not supported.', $Lookup[$i]['Type'])); + } + } + } + + // Process (2) Whole LookupList + // Get Coverage tables and prepare preg_replace + for ($i = 0; $i < $LookupCount; $i++) { + for ($c = 0; $c < $Lookup[$i]['SubtableCount']; $c++) { + $SubstFormat = $Lookup[$i]['Subtable'][$c]['Format']; + + // LookupType 1: Single Substitution Subtable 1 => 1 + if ($Lookup[$i]['Type'] == 1) { + $this->seek($Lookup[$i]['Subtable'][$c]['CoverageTableOffset']); + $glyphs = $this->_getCoverage(false); + for ($g = 0; $g < count($glyphs); $g++) { + $replace = []; + $substitute = []; + $replace[] = unicode_hex($this->glyphToChar[$glyphs[$g]][0]); + // Flag = Ignore + if ($this->_checkGSUBignore($Lookup[$i]['Flag'], $replace[0], $Lookup[$i]['MarkFilteringSet'])) { + continue; + } + if (isset($Lookup[$i]['Subtable'][$c]['DeltaGlyphID'])) { // Format 1 + $substitute[] = unicode_hex($this->glyphToChar[($glyphs[$g] + $Lookup[$i]['Subtable'][$c]['DeltaGlyphID'])][0]); + } else { // Format 2 + $substitute[] = unicode_hex($this->glyphToChar[($Lookup[$i]['Subtable'][$c]['Glyphs'][$g])][0]); + } + $Lookup[$i]['Subtable'][$c]['subs'][] = ['Replace' => $replace, 'substitute' => $substitute]; + } + } // LookupType 2: Multiple Substitution Subtable 1 => n + elseif ($Lookup[$i]['Type'] == 2) { + $this->seek($Lookup[$i]['Subtable'][$c]['CoverageTableOffset']); + $glyphs = $this->_getCoverage(); + for ($g = 0; $g < count($glyphs); $g++) { + $replace = []; + $substitute = []; + $replace[] = $glyphs[$g]; + // Flag = Ignore + if ($this->_checkGSUBignore($Lookup[$i]['Flag'], $replace[0], $Lookup[$i]['MarkFilteringSet'])) { + continue; + } + if (!isset($Lookup[$i]['Subtable'][$c]['Sequences'][$g]['SubstituteGlyphID']) || count($Lookup[$i]['Subtable'][$c]['Sequences'][$g]['SubstituteGlyphID']) == 0) { + continue; + } // Illegal for GlyphCount to be 0; either error in font, or something has gone wrong - lets carry on for now! + foreach ($Lookup[$i]['Subtable'][$c]['Sequences'][$g]['SubstituteGlyphID'] as $sub) { + $substitute[] = unicode_hex($this->glyphToChar[$sub][0]); + } + $Lookup[$i]['Subtable'][$c]['subs'][] = ['Replace' => $replace, 'substitute' => $substitute]; + } + } // LookupType 3: Alternate Forms 1 => 1 (only first alternate form is used) + elseif ($Lookup[$i]['Type'] == 3) { + $this->seek($Lookup[$i]['Subtable'][$c]['CoverageTableOffset']); + $glyphs = $this->_getCoverage(); + for ($g = 0; $g < count($glyphs); $g++) { + $replace = []; + $substitute = []; + $replace[] = $glyphs[$g]; + // Flag = Ignore + if ($this->_checkGSUBignore($Lookup[$i]['Flag'], $replace[0], $Lookup[$i]['MarkFilteringSet'])) { + continue; + } + $gid = $Lookup[$i]['Subtable'][$c]['AlternateSets'][$g]['SubstituteGlyphID'][0]; + if (!isset($this->glyphToChar[$gid][0])) { + continue; + } + $substitute[] = unicode_hex($this->glyphToChar[$gid][0]); + $Lookup[$i]['Subtable'][$c]['subs'][] = ['Replace' => $replace, 'substitute' => $substitute]; + } + } // LookupType 4: Ligature Substitution Subtable n => 1 + elseif ($Lookup[$i]['Type'] == 4) { + $this->seek($Lookup[$i]['Subtable'][$c]['CoverageTableOffset']); + $glyphs = $this->_getCoverage(); + $LigSetCount = $Lookup[$i]['Subtable'][$c]['LigSetCount']; + for ($s = 0; $s < $LigSetCount; $s++) { + for ($g = 0; $g < $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['LigCount']; $g++) { + $replace = []; + $substitute = []; + $replace[] = $glyphs[$s]; + // Flag = Ignore + if ($this->_checkGSUBignore($Lookup[$i]['Flag'], $replace[0], $Lookup[$i]['MarkFilteringSet'])) { + continue; + } + for ($l = 1; $l < $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['Ligature'][$g]['CompCount']; $l++) { + $gid = $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['Ligature'][$g]['GlyphID'][$l]; + $rpl = unicode_hex($this->glyphToChar[$gid][0]); + // Flag = Ignore + if ($this->_checkGSUBignore($Lookup[$i]['Flag'], $rpl, $Lookup[$i]['MarkFilteringSet'])) { + continue 2; + } + $replace[] = $rpl; + } + $gid = $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['Ligature'][$g]['LigGlyph']; + if (!isset($this->glyphToChar[$gid][0])) { + continue; + } + $substitute[] = unicode_hex($this->glyphToChar[$gid][0]); + $Lookup[$i]['Subtable'][$c]['subs'][] = ['Replace' => $replace, 'substitute' => $substitute, 'CompCount' => $Lookup[$i]['Subtable'][$c]['LigSet'][$s]['Ligature'][$g]['CompCount']]; + } + } + } // LookupType 5: Contextual Substitution Subtable + elseif ($Lookup[$i]['Type'] == 5) { + // Format 1: Context Substitution + if ($SubstFormat == 1) { + $this->seek($Lookup[$i]['Subtable'][$c]['CoverageTableOffset']); + $Lookup[$i]['Subtable'][$c]['CoverageGlyphs'] = $CoverageGlyphs = $this->_getCoverage(); + + for ($s = 0; $s < $Lookup[$i]['Subtable'][$c]['SubRuleSetCount']; $s++) { + $SubRuleSet = $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]; + $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['FirstGlyph'] = $CoverageGlyphs[$s]; + for ($r = 0; $r < $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRuleCount']; $r++) { + $GlyphCount = $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRule'][$r]['GlyphCount']; + for ($g = 1; $g < $GlyphCount; $g++) { + $glyphID = $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRule'][$r]['Input'][$g]; + $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRule'][$r]['InputGlyphs'][$g] = unicode_hex($this->glyphToChar[$glyphID][0]); + } + } + } + } // Format 2: Class-based Context Glyph Substitution + elseif ($SubstFormat == 2) { + $this->seek($Lookup[$i]['Subtable'][$c]['CoverageTableOffset']); + $Lookup[$i]['Subtable'][$c]['CoverageGlyphs'] = $CoverageGlyphs = $this->_getCoverage(); + + $InputClasses = $this->_getClasses($Lookup[$i]['Subtable'][$c]['ClassDefOffset']); + $Lookup[$i]['Subtable'][$c]['InputClasses'] = $InputClasses; + for ($s = 0; $s < $Lookup[$i]['Subtable'][$c]['SubClassSetCnt']; $s++) { + if ($Lookup[$i]['Subtable'][$c]['SubClassSetOffset'][$s] > 0) { + $this->seek($Lookup[$i]['Subtable'][$c]['SubClassSetOffset'][$s]); + $Lookup[$i]['Subtable'][$c]['SubClassSet'][$s]['SubClassRuleCnt'] = $SubClassRuleCnt = $this->read_ushort(); + $SubClassRule = []; + for ($b = 0; $b < $SubClassRuleCnt; $b++) { + $SubClassRule[$b] = $Lookup[$i]['Subtable'][$c]['SubClassSetOffset'][$s] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['SubClassSet'][$s]['SubClassRule'][$b] = $SubClassRule[$b]; + } + } + } + + for ($s = 0; $s < $Lookup[$i]['Subtable'][$c]['SubClassSetCnt']; $s++) { + if ($Lookup[$i]['Subtable'][$c]['SubClassSetOffset'][$s] > 0) { + $SubClassRuleCnt = $Lookup[$i]['Subtable'][$c]['SubClassSet'][$s]['SubClassRuleCnt']; + for ($b = 0; $b < $SubClassRuleCnt; $b++) { + $this->seek($Lookup[$i]['Subtable'][$c]['SubClassSet'][$s]['SubClassRule'][$b]); + $Rule = []; + $Rule['InputGlyphCount'] = $this->read_ushort(); + $Rule['SubstCount'] = $this->read_ushort(); + for ($r = 1; $r < $Rule['InputGlyphCount']; $r++) { + $Rule['Input'][$r] = $this->read_ushort(); + } + for ($r = 0; $r < $Rule['SubstCount']; $r++) { + $Rule['SequenceIndex'][$r] = $this->read_ushort(); + $Rule['LookupListIndex'][$r] = $this->read_ushort(); + } + + $Lookup[$i]['Subtable'][$c]['SubClassSet'][$s]['SubClassRule'][$b] = $Rule; + } + } + } + } // Format 3: Coverage-based Context Glyph Substitution + elseif ($SubstFormat == 3) { + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['InputGlyphCount']; $b++) { + $this->seek($Lookup[$i]['Subtable'][$c]['CoverageInput'][$b]); + $glyphs = $this->_getCoverage(); + $Lookup[$i]['Subtable'][$c]['CoverageInputGlyphs'][] = implode("|", $glyphs); + } + throw new \Mpdf\MpdfException("Lookup Type 5, SubstFormat 3 not tested. Please report this with the name of font used - " . $this->fontkey); + } + } // LookupType 6: Chaining Contextual Substitution Subtable + elseif ($Lookup[$i]['Type'] == 6) { + // Format 1: Simple Chaining Context Glyph Substitution p255 + if ($SubstFormat == 1) { + $this->seek($Lookup[$i]['Subtable'][$c]['CoverageTableOffset']); + $Lookup[$i]['Subtable'][$c]['CoverageGlyphs'] = $CoverageGlyphs = $this->_getCoverage(); + + $ChainSubRuleSetCnt = $Lookup[$i]['Subtable'][$c]['ChainSubRuleSetCount']; + + for ($s = 0; $s < $ChainSubRuleSetCnt; $s++) { + $this->seek($Lookup[$i]['Subtable'][$c]['ChainSubRuleSetOffset'][$s]); + $ChainSubRuleCnt = $Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRuleCount'] = $this->read_ushort(); + for ($r = 0; $r < $ChainSubRuleCnt; $r++) { + $Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRuleOffset'][$r] = $Lookup[$i]['Subtable'][$c]['ChainSubRuleSetOffset'][$s] + $this->read_ushort(); + } + } + for ($s = 0; $s < $ChainSubRuleSetCnt; $s++) { + $ChainSubRuleCnt = $Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRuleCount']; + for ($r = 0; $r < $ChainSubRuleCnt; $r++) { + // ChainSubRule + $this->seek($Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRuleOffset'][$r]); + + $BacktrackGlyphCount = $Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRule'][$r]['BacktrackGlyphCount'] = $this->read_ushort(); + for ($g = 0; $g < $BacktrackGlyphCount; $g++) { + $glyphID = $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRule'][$r]['BacktrackGlyphs'][$g] = unicode_hex($this->glyphToChar[$glyphID][0]); + } + + $InputGlyphCount = $Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRule'][$r]['InputGlyphCount'] = $this->read_ushort(); + for ($g = 1; $g < $InputGlyphCount; $g++) { + $glyphID = $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRule'][$r]['InputGlyphs'][$g] = unicode_hex($this->glyphToChar[$glyphID][0]); + } + + $LookaheadGlyphCount = $Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRule'][$r]['LookaheadGlyphCount'] = $this->read_ushort(); + for ($g = 0; $g < $LookaheadGlyphCount; $g++) { + $glyphID = $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRule'][$r]['LookaheadGlyphs'][$g] = unicode_hex($this->glyphToChar[$glyphID][0]); + } + + $SubstCount = $Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRule'][$r]['SubstCount'] = $this->read_ushort(); + for ($lu = 0; $lu < $SubstCount; $lu++) { + $Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRule'][$r]['SequenceIndex'][$lu] = $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRule'][$r]['LookupListIndex'][$lu] = $this->read_ushort(); + } + } + } + } // Format 2: Class-based Chaining Context Glyph Substitution p257 + elseif ($SubstFormat == 2) { + $this->seek($Lookup[$i]['Subtable'][$c]['CoverageTableOffset']); + $Lookup[$i]['Subtable'][$c]['CoverageGlyphs'] = $CoverageGlyphs = $this->_getCoverage(); + + $BacktrackClasses = $this->_getClasses($Lookup[$i]['Subtable'][$c]['BacktrackClassDefOffset']); + $Lookup[$i]['Subtable'][$c]['BacktrackClasses'] = $BacktrackClasses; + + $InputClasses = $this->_getClasses($Lookup[$i]['Subtable'][$c]['InputClassDefOffset']); + $Lookup[$i]['Subtable'][$c]['InputClasses'] = $InputClasses; + + $LookaheadClasses = $this->_getClasses($Lookup[$i]['Subtable'][$c]['LookaheadClassDefOffset']); + $Lookup[$i]['Subtable'][$c]['LookaheadClasses'] = $LookaheadClasses; + + for ($s = 0; $s < $Lookup[$i]['Subtable'][$c]['ChainSubClassSetCnt']; $s++) { + if ($Lookup[$i]['Subtable'][$c]['ChainSubClassSetOffset'][$s] > 0) { + $this->seek($Lookup[$i]['Subtable'][$c]['ChainSubClassSetOffset'][$s]); + $Lookup[$i]['Subtable'][$c]['ChainSubClassSet'][$s]['ChainSubClassRuleCnt'] = $ChainSubClassRuleCnt = $this->read_ushort(); + $ChainSubClassRule = []; + for ($b = 0; $b < $ChainSubClassRuleCnt; $b++) { + $ChainSubClassRule[$b] = $Lookup[$i]['Subtable'][$c]['ChainSubClassSetOffset'][$s] + $this->read_ushort(); + $Lookup[$i]['Subtable'][$c]['ChainSubClassSet'][$s]['ChainSubClassRule'][$b] = $ChainSubClassRule[$b]; + } + } + } + + for ($s = 0; $s < $Lookup[$i]['Subtable'][$c]['ChainSubClassSetCnt']; $s++) { + if (isset($Lookup[$i]['Subtable'][$c]['ChainSubClassSet'][$s]['ChainSubClassRuleCnt'])) { + $ChainSubClassRuleCnt = $Lookup[$i]['Subtable'][$c]['ChainSubClassSet'][$s]['ChainSubClassRuleCnt']; + } else { + $ChainSubClassRuleCnt = 0; + } + for ($b = 0; $b < $ChainSubClassRuleCnt; $b++) { + if ($Lookup[$i]['Subtable'][$c]['ChainSubClassSetOffset'][$s] > 0) { + $this->seek($Lookup[$i]['Subtable'][$c]['ChainSubClassSet'][$s]['ChainSubClassRule'][$b]); + $Rule = []; + $Rule['BacktrackGlyphCount'] = $this->read_ushort(); + for ($r = 0; $r < $Rule['BacktrackGlyphCount']; $r++) { + $Rule['Backtrack'][$r] = $this->read_ushort(); + } + $Rule['InputGlyphCount'] = $this->read_ushort(); + for ($r = 1; $r < $Rule['InputGlyphCount']; $r++) { + $Rule['Input'][$r] = $this->read_ushort(); + } + $Rule['LookaheadGlyphCount'] = $this->read_ushort(); + for ($r = 0; $r < $Rule['LookaheadGlyphCount']; $r++) { + $Rule['Lookahead'][$r] = $this->read_ushort(); + } + $Rule['SubstCount'] = $this->read_ushort(); + for ($r = 0; $r < $Rule['SubstCount']; $r++) { + $Rule['SequenceIndex'][$r] = $this->read_ushort(); + $Rule['LookupListIndex'][$r] = $this->read_ushort(); + } + + $Lookup[$i]['Subtable'][$c]['ChainSubClassSet'][$s]['ChainSubClassRule'][$b] = $Rule; + } + } + } + } // Format 3: Coverage-based Chaining Context Glyph Substitution p259 + elseif ($SubstFormat == 3) { + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['BacktrackGlyphCount']; $b++) { + $this->seek($Lookup[$i]['Subtable'][$c]['CoverageBacktrack'][$b]); + $glyphs = $this->_getCoverage(); + $Lookup[$i]['Subtable'][$c]['CoverageBacktrackGlyphs'][] = implode("|", $glyphs); + } + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['InputGlyphCount']; $b++) { + $this->seek($Lookup[$i]['Subtable'][$c]['CoverageInput'][$b]); + $glyphs = $this->_getCoverage(); + $Lookup[$i]['Subtable'][$c]['CoverageInputGlyphs'][] = implode("|", $glyphs); + // Don't use above value as these are ordered numerically not as need to process + } + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['LookaheadGlyphCount']; $b++) { + $this->seek($Lookup[$i]['Subtable'][$c]['CoverageLookahead'][$b]); + $glyphs = $this->_getCoverage(); + $Lookup[$i]['Subtable'][$c]['CoverageLookaheadGlyphs'][] = implode("|", $glyphs); + } + } + } + } + } + + $GSUBScriptLang = []; + $rtlpua = []; // All glyphs added to PUA [for magic_reverse] + foreach ($gsub as $st => $scripts) { + foreach ($scripts as $t => $langsys) { + $lul = []; // array of LookupListIndexes + $tags = []; // corresponding array of feature tags e.g. 'ccmp' + + foreach ($langsys as $tag => $ft) { + foreach ($ft as $ll) { + $lul[$ll] = $tag; + } + } + ksort($lul); // Order the Lookups in the order they are in the GUSB table, regardless of Feature order + $volt = $this->_getGSUBarray($Lookup, $lul, $st); + + // Interrogate $volt + // isol, fin, medi, init(arab syrc) into $rtlSUB for use in ArabJoin + // but also identify all RTL chars in PUA for magic_reverse (arab syrc hebr thaa nko samr) + // identify reph, matras, vatu, half forms etc for Indic for final re-ordering + $rtl = []; + $rtlSUB = []; + $finals = ''; + + if (strpos('arab syrc hebr thaa nko samr', $st) !== false) { // all RTL scripts [any/all languages] ? Mandaic + + foreach ($volt as $v) { + // isol fina fin2 fin3 medi med2 for Syriac + // ISOLATED FORM :: FINAL :: INITIAL :: MEDIAL :: MED2 :: FIN2 :: FIN3 + if (strpos('isol fina init medi fin2 fin3 med2', $v['tag']) !== false) { + + $key = $v['match']; + $key = preg_replace('/[\(\)]*/', '', $key); + $sub = $v['replace']; + if ($v['tag'] === 'isol') { + $kk = 0; + } elseif ($v['tag'] === 'fina') { + $kk = 1; + } elseif ($v['tag'] === 'init') { + $kk = 2; + } elseif ($v['tag'] === 'medi') { + $kk = 3; + } elseif ($v['tag'] === 'med2') { + $kk = 4; + } elseif ($v['tag'] === 'fin2') { + $kk = 5; + } elseif ($v['tag'] === 'fin3') { + $kk = 6; + } + + $rtl[$key][$kk] = $sub; + if (isset($v['prel']) && count($v['prel'])) { + $rtl[$key]['prel'][$kk] = $v['prel']; + } + if (isset($v['postl']) && count($v['postl'])) { + $rtl[$key]['postl'][$kk] = $v['postl']; + } + if (isset($v['ignore']) && $v['ignore']) { + $rtl[$key]['ignore'][$kk] = $v['ignore']; + } + $rtlpua[] = $sub; + + } else { // Add any other glyphs which are in PUA + if (isset($v['context']) && $v['context']) { + foreach ($v['rules'] as $vs) { + $matchCount = count($vs['match']); + for ($i = 0; $i < $matchCount; $i++) { + if (isset($vs['replace'][$i]) && preg_match('/^0[A-F0-9]{4}$/', $vs['match'][$i])) { + if (preg_match('/^0[EF][A-F0-9]{3}$/', $vs['replace'][$i])) { + $rtlpua[] = $vs['replace'][$i]; + } + } + } + } + } else { + preg_match_all('/\((0[A-F0-9]{4})\)/', $v['match'], $m); + $matchCount = count($m[0]); + for ($i = 0; $i < $matchCount; $i++) { + $sb = explode(' ', $v['replace']); + foreach ($sb as $sbg) { + if (preg_match('/(0[EF][A-F0-9]{3})/', $sbg, $mr)) { + $rtlpua[] = $mr[1]; + } + } + } + } + } + } + + // For kashida, need to determine all final forms except ones already identified by kashida priority rules (see \Mpdf\Otl) + foreach ($rtl as $base => $variants) { + if (isset($variants[1])) { // i.e. final form + if (strpos('0FE8E 0FE94 0FEA2 0FEAA 0FEAE 0FEC2 0FEDA 0FEDE 0FB93 0FECA 0FED2 0FED6 0FEEE 0FEF0 0FEF2', $variants[1]) === false) { // not already included + // This version does not exclude RA (0631) FEAE; Ya (064A) FEF2; Alef Maqsurah (0649) FEF0 which + // are selected in priority if connected to a medial Bah + //if (strpos('0FE8E 0FE94 0FEA2 0FEAA 0FEC2 0FEDA 0FEDE 0FB93 0FECA 0FED2 0FED6 0FEEE', $variants[1])===false) { // not already included + $finals .= $variants[1] . ' '; + } + } + } + + ksort($rtl); + $rtlSUB = $rtl; + } + + // INDIC - Dynamic properties + $rphf = []; + $half = []; + $pref = []; + $blwf = []; + $pstf = []; + + if (strpos('dev2 bng2 gur2 gjr2 ory2 tml2 tel2 knd2 mlm2 deva beng guru gujr orya taml telu knda mlym', $st) !== false) { // all INDIC scripts [any/all languages] + if (strpos('deva beng guru gujr orya taml telu knda mlym', $st) !== false) { + $is_old_spec = true; + } else { + $is_old_spec = false; + } + + // First get 'locl' substitutions (reversed!) + $loclsubs = []; + foreach ($volt as $v) { + if (strpos('locl', $v['tag']) !== false) { + $key = $v['match']; + $key = preg_replace('/[\(\)]*/', '', $key); + $sub = $v['replace']; + if ($key && strlen(trim($key)) == 5 && $sub) { + $loclsubs[$sub] = $key; + } + } + } + + foreach ($volt as $v) { + // <rphf> <half> <pref> <blwf> <pstf> + // defines consonant types: + // Reph <rphf> + // Half forms <half> + // Pre-base-reordering forms of Ra/Rra <pref> + // Below-base forms <blwf> + // Post-base forms <pstf> + // applied together with <locl> feature to input sequences consisting of two characters + // This is done for each consonant + // for <rphf> and <half>, features are applied to Consonant + Halant combinations + // for <pref>, <blwf> and <pstf>, features are applied to Halant + Consonant combinations + // Old version eg 'deva' <pref>, <blwf> and <pstf>, features are applied to Consonant + Halant + // Some malformed fonts still do Consonant + Halant for these - so match both?? + // If these two glyphs form a ligature, with no additional glyphs in context + // this means the consonant has the corresponding form + // Currently set to cope with both + // See also classes/otl.php + + if (strpos('rphf half pref blwf pstf', $v['tag']) !== false) { + if (isset($v['context']) && $v['context'] && $v['nBacktrack'] == 0 && $v['nLookahead'] == 0) { + foreach ($v['rules'] as $vs) { + if (count($vs['match']) == 2 && count($vs['replace']) == 1) { + $sub = $vs['replace'][0]; + // If Halant Cons <pref>, <blwf> and <pstf> in New version only + if (strpos('0094D 009CD 00A4D 00ACD 00B4D 00BCD 00C4D 00CCD 00D4D', $vs['match'][0]) !== false && strpos('pref blwf pstf', $v['tag']) !== false && !$is_old_spec) { + $key = $vs['match'][1]; + $tag = $v['tag']; + if (isset($loclsubs[$key])) { + ${$tag[$loclsubs[$key]]} = $sub; + } + $tmp = &$$tag; + $tmp[hexdec($key)] = hexdec($sub); + } // If Cons Halant <rphf> and <half> always + // and <pref>, <blwf> and <pstf> in Old version + elseif (strpos('0094D 009CD 00A4D 00ACD 00B4D 00BCD 00C4D 00CCD 00D4D', $vs['match'][1]) !== false && (strpos('rphf half', $v['tag']) !== false || (strpos('pref blwf pstf', $v['tag']) !== false && ($is_old_spec || _OTL_OLD_SPEC_COMPAT_2)))) { + $key = $vs['match'][0]; + $tag = $v['tag']; + if (isset($loclsubs[$key])) { + ${$tag[$loclsubs[$key]]} = $sub; + } + $tmp = &$$tag; + $tmp[hexdec($key)] = hexdec($sub); + } + } + } + } elseif (!isset($v['context'])) { + $key = $v['match']; + $key = preg_replace('/[\(\)]*/', '', $key); + $sub = $v['replace']; + if ($key && strlen(trim($key)) == 11 && $sub) { + // If Cons Halant <rphf> and <half> always + // and <pref>, <blwf> and <pstf> in Old version + // If Halant Cons <pref>, <blwf> and <pstf> in New version only + if (strpos('0094D 009CD 00A4D 00ACD 00B4D 00BCD 00C4D 00CCD 00D4D', substr($key, 0, 5)) !== false && strpos('pref blwf pstf', $v['tag']) !== false && !$is_old_spec) { + $key = substr($key, 6, 5); + $tag = $v['tag']; + if (isset($loclsubs[$key])) { + ${$tag[$loclsubs[$key]]} = $sub; + } + $tmp = &$$tag; + $tmp[hexdec($key)] = hexdec($sub); + } elseif (strpos('0094D 009CD 00A4D 00ACD 00B4D 00BCD 00C4D 00CCD 00D4D', substr($key, 6, 5)) !== false && (strpos('rphf half', $v['tag']) !== false || (strpos('pref blwf pstf', $v['tag']) !== false && ($is_old_spec || _OTL_OLD_SPEC_COMPAT_2)))) { + $key = substr($key, 0, 5); + $tag = $v['tag']; + if (isset($loclsubs[$key])) { + ${$tag[$loclsubs[$key]]} = $sub; + } + $tmp = &$$tag; + $tmp[hexdec($key)] = hexdec($sub); + } + } + } + } + } + } + + if (count($rtl) || count($rphf) || count($half) || count($pref) || count($blwf) || count($pstf) || $finals) { + $font = [ + 'rtlSUB' => $rtlSUB, + 'finals' => $finals, + 'rphf' => $rphf, + 'half' => $half, + 'pref' => $pref, + 'blwf' => $blwf, + 'pstf' => $pstf, + ]; + + $this->fontCache->jsonWrite($this->fontkey . '.GSUB.' . $st . '.' . $t . '.json', $font); + } + + if (!isset($GSUBScriptLang[$st])) { + $GSUBScriptLang[$st] = ''; + } + $GSUBScriptLang[$st] .= $t . ' '; + } + } + + // All RTL glyphs from font added to (or already in) PUA [reqd for magic_reverse] + $rtlPUAstr = ''; + if (count($rtlpua)) { + $rtlpua = array_unique($rtlpua); + sort($rtlpua); + $n = count($rtlpua); + for ($i = 0; $i < $n; $i++) { + if (hexdec($rtlpua[$i]) < hexdec('E000') || hexdec($rtlpua[$i]) > hexdec('F8FF')) { + unset($rtlpua[$i]); + } + } + sort($rtlpua, SORT_STRING); + + $rangeid = -1; + $range = []; + $prevgid = -2; + + // for each character + foreach ($rtlpua as $gidhex) { + $gid = hexdec($gidhex); + if ($gid == ($prevgid + 1)) { + $range[$rangeid]['end'] = $gidhex; + $range[$rangeid]['count']++; + } else { + // new range + $rangeid++; + $range[$rangeid] = []; + $range[$rangeid]['start'] = $gidhex; + $range[$rangeid]['end'] = $gidhex; + $range[$rangeid]['count'] = 1; + } + $prevgid = $gid; + } + + foreach ($range as $rg) { + if ($rg['count'] == 1) { + $rtlPUAstr .= "\x{" . $rg['start'] . "}"; + } elseif ($rg['count'] == 2) { + $rtlPUAstr .= "\x{" . $rg['start'] . "}\x{" . $rg['end'] . "}"; + } else { + $rtlPUAstr .= "\x{" . $rg['start'] . "}-\x{" . $rg['end'] . "}"; + } + } + } + + return [$GSUBScriptLang, $gsub, $GSLookup, $rtlPUAstr]; + } + + // GSUB functions + function _getGSUBarray(&$Lookup, &$lul, $scripttag) + { + // Process (3) LookupList for specific Script-LangSys + // Generate preg_replace + $volt = []; + $reph = ''; + $matraE = ''; + $vatu = ''; + + foreach ($lul as $i => $tag) { + for ($c = 0; $c < $Lookup[$i]['SubtableCount']; $c++) { + $SubstFormat = $Lookup[$i]['Subtable'][$c]['Format']; + + // LookupType 1: Single Substitution Subtable + if ($Lookup[$i]['Type'] == 1) { + $subCount = count($Lookup[$i]['Subtable'][$c]['subs']); + for ($s = 0; $s < $subCount; $s++) { + $inputGlyphs = $Lookup[$i]['Subtable'][$c]['subs'][$s]['Replace']; + $substitute = $Lookup[$i]['Subtable'][$c]['subs'][$s]['substitute'][0]; + // Ignore has already been applied earlier on + $repl = $this->_makeGSUBinputMatch($inputGlyphs, "()"); + $subs = $this->_makeGSUBinputReplacement(1, $substitute, "()", 0, 1, 0); + $volt[] = ['match' => $repl, 'replace' => $subs, 'tag' => $tag, 'key' => $inputGlyphs[0], 'type' => 1]; + } + } // LookupType 2: Multiple Substitution Subtable + elseif ($Lookup[$i]['Type'] == 2) { + for ($s = 0; $s < count($Lookup[$i]['Subtable'][$c]['subs']); $s++) { + $inputGlyphs = $Lookup[$i]['Subtable'][$c]['subs'][$s]['Replace']; + $substitute = implode(" ", $Lookup[$i]['Subtable'][$c]['subs'][$s]['substitute']); + // Ignore has already been applied earlier on + $repl = $this->_makeGSUBinputMatch($inputGlyphs, "()"); + $subs = $this->_makeGSUBinputReplacement(1, $substitute, "()", 0, 1, 0); + $volt[] = ['match' => $repl, 'replace' => $subs, 'tag' => $tag, 'key' => $inputGlyphs[0], 'type' => 2]; + } + } // LookupType 3: Alternate Forms + elseif ($Lookup[$i]['Type'] == 3) { + for ($s = 0; $s < count($Lookup[$i]['Subtable'][$c]['subs']); $s++) { + $inputGlyphs = $Lookup[$i]['Subtable'][$c]['subs'][$s]['Replace']; + $substitute = $Lookup[$i]['Subtable'][$c]['subs'][$s]['substitute'][0]; + // Ignore has already been applied earlier on + $repl = $this->_makeGSUBinputMatch($inputGlyphs, "()"); + $subs = $this->_makeGSUBinputReplacement(1, $substitute, "()", 0, 1, 0); + $volt[] = ['match' => $repl, 'replace' => $subs, 'tag' => $tag, 'key' => $inputGlyphs[0], 'type' => 3]; + } + } // LookupType 4: Ligature Substitution Subtable + elseif ($Lookup[$i]['Type'] == 4) { + for ($s = 0; $s < count($Lookup[$i]['Subtable'][$c]['subs']); $s++) { + $inputGlyphs = $Lookup[$i]['Subtable'][$c]['subs'][$s]['Replace']; + $substitute = $Lookup[$i]['Subtable'][$c]['subs'][$s]['substitute'][0]; + // Ignore has already been applied earlier on + $ignore = $this->_getGSUBignoreString($Lookup[$i]['Flag'], $Lookup[$i]['MarkFilteringSet']); + $repl = $this->_makeGSUBinputMatch($inputGlyphs, $ignore); + $subs = $this->_makeGSUBinputReplacement(count($inputGlyphs), $substitute, $ignore, 0, count($inputGlyphs), 0); + $volt[] = ['match' => $repl, 'replace' => $subs, 'tag' => $tag, 'key' => $inputGlyphs[0], 'type' => 4, 'CompCount' => $Lookup[$i]['Subtable'][$c]['subs'][$s]['CompCount'], 'Lig' => $substitute]; + } + } // LookupType 5: Chaining Contextual Substitution Subtable + elseif ($Lookup[$i]['Type'] == 5) { + // Format 1: Context Substitution + if ($SubstFormat == 1) { + $ignore = $this->_getGSUBignoreString($Lookup[$i]['Flag'], $Lookup[$i]['MarkFilteringSet']); + for ($s = 0; $s < $Lookup[$i]['Subtable'][$c]['SubRuleSetCount']; $s++) { + // SubRuleSet + $subRule = []; + foreach ($Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['SubRule'] as $rule) { + // SubRule + $inputGlyphs = []; + if ($rule['GlyphCount'] > 1) { + $inputGlyphs = $rule['InputGlyphs']; + } + $inputGlyphs[0] = $Lookup[$i]['Subtable'][$c]['SubRuleSet'][$s]['FirstGlyph']; + ksort($inputGlyphs); + $nInput = count($inputGlyphs); + + $contextInputMatch = $this->_makeGSUBcontextInputMatch($inputGlyphs, $ignore, [], 0); + $subRule = ['context' => 1, 'tag' => $tag, 'matchback' => '', 'match' => $contextInputMatch, 'nBacktrack' => 0, 'nInput' => $nInput, 'nLookahead' => 0, 'rules' => [],]; + + for ($b = 0; $b < $rule['SubstCount']; $b++) { + $lup = $rule['SubstLookupRecord'][$b]['LookupListIndex']; + $seqIndex = $rule['SubstLookupRecord'][$b]['SequenceIndex']; + + // $Lookup[$lup] = secondary Lookup + for ($lus = 0; $lus < $Lookup[$lup]['SubtableCount']; $lus++) { + if (count($Lookup[$lup]['Subtable'][$lus]['subs'])) { + foreach ($Lookup[$lup]['Subtable'][$lus]['subs'] as $luss) { + $lookupGlyphs = $luss['Replace']; + $mLen = count($lookupGlyphs); + + // Only apply if the (first) 'Replace' glyph from the + // Lookup list is in the [inputGlyphs] at ['SequenceIndex'] + // then apply the substitution + if (strpos($inputGlyphs[$seqIndex], $lookupGlyphs[0]) === false) { + continue; + } + $REPL = implode(" ", $luss['substitute']); + if (strpos("isol fina fin2 fin3 medi med2 init ", $tag) !== false && $scripttag == 'arab') { + $volt[] = ['match' => $lookupGlyphs[0], 'replace' => $REPL, 'tag' => $tag, 'prel' => $backtrackGlyphs, 'postl' => $lookaheadGlyphs, 'ignore' => $ignore]; + } else { + $subRule['rules'][] = ['type' => $Lookup[$lup]['Type'], 'match' => $lookupGlyphs, 'replace' => $luss['substitute'], 'seqIndex' => $seqIndex, 'key' => $lookupGlyphs[0],]; + } + } + } + } + } + + if (count($subRule['rules'])) { + $volt[] = $subRule; + } + } + } + } // Format 2: Class-based Context Glyph Substitution + elseif ($SubstFormat == 2) { + $ignore = $this->_getGSUBignoreString($Lookup[$i]['Flag'], $Lookup[$i]['MarkFilteringSet']); + foreach ($Lookup[$i]['Subtable'][$c]['SubClassSet'] as $inputClass => $cscs) { + for ($cscrule = 0; $cscrule < $cscs['SubClassRuleCnt']; $cscrule++) { + $rule = $cscs['SubClassRule'][$cscrule]; + + $inputGlyphs = []; + + $inputGlyphs[0] = $Lookup[$i]['Subtable'][$c]['InputClasses'][$inputClass]; + if ($rule['InputGlyphCount'] > 1) { + // NB starts at 1 + for ($gcl = 1; $gcl < $rule['InputGlyphCount']; $gcl++) { + $classindex = $rule['Input'][$gcl]; + if (isset($Lookup[$i]['Subtable'][$c]['InputClasses'][$classindex])) { + $inputGlyphs[$gcl] = $Lookup[$i]['Subtable'][$c]['InputClasses'][$classindex]; + } // if class[0] = all glyphs excluding those specified in all other classes + // set to blank '' for now + else { + $inputGlyphs[$gcl] = ''; + } + } + } + + $nInput = $rule['InputGlyphCount']; + $nIsubs = (2 * $nInput) - 1; + + $contextInputMatch = $this->_makeGSUBcontextInputMatch($inputGlyphs, $ignore, [], 0); + $subRule = ['context' => 1, 'tag' => $tag, 'matchback' => '', 'match' => $contextInputMatch, 'nBacktrack' => 0, 'nInput' => $nInput, 'nLookahead' => 0, 'rules' => [],]; + + for ($b = 0; $b < $rule['SubstCount']; $b++) { + $lup = $rule['LookupListIndex'][$b]; + $seqIndex = $rule['SequenceIndex'][$b]; + + // $Lookup[$lup] = secondary Lookup + for ($lus = 0; $lus < $Lookup[$lup]['SubtableCount']; $lus++) { + if (isset($Lookup[$lup]['Subtable'][$lus]['subs']) && count($Lookup[$lup]['Subtable'][$lus]['subs'])) { + foreach ($Lookup[$lup]['Subtable'][$lus]['subs'] as $luss) { + $lookupGlyphs = $luss['Replace']; + $mLen = count($lookupGlyphs); + + // Only apply if the (first) 'Replace' glyph from the + // Lookup list is in the [inputGlyphs] at ['SequenceIndex'] + // then apply the substitution + if (strpos($inputGlyphs[$seqIndex], $lookupGlyphs[0]) === false) { + continue; + } + + // Returns e.g. ¦(0612)¦(ignore) (0613)¦(ignore) (0614)¦ + $contextInputMatch = $this->_makeGSUBcontextInputMatch($inputGlyphs, $ignore, $lookupGlyphs, $seqIndex); + $REPL = implode(" ", $luss['substitute']); + // Returns e.g. "REPL\${6}\${8}" or "\${1}\${2} \${3} REPL\${4}\${6}\${8} \${9}" + + if (strpos("isol fina fin2 fin3 medi med2 init ", $tag) !== false && $scripttag == 'arab') { + $volt[] = ['match' => $lookupGlyphs[0], 'replace' => $REPL, 'tag' => $tag, 'prel' => $backtrackGlyphs, 'postl' => $lookaheadGlyphs, 'ignore' => $ignore]; + } else { + $subRule['rules'][] = ['type' => $Lookup[$lup]['Type'], 'match' => $lookupGlyphs, 'replace' => $luss['substitute'], 'seqIndex' => $seqIndex, 'key' => $lookupGlyphs[0],]; + } + } + } + } + } + if (count($subRule['rules'])) { + $volt[] = $subRule; + } + } + } + + } // Format 3: Coverage-based Context Glyph Substitution p259 + elseif ($SubstFormat == 3) { + + // IgnoreMarks flag set on main Lookup table + $ignore = $this->_getGSUBignoreString($Lookup[$i]['Flag'], $Lookup[$i]['MarkFilteringSet']); + $inputGlyphs = $Lookup[$i]['Subtable'][$c]['CoverageInputGlyphs']; + $CoverageInputGlyphs = implode('|', $inputGlyphs); + $nInput = $Lookup[$i]['Subtable'][$c]['InputGlyphCount']; + + if ($Lookup[$i]['Subtable'][$c]['BacktrackGlyphCount']) { + $backtrackGlyphs = $Lookup[$i]['Subtable'][$c]['CoverageBacktrackGlyphs']; + } else { + $backtrackGlyphs = []; + } + + // Returns e.g. ¦(FEEB|FEEC)(ignore) ¦(FD12|FD13)(ignore) ¦ + $backtrackMatch = $this->_makeGSUBbacktrackMatch($backtrackGlyphs, $ignore); + + if ($Lookup[$i]['Subtable'][$c]['LookaheadGlyphCount']) { + $lookaheadGlyphs = $Lookup[$i]['Subtable'][$c]['CoverageLookaheadGlyphs']; + } else { + $lookaheadGlyphs = []; + } + + // Returns e.g. ¦(ignore) (FD12|FD13)¦(ignore) (FEEB|FEEC)¦ + $lookaheadMatch = $this->_makeGSUBlookaheadMatch($lookaheadGlyphs, $ignore); + + $nBsubs = 2 * count($backtrackGlyphs); + $nIsubs = (2 * $nInput) - 1; + $contextInputMatch = $this->_makeGSUBcontextInputMatch($inputGlyphs, $ignore, [], 0); + $subRule = ['context' => 1, 'tag' => $tag, 'matchback' => $backtrackMatch, 'match' => ($contextInputMatch . $lookaheadMatch), 'nBacktrack' => count($backtrackGlyphs), 'nInput' => $nInput, 'nLookahead' => count($lookaheadGlyphs), 'rules' => [],]; + + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['SubstCount']; $b++) { + $lup = $Lookup[$i]['Subtable'][$c]['SubstLookupRecord'][$b]['LookupListIndex']; + $seqIndex = $Lookup[$i]['Subtable'][$c]['SubstLookupRecord'][$b]['SequenceIndex']; + for ($lus = 0; $lus < $Lookup[$lup]['SubtableCount']; $lus++) { + if (count($Lookup[$lup]['Subtable'][$lus]['subs'])) { + foreach ($Lookup[$lup]['Subtable'][$lus]['subs'] as $luss) { + $lookupGlyphs = $luss['Replace']; + $mLen = count($lookupGlyphs); + + // Only apply if the (first) 'Replace' glyph from the + // Lookup list is in the [inputGlyphs] at ['SequenceIndex'] + // then apply the substitution + if (strpos($inputGlyphs[$seqIndex], $lookupGlyphs[0]) === false) { + continue; + } + + // Returns e.g. ¦(0612)¦(ignore) (0613)¦(ignore) (0614)¦ + $contextInputMatch = $this->_makeGSUBcontextInputMatch($inputGlyphs, $ignore, $lookupGlyphs, $seqIndex); + $REPL = implode(" ", $luss['substitute']); + + if (strpos("isol fina fin2 fin3 medi med2 init ", $tag) !== false && $scripttag == 'arab') { + $volt[] = ['match' => $lookupGlyphs[0], 'replace' => $REPL, 'tag' => $tag, 'prel' => $backtrackGlyphs, 'postl' => $lookaheadGlyphs, 'ignore' => $ignore]; + } else { + $subRule['rules'][] = ['type' => $Lookup[$lup]['Type'], 'match' => $lookupGlyphs, 'replace' => $luss['substitute'], 'seqIndex' => $seqIndex, 'key' => $lookupGlyphs[0],]; + } + } + } + } + } + if (count($subRule['rules'])) { + $volt[] = $subRule; + } + } + + } // LookupType 6: ing Contextual Substitution Subtable + elseif ($Lookup[$i]['Type'] == 6) { + + // Format 1: Simple Chaining Context Glyph Substitution p255 + if ($SubstFormat == 1) { + $ignore = $this->_getGSUBignoreString($Lookup[$i]['Flag'], $Lookup[$i]['MarkFilteringSet']); + for ($s = 0; $s < $Lookup[$i]['Subtable'][$c]['ChainSubRuleSetCount']; $s++) { + + // ChainSubRuleSet + $subRule = []; + $firstInputGlyph = $Lookup[$i]['Subtable'][$c]['CoverageGlyphs'][$s]; // First input gyyph + + foreach ($Lookup[$i]['Subtable'][$c]['ChainSubRuleSet'][$s]['ChainSubRule'] as $rule) { + // ChainSubRule + $inputGlyphs = []; + if ($rule['InputGlyphCount'] > 1) { + $inputGlyphs = $rule['InputGlyphs']; + } + $inputGlyphs[0] = $firstInputGlyph; + ksort($inputGlyphs); + $nInput = count($inputGlyphs); + + if ($rule['BacktrackGlyphCount']) { + $backtrackGlyphs = $rule['BacktrackGlyphs']; + } else { + $backtrackGlyphs = []; + } + $backtrackMatch = $this->_makeGSUBbacktrackMatch($backtrackGlyphs, $ignore); + + if ($rule['LookaheadGlyphCount']) { + $lookaheadGlyphs = $rule['LookaheadGlyphs']; + } else { + $lookaheadGlyphs = []; + } + + $lookaheadMatch = $this->_makeGSUBlookaheadMatch($lookaheadGlyphs, $ignore); + + $nBsubs = 2 * count($backtrackGlyphs); + $nIsubs = (2 * $nInput) - 1; + + $contextInputMatch = $this->_makeGSUBcontextInputMatch($inputGlyphs, $ignore, [], 0); + $subRule = ['context' => 1, 'tag' => $tag, 'matchback' => $backtrackMatch, 'match' => ($contextInputMatch . $lookaheadMatch), 'nBacktrack' => count($backtrackGlyphs), 'nInput' => $nInput, 'nLookahead' => count($lookaheadGlyphs), 'rules' => [],]; + + for ($b = 0; $b < $rule['SubstCount']; $b++) { + $lup = $rule['LookupListIndex'][$b]; + $seqIndex = $rule['SequenceIndex'][$b]; + + // $Lookup[$lup] = secondary Lookup + for ($lus = 0; $lus < $Lookup[$lup]['SubtableCount']; $lus++) { + if (count($Lookup[$lup]['Subtable'][$lus]['subs'])) { + foreach ($Lookup[$lup]['Subtable'][$lus]['subs'] as $luss) { + $lookupGlyphs = $luss['Replace']; + $mLen = count($lookupGlyphs); + + // Only apply if the (first) 'Replace' glyph from the + // Lookup list is in the [inputGlyphs] at ['SequenceIndex'] + // then apply the substitution + if (strpos($inputGlyphs[$seqIndex], $lookupGlyphs[0]) === false) { + continue; + } + + // Returns e.g. ¦(0612)¦(ignore) (0613)¦(ignore) (0614)¦ + $contextInputMatch = $this->_makeGSUBcontextInputMatch($inputGlyphs, $ignore, $lookupGlyphs, $seqIndex); + + $REPL = implode(" ", $luss['substitute']); + + if (strpos("isol fina fin2 fin3 medi med2 init ", $tag) !== false && $scripttag == 'arab') { + $volt[] = ['match' => $lookupGlyphs[0], 'replace' => $REPL, 'tag' => $tag, 'prel' => $backtrackGlyphs, 'postl' => $lookaheadGlyphs, 'ignore' => $ignore]; + } else { + $subRule['rules'][] = ['type' => $Lookup[$lup]['Type'], 'match' => $lookupGlyphs, 'replace' => $luss['substitute'], 'seqIndex' => $seqIndex, 'key' => $lookupGlyphs[0],]; + } + } + } + } + } + + if (count($subRule['rules'])) { + $volt[] = $subRule; + } + } + } + + } // Format 2: Class-based Chaining Context Glyph Substitution p257 + elseif ($SubstFormat == 2) { + $ignore = $this->_getGSUBignoreString($Lookup[$i]['Flag'], $Lookup[$i]['MarkFilteringSet']); + foreach ($Lookup[$i]['Subtable'][$c]['ChainSubClassSet'] as $inputClass => $cscs) { + for ($cscrule = 0; $cscrule < $cscs['ChainSubClassRuleCnt']; $cscrule++) { + $rule = $cscs['ChainSubClassRule'][$cscrule]; + + // These contain classes of glyphs as strings + // $Lookup[$i]['Subtable'][$c]['InputClasses'][(class)] e.g. 02E6|02E7|02E8 + // $Lookup[$i]['Subtable'][$c]['LookaheadClasses'][(class)] + // $Lookup[$i]['Subtable'][$c]['BacktrackClasses'][(class)] + // These contain arrays of classIndexes + // [Backtrack] [Lookahead] and [Input] (Input is from the second position only) + + $inputGlyphs = []; + + if (isset($Lookup[$i]['Subtable'][$c]['InputClasses'][$inputClass])) { + $inputGlyphs[0] = $Lookup[$i]['Subtable'][$c]['InputClasses'][$inputClass]; + } else { + $inputGlyphs[0] = ''; + } + if ($rule['InputGlyphCount'] > 1) { + // NB starts at 1 + for ($gcl = 1; $gcl < $rule['InputGlyphCount']; $gcl++) { + $classindex = $rule['Input'][$gcl]; + if (isset($Lookup[$i]['Subtable'][$c]['InputClasses'][$classindex])) { + $inputGlyphs[$gcl] = $Lookup[$i]['Subtable'][$c]['InputClasses'][$classindex]; + } // if class[0] = all glyphs excluding those specified in all other classes + // set to blank '' for now + else { + $inputGlyphs[$gcl] = ''; + } + } + } + + $nInput = $rule['InputGlyphCount']; + + if ($rule['BacktrackGlyphCount']) { + for ($gcl = 0; $gcl < $rule['BacktrackGlyphCount']; $gcl++) { + $classindex = $rule['Backtrack'][$gcl]; + if (isset($Lookup[$i]['Subtable'][$c]['BacktrackClasses'][$classindex])) { + $backtrackGlyphs[$gcl] = $Lookup[$i]['Subtable'][$c]['BacktrackClasses'][$classindex]; + } // if class[0] = all glyphs excluding those specified in all other classes + // set to blank '' for now + else { + $backtrackGlyphs[$gcl] = ''; + } + } + } else { + $backtrackGlyphs = []; + } + // Returns e.g. ¦(FEEB|FEEC)(ignore) ¦(FD12|FD13)(ignore) ¦ + $backtrackMatch = $this->_makeGSUBbacktrackMatch($backtrackGlyphs, $ignore); + + if ($rule['LookaheadGlyphCount']) { + for ($gcl = 0; $gcl < $rule['LookaheadGlyphCount']; $gcl++) { + $classindex = $rule['Lookahead'][$gcl]; + if (isset($Lookup[$i]['Subtable'][$c]['LookaheadClasses'][$classindex])) { + $lookaheadGlyphs[$gcl] = $Lookup[$i]['Subtable'][$c]['LookaheadClasses'][$classindex]; + } // if class[0] = all glyphs excluding those specified in all other classes + // set to blank '' for now + else { + $lookaheadGlyphs[$gcl] = ''; + } + } + } else { + $lookaheadGlyphs = []; + } + // Returns e.g. ¦(ignore) (FD12|FD13)¦(ignore) (FEEB|FEEC)¦ + $lookaheadMatch = $this->_makeGSUBlookaheadMatch($lookaheadGlyphs, $ignore); + + $nBsubs = 2 * count($backtrackGlyphs); + $nIsubs = (2 * $nInput) - 1; + + $contextInputMatch = $this->_makeGSUBcontextInputMatch($inputGlyphs, $ignore, [], 0); + $subRule = ['context' => 1, 'tag' => $tag, 'matchback' => $backtrackMatch, 'match' => ($contextInputMatch . $lookaheadMatch), 'nBacktrack' => count($backtrackGlyphs), 'nInput' => $nInput, 'nLookahead' => count($lookaheadGlyphs), 'rules' => [],]; + + for ($b = 0; $b < $rule['SubstCount']; $b++) { + $lup = $rule['LookupListIndex'][$b]; + $seqIndex = $rule['SequenceIndex'][$b]; + + // $Lookup[$lup] = secondary Lookup + for ($lus = 0; $lus < $Lookup[$lup]['SubtableCount']; $lus++) { + if (count($Lookup[$lup]['Subtable'][$lus]['subs'])) { + foreach ($Lookup[$lup]['Subtable'][$lus]['subs'] as $luss) { + $lookupGlyphs = $luss['Replace']; + $mLen = count($lookupGlyphs); + + // Only apply if the (first) 'Replace' glyph from the + // Lookup list is in the [inputGlyphs] at ['SequenceIndex'] + // then apply the substitution + if (strpos($inputGlyphs[$seqIndex], $lookupGlyphs[0]) === false) { + continue; + } + + // Returns e.g. ¦(0612)¦(ignore) (0613)¦(ignore) (0614)¦ + $contextInputMatch = $this->_makeGSUBcontextInputMatch($inputGlyphs, $ignore, $lookupGlyphs, $seqIndex); + $REPL = implode(" ", $luss['substitute']); + // Returns e.g. "REPL\${6}\${8}" or "\${1}\${2} \${3} REPL\${4}\${6}\${8} \${9}" + + if (strpos("isol fina fin2 fin3 medi med2 init ", $tag) !== false && $scripttag == 'arab') { + $volt[] = ['match' => $lookupGlyphs[0], 'replace' => $REPL, 'tag' => $tag, 'prel' => $backtrackGlyphs, 'postl' => $lookaheadGlyphs, 'ignore' => $ignore]; + } else { + $subRule['rules'][] = ['type' => $Lookup[$lup]['Type'], 'match' => $lookupGlyphs, 'replace' => $luss['substitute'], 'seqIndex' => $seqIndex, 'key' => $lookupGlyphs[0],]; + } + } + } + } + } + if (count($subRule['rules'])) { + $volt[] = $subRule; + } + } + } + + } // Format 3: Coverage-based Chaining Context Glyph Substitution p259 + elseif ($SubstFormat == 3) { + // IgnoreMarks flag set on main Lookup table + $ignore = $this->_getGSUBignoreString($Lookup[$i]['Flag'], $Lookup[$i]['MarkFilteringSet']); + $inputGlyphs = $Lookup[$i]['Subtable'][$c]['CoverageInputGlyphs']; + $CoverageInputGlyphs = implode('|', $inputGlyphs); + $nInput = $Lookup[$i]['Subtable'][$c]['InputGlyphCount']; + + if ($Lookup[$i]['Subtable'][$c]['BacktrackGlyphCount']) { + $backtrackGlyphs = $Lookup[$i]['Subtable'][$c]['CoverageBacktrackGlyphs']; + } else { + $backtrackGlyphs = []; + } + // Returns e.g. ¦(FEEB|FEEC)(ignore) ¦(FD12|FD13)(ignore) ¦ + $backtrackMatch = $this->_makeGSUBbacktrackMatch($backtrackGlyphs, $ignore); + + if ($Lookup[$i]['Subtable'][$c]['LookaheadGlyphCount']) { + $lookaheadGlyphs = $Lookup[$i]['Subtable'][$c]['CoverageLookaheadGlyphs']; + } else { + $lookaheadGlyphs = []; + } + // Returns e.g. ¦(ignore) (FD12|FD13)¦(ignore) (FEEB|FEEC)¦ + $lookaheadMatch = $this->_makeGSUBlookaheadMatch($lookaheadGlyphs, $ignore); + + $nBsubs = 2 * count($backtrackGlyphs); + $nIsubs = (2 * $nInput) - 1; + $contextInputMatch = $this->_makeGSUBcontextInputMatch($inputGlyphs, $ignore, [], 0); + $subRule = ['context' => 1, 'tag' => $tag, 'matchback' => $backtrackMatch, 'match' => ($contextInputMatch . $lookaheadMatch), 'nBacktrack' => count($backtrackGlyphs), 'nInput' => $nInput, 'nLookahead' => count($lookaheadGlyphs), 'rules' => [],]; + + for ($b = 0; $b < $Lookup[$i]['Subtable'][$c]['SubstCount']; $b++) { + $lup = $Lookup[$i]['Subtable'][$c]['SubstLookupRecord'][$b]['LookupListIndex']; + $seqIndex = $Lookup[$i]['Subtable'][$c]['SubstLookupRecord'][$b]['SequenceIndex']; + for ($lus = 0; $lus < $Lookup[$lup]['SubtableCount']; $lus++) { + if (count($Lookup[$lup]['Subtable'][$lus]['subs'])) { + foreach ($Lookup[$lup]['Subtable'][$lus]['subs'] as $luss) { + $lookupGlyphs = $luss['Replace']; + $mLen = count($lookupGlyphs); + + // Only apply if the (first) 'Replace' glyph from the + // Lookup list is in the [inputGlyphs] at ['SequenceIndex'] + // then apply the substitution + if (strpos($inputGlyphs[$seqIndex], $lookupGlyphs[0]) === false) { + continue; + } + + // Returns e.g. ¦(0612)¦(ignore) (0613)¦(ignore) (0614)¦ + $contextInputMatch = $this->_makeGSUBcontextInputMatch($inputGlyphs, $ignore, $lookupGlyphs, $seqIndex); + $REPL = implode(" ", $luss['substitute']); + + if (strpos("isol fina fin2 fin3 medi med2 init ", $tag) !== false && $scripttag == 'arab') { + $volt[] = ['match' => $lookupGlyphs[0], 'replace' => $REPL, 'tag' => $tag, 'prel' => $backtrackGlyphs, 'postl' => $lookaheadGlyphs, 'ignore' => $ignore]; + } else { + $subRule['rules'][] = ['type' => $Lookup[$lup]['Type'], 'match' => $lookupGlyphs, 'replace' => $luss['substitute'], 'seqIndex' => $seqIndex, 'key' => $lookupGlyphs[0],]; + } + } + } + } + } + if (count($subRule['rules'])) { + $volt[] = $subRule; + } + } + } + } + } + + return $volt; + } + + function _checkGSUBignore($flag, $glyph, $MarkFilteringSet) + { + $ignore = false; + // Flag & 0x0008 = Ignore Marks - (unless already done with MarkAttachmentType) + if ((($flag & 0x0008) == 0x0008 && ($flag & 0xFF00) == 0) && strpos($this->GlyphClassMarks, $glyph)) { + $ignore = true; + } + if ((($flag & 0x0004) == 0x0004) && strpos($this->GlyphClassLigatures, $glyph)) { + $ignore = true; + } + if ((($flag & 0x0002) == 0x0002) && strpos($this->GlyphClassBases, $glyph)) { + $ignore = true; + } + // Flag & 0xFF?? = MarkAttachmentType + if ($flag & 0xFF00) { + // "a lookup must ignore any mark glyphs that are not in the specified mark attachment class" + // $this->MarkAttachmentType is already adjusted for this i.e. contains all Marks except those in the MarkAttachmentClassDef table + if (strpos($this->MarkAttachmentType[($flag >> 8)], $glyph)) { + $ignore = true; + } + } + // Flag & 0x0010 = UseMarkFilteringSet + if (($flag & 0x0010) && strpos($this->MarkGlyphSets[$MarkFilteringSet], $glyph)) { + $ignore = true; + } + + return $ignore; + } + + function _getGSUBignoreString($flag, $MarkFilteringSet) + { + // If ignoreFlag set, combine all ignore glyphs into -> "((?:(?: FBA1| FBA2| FBA3))*)" + // else "()" + // for Input - set on secondary Lookup table if in Context, and set Backtrack and Lookahead on Context Lookup + $str = ""; + $ignoreflag = 0; + + // Flag & 0xFF?? = MarkAttachmentType + if ($flag & 0xFF00) { + // "a lookup must ignore any mark glyphs that are not in the specified mark attachment class" + // $this->MarkAttachmentType is already adjusted for this i.e. contains all Marks except those in the MarkAttachmentClassDef table + $MarkAttachmentType = $flag >> 8; + $ignoreflag = $flag; + $str = $this->MarkAttachmentType[$MarkAttachmentType]; + } + + // Flag & 0x0010 = UseMarkFilteringSet + if ($flag & 0x0010) { + throw new \Mpdf\MpdfException("This font " . $this->fontkey . " contains MarkGlyphSets - Not tested yet"); + $str = $this->MarkGlyphSets[$MarkFilteringSet]; + } + + // If Ignore Marks set, supercedes any above + // Flag & 0x0008 = Ignore Marks - (unless already done with MarkAttachmentType) + if (($flag & 0x0008) == 0x0008 && ($flag & 0xFF00) == 0) { + $ignoreflag = 8; + $str = $this->GlyphClassMarks; + } + + // Flag & 0x0004 = Ignore Ligatures + if (($flag & 0x0004) == 0x0004) { + $ignoreflag += 4; + if ($str) { + $str .= "|"; + } + $str .= $this->GlyphClassLigatures; + } + // Flag & 0x0002 = Ignore BaseGlyphs + if (($flag & 0x0002) == 0x0002) { + $ignoreflag += 2; + if ($str) { + $str .= "|"; + } + $str .= $this->GlyphClassBases; + } + if ($str) { + // This originally returned e.g. ((?:(?:[IGNORE8]))*) when NOT specific to a Lookup e.g. rtlSub in + // arabictypesetting.GSUB.arab.DFLT.php + // This would save repeatedly saving long text strings if used multiple times + // When writing e.g. arabictypesetting.GSUB.arab.DFLT.php to file, included as $ignore[8] + // Would need to also write the $ignore array to that file + // // If UseMarkFilteringSet (specific to the Lookup) return the string + // if (($flag & 0x0010) && ($flag & 0x0008) != 0x0008) { + // return "((?:(?:" . $str . "))*)"; + // } + // else { return "((?:(?:" . "[IGNORE".$ignoreflag."]" . "))*)"; } + // // e.g. ((?:(?: 0031| 0032| 0033| 0034| 0045))*) + // But never finished coding it to add the $ignore array to the file, and it doesn't seem to occur often enough to be worth + // writing. So just output it as a string: + return "((?:(?:" . $str . "))*)"; + } else { + return "()"; + } + } + + // GSUB Patterns + + /* + BACKTRACK INPUT LOOKAHEAD + ================================== ================== ================================== + (FEEB|FEEC)(ign) ¦(FD12|FD13)(ign) ¦(0612)¦(ign) (0613)¦(ign) (FD12|FD13)¦(ign) (FEEB|FEEC) + ---------------- ---------------- ----- ------------ --------------- --------------- + Backtrack 1 Backtrack 2 Input 1 Input 2 Lookahead 1 Lookahead 2 + -------- --- --------- --- ---- --- ---- --- --------- --- ------- + \${1} \${2} \${3} \${4} \${5+} \${6+} \${7+} \${8+} + + nBacktrack = 2 nInput = 2 nLookahead = 2 + + nBsubs = 2xnBack nIsubs = (nBsubs+) nLsubs = (nBsubs+nIsubs+) 2xnLookahead + "\${1}\${2} " (nInput*2)-1 "\${5+} \${6+}" + "REPL" + + ¦\${1}\${2} ¦\${3}\${4} ¦REPL¦\${5+} \${6+}¦\${7+} \${8+}¦ + + + INPUT nInput = 5 + ============================================================ + ¦(0612)¦(ign) (0613)¦(ign) (0614)¦(ign) (0615)¦(ign) (0615)¦ + \${1} \${2} \${3} \${4} \${5} \${6} \${7} \${8} \${9} (All backreference numbers are + nBsubs) + ----- ------------ ------------ ------------ ------------ + Input 1 Input 2 Input 3 Input 4 Input 5 + + A====== SequenceIndex=1 ; Lookup match nGlyphs=1 + B=================== SequenceIndex=1 ; Lookup match nGlyphs=2 + C=============================== SequenceIndex=1 ; Lookup match nGlyphs=3 + D======================= SequenceIndex=2 ; Lookup match nGlyphs=2 + E===================================== SequenceIndex=2 ; Lookup match nGlyphs=3 + F====================== SequenceIndex=4 ; Lookup match nGlyphs=2 + + All backreference numbers are + nBsubs + A - "REPL\${2} \${3}\${4} \${5}\${6} \${7}\${8} \${9}" + B - "REPL\${2}\${4} \${5}\${6} \${7}\${8} \${9}" + C - "REPL\${2}\${4}\${6} \${7}\${8} \${9}" + D - "\${1} REPL\${2}\${4}\${6} \${7}\${8} \${9}" + E - "\${1} REPL\${2}\${4}\${6}\${8} \${9}" + F - "\${1}\${2} \${3}\${4} \${5} REPL\${6}\${8}" + */ + + function _makeGSUBcontextInputMatch($inputGlyphs, $ignore, $lookupGlyphs, $seqIndex) + { + // $ignore = "((?:(?: FBA1| FBA2| FBA3))*)" or "()" + // Returns e.g. ¦(0612)¦(ignore) (0613)¦(ignore) (0614)¦ + // $inputGlyphs = array of glyphs(glyphstrings) making up Input sequence in Context + // $lookupGlyphs = array of glyphs (single Glyphs) making up Lookup Input sequence + $mLen = count($lookupGlyphs); // nGlyphs in the secondary Lookup match + $nInput = count($inputGlyphs); // nGlyphs in the Primary Input sequence + $str = ""; + for ($i = 0; $i < $nInput; $i++) { + if ($i > 0) { + $str .= $ignore . " "; + } + if ($i >= $seqIndex && $i < ($seqIndex + $mLen)) { + $str .= "(" . $lookupGlyphs[($i - $seqIndex)] . ")"; + } else { + $str .= "(" . $inputGlyphs[($i)] . ")"; + } + } + + return $str; + } + + function _makeGSUBinputMatch($inputGlyphs, $ignore) + { + // $ignore = "((?:(?: FBA1| FBA2| FBA3))*)" or "()" + // Returns e.g. ¦(0612)¦(ignore) (0613)¦(ignore) (0614)¦ + // $inputGlyphs = array of glyphs(glyphstrings) making up Input sequence in Context + // $lookupGlyphs = array of glyphs making up Lookup Input sequence - if applicable + $str = ""; + for ($i = 1; $i <= count($inputGlyphs); $i++) { + if ($i > 1) { + $str .= $ignore . " "; + } + $str .= "(" . $inputGlyphs[($i - 1)] . ")"; + } + + return $str; + } + + function _makeGSUBbacktrackMatch($backtrackGlyphs, $ignore) + { + // $ignore = "((?:(?: FBA1| FBA2| FBA3))*)" or "()" + // Returns e.g. ¦(FEEB|FEEC)(ignore) ¦(FD12|FD13)(ignore) ¦ + // $backtrackGlyphs = array of glyphstrings making up Backtrack sequence + // 3 2 1 0 + // each item being e.g. E0AD|E0AF|F1FD + $str = ""; + for ($i = (count($backtrackGlyphs) - 1); $i >= 0; $i--) { + $str .= "(" . $backtrackGlyphs[$i] . ")" . $ignore . " "; + } + + return $str; + } + + function _makeGSUBlookaheadMatch($lookaheadGlyphs, $ignore) + { + // $ignore = "((?:(?: FBA1| FBA2| FBA3))*)" or "()" + // Returns e.g. ¦(ignore) (FD12|FD13)¦(ignore) (FEEB|FEEC)¦ + // $lookaheadGlyphs = array of glyphstrings making up Lookahead sequence + // 0 1 2 3 + // each item being e.g. E0AD|E0AF|F1FD + $str = ""; + for ($i = 0; $i < count($lookaheadGlyphs); $i++) { + $str .= $ignore . " (" . $lookaheadGlyphs[$i] . ")"; + } + + return $str; + } + + function _makeGSUBinputReplacement($nInput, $REPL, $ignore, $nBsubs, $mLen, $seqIndex) + { + // Returns e.g. "REPL\${6}\${8}" or "\${1}\${2} \${3} REPL\${4}\${6}\${8} \${9}" + // $nInput nGlyphs in the Primary Input sequence + // $REPL replacement glyphs from secondary lookup + // $ignore = "((?:(?: FBA1| FBA2| FBA3))*)" or "()" + // $nBsubs Number of Backtrack substitutions (= 2x Number of Backtrack glyphs) + // $mLen nGlyphs in the secondary Lookup match - if no secondary lookup, should=$nInput + // $seqIndex Sequence Index to apply the secondary match + if ($ignore == "()") { + $ign = false; + } else { + $ign = true; + } + $str = ""; + if ($nInput == 1) { + $str = $REPL; + } elseif ($nInput > 1) { + if ($mLen == $nInput) { // whole string replaced + $str = $REPL; + if ($ign) { + // for every nInput over 1, add another replacement backreference, to move IGNORES after replacement + for ($x = 2; $x <= $nInput; $x++) { + $str .= '\\' . ($nBsubs + (2 * ($x - 1))); + } + } + } else { // if only part of string replaced: + for ($x = 1; $x < ($seqIndex + 1); $x++) { + if ($x == 1) { + $str .= '\\' . ($nBsubs + 1); + } else { + if ($ign) { + $str .= '\\' . ($nBsubs + (2 * ($x - 1))); + } + $str .= ' \\' . ($nBsubs + 1 + (2 * ($x - 1))); + } + } + if ($seqIndex > 0) { + $str .= " "; + } + $str .= $REPL; + if ($ign) { + for ($x = (max(($seqIndex + 1), 2)); $x < ($seqIndex + 1 + $mLen); $x++) { // move IGNORES after replacement + $str .= '\\' . ($nBsubs + (2 * ($x - 1))); + } + } + for ($x = ($seqIndex + 1 + $mLen); $x <= $nInput; $x++) { + if ($ign) { + $str .= '\\' . ($nBsubs + (2 * ($x - 1))); + } + $str .= ' \\' . ($nBsubs + 1 + (2 * ($x - 1))); + } + } + } + + return $str; + } + + function _getCoverage($convert2hex = true, $mode = 1) + { + $g = []; + $ctr = 0; + $CoverageFormat = $this->read_ushort(); + if ($CoverageFormat == 1) { + $CoverageGlyphCount = $this->read_ushort(); + for ($gid = 0; $gid < $CoverageGlyphCount; $gid++) { + $glyphID = $this->read_ushort(); + $uni = $this->glyphToChar[$glyphID][0]; + if ($convert2hex) { + $g[] = unicode_hex($uni); + } elseif ($mode == 2) { + $g[$uni] = $ctr; + $ctr++; + } else { + $g[] = $glyphID; + } + } + } + if ($CoverageFormat == 2) { + $RangeCount = $this->read_ushort(); + for ($r = 0; $r < $RangeCount; $r++) { + $start = $this->read_ushort(); + $end = $this->read_ushort(); + $StartCoverageIndex = $this->read_ushort(); // n/a + for ($glyphID = $start; $glyphID <= $end; $glyphID++) { + $uni = $this->glyphToChar[$glyphID][0]; + if ($convert2hex) { + $g[] = unicode_hex($uni); + } elseif ($mode == 2) { + $uni = $g[$uni] = $ctr; + $ctr++; + } else { + $g[] = $glyphID; + } + } + } + } + + return $g; + } + + function _getClasses($offset) + { + $this->seek($offset); + $ClassFormat = $this->read_ushort(); + $GlyphByClass = []; + if ($ClassFormat == 1) { + $StartGlyph = $this->read_ushort(); + $GlyphCount = $this->read_ushort(); + for ($i = 0; $i < $GlyphCount; $i++) { + $startGlyphID = $StartGlyph + $i; + $endGlyphID = $StartGlyph + $i; + $class = $this->read_ushort(); + for ($g = $startGlyphID; $g <= $endGlyphID; $g++) { + if (isset($this->glyphToChar[$g][0])) { + $GlyphByClass[$class][] = unicode_hex($this->glyphToChar[$g][0]); + } + } + } + } elseif ($ClassFormat == 2) { + $tableCount = $this->read_ushort(); + for ($i = 0; $i < $tableCount; $i++) { + $startGlyphID = $this->read_ushort(); + $endGlyphID = $this->read_ushort(); + $class = $this->read_ushort(); + for ($g = $startGlyphID; $g <= $endGlyphID; $g++) { + if ($this->glyphToChar[$g][0]) { + $GlyphByClass[$class][] = unicode_hex($this->glyphToChar[$g][0]); + } + } + } + } + $gbc = []; + foreach ($GlyphByClass as $class => $garr) { + $gbc[$class] = implode('|', $garr); + } + + return $gbc; + } + + function _getGPOStables() + { + /////////////////////////////////// + // GPOS - Glyph Positioning + /////////////////////////////////// + if (!isset($this->tables["GPOS"])) { + return [[], [], []]; + } + + $ffeats = []; + $gpos_offset = $this->seek_table("GPOS"); + $this->skip(4); + $ScriptList_offset = $gpos_offset + $this->read_ushort(); + $FeatureList_offset = $gpos_offset + $this->read_ushort(); + $LookupList_offset = $gpos_offset + $this->read_ushort(); + + // ScriptList + $this->seek($ScriptList_offset); + $ScriptCount = $this->read_ushort(); + for ($i = 0; $i < $ScriptCount; $i++) { + $ScriptTag = $this->read_tag(); // = "beng", "deva" etc. + $ScriptTableOffset = $this->read_ushort(); + $ffeats[$ScriptTag] = $ScriptList_offset + $ScriptTableOffset; + } + + // Script Table + foreach ($ffeats as $t => $o) { + $ls = []; + $this->seek($o); + $DefLangSys_offset = $this->read_ushort(); + if ($DefLangSys_offset > 0) { + $ls['DFLT'] = $DefLangSys_offset + $o; + } + $LangSysCount = $this->read_ushort(); + for ($i = 0; $i < $LangSysCount; $i++) { + $LangTag = $this->read_tag(); // = + $LangTableOffset = $this->read_ushort(); + $ls[$LangTag] = $o + $LangTableOffset; + } + $ffeats[$t] = $ls; + } + + // Get FeatureIndexList + // LangSys Table - from first listed langsys + foreach ($ffeats as $st => $scripts) { + foreach ($scripts as $t => $o) { + $FeatureIndex = []; + $langsystable_offset = $o; + $this->seek($langsystable_offset); + $LookUpOrder = $this->read_ushort(); //==NULL + $ReqFeatureIndex = $this->read_ushort(); + if ($ReqFeatureIndex != 0xFFFF) { + $FeatureIndex[] = $ReqFeatureIndex; + } + $FeatureCount = $this->read_ushort(); + for ($i = 0; $i < $FeatureCount; $i++) { + $FeatureIndex[] = $this->read_ushort(); // = index of feature + } + $ffeats[$st][$t] = $FeatureIndex; + } + } + // Feauture List => LookupListIndex es + $this->seek($FeatureList_offset); + $FeatureCount = $this->read_ushort(); + $Feature = []; + for ($i = 0; $i < $FeatureCount; $i++) { + $tag = $this->read_tag(); + if ($tag === 'kern') { + $this->haskernGPOS = true; + } + $Feature[$i] = ['tag' => $tag]; + $Feature[$i]['offset'] = $FeatureList_offset + $this->read_ushort(); + } + + for ($i = 0; $i < $FeatureCount; $i++) { + $this->seek($Feature[$i]['offset']); + $this->read_ushort(); // null + $Feature[$i]['LookupCount'] = $Lookupcount = $this->read_ushort(); + $Feature[$i]['LookupListIndex'] = []; + for ($c = 0; $c < $Lookupcount; $c++) { + $Feature[$i]['LookupListIndex'][] = $this->read_ushort(); + } + } + + foreach ($ffeats as $st => $scripts) { + foreach ($scripts as $t => $o) { + $FeatureIndex = $ffeats[$st][$t]; + foreach ($FeatureIndex as $k => $fi) { + $ffeats[$st][$t][$k] = $Feature[$fi]; + } + } + } + + $gpos = []; + $GPOSScriptLang = []; + foreach ($ffeats as $st => $scripts) { + + foreach ($scripts as $t => $langsys) { + + $lg = []; + foreach ($langsys as $ft) { + $lg[$ft['LookupListIndex'][0]] = $ft; + } + + // list of Lookups in order they need to be run i.e. order listed in Lookup table + ksort($lg); + foreach ($lg as $ft) { + $gpos[$st][$t][$ft['tag']] = $ft['LookupListIndex']; + } + if (!isset($GPOSScriptLang[$st])) { + $GPOSScriptLang[$st] = ''; + } + $GPOSScriptLang[$st] .= $t . ' '; + } + } + + // Get metadata and offsets for whole Lookup List table + $this->seek($LookupList_offset); + $LookupCount = $this->read_ushort(); + $Lookup = []; + $Offsets = []; + $SubtableCount = []; + + for ($i = 0; $i < $LookupCount; $i++) { + $Offsets[$i] = $LookupList_offset + $this->read_ushort(); + } + + for ($i = 0; $i < $LookupCount; $i++) { + $this->seek($Offsets[$i]); + $Lookup[$i]['Type'] = $this->read_ushort(); + $Lookup[$i]['Flag'] = $flag = $this->read_ushort(); + $Lookup[$i]['SubtableCount'] = $SubtableCount[$i] = $this->read_ushort(); + for ($c = 0; $c < $SubtableCount[$i]; $c++) { + $Lookup[$i]['Subtables'][$c] = $Offsets[$i] + $this->read_ushort(); + } + // MarkFilteringSet = Index (base 0) into GDEF mark glyph sets structure + if (($flag & 0x0010) === 0x0010) { + $Lookup[$i]['MarkFilteringSet'] = $this->read_ushort(); + } else { + $Lookup[$i]['MarkFilteringSet'] = ''; + } + + // Lookup Type 9: Extension + if ($Lookup[$i]['Type'] == 9) { + // Overwrites new offset (32-bit) for each subtable, and a new lookup Type + for ($c = 0; $c < $SubtableCount[$i]; $c++) { + $this->seek($Lookup[$i]['Subtables'][$c]); + $ExtensionPosFormat = $this->read_ushort(); + $type = $this->read_ushort(); + $Lookup[$i]['Subtables'][$c] = $Lookup[$i]['Subtables'][$c] + $this->read_ulong(); + } + $Lookup[$i]['Type'] = $type; + } + } + + // Process Whole LookupList - Get LuCoverage = Lookup coverage just for first glyph + $this->LuCoverage = []; + for ($i = 0; $i < $LookupCount; $i++) { + for ($c = 0; $c < $Lookup[$i]['SubtableCount']; $c++) { + $this->seek($Lookup[$i]['Subtables'][$c]); + $PosFormat = $this->read_ushort(); + + if ($Lookup[$i]['Type'] == 7 && $PosFormat == 3) { + $this->skip(4); + } elseif ($Lookup[$i]['Type'] == 8 && $PosFormat == 3) { + $BacktrackGlyphCount = $this->read_ushort(); + $this->skip(2 * $BacktrackGlyphCount + 2); + } + // NB Coverage only looks at glyphs for position 1 (i.e. 7.3 and 8.3) // NEEDS TO READ ALL ******************** + // NB For e.g. Type 4, this may be the Coverage for the Mark + $Coverage = $Lookup[$i]['Subtables'][$c] + $this->read_ushort(); + $this->seek($Coverage); + $glyphs = $this->_getCoverage(false, 2); + $this->LuCoverage[$i][$c] = $glyphs; + } + } + + $this->fontCache->jsonWrite($this->fontkey . '.GPOSdata.json', $this->LuCoverage); + + return [$GPOSScriptLang, $gpos, $Lookup]; + } + + function makeSubset($file, &$subset, $TTCfontID = 0, $debug = false, $useOTL = false) + { + $this->useOTL = $useOTL; + $this->filename = $file; + $this->fh = fopen($file, 'rb'); + + if (!$this->fh) { + throw new \Mpdf\MpdfException(sprintf('Unable to open file %s', $file)); + } + + $this->_pos = 0; + $this->charWidths = ''; + $this->glyphPos = []; + $this->charToGlyph = []; + $this->tables = []; + $this->otables = []; + $this->ascent = 0; + $this->descent = 0; + $this->strikeoutSize = 0; + $this->strikeoutPosition = 0; + $this->numTTCFonts = 0; + $this->TTCFonts = []; + $this->skip(4); + $this->maxUni = 0; + + if ($TTCfontID > 0) { + $this->version = $version = $this->read_ulong(); // TTC Header version now + if (!in_array($version, [0x00010000, 0x00020000], true)) { + throw new \Mpdf\MpdfException(sprintf('Error parsing TrueType Collection: version=%s - %s', $version, $file)); + } + $this->numTTCFonts = $this->read_ulong(); + for ($i = 1; $i <= $this->numTTCFonts; $i++) { + $this->TTCFonts[$i]['offset'] = $this->read_ulong(); + } + $this->seek($this->TTCFonts[$TTCfontID]['offset']); + $this->version = $version = $this->read_ulong(); // TTFont version again now + } + $this->readTableDirectory($debug); + + // head - Font header table + $this->seek_table('head'); + $this->skip(50); + $indexToLocFormat = $this->read_ushort(); + $glyphDataFormat = $this->read_ushort(); + + // hhea - Horizontal header table + $this->seek_table('hhea'); + $this->skip(32); + $metricDataFormat = $this->read_ushort(); + $orignHmetrics = $numberOfHMetrics = $this->read_ushort(); + + // maxp - Maximum profile table + $this->seek_table('maxp'); + $this->skip(4); + $numGlyphs = $this->read_ushort(); + + // cmap - Character to glyph index mapping table + $cmap_offset = $this->seek_table('cmap'); + $this->skip(2); + $cmapTableCount = $this->read_ushort(); + $unicode_cmap_offset = 0; + for ($i = 0; $i < $cmapTableCount; $i++) { + $platformID = $this->read_ushort(); + $encodingID = $this->read_ushort(); + $offset = $this->read_ulong(); + $save_pos = $this->_pos; + if (($platformID == 3 && $encodingID == 1) || $platformID == 0) { // Microsoft, Unicode + $format = $this->get_ushort($cmap_offset + $offset); + if ($format == 4) { + $unicode_cmap_offset = $cmap_offset + $offset; + break; + } + } + $this->seek($save_pos); + } + + if (!$unicode_cmap_offset) { + throw new \Mpdf\MpdfException(sprintf('Font "%s" does not have Unicode cmap (platform 3, encoding 1, format 4, or platform 0 [any encoding] format 4)', $this->filename)); + } + + $glyphToChar = []; + $charToGlyph = []; + $this->getCMAP4($unicode_cmap_offset, $glyphToChar, $charToGlyph); + + // Map Unmapped glyphs - from $numGlyphs + if ($useOTL) { + $bctr = 0xE000; + for ($gid = 1; $gid < $numGlyphs; $gid++) { + if (!isset($glyphToChar[$gid])) { + while (isset($charToGlyph[$bctr])) { + $bctr++; + } // Avoid overwriting a glyph already mapped in PUA + if ($bctr > 0xF8FF) { + throw new \Mpdf\MpdfException($file . " : WARNING - Font cannot map all included glyphs into Private Use Area U+E000 - U+F8FF; cannot use useOTL on this font"); + } + $glyphToChar[$gid][] = $bctr; + $charToGlyph[$bctr] = $gid; + $bctr++; + } + } + } + + $this->charToGlyph = $charToGlyph; + $this->glyphToChar = $glyphToChar; + + // hmtx - Horizontal metrics table + $scale = 1; // not used + $this->getHMTX($numberOfHMetrics, $numGlyphs, $glyphToChar, $scale); + + // loca - Index to location + $this->getLOCA($indexToLocFormat, $numGlyphs); + + $subsetglyphs = [0 => 0, 1 => 1, 2 => 2]; + $subsetCharToGlyph = []; + foreach ($subset as $code) { + if (isset($this->charToGlyph[$code])) { + $subsetglyphs[$this->charToGlyph[$code]] = $code; // Old Glyph ID => Unicode + $subsetCharToGlyph[$code] = $this->charToGlyph[$code]; // Unicode to old GlyphID + } + $this->maxUni = max($this->maxUni, $code); + } + + list($start, $dummy) = $this->get_table_pos('glyf'); + + $glyphSet = []; + ksort($subsetglyphs); + $n = 0; + $fsLastCharIndex = 0; // maximum Unicode index (character code) in this font, according to the cmap subtable for platform ID 3 and platform- specific encoding ID 0 or 1. + foreach ($subsetglyphs as $originalGlyphIdx => $uni) { + $fsLastCharIndex = max($fsLastCharIndex, $uni); + $glyphSet[$originalGlyphIdx] = $n; // old glyphID to new glyphID + $n++; + } + + $codeToGlyph = []; + ksort($subsetCharToGlyph); + foreach ($subsetCharToGlyph as $uni => $originalGlyphIdx) { + $codeToGlyph[$uni] = $glyphSet[$originalGlyphIdx]; + } + $this->codeToGlyph = $codeToGlyph; + + ksort($subsetglyphs); + foreach ($subsetglyphs as $originalGlyphIdx => $uni) { + $this->getGlyphs($originalGlyphIdx, $start, $glyphSet, $subsetglyphs); + } + + $numGlyphs = $numberOfHMetrics = count($subsetglyphs); + + // name - table copied from the original + // MS spec says that "Platform and encoding ID's in the name table should be consistent with those in the cmap table. + // If they are not, the font will not load in Windows" + // Doesn't seem to be a problem? + $this->add('name', $this->get_table('name')); + + // tables copied from the original + $tags = ['cvt ', 'fpgm', 'prep', 'gasp']; + foreach ($tags as $tag) { + if (isset($this->tables[$tag])) { + $this->add($tag, $this->get_table($tag)); + } + } + + // post - PostScript + if (isset($this->tables['post'])) { + $opost = $this->get_table('post'); + $post = "\x00\x03\x00\x00" . substr($opost, 4, 12) . "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"; + $this->add('post', $post); + } + + // Sort CID2GID map into segments of contiguous codes + ksort($codeToGlyph); + unset($codeToGlyph[0]); + + $rangeid = 0; + $range = []; + $prevcid = -2; + $prevglidx = -1; + + // for each character + foreach ($codeToGlyph as $cid => $glidx) { + if ($cid == ($prevcid + 1) && $glidx == ($prevglidx + 1)) { + $range[$rangeid][] = $glidx; + } else { + // new range + $rangeid = $cid; + $range[$rangeid] = []; + $range[$rangeid][] = $glidx; + } + $prevcid = $cid; + $prevglidx = $glidx; + } + + // cmap - Character to glyph mapping + $segCount = count($range) + 1; // + 1 Last segment has missing character 0xFFFF + $searchRange = 1; + $entrySelector = 0; + + while ($searchRange * 2 <= $segCount) { + $searchRange *= 2; + ++$entrySelector; + } + + $searchRange *= 2; + $rangeShift = $segCount * 2 - $searchRange; + $length = 16 + (8 * $segCount) + ($numGlyphs + 1); + $cmap = [ + 0, 3, // Index : version, number of encoding subtables + 0, 0, // Encoding Subtable : platform (UNI=0), encoding 0 + 0, 28, // Encoding Subtable : offset (hi,lo) + 0, 3, // Encoding Subtable : platform (UNI=0), encoding 3 + 0, 28, // Encoding Subtable : offset (hi,lo) + 3, 1, // Encoding Subtable : platform (MS=3), encoding 1 + 0, 28, // Encoding Subtable : offset (hi,lo) + 4, $length, 0, // Format 4 Mapping subtable: format, length, language + $segCount * 2, + $searchRange, + $entrySelector, + $rangeShift, + ]; + + // endCode(s) + foreach ($range as $start => $subrange) { + $endCode = $start + (count($subrange) - 1); + $cmap[] = $endCode; // endCode(s) + } + + $cmap[] = 0xFFFF; // endCode of last Segment + $cmap[] = 0; // reservedPad + + // startCode(s) + foreach ($range as $start => $subrange) { + $cmap[] = $start; // startCode(s) + } + + $cmap[] = 0xFFFF; // startCode of last Segment + + // idDelta(s) + foreach ($range as $start => $subrange) { + $idDelta = -($start - $subrange[0]); + $n += count($subrange); + $cmap[] = $idDelta; // idDelta(s) + } + + $cmap[] = 1; // idDelta of last Segment + // idRangeOffset(s) + + foreach ($range as $subrange) { + $cmap[] = 0; // idRangeOffset[segCount] Offset in bytes to glyph indexArray, or 0 + } + + $cmap[] = 0; // idRangeOffset of last Segment + foreach ($range as $subrange) { + foreach ($subrange as $glidx) { + $cmap[] = $glidx; + } + } + + $cmap[] = 0; // Mapping for last character + $cmapstr = ''; + + foreach ($cmap as $cm) { + $cmapstr .= pack('n', $cm); + } + $this->add('cmap', $cmapstr); + + // glyf - Glyph data + list($glyfOffset, $glyfLength) = $this->get_table_pos('glyf'); + if ($glyfLength < $this->maxStrLenRead) { + $glyphData = $this->get_table('glyf'); + } + + $offsets = []; + $glyf = ''; + $pos = 0; + $hmtxstr = ''; + $xMinT = 0; + $yMinT = 0; + $xMaxT = 0; + $yMaxT = 0; + $advanceWidthMax = 0; + $minLeftSideBearing = 0; + $minRightSideBearing = 0; + $xMaxExtent = 0; + $maxPoints = 0; // points in non-compound glyph + $maxContours = 0; // contours in non-compound glyph + $maxComponentPoints = 0; // points in compound glyph + $maxComponentContours = 0; // contours in compound glyph + $maxComponentElements = 0; // number of glyphs referenced at top level + $maxComponentDepth = 0; // levels of recursion, set to 0 if font has only simple glyphs + $this->glyphdata = []; + + foreach ($subsetglyphs as $originalGlyphIdx => $uni) { + // hmtx - Horizontal Metrics + $hm = $this->getHMetric($orignHmetrics, $originalGlyphIdx); + $hmtxstr .= $hm; + + $offsets[] = $pos; + $glyphPos = $this->glyphPos[$originalGlyphIdx]; + $glyphLen = $this->glyphPos[$originalGlyphIdx + 1] - $glyphPos; + if ($glyfLength < $this->maxStrLenRead) { + $data = substr($glyphData, $glyphPos, $glyphLen); + } else { + if ($glyphLen > 0) { + $data = $this->get_chunk($glyfOffset + $glyphPos, $glyphLen); + } else { + $data = ''; + } + } + + if ($glyphLen > 0) { + if (_RECALC_PROFILE) { + $xMin = $this->unpack_short(substr($data, 2, 2)); + $yMin = $this->unpack_short(substr($data, 4, 2)); + $xMax = $this->unpack_short(substr($data, 6, 2)); + $yMax = $this->unpack_short(substr($data, 8, 2)); + $xMinT = min($xMinT, $xMin); + $yMinT = min($yMinT, $yMin); + $xMaxT = max($xMaxT, $xMax); + $yMaxT = max($yMaxT, $yMax); + $aw = $this->unpack_short(substr($hm, 0, 2)); + $lsb = $this->unpack_short(substr($hm, 2, 2)); + $advanceWidthMax = max($advanceWidthMax, $aw); + $minLeftSideBearing = min($minLeftSideBearing, $lsb); + $minRightSideBearing = min($minRightSideBearing, ($aw - $lsb - ($xMax - $xMin))); + $xMaxExtent = max($xMaxExtent, ($lsb + ($xMax - $xMin))); + } + $up = unpack("n", substr($data, 0, 2)); + } + if ($glyphLen > 2 && ($up[1] & (1 << 15))) { // If number of contours <= -1 i.e. composiste glyph + $pos_in_glyph = 10; + $flags = GlyphOperator::MORE; + $nComponentElements = 0; + while ($flags & GlyphOperator::MORE) { + $nComponentElements += 1; // number of glyphs referenced at top level + $up = unpack("n", substr($data, $pos_in_glyph, 2)); + $flags = $up[1]; + $up = unpack("n", substr($data, $pos_in_glyph + 2, 2)); + $glyphIdx = $up[1]; + $this->glyphdata[$originalGlyphIdx]['compGlyphs'][] = $glyphIdx; + $data = $this->_set_ushort($data, $pos_in_glyph + 2, $glyphSet[$glyphIdx]); + $pos_in_glyph += 4; + if ($flags & GlyphOperator::WORDS) { + $pos_in_glyph += 4; + } else { + $pos_in_glyph += 2; + } + if ($flags & GlyphOperator::SCALE) { + $pos_in_glyph += 2; + } elseif ($flags & GlyphOperator::XYSCALE) { + $pos_in_glyph += 4; + } elseif ($flags & GlyphOperator::TWOBYTWO) { + $pos_in_glyph += 8; + } + } + $maxComponentElements = max($maxComponentElements, $nComponentElements); + + } // Simple Glyph + elseif (_RECALC_PROFILE && $glyphLen > 2 && $up[1] < (1 << 15) && $up[1] > 0) { // Number of contours > 0 simple glyph + $nContours = $up[1]; + $this->glyphdata[$originalGlyphIdx]['nContours'] = $nContours; + $maxContours = max($maxContours, $nContours); + + // Count number of points in simple glyph + $pos_in_glyph = 10 + ($nContours * 2) - 2; // Last endContourPoint + $up = unpack("n", substr($data, $pos_in_glyph, 2)); + $points = $up[1] + 1; + $this->glyphdata[$originalGlyphIdx]['nPoints'] = $points; + $maxPoints = max($maxPoints, $points); + } + + $glyf .= $data; + $pos += $glyphLen; + if ($pos % 4 != 0) { + $padding = 4 - ($pos % 4); + $glyf .= str_repeat("\0", $padding); + $pos += $padding; + } + } + + if (_RECALC_PROFILE) { + foreach ($this->glyphdata as $originalGlyphIdx => $val) { + $maxdepth = $depth = -1; + $points = 0; + $contours = 0; + $this->getGlyphData($originalGlyphIdx, $maxdepth, $depth, $points, $contours); + $maxComponentDepth = max($maxComponentDepth, $maxdepth); + $maxComponentPoints = max($maxComponentPoints, $points); + $maxComponentContours = max($maxComponentContours, $contours); + } + } + + $offsets[] = $pos; + $this->add('glyf', $glyf); + + // hmtx - Horizontal Metrics + $this->add('hmtx', $hmtxstr); + + // loca - Index to location + $locastr = ''; + if ((($pos + 1) >> 1) > 0xFFFF) { + $indexToLocFormat = 1; // long format + foreach ($offsets as $offset) { + $locastr .= pack("N", $offset); + } + } else { + $indexToLocFormat = 0; // short format + foreach ($offsets as $offset) { + $locastr .= pack("n", ($offset / 2)); + } + } + $this->add('loca', $locastr); + + // head - Font header + $head = $this->get_table('head'); + $head = $this->_set_ushort($head, 50, $indexToLocFormat); + + if (_RECALC_PROFILE) { + $head = $this->_set_short($head, 36, $xMinT); // for all glyph bounding boxes + $head = $this->_set_short($head, 38, $yMinT); // for all glyph bounding boxes + $head = $this->_set_short($head, 40, $xMaxT); // for all glyph bounding boxes + $head = $this->_set_short($head, 42, $yMaxT); // for all glyph bounding boxes + $head[17] = chr($head[17] & ~(1 << 4)); // Unset Bit 4 (as hdmx/LTSH tables not included) + } + + $this->add('head', $head); + + // hhea - Horizontal Header + $hhea = $this->get_table('hhea'); + $hhea = $this->_set_ushort($hhea, 34, $numberOfHMetrics); + if (_RECALC_PROFILE) { + $hhea = $this->_set_ushort($hhea, 10, $advanceWidthMax); + $hhea = $this->_set_short($hhea, 12, $minLeftSideBearing); + $hhea = $this->_set_short($hhea, 14, $minRightSideBearing); + $hhea = $this->_set_short($hhea, 16, $xMaxExtent); + } + $this->add('hhea', $hhea); + + // maxp - Maximum Profile + $maxp = $this->get_table('maxp'); + $maxp = $this->_set_ushort($maxp, 4, $numGlyphs); + if (_RECALC_PROFILE) { + $maxp = $this->_set_ushort($maxp, 6, $maxPoints); // points in non-compound glyph + $maxp = $this->_set_ushort($maxp, 8, $maxContours); // contours in non-compound glyph + $maxp = $this->_set_ushort($maxp, 10, $maxComponentPoints); // points in compound glyph + $maxp = $this->_set_ushort($maxp, 12, $maxComponentContours); // contours in compound glyph + $maxp = $this->_set_ushort($maxp, 28, $maxComponentElements); // number of glyphs referenced at top level + $maxp = $this->_set_ushort($maxp, 30, $maxComponentDepth); // levels of recursion, set to 0 if font has only simple glyphs + } + $this->add('maxp', $maxp); + + // OS/2 - OS/2 + if (isset($this->tables['OS/2'])) { + $os2_offset = $this->seek_table("OS/2"); + if (_RECALC_PROFILE) { + $fsSelection = $this->get_ushort($os2_offset + 62); + $fsSelection = ($fsSelection & ~(1 << 6)); // 2-byte bit field containing information concerning the nature of the font patterns + // bit#0 = Italic; bit#5=Bold + // Match name table's font subfamily string + // Clear bit#6 used for 'Regular' and optional + } + + // NB Currently this method never subsets characters above BMP + // Could set nonBMP bit according to $this->maxUni + $nonBMP = $this->get_ushort($os2_offset + 46); + $nonBMP = ($nonBMP & ~(1 << 9)); // Unset Bit 57 (indicates non-BMP) - for interactive forms + + $os2 = $this->get_table('OS/2'); + if (_RECALC_PROFILE) { + $os2 = $this->_set_ushort($os2, 62, $fsSelection); + $os2 = $this->_set_ushort($os2, 66, $fsLastCharIndex); + $os2 = $this->_set_ushort($os2, 42, 0x0000); // ulCharRange (ulUnicodeRange) bits 24-31 | 16-23 + $os2 = $this->_set_ushort($os2, 44, 0x0000); // ulCharRange (Unicode ranges) bits 8-15 | 0-7 + $os2 = $this->_set_ushort($os2, 46, $nonBMP); // ulCharRange (Unicode ranges) bits 56-63 | 48-55 + $os2 = $this->_set_ushort($os2, 48, 0x0000); // ulCharRange (Unicode ranges) bits 40-47 | 32-39 + $os2 = $this->_set_ushort($os2, 50, 0x0000); // ulCharRange (Unicode ranges) bits 88-95 | 80-87 + $os2 = $this->_set_ushort($os2, 52, 0x0000); // ulCharRange (Unicode ranges) bits 72-79 | 64-71 + $os2 = $this->_set_ushort($os2, 54, 0x0000); // ulCharRange (Unicode ranges) bits 120-127 | 112-119 + $os2 = $this->_set_ushort($os2, 56, 0x0000); // ulCharRange (Unicode ranges) bits 104-111 | 96-103 + } + $os2 = $this->_set_ushort($os2, 46, $nonBMP); // Unset Bit 57 (indicates non-BMP) - for interactive forms + + $this->add('OS/2', $os2); + } + + fclose($this->fh); + + // Put the TTF file together + $stm = ''; + $this->endTTFile($stm); + + return $stm; + } + + function makeSubsetSIP($file, &$subset, $TTCfontID = 0, $debug = false, $useOTL = 0) + { + $this->fh = fopen($file, 'rb'); + + if (!$this->fh) { + throw new \Mpdf\MpdfException(sprintf('Unable to open file "%s"', $file)); + } + + $this->filename = $file; + $this->_pos = 0; + $this->useOTL = $useOTL; // mPDF 5.7.1 + $this->charWidths = ''; + $this->glyphPos = []; + $this->charToGlyph = []; + $this->tables = []; + $this->otables = []; + $this->ascent = 0; + $this->descent = 0; + $this->strikeoutSize = 0; + $this->strikeoutPosition = 0; + $this->numTTCFonts = 0; + $this->TTCFonts = []; + $this->skip(4); + + if ($TTCfontID > 0) { + $this->version = $version = $this->read_ulong(); // TTC Header version now + if (!in_array($version, [0x00010000, 0x00020000])) { + throw new \Mpdf\MpdfException("ERROR - Error parsing TrueType Collection: version=" . $version . " - " . $file); + } + $this->numTTCFonts = $this->read_ulong(); + for ($i = 1; $i <= $this->numTTCFonts; $i++) { + $this->TTCFonts[$i]['offset'] = $this->read_ulong(); + } + $this->seek($this->TTCFonts[$TTCfontID]['offset']); + $this->version = $version = $this->read_ulong(); // TTFont version again now + } + $this->readTableDirectory($debug); + + // head - Font header table + $this->seek_table('head'); + $this->skip(50); + $indexToLocFormat = $this->read_ushort(); + $glyphDataFormat = $this->read_ushort(); + + // hhea - Horizontal header table + $this->seek_table('hhea'); + $this->skip(32); + $metricDataFormat = $this->read_ushort(); + $orignHmetrics = $numberOfHMetrics = $this->read_ushort(); + + // maxp - Maximum profile table + $this->seek_table('maxp'); + $this->skip(4); + $numGlyphs = $this->read_ushort(); + + // cmap - Character to glyph index mapping table + $cmap_offset = $this->seek_table('cmap'); + $this->skip(2); + $cmapTableCount = $this->read_ushort(); + $unicode_cmap_offset = 0; + for ($i = 0; $i < $cmapTableCount; $i++) { + + $platformID = $this->read_ushort(); + $encodingID = $this->read_ushort(); + $offset = $this->read_ulong(); + $save_pos = $this->_pos; + + if (($platformID == 3 && $encodingID == 10) || $platformID == 0) { // Microsoft, Unicode Format 12 table HKCS + $format = $this->get_ushort($cmap_offset + $offset); + if ($format == 12) { + $unicode_cmap_offset = $cmap_offset + $offset; + break; + } + } + + if (($platformID == 3 && $encodingID == 1) || $platformID == 0) { // Microsoft, Unicode + $format = $this->get_ushort($cmap_offset + $offset); + if ($format == 4) { + $unicode_cmap_offset = $cmap_offset + $offset; + } + } + + $this->seek($save_pos); + } + + if (!$unicode_cmap_offset) { + throw new \Mpdf\MpdfException(sprintf('Font "%s" does not have cmap for Unicode (platform 3, encoding 1, format 4, or platform 0, any encoding, format 4)', $file)); + } + + // Format 12 CMAP does characters above Unicode BMP i.e. some HKCS characters U+20000 and above + if ($format == 12) { + $this->maxUniChar = 0; + $this->seek($unicode_cmap_offset + 4); + $length = $this->read_ulong(); + $limit = $unicode_cmap_offset + $length; + $this->skip(4); + + $nGroups = $this->read_ulong(); + + $glyphToChar = []; + $charToGlyph = []; + for ($i = 0; $i < $nGroups; $i++) { + $startCharCode = $this->read_ulong(); + $endCharCode = $this->read_ulong(); + $startGlyphCode = $this->read_ulong(); + $offset = 0; + for ($unichar = $startCharCode; $unichar <= $endCharCode; $unichar++) { + $glyph = $startGlyphCode + $offset; + $offset++; + // ZZZ98 + if ($unichar < 0x30000) { + $charToGlyph[$unichar] = $glyph; + $this->maxUniChar = max($unichar, $this->maxUniChar); + $glyphToChar[$glyph][] = $unichar; + } + } + } + } else { + $glyphToChar = []; + $charToGlyph = []; + $this->getCMAP4($unicode_cmap_offset, $glyphToChar, $charToGlyph); + } + + // Map Unmapped glyphs - from $numGlyphs + if ($useOTL) { + $bctr = 0xE000; + for ($gid = 1; $gid < $numGlyphs; $gid++) { + if (!isset($glyphToChar[$gid])) { + while (isset($charToGlyph[$bctr])) { + $bctr++; + } // Avoid overwriting a glyph already mapped in PUA + // ZZZ98 + if ($bctr > 0xF8FF && $bctr < 0x2CEB0) { + $bctr = 0x2CEB0; + while (isset($charToGlyph[$bctr])) { + $bctr++; + } + } + $glyphToChar[$gid][] = $bctr; + $charToGlyph[$bctr] = $gid; + $this->maxUniChar = max($bctr, $this->maxUniChar); + $bctr++; + } + } + } + + // hmtx - Horizontal metrics table + $scale = 1; // not used here + $this->getHMTX($numberOfHMetrics, $numGlyphs, $glyphToChar, $scale); + + // loca - Index to location + $this->getLOCA($indexToLocFormat, $numGlyphs); + + $glyphMap = [0 => 0]; + $glyphSet = [0 => 0]; + $codeToGlyph = []; + + // Set a substitute if ASCII characters do not have glyphs + if (isset($charToGlyph[0x3F])) { + $subs = $charToGlyph[0x3F]; + } else { // Question mark + $subs = $charToGlyph[32]; + } + + foreach ($subset as $code) { + if (isset($charToGlyph[$code])) { + $originalGlyphIdx = $charToGlyph[$code]; + } elseif ($code < 128) { + $originalGlyphIdx = $subs; + } else { + $originalGlyphIdx = 0; + } + if (!isset($glyphSet[$originalGlyphIdx])) { + $glyphSet[$originalGlyphIdx] = count($glyphMap); + $glyphMap[] = $originalGlyphIdx; + } + $codeToGlyph[$code] = $glyphSet[$originalGlyphIdx]; + } + + list($start, $dummy) = $this->get_table_pos('glyf'); + + $n = 0; + while ($n < count($glyphMap)) { + $originalGlyphIdx = $glyphMap[$n]; + $glyphPos = $this->glyphPos[$originalGlyphIdx]; + $glyphLen = $this->glyphPos[$originalGlyphIdx + 1] - $glyphPos; + ++$n; + if (!$glyphLen) { + continue; + } + $this->seek($start + $glyphPos); + $numberOfContours = $this->read_short(); + if ($numberOfContours < 0) { + $this->skip(8); + $flags = GlyphOperator::MORE; + while ($flags & GlyphOperator::MORE) { + $flags = $this->read_ushort(); + $glyphIdx = $this->read_ushort(); + if (!isset($glyphSet[$glyphIdx])) { + $glyphSet[$glyphIdx] = count($glyphMap); + $glyphMap[] = $glyphIdx; + } + if ($flags & GlyphOperator::WORDS) { + $this->skip(4); + } else { + $this->skip(2); + } + if ($flags & GlyphOperator::SCALE) { + $this->skip(2); + } elseif ($flags & GlyphOperator::XYSCALE) { + $this->skip(4); + } elseif ($flags & GlyphOperator::TWOBYTWO) { + $this->skip(8); + } + } + } + } + + $numGlyphs = $n = count($glyphMap); + $numberOfHMetrics = $n; + + // MS spec says that "Platform and encoding ID's in the name table should be consistent with those in the cmap table. + // If they are not, the font will not load in Windows" + // Doesn't seem to be a problem? + // Needs to have a name entry in 3,0 (e.g. symbol) - original font will be 3,1 (i.e. Unicode) + $name = $this->get_table('name'); + $name_offset = $this->seek_table("name"); + $format = $this->read_ushort(); + $numRecords = $this->read_ushort(); + $string_data_offset = $name_offset + $this->read_ushort(); + for ($i = 0; $i < $numRecords; $i++) { + $platformId = $this->read_ushort(); + $encodingId = $this->read_ushort(); + if ($platformId == 3 && $encodingId == 1) { + $pos = 6 + ($i * 12) + 2; + $name = $this->_set_ushort($name, $pos, 0x00); // Change encoding to 3,0 rather than 3,1 + } + $this->skip(8); + } + $this->add('name', $name); + + // OS/2 + if (isset($this->tables['OS/2'])) { + $os2 = $this->get_table('OS/2'); + $os2 = $this->_set_ushort($os2, 42, 0x00); // ulCharRange (Unicode ranges) + $os2 = $this->_set_ushort($os2, 44, 0x00); // ulCharRange (Unicode ranges) + $os2 = $this->_set_ushort($os2, 46, 0x00); // ulCharRange (Unicode ranges) + $os2 = $this->_set_ushort($os2, 48, 0x00); // ulCharRange (Unicode ranges) + + $os2 = $this->_set_ushort($os2, 50, 0x00); // ulCharRange (Unicode ranges) + $os2 = $this->_set_ushort($os2, 52, 0x00); // ulCharRange (Unicode ranges) + $os2 = $this->_set_ushort($os2, 54, 0x00); // ulCharRange (Unicode ranges) + $os2 = $this->_set_ushort($os2, 56, 0x00); // ulCharRange (Unicode ranges) + // Set Symbol character only in ulCodePageRange + $os2 = $this->_set_ushort($os2, 78, 0x8000); // ulCodePageRange = Bit #31 Symbol **** 78 = Bit 16-31 + $os2 = $this->_set_ushort($os2, 80, 0x0000); // ulCodePageRange = Bit #31 Symbol **** 80 = Bit 0-15 + $os2 = $this->_set_ushort($os2, 82, 0x0000); // ulCodePageRange = Bit #32- Symbol **** 82 = Bits 48-63 + $os2 = $this->_set_ushort($os2, 84, 0x0000); // ulCodePageRange = Bit #32- Symbol **** 84 = Bits 32-47 + + $os2 = $this->_set_ushort($os2, 64, 0x01); // FirstCharIndex + $os2 = $this->_set_ushort($os2, 66, count($subset)); // LastCharIndex + // Set PANOSE first bit to 5 for Symbol + $os2 = $this->splice($os2, 32, chr(5) . chr(0) . chr(1) . chr(0) . chr(1) . chr(0) . chr(0) . chr(0) . chr(0) . chr(0)); + $this->add('OS/2', $os2); + } + + //tables copied from the original + $tags = ['cvt ', 'fpgm', 'prep', 'gasp']; + foreach ($tags as $tag) { // 1.02 + if (isset($this->tables[$tag])) { + $this->add($tag, $this->get_table($tag)); + } + } + + // post - PostScript + if (isset($this->tables['post'])) { + $opost = $this->get_table('post'); + $post = "\x00\x03\x00\x00" . substr($opost, 4, 12) . "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"; + } + $this->add('post', $post); + + // hhea - Horizontal Header + $hhea = $this->get_table('hhea'); + $hhea = $this->_set_ushort($hhea, 34, $numberOfHMetrics); + $this->add('hhea', $hhea); + + // maxp - Maximum Profile + $maxp = $this->get_table('maxp'); + $maxp = $this->_set_ushort($maxp, 4, $numGlyphs); + $this->add('maxp', $maxp); + + // CMap table Formats [1,0,]6 and [3,0,]4 + // Sort CID2GID map into segments of contiguous codes + $rangeid = 0; + $range = []; + $prevcid = -2; + $prevglidx = -1; + + // for each character + foreach ($subset as $cid => $code) { + $glidx = $codeToGlyph[$code]; + if ($cid == ($prevcid + 1) && $glidx == ($prevglidx + 1)) { + $range[$rangeid][] = $glidx; + } else { + // new range + $rangeid = $cid; + $range[$rangeid] = []; + $range[$rangeid][] = $glidx; + } + $prevcid = $cid; + $prevglidx = $glidx; + } + + // cmap - Character to glyph mapping + $segCount = count($range) + 1; // + 1 Last segment has missing character 0xFFFF + $searchRange = 1; + $entrySelector = 0; + + while ($searchRange * 2 <= $segCount) { + $searchRange = $searchRange * 2; + $entrySelector = $entrySelector + 1; + } + + $searchRange = $searchRange * 2; + $rangeShift = $segCount * 2 - $searchRange; + $length = 16 + (8 * $segCount) + ($numGlyphs + 1); + $cmap = [ + 4, $length, 0, // Format 4 Mapping subtable: format, length, language + $segCount * 2, + $searchRange, + $entrySelector, + $rangeShift, + ]; + + // endCode(s) + foreach ($range as $start => $subrange) { + $endCode = $start + (count($subrange) - 1); + $cmap[] = $endCode; // endCode(s) + } + $cmap[] = 0xFFFF; // endCode of last Segment + $cmap[] = 0; // reservedPad + + // startCode(s) + foreach ($range as $start => $subrange) { + $cmap[] = $start; // startCode(s) + } + $cmap[] = 0xFFFF; // startCode of last Segment + + // idDelta(s) + foreach ($range as $start => $subrange) { + $idDelta = -($start - $subrange[0]); + $n += count($subrange); + $cmap[] = $idDelta; // idDelta(s) + } + $cmap[] = 1; // idDelta of last Segment + + // idRangeOffset(s) + foreach ($range as $subrange) { + $cmap[] = 0; // idRangeOffset[segCount] Offset in bytes to glyph indexArray, or 0 + } + + $cmap[] = 0; // idRangeOffset of last Segment + foreach ($range as $subrange) { + foreach ($subrange as $glidx) { + $cmap[] = $glidx; + } + } + + $cmap[] = 0; // Mapping for last character + $cmapstr4 = ''; + foreach ($cmap as $cm) { + $cmapstr4 .= pack("n", $cm); + } + + // cmap - Character to glyph mapping + $entryCount = count($subset); + $length = 10 + $entryCount * 2; + + $off = 20 + $length; + $hoff = $off >> 16; + $loff = $off & 0xFFFF; + + $cmap = [ + 0, 2, // Index : version, number of subtables + 1, 0, // Subtable : platform, encoding + 0, 20, // offset (hi,lo) + 3, 0, // Subtable : platform, encoding // See note above for 'name' + $hoff, $loff, // offset (hi,lo) + 6, $length, // Format 6 Mapping table: format, length + 0, 1, // language, First char code + $entryCount, + ]; + + $cmapstr = ''; + foreach ($subset as $code) { + $cmap[] = $codeToGlyph[$code]; + } + + foreach ($cmap as $cm) { + $cmapstr .= pack("n", $cm); + } + + $cmapstr .= $cmapstr4; + $this->add('cmap', $cmapstr); + + // hmtx - Horizontal Metrics + $hmtxstr = ''; + for ($n = 0; $n < $numGlyphs; $n++) { + $originalGlyphIdx = $glyphMap[$n]; + $hm = $this->getHMetric($orignHmetrics, $originalGlyphIdx); + $hmtxstr .= $hm; + } + $this->add('hmtx', $hmtxstr); + + // glyf - Glyph data + list($glyfOffset, $glyfLength) = $this->get_table_pos('glyf'); + if ($glyfLength < $this->maxStrLenRead) { + $glyphData = $this->get_table('glyf'); + } + + $offsets = []; + $glyf = ''; + $pos = 0; + for ($n = 0; $n < $numGlyphs; $n++) { + + $offsets[] = $pos; + $originalGlyphIdx = $glyphMap[$n]; + $glyphPos = $this->glyphPos[$originalGlyphIdx]; + $glyphLen = $this->glyphPos[$originalGlyphIdx + 1] - $glyphPos; + + if ($glyfLength < $this->maxStrLenRead) { + $data = substr($glyphData, $glyphPos, $glyphLen); + } else { + if ($glyphLen > 0) { + $data = $this->get_chunk($glyfOffset + $glyphPos, $glyphLen); + } else { + $data = ''; + } + } + + if ($glyphLen > 0) { + $up = unpack('n', substr($data, 0, 2)); + } + + if ($glyphLen > 2 && ($up[1] & (1 << 15))) { + + $pos_in_glyph = 10; + $flags = GlyphOperator::MORE; + + while ($flags & GlyphOperator::MORE) { + $up = unpack('n', substr($data, $pos_in_glyph, 2)); + $flags = $up[1]; + $up = unpack('n', substr($data, $pos_in_glyph + 2, 2)); + $glyphIdx = $up[1]; + $data = $this->_set_ushort($data, $pos_in_glyph + 2, $glyphSet[$glyphIdx]); + $pos_in_glyph += 4; + + if ($flags & GlyphOperator::WORDS) { + $pos_in_glyph += 4; + } else { + $pos_in_glyph += 2; + } + + if ($flags & GlyphOperator::SCALE) { + $pos_in_glyph += 2; + } elseif ($flags & GlyphOperator::XYSCALE) { + $pos_in_glyph += 4; + } elseif ($flags & GlyphOperator::TWOBYTWO) { + $pos_in_glyph += 8; + } + } + } + + $glyf .= $data; + $pos += $glyphLen; + + if ($pos % 4 != 0) { + $padding = 4 - ($pos % 4); + $glyf .= str_repeat("\0", $padding); + $pos += $padding; + } + } + + $offsets[] = $pos; + $this->add('glyf', $glyf); + + // loca - Index to location + $locastr = ''; + if ((($pos + 1) >> 1) > 0xFFFF) { + $indexToLocFormat = 1; // long format + foreach ($offsets as $offset) { + $locastr .= pack("N", $offset); + } + } else { + $indexToLocFormat = 0; // short format + foreach ($offsets as $offset) { + $locastr .= pack("n", ($offset / 2)); + } + } + + $this->add('loca', $locastr); + + // head - Font header + $head = $this->get_table('head'); + $head = $this->_set_ushort($head, 50, $indexToLocFormat); + $this->add('head', $head); + + fclose($this->fh); + + $stm = ''; + $this->endTTFile($stm); + + return $stm; + } + + function getGlyphData($originalGlyphIdx, &$maxdepth, &$depth, &$points, &$contours) + { + $depth++; + $maxdepth = max($maxdepth, $depth); + + if (count($this->glyphdata[$originalGlyphIdx]['compGlyphs'])) { + foreach ($this->glyphdata[$originalGlyphIdx]['compGlyphs'] as $glyphIdx) { + $this->getGlyphData($glyphIdx, $maxdepth, $depth, $points, $contours); + } + } elseif (($this->glyphdata[$originalGlyphIdx]['nContours'] > 0) && $depth > 0) { // simple + $contours += $this->glyphdata[$originalGlyphIdx]['nContours']; + $points += $this->glyphdata[$originalGlyphIdx]['nPoints']; + } + + $depth--; + } + + function getGlyphs($originalGlyphIdx, &$start, &$glyphSet, &$subsetglyphs) + { + $glyphPos = $this->glyphPos[$originalGlyphIdx]; + $glyphLen = $this->glyphPos[$originalGlyphIdx + 1] - $glyphPos; + + if (!$glyphLen) { + return; + } + + $this->seek($start + $glyphPos); + $numberOfContours = $this->read_short(); + + if ($numberOfContours < 0) { + $this->skip(8); + $flags = GlyphOperator::MORE; + while ($flags & GlyphOperator::MORE) { + $flags = $this->read_ushort(); + $glyphIdx = $this->read_ushort(); + if (!isset($glyphSet[$glyphIdx])) { + $glyphSet[$glyphIdx] = count($subsetglyphs); // old glyphID to new glyphID + $subsetglyphs[$glyphIdx] = true; + } + $savepos = ftell($this->fh); + $this->getGlyphs($glyphIdx, $start, $glyphSet, $subsetglyphs); + $this->seek($savepos); + if ($flags & GlyphOperator::WORDS) { + $this->skip(4); + } else { + $this->skip(2); + } + if ($flags & GlyphOperator::SCALE) { + $this->skip(2); + } elseif ($flags & GlyphOperator::XYSCALE) { + $this->skip(4); + } elseif ($flags & GlyphOperator::TWOBYTWO) { + $this->skip(8); + } + } + } + } + + function getHMTX($numberOfHMetrics, $numGlyphs, &$glyphToChar, $scale) + { + $start = $this->seek_table('hmtx'); + $aw = 0; + $this->charWidths = str_pad('', 256 * 256 * 2, "\x00"); + + if ($this->maxUniChar > 65536) { + $this->charWidths .= str_pad('', 256 * 256 * 2, "\x00"); + } // Plane 1 SMP + + if ($this->maxUniChar > 131072) { + $this->charWidths .= str_pad('', 256 * 256 * 2, "\x00"); + } // Plane 2 SMP + + $nCharWidths = 0; + if (($numberOfHMetrics * 4) < $this->maxStrLenRead) { + $data = $this->get_chunk($start, $numberOfHMetrics * 4); + $arr = unpack('n*', $data); + } else { + $this->seek($start); + } + + for ($glyph = 0; $glyph < $numberOfHMetrics; $glyph++) { + + if (($numberOfHMetrics * 4) < $this->maxStrLenRead) { + $aw = $arr[($glyph * 2) + 1]; + } else { + $aw = $this->read_ushort(); + $lsb = $this->read_ushort(); + } + if (isset($glyphToChar[$glyph]) || $glyph == 0) { + if ($aw >= (1 << 15)) { + $aw = 0; + } + + // 1.03 Some (arabic) fonts have -ve values for width + // although should be unsigned value - comes out as e.g. 65108 (intended -50) + if ($glyph === 0) { + $this->defaultWidth = $scale * $aw; + continue; + } + + foreach ($glyphToChar[$glyph] as $char) { + if ($char != 0 && $char != 65535) { + $w = (int) round($scale * $aw); + if ($w === 0) { + $w = 65535; + } + if ($char < 196608) { + $this->charWidths[$char * 2] = chr($w >> 8); + $this->charWidths[$char * 2 + 1] = chr($w & 0xFF); + $nCharWidths++; + } + } + } + } + } + + $data = $this->get_chunk(($start + $numberOfHMetrics * 4), ($numGlyphs * 2)); + $arr = unpack("n*", $data); + $diff = $numGlyphs - $numberOfHMetrics; + $w = (int) round($scale * $aw); + if ($w === 0) { + $w = 65535; + } + for ($pos = 0; $pos < $diff; $pos++) { + $glyph = $pos + $numberOfHMetrics; + if (isset($glyphToChar[$glyph])) { + foreach ($glyphToChar[$glyph] as $char) { + if ($char != 0 && $char != 65535) { + if ($char < 196608) { + $this->charWidths[$char * 2] = chr($w >> 8); + $this->charWidths[$char * 2 + 1] = chr($w & 0xFF); + $nCharWidths++; + } + } + } + } + } + + // NB 65535 is a set width of 0 + // First bytes define number of chars in font + $this->charWidths[0] = chr($nCharWidths >> 8); + $this->charWidths[1] = chr($nCharWidths & 0xFF); + } + + function getHMetric($numberOfHMetrics, $gid) + { + $start = $this->seek_table("hmtx"); + if ($gid < $numberOfHMetrics) { + $this->seek($start + ($gid * 4)); + $hm = fread($this->fh, 4); + } else { + $this->seek($start + (($numberOfHMetrics - 1) * 4)); + $hm = fread($this->fh, 2); + $this->seek($start + ($numberOfHMetrics * 2) + ($gid * 2)); + $hm .= fread($this->fh, 2); + } + + return $hm; + } + + function getLOCA($indexToLocFormat, $numGlyphs) + { + $start = $this->seek_table('loca'); + $this->glyphPos = []; + if ($indexToLocFormat == 0) { + $data = $this->get_chunk($start, ($numGlyphs * 2) + 2); + $arr = unpack("n*", $data); + for ($n = 0; $n <= $numGlyphs; $n++) { + $this->glyphPos[] = ($arr[$n + 1] * 2); + } + } elseif ($indexToLocFormat == 1) { + $data = $this->get_chunk($start, ($numGlyphs * 4) + 4); + $arr = unpack("N*", $data); + for ($n = 0; $n <= $numGlyphs; $n++) { + $this->glyphPos[] = ($arr[$n + 1]); + } + } else { + throw new \Mpdf\MpdfException('Unknown location table format ' . $indexToLocFormat); + } + } + + /** + * CMAP Format 4 + */ + function getCMAP4($unicode_cmap_offset, &$glyphToChar, &$charToGlyph) + { + $this->maxUniChar = 0; + $this->seek($unicode_cmap_offset + 2); + $length = $this->read_ushort(); + $limit = $unicode_cmap_offset + $length; + $this->skip(2); + + $segCount = $this->read_ushort() / 2; + $this->skip(6); + $endCount = []; + + for ($i = 0; $i < $segCount; $i++) { + $endCount[] = $this->read_ushort(); + } + + $this->skip(2); + $startCount = []; + + for ($i = 0; $i < $segCount; $i++) { + $startCount[] = $this->read_ushort(); + } + + $idDelta = []; + + for ($i = 0; $i < $segCount; $i++) { + $idDelta[] = $this->read_short(); + } // ???? was unsigned short + + $idRangeOffset_start = $this->_pos; + $idRangeOffset = []; + + for ($i = 0; $i < $segCount; $i++) { + $idRangeOffset[] = $this->read_ushort(); + } + + for ($n = 0; $n < $segCount; $n++) { + $endpoint = ($endCount[$n] + 1); + for ($unichar = $startCount[$n]; $unichar < $endpoint; $unichar++) { + if ($idRangeOffset[$n] == 0) { + $glyph = ($unichar + $idDelta[$n]) & 0xFFFF; + } else { + $offset = ($unichar - $startCount[$n]) * 2 + $idRangeOffset[$n]; + $offset = $idRangeOffset_start + 2 * $n + $offset; + if ($offset >= $limit) { + $glyph = 0; + } else { + $glyph = $this->get_ushort($offset); + if ($glyph != 0) { + $glyph = ($glyph + $idDelta[$n]) & 0xFFFF; + } + } + } + $charToGlyph[$unichar] = $glyph; + if ($unichar < 196608) { + $this->maxUniChar = max($unichar, $this->maxUniChar); + } + $glyphToChar[$glyph][] = $unichar; + } + } + } + + function endTTFile(&$stm) + { + $stm = ''; + $numTables = count($this->otables); + $searchRange = 1; + $entrySelector = 0; + while ($searchRange * 2 <= $numTables) { + $searchRange *= 2; + $entrySelector += 1; + } + $searchRange *= 16; + $rangeShift = $numTables * 16 - $searchRange; + + // Header + if (_TTF_MAC_HEADER) { + $stm .= pack('Nnnnn', 0x74727565, $numTables, $searchRange, $entrySelector, $rangeShift); // Mac + } else { + $stm .= pack('Nnnnn', 0x00010000, $numTables, $searchRange, $entrySelector, $rangeShift); // Windows + } + + // Table directory + $tables = $this->otables; + ksort($tables); + $offset = 12 + $numTables * 16; + foreach ($tables as $tag => $data) { + if ($tag === 'head') { + $head_start = $offset; + } + $stm .= $tag; + $checksum = $this->calcChecksum($data); + $stm .= pack('nn', $checksum[0], $checksum[1]); + $stm .= pack('NN', $offset, strlen($data)); + $paddedLength = (strlen($data) + 3) & ~3; + $offset += $paddedLength; + } + + // Table data + foreach ($tables as $tag => $data) { + $data .= "\0\0\0"; + $stm .= substr($data, 0, (strlen($data) & ~3)); + } + + $checksum = $this->calcChecksum($stm); + $checksum = $this->sub32([0xB1B0, 0xAFBA], $checksum); + $chk = pack("nn", $checksum[0], $checksum[1]); + $stm = $this->splice($stm, ($head_start + 8), $chk); + + return $stm; + } + + function repackageTTF($file, $TTCfontID = 0, $debug = false, $useOTL = false) + { + $this->useOTL = $useOTL; + $this->filename = $file; + $this->fh = fopen($file, 'rb'); + + if (!$this->fh) { + throw new \Mpdf\MpdfException(sprintf('Unable to open file "%s"', $file)); + } + + $this->_pos = 0; + $this->charWidths = ''; + $this->glyphPos = []; + $this->charToGlyph = []; + $this->tables = []; + $this->otables = []; + $this->ascent = 0; + $this->descent = 0; + $this->strikeoutSize = 0; + $this->strikeoutPosition = 0; + $this->numTTCFonts = 0; + $this->TTCFonts = []; + $this->skip(4); + $this->maxUni = 0; + + if ($TTCfontID > 0) { + $this->version = $version = $this->read_ulong(); // TTC Header version now + if (!in_array($version, [0x00010000, 0x00020000], true)) { + throw new \Mpdf\MpdfException(sprintf('Error parsing TrueType Collection: version=%s - %s', $version, $file)); + } + $this->numTTCFonts = $this->read_ulong(); + for ($i = 1; $i <= $this->numTTCFonts; $i++) { + $this->TTCFonts[$i]['offset'] = $this->read_ulong(); + } + $this->seek($this->TTCFonts[$TTCfontID]['offset']); + $this->version = $version = $this->read_ulong(); // TTFont version again now + } + + $this->readTableDirectory($debug); + $tags = ['OS/2', 'glyf', 'head', 'hhea', 'hmtx', 'loca', 'maxp', 'name', 'post', 'cvt ', 'fpgm', 'gasp', 'prep']; + + foreach ($tags as $tag) { + if (isset($this->tables[$tag])) { + $this->add($tag, $this->get_table($tag)); + } + } + + if ($useOTL) { + + // maxp - Maximum profile table + $this->seek_table('maxp'); + $this->skip(4); + $numGlyphs = $this->read_ushort(); + + // cmap - Character to glyph index mapping table + $cmap_offset = $this->seek_table('cmap'); + $this->skip(2); + $cmapTableCount = $this->read_ushort(); + $unicode_cmap_offset = 0; + for ($i = 0; $i < $cmapTableCount; $i++) { + $platformID = $this->read_ushort(); + $encodingID = $this->read_ushort(); + $offset = $this->read_ulong(); + $save_pos = $this->_pos; + if (($platformID == 3 && $encodingID == 1) || $platformID == 0) { // Microsoft, Unicode + $format = $this->get_ushort($cmap_offset + $offset); + if ($format == 4) { + $unicode_cmap_offset = $cmap_offset + $offset; + break; + } + } + $this->seek($save_pos); + } + + if (!$unicode_cmap_offset) { + throw new \Mpdf\MpdfException(sprintf('Font "%s" does not have cmap for Unicode (platform 3, encoding 1, format 4, or platform 0, any encoding, format 4)', $this->filename)); + } + + $glyphToChar = []; + $charToGlyph = []; + $this->getCMAP4($unicode_cmap_offset, $glyphToChar, $charToGlyph); + + // Map Unmapped glyphs - from $numGlyphs + $bctr = 0xE000; + for ($gid = 1; $gid < $numGlyphs; $gid++) { + if (!isset($glyphToChar[$gid])) { + while (isset($charToGlyph[$bctr])) { + $bctr++; + } // Avoid overwriting a glyph already mapped in PUA (6,400) + if ($bctr > 0xF8FF) { + throw new \Mpdf\MpdfException("Problem. Trying to repackage TF file; not enough space for unmapped glyphs"); + } + $glyphToChar[$gid][] = $bctr; + $charToGlyph[$bctr] = $gid; + $bctr++; + } + } + + // Sort CID2GID map into segments of contiguous codes + unset($charToGlyph[65535]); + unset($charToGlyph[0]); + + ksort($charToGlyph); + $rangeid = 0; + $range = []; + $prevcid = -2; + $prevglidx = -1; + + // for each character + foreach ($charToGlyph as $cid => $glidx) { + if ($cid == ($prevcid + 1) && $glidx == ($prevglidx + 1)) { + $range[$rangeid][] = $glidx; + } else { + // new range + $rangeid = $cid; + $range[$rangeid] = []; + $range[$rangeid][] = $glidx; + } + $prevcid = $cid; + $prevglidx = $glidx; + } + + // CMap table + // cmap - Character to glyph mapping + $segCount = count($range) + 1; // + 1 Last segment has missing character 0xFFFF + $searchRange = 1; + $entrySelector = 0; + + while ($searchRange * 2 <= $segCount) { + $searchRange *= 2; + ++$entrySelector; + } + + $searchRange *= 2; + $rangeShift = $segCount * 2 - $searchRange; + $length = 16 + (8 * $segCount) + ($numGlyphs + 1); + $cmap = [0, 3, // Index : version, number of encoding subtables + 0, 0, // Encoding Subtable : platform (UNI=0), encoding 0 + 0, 28, // Encoding Subtable : offset (hi,lo) + 0, 3, // Encoding Subtable : platform (UNI=0), encoding 3 + 0, 28, // Encoding Subtable : offset (hi,lo) + 3, 1, // Encoding Subtable : platform (MS=3), encoding 1 + 0, 28, // Encoding Subtable : offset (hi,lo) + 4, $length, 0, // Format 4 Mapping subtable: format, length, language + $segCount * 2, + $searchRange, + $entrySelector, + $rangeShift]; + + // endCode(s) + foreach ($range as $start => $subrange) { + $endCode = $start + (count($subrange) - 1); + $cmap[] = $endCode; // endCode(s) + } + $cmap[] = 0xFFFF; // endCode of last Segment + $cmap[] = 0; // reservedPad + + // startCode(s) + foreach ($range as $start => $subrange) { + $cmap[] = $start; // startCode(s) + } + $cmap[] = 0xFFFF; // startCode of last Segment + + // idDelta(s) + foreach ($range as $start => $subrange) { + $idDelta = -($start - $subrange[0]); + $cmap[] = $idDelta; // idDelta(s) + } + + $cmap[] = 1; // idDelta of last Segment + // idRangeOffset(s) + foreach ($range as $subrange) { + $cmap[] = 0; // idRangeOffset[segCount] Offset in bytes to glyph indexArray, or 0 + } + + $cmap[] = 0; // idRangeOffset of last Segment + foreach ($range as $subrange) { + foreach ($subrange as $glidx) { + $cmap[] = $glidx; + } + } + $cmap[] = 0; // Mapping for last character + $cmapstr = ''; + foreach ($cmap as $cm) { + $cmapstr .= pack('n', $cm); + } + + $this->add('cmap', $cmapstr); + } else { + $this->add('cmap', $this->get_table('cmap')); + } + + fclose($this->fh); + $stm = ''; + $this->endTTFile($stm); + + return $stm; + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/TTFontFileAnalysis.php b/src/bb-vendor/mpdf/mpdf/src/TTFontFileAnalysis.php new file mode 100644 index 000000000..2851ea0b0 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/TTFontFileAnalysis.php @@ -0,0 +1,454 @@ +<?php + +namespace Mpdf; + +class TTFontFileAnalysis extends TTFontFile +{ + + // Used to get font information from files in directory + function extractCoreInfo($file, $TTCfontID = 0) + { + $this->filename = $file; + $this->fh = fopen($file, 'rb'); + if (!$this->fh) { + throw new \Mpdf\MpdfException('ERROR - Can\'t open file ' . $file); + } + $this->_pos = 0; + $this->charWidths = ''; + $this->glyphPos = []; + $this->charToGlyph = []; + $this->tables = []; + $this->otables = []; + $this->ascent = 0; + $this->descent = 0; + $this->numTTCFonts = 0; + $this->TTCFonts = []; + $this->version = $version = $this->read_ulong(); + $this->panose = []; // mPDF 5.0 + + if ($version == 0x4F54544F) { + throw new \Mpdf\MpdfException('ERROR - NOT ADDED as Postscript outlines are not supported - ' . $file); + } + + if ($version == 0x74746366) { + if ($TTCfontID > 0) { + $this->version = $version = $this->read_ulong(); // TTC Header version now + if (!in_array($version, [0x00010000, 0x00020000])) { + throw new \Mpdf\MpdfException("ERROR - NOT ADDED as Error parsing TrueType Collection: version=" . $version . " - " . $file); + } + } else { + throw new \Mpdf\MpdfException("ERROR - Error parsing TrueType Collection - " . $file); + } + $this->numTTCFonts = $this->read_ulong(); + for ($i = 1; $i <= $this->numTTCFonts; $i++) { + $this->TTCFonts[$i]['offset'] = $this->read_ulong(); + } + $this->seek($this->TTCFonts[$TTCfontID]['offset']); + $this->version = $version = $this->read_ulong(); // TTFont version again now + $this->readTableDirectory(false); + } else { + if (!in_array($version, [0x00010000, 0x74727565])) { + throw new \Mpdf\MpdfException("ERROR - NOT ADDED as Not a TrueType font: version=" . $version . " - " . $file); + } + $this->readTableDirectory(false); + } + + /* Included for testing... + $cmap_offset = $this->seek_table("cmap"); + $this->skip(2); + $cmapTableCount = $this->read_ushort(); + $unicode_cmap_offset = 0; + for ($i=0;$i<$cmapTableCount;$i++) { + $x[$i]['platformId'] = $this->read_ushort(); + $x[$i]['encodingId'] = $this->read_ushort(); + $x[$i]['offset'] = $this->read_ulong(); + $save_pos = $this->_pos; + $x[$i]['format'] = $this->get_ushort($cmap_offset + $x[$i]['offset'] ); + $this->seek($save_pos ); + } + print_r($x); exit; + */ + /////////////////////////////////// + // name - Naming table + /////////////////////////////////// + + /* Test purposes - displays table of names + $name_offset = $this->seek_table("name"); + $format = $this->read_ushort(); + if ($format != 0 && $format != 1) // mPDF 5.3.73 + die("Unknown name table format ".$format); + $numRecords = $this->read_ushort(); + $string_data_offset = $name_offset + $this->read_ushort(); + for ($i=0;$i<$numRecords; $i++) { + $x[$i]['platformId'] = $this->read_ushort(); + $x[$i]['encodingId'] = $this->read_ushort(); + $x[$i]['languageId'] = $this->read_ushort(); + $x[$i]['nameId'] = $this->read_ushort(); + $x[$i]['length'] = $this->read_ushort(); + $x[$i]['offset'] = $this->read_ushort(); + + $N = ''; + if ($x[$i]['platformId'] == 1 && $x[$i]['encodingId'] == 0 && $x[$i]['languageId'] == 0) { // Roman + $opos = $this->_pos; + $N = $this->get_chunk($string_data_offset + $x[$i]['offset'] , $x[$i]['length'] ); + $this->_pos = $opos; + $this->seek($opos); + } + else { // Unicode + $opos = $this->_pos; + $this->seek($string_data_offset + $x[$i]['offset'] ); + $length = $x[$i]['length'] ; + if ($length % 2 != 0) + $length -= 1; + // die("PostScript name is UTF-16BE string of odd length"); + $length /= 2; + $N = ''; + while ($length > 0) { + $char = $this->read_ushort(); + $N .= (chr($char)); + $length -= 1; + } + $this->_pos = $opos; + $this->seek($opos); + } + $x[$i]['names'][$nameId] = $N; + } + print_r($x); exit; + */ + + $name_offset = $this->seek_table("name"); + $format = $this->read_ushort(); + if ($format != 0 && $format != 1) { // mPDF 5.3.73 + throw new \Mpdf\MpdfException("ERROR - NOT ADDED as Unknown name table format " . $format . " - " . $file); + } + $numRecords = $this->read_ushort(); + $string_data_offset = $name_offset + $this->read_ushort(); + $names = [1 => '', 2 => '', 3 => '', 4 => '', 6 => '']; + $K = array_keys($names); + $nameCount = count($names); + for ($i = 0; $i < $numRecords; $i++) { + $platformId = $this->read_ushort(); + $encodingId = $this->read_ushort(); + $languageId = $this->read_ushort(); + $nameId = $this->read_ushort(); + $length = $this->read_ushort(); + $offset = $this->read_ushort(); + if (!in_array($nameId, $K)) { + continue; + } + $N = ''; + if ($platformId == 3 && $encodingId == 1 && $languageId == 0x409) { // Microsoft, Unicode, US English, PS Name + $opos = $this->_pos; + $this->seek($string_data_offset + $offset); + if ($length % 2 != 0) { + $length += 1; + } + $length /= 2; + $N = ''; + while ($length > 0) { + $char = $this->read_ushort(); + $N .= (chr($char)); + $length -= 1; + } + $this->_pos = $opos; + $this->seek($opos); + } elseif ($platformId == 1 && $encodingId == 0 && $languageId == 0) { // Macintosh, Roman, English, PS Name + $opos = $this->_pos; + $N = $this->get_chunk($string_data_offset + $offset, $length); + $this->_pos = $opos; + $this->seek($opos); + } + if ($N && $names[$nameId] == '') { + $names[$nameId] = $N; + $nameCount -= 1; + if ($nameCount == 0) { + break; + } + } + } + if ($names[6]) { + $psName = preg_replace('/ /', '-', $names[6]); + } elseif ($names[4]) { + $psName = preg_replace('/ /', '-', $names[4]); + } elseif ($names[1]) { + $psName = preg_replace('/ /', '-', $names[1]); + } else { + $psName = ''; + } + if (!$names[1] && !$psName) { + throw new \Mpdf\MpdfException("ERROR - NOT ADDED as Could not find valid font name - " . $file); + } + $this->name = $psName; + if ($names[1]) { + $this->familyName = $names[1]; + } else { + $this->familyName = $psName; + } + if ($names[2]) { + $this->styleName = $names[2]; + } else { + $this->styleName = 'Regular'; + } + + /////////////////////////////////// + // head - Font header table + /////////////////////////////////// + $this->seek_table("head"); + $ver_maj = $this->read_ushort(); + $ver_min = $this->read_ushort(); + if ($ver_maj != 1) { + throw new \Mpdf\MpdfException('ERROR - NOT ADDED as Unknown head table version ' . $ver_maj . '.' . $ver_min . " - " . $file); + } + $this->fontRevision = $this->read_ushort() . $this->read_ushort(); + $this->skip(4); + $magic = $this->read_ulong(); + if ($magic != 0x5F0F3CF5) { + throw new \Mpdf\MpdfException('ERROR - NOT ADDED as Invalid head table magic ' . $magic . " - " . $file); + } + $this->skip(2); + $this->unitsPerEm = $unitsPerEm = $this->read_ushort(); + $scale = 1000 / $unitsPerEm; + $this->skip(24); + $macStyle = $this->read_short(); + $this->skip(4); + $indexLocFormat = $this->read_short(); + + /////////////////////////////////// + // OS/2 - OS/2 and Windows metrics table + /////////////////////////////////// + $sFamily = ''; + $panose = ''; + $fsSelection = ''; + if (isset($this->tables["OS/2"])) { + $this->seek_table("OS/2"); + $this->skip(30); + $sF = $this->read_short(); + $sFamily = ($sF >> 8); + $this->_pos += 10; //PANOSE = 10 byte length + $panose = fread($this->fh, 10); + $this->panose = []; + for ($p = 0; $p < strlen($panose); $p++) { + $this->panose[] = ord($panose[$p]); + } + $this->skip(20); + $fsSelection = $this->read_short(); + } + + /////////////////////////////////// + // post - PostScript table + /////////////////////////////////// + $this->seek_table("post"); + $this->skip(4); + $this->italicAngle = $this->read_short() + $this->read_ushort() / 65536.0; + $this->skip(4); + $isFixedPitch = $this->read_ulong(); + + + + /////////////////////////////////// + // cmap - Character to glyph index mapping table + /////////////////////////////////// + $cmap_offset = $this->seek_table("cmap"); + $this->skip(2); + $cmapTableCount = $this->read_ushort(); + $unicode_cmap_offset = 0; + for ($i = 0; $i < $cmapTableCount; $i++) { + $platformID = $this->read_ushort(); + $encodingID = $this->read_ushort(); + $offset = $this->read_ulong(); + $save_pos = $this->_pos; + if (($platformID == 3 && $encodingID == 1) || $platformID == 0) { // Microsoft, Unicode + $format = $this->get_ushort($cmap_offset + $offset); + if ($format == 4) { + if (!$unicode_cmap_offset) { + $unicode_cmap_offset = $cmap_offset + $offset; + } + } + } elseif ((($platformID == 3 && $encodingID == 10) || $platformID == 0)) { // Microsoft, Unicode Format 12 table HKCS + $format = $this->get_ushort($cmap_offset + $offset); + if ($format == 12) { + $unicode_cmap_offset = $cmap_offset + $offset; + break; + } + } + $this->seek($save_pos); + } + + if (!$unicode_cmap_offset) { + throw new \Mpdf\MpdfException('ERROR - Font (' . $this->filename . ') NOT ADDED as it is not Unicode encoded, and cannot be used by mPDF'); + } + + $rtl = false; + $indic = false; + $cjk = false; + $sip = false; + $smp = false; + $pua = false; + $puaag = false; + $glyphToChar = []; + $unAGlyphs = ''; + // Format 12 CMAP does characters above Unicode BMP i.e. some HKCS characters U+20000 and above + if ($format == 12) { + $this->seek($unicode_cmap_offset + 4); + $length = $this->read_ulong(); + $limit = $unicode_cmap_offset + $length; + $this->skip(4); + $nGroups = $this->read_ulong(); + for ($i = 0; $i < $nGroups; $i++) { + $startCharCode = $this->read_ulong(); + $endCharCode = $this->read_ulong(); + $startGlyphCode = $this->read_ulong(); + if (($endCharCode > 0x20000 && $endCharCode < 0x2A6DF) || ($endCharCode > 0x2F800 && $endCharCode < 0x2FA1F)) { + $sip = true; + } + if ($endCharCode > 0x10000 && $endCharCode < 0x1FFFF) { + $smp = true; + } + if (($endCharCode > 0x0590 && $endCharCode < 0x077F) || ($endCharCode > 0xFE70 && $endCharCode < 0xFEFF) || ($endCharCode > 0xFB50 && $endCharCode < 0xFDFF)) { + $rtl = true; + } + if ($endCharCode > 0x0900 && $endCharCode < 0x0DFF) { + $indic = true; + } + if ($endCharCode > 0xE000 && $endCharCode < 0xF8FF) { + $pua = true; + if ($endCharCode > 0xF500 && $endCharCode < 0xF7FF) { + $puaag = true; + } + } + if (($endCharCode > 0x2E80 && $endCharCode < 0x4DC0) || ($endCharCode > 0x4E00 && $endCharCode < 0xA4CF) || ($endCharCode > 0xAC00 && $endCharCode < 0xD7AF) || ($endCharCode > 0xF900 && $endCharCode < 0xFAFF) || ($endCharCode > 0xFE30 && $endCharCode < 0xFE4F)) { + $cjk = true; + } + + $offset = 0; + // Get each glyphToChar - only point if going to analyse un-mapped Arabic Glyphs + if (isset($this->tables['post'])) { + for ($unichar = $startCharCode; $unichar <= $endCharCode; $unichar++) { + $glyph = $startGlyphCode + $offset; + $offset++; + $glyphToChar[$glyph][] = $unichar; + } + } + } + } else { // Format 4 CMap + $this->seek($unicode_cmap_offset + 2); + $length = $this->read_ushort(); + $limit = $unicode_cmap_offset + $length; + $this->skip(2); + + $segCount = $this->read_ushort() / 2; + $this->skip(6); + $endCount = []; + for ($i = 0; $i < $segCount; $i++) { + $endCount[] = $this->read_ushort(); + } + $this->skip(2); + $startCount = []; + for ($i = 0; $i < $segCount; $i++) { + $startCount[] = $this->read_ushort(); + } + $idDelta = []; + for ($i = 0; $i < $segCount; $i++) { + $idDelta[] = $this->read_short(); + } + $idRangeOffset_start = $this->_pos; + $idRangeOffset = []; + for ($i = 0; $i < $segCount; $i++) { + $idRangeOffset[] = $this->read_ushort(); + } + + for ($n = 0; $n < $segCount; $n++) { + if (($endCount[$n] > 0x0590 && $endCount[$n] < 0x077F) || ($endCount[$n] > 0xFE70 && $endCount[$n] < 0xFEFF) || ($endCount[$n] > 0xFB50 && $endCount[$n] < 0xFDFF)) { + $rtl = true; + } + if ($endCount[$n] > 0x0900 && $endCount[$n] < 0x0DFF) { + $indic = true; + } + if (($endCount[$n] > 0x2E80 && $endCount[$n] < 0x4DC0) || ($endCount[$n] > 0x4E00 && $endCount[$n] < 0xA4CF) || ($endCount[$n] > 0xAC00 && $endCount[$n] < 0xD7AF) || ($endCount[$n] > 0xF900 && $endCount[$n] < 0xFAFF) || ($endCount[$n] > 0xFE30 && $endCount[$n] < 0xFE4F)) { + $cjk = true; + } + if ($endCount[$n] > 0xE000 && $endCount[$n] < 0xF8FF) { + $pua = true; + if ($endCount[$n] > 0xF500 && $endCount[$n] < 0xF7FF) { + $puaag = true; + } + } + // Get each glyphToChar - only point if going to analyse un-mapped Arabic Glyphs + if (isset($this->tables['post'])) { + $endpoint = ($endCount[$n] + 1); + for ($unichar = $startCount[$n]; $unichar < $endpoint; $unichar++) { + if ($idRangeOffset[$n] == 0) { + $glyph = ($unichar + $idDelta[$n]) & 0xFFFF; + } else { + $offset = ($unichar - $startCount[$n]) * 2 + $idRangeOffset[$n]; + $offset = $idRangeOffset_start + 2 * $n + $offset; + if ($offset >= $limit) { + $glyph = 0; + } else { + $glyph = $this->get_ushort($offset); + if ($glyph != 0) { + $glyph = ($glyph + $idDelta[$n]) & 0xFFFF; + } + } + } + $glyphToChar[$glyph][] = $unichar; + } + } + } + } + + + $bold = false; + $italic = false; + $ftype = ''; + if ($macStyle & (1 << 0)) { + $bold = true; + } // bit 0 bold + elseif ($fsSelection & (1 << 5)) { + $bold = true; + } // 5 BOLD Characters are emboldened + + if ($macStyle & (1 << 1)) { + $italic = true; + } // bit 1 italic + elseif ($fsSelection & (1 << 0)) { + $italic = true; + } // 0 ITALIC Font contains Italic characters, otherwise they are upright + elseif ($this->italicAngle <> 0) { + $italic = true; + } + + if ($isFixedPitch) { + $ftype = 'mono'; + } elseif ($sFamily > 0 && $sFamily < 8) { + $ftype = 'serif'; + } elseif ($sFamily == 8) { + $ftype = 'sans'; + } elseif ($sFamily == 10) { + $ftype = 'cursive'; + } + // Use PANOSE + if ($panose) { + $bFamilyType = ord($panose[0]); + if ($bFamilyType == 2) { + $bSerifStyle = ord($panose[1]); + if (!$ftype) { + if ($bSerifStyle > 1 && $bSerifStyle < 11) { + $ftype = 'serif'; + } elseif ($bSerifStyle > 10) { + $ftype = 'sans'; + } + } + $bProportion = ord($panose[3]); + if ($bProportion == 9 || $bProportion == 1) { + $ftype = 'mono'; + } // ==1 i.e. No Fit needed for OCR-a and -b + } elseif ($bFamilyType == 3) { + $ftype = 'cursive'; + } + } + + fclose($this->fh); + return [$this->familyName, $bold, $italic, $ftype, $TTCfontID, $rtl, $indic, $cjk, $sip, $smp, $puaag, $pua, $unAGlyphs]; + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/TableOfContents.php b/src/bb-vendor/mpdf/mpdf/src/TableOfContents.php new file mode 100644 index 000000000..82ce748e8 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/TableOfContents.php @@ -0,0 +1,908 @@ +<?php + +namespace Mpdf; + +use Mpdf\Utils\Arrays; +use DeepCopy\DeepCopy; + +class TableOfContents +{ + + private $mpdf; + + private $sizeConverter; + + var $_toc; + + var $TOCmark; + + var $TOCoutdent; // mPDF 5.6.31 + + var $TOCpreHTML; + + var $TOCpostHTML; + + var $TOCbookmarkText; + + var $TOCusePaging; + + var $TOCuseLinking; + + var $TOCorientation; + + var $TOC_margin_left; + + var $TOC_margin_right; + + var $TOC_margin_top; + + var $TOC_margin_bottom; + + var $TOC_margin_header; + + var $TOC_margin_footer; + + var $TOC_odd_header_name; + + var $TOC_even_header_name; + + var $TOC_odd_footer_name; + + var $TOC_even_footer_name; + + var $TOC_odd_header_value; + + var $TOC_even_header_value; + + var $TOC_odd_footer_value; + + var $TOC_even_footer_value; + + var $TOC_page_selector; + + var $TOC_resetpagenum; // mPDF 6 + + var $TOC_pagenumstyle; // mPDF 6 + + var $TOC_suppress; // mPDF 6 + + var $TOCsheetsize; + + var $m_TOC; + + /** + * @var bool Determine if the TOC should be cloned to calculate the correct page numbers + */ + protected $tocTocPaintBegun = false; + + public function __construct(Mpdf $mpdf, SizeConverter $sizeConverter) + { + $this->mpdf = $mpdf; + $this->sizeConverter = $sizeConverter; + + $this->_toc = []; + $this->TOCmark = 0; + $this->m_TOC = []; + } + + /** + * Mark the TOC Paint as having begun + */ + public function beginTocPaint() + { + $this->tocTocPaintBegun = true; + } + + public function TOCpagebreak( + $tocfont = '', + $tocfontsize = '', + $tocindent = '', + $TOCusePaging = true, + $TOCuseLinking = '', + $toc_orientation = '', + $toc_mgl = '', + $toc_mgr = '', + $toc_mgt = '', + $toc_mgb = '', + $toc_mgh = '', + $toc_mgf = '', + $toc_ohname = '', + $toc_ehname = '', + $toc_ofname = '', + $toc_efname = '', + $toc_ohvalue = 0, + $toc_ehvalue = 0, + $toc_ofvalue = 0, + $toc_efvalue = 0, + $toc_preHTML = '', + $toc_postHTML = '', + $toc_bookmarkText = '', + $resetpagenum = '', + $pagenumstyle = '', + $suppress = '', + $orientation = '', + $mgl = '', + $mgr = '', + $mgt = '', + $mgb = '', + $mgh = '', + $mgf = '', + $ohname = '', + $ehname = '', + $ofname = '', + $efname = '', + $ohvalue = 0, + $ehvalue = 0, + $ofvalue = 0, + $efvalue = 0, + $toc_id = 0, + $pagesel = '', + $toc_pagesel = '', + $sheetsize = '', + $toc_sheetsize = '', + $tocoutdent = '', + $toc_resetpagenum = '', + $toc_pagenumstyle = '', + $toc_suppress = '' + ) { + + if (strtoupper($toc_id) == 'ALL') { + $toc_id = '_mpdf_all'; + } elseif (!$toc_id) { + $toc_id = 0; + } else { + $toc_id = strtolower($toc_id); + } + + if ($TOCusePaging === false || strtolower($TOCusePaging) == "off" || $TOCusePaging === 0 || $TOCusePaging === "0" || $TOCusePaging === "") { + $TOCusePaging = false; + } else { + $TOCusePaging = true; + } + if (!$TOCuseLinking) { + $TOCuseLinking = false; + } + if ($toc_id) { + $this->m_TOC[$toc_id]['TOCmark'] = $this->mpdf->page; + $this->m_TOC[$toc_id]['TOCoutdent'] = $tocoutdent; + $this->m_TOC[$toc_id]['TOCorientation'] = $toc_orientation; + $this->m_TOC[$toc_id]['TOCuseLinking'] = $TOCuseLinking; + $this->m_TOC[$toc_id]['TOCusePaging'] = $TOCusePaging; + + if ($toc_preHTML) { + $this->m_TOC[$toc_id]['TOCpreHTML'] = $toc_preHTML; + } + if ($toc_postHTML) { + $this->m_TOC[$toc_id]['TOCpostHTML'] = $toc_postHTML; + } + if ($toc_bookmarkText) { + $this->m_TOC[$toc_id]['TOCbookmarkText'] = $toc_bookmarkText; + } + + $this->m_TOC[$toc_id]['TOC_margin_left'] = $toc_mgl; + $this->m_TOC[$toc_id]['TOC_margin_right'] = $toc_mgr; + $this->m_TOC[$toc_id]['TOC_margin_top'] = $toc_mgt; + $this->m_TOC[$toc_id]['TOC_margin_bottom'] = $toc_mgb; + $this->m_TOC[$toc_id]['TOC_margin_header'] = $toc_mgh; + $this->m_TOC[$toc_id]['TOC_margin_footer'] = $toc_mgf; + $this->m_TOC[$toc_id]['TOC_odd_header_name'] = $toc_ohname; + $this->m_TOC[$toc_id]['TOC_even_header_name'] = $toc_ehname; + $this->m_TOC[$toc_id]['TOC_odd_footer_name'] = $toc_ofname; + $this->m_TOC[$toc_id]['TOC_even_footer_name'] = $toc_efname; + $this->m_TOC[$toc_id]['TOC_odd_header_value'] = $toc_ohvalue; + $this->m_TOC[$toc_id]['TOC_even_header_value'] = $toc_ehvalue; + $this->m_TOC[$toc_id]['TOC_odd_footer_value'] = $toc_ofvalue; + $this->m_TOC[$toc_id]['TOC_even_footer_value'] = $toc_efvalue; + $this->m_TOC[$toc_id]['TOC_page_selector'] = $toc_pagesel; + $this->m_TOC[$toc_id]['TOC_resetpagenum'] = $toc_resetpagenum; // mPDF 6 + $this->m_TOC[$toc_id]['TOC_pagenumstyle'] = $toc_pagenumstyle; // mPDF 6 + $this->m_TOC[$toc_id]['TOC_suppress'] = $toc_suppress; // mPDF 6 + $this->m_TOC[$toc_id]['TOCsheetsize'] = $toc_sheetsize; + } else { + $this->TOCmark = $this->mpdf->page; + $this->TOCoutdent = $tocoutdent; + $this->TOCorientation = $toc_orientation; + $this->TOCuseLinking = $TOCuseLinking; + $this->TOCusePaging = $TOCusePaging; + + if ($toc_preHTML) { + $this->TOCpreHTML = $toc_preHTML; + } + if ($toc_postHTML) { + $this->TOCpostHTML = $toc_postHTML; + } + if ($toc_bookmarkText) { + $this->TOCbookmarkText = $toc_bookmarkText; + } + + $this->TOC_margin_left = $toc_mgl; + $this->TOC_margin_right = $toc_mgr; + $this->TOC_margin_top = $toc_mgt; + $this->TOC_margin_bottom = $toc_mgb; + $this->TOC_margin_header = $toc_mgh; + $this->TOC_margin_footer = $toc_mgf; + $this->TOC_odd_header_name = $toc_ohname; + $this->TOC_even_header_name = $toc_ehname; + $this->TOC_odd_footer_name = $toc_ofname; + $this->TOC_even_footer_name = $toc_efname; + $this->TOC_odd_header_value = $toc_ohvalue; + $this->TOC_even_header_value = $toc_ehvalue; + $this->TOC_odd_footer_value = $toc_ofvalue; + $this->TOC_even_footer_value = $toc_efvalue; + $this->TOC_page_selector = $toc_pagesel; + $this->TOC_resetpagenum = $toc_resetpagenum; // mPDF 6 + $this->TOC_pagenumstyle = $toc_pagenumstyle; // mPDF 6 + $this->TOC_suppress = $toc_suppress; // mPDF 6 + $this->TOCsheetsize = $toc_sheetsize; + } + } + + /** + * Initiate, and Mark a place for the Table of Contents to be inserted + */ + public function TOC( + $tocfont = '', + $tocfontsize = 0, + $tocindent = 0, + $resetpagenum = '', + $pagenumstyle = '', + $suppress = '', + $toc_orientation = '', + $TOCusePaging = true, + $TOCuseLinking = false, + $toc_id = 0, + $tocoutdent = '', + $toc_resetpagenum = '', + $toc_pagenumstyle = '', + $toc_suppress = '' + ) { + + if (strtoupper($toc_id) == 'ALL') { + $toc_id = '_mpdf_all'; + } elseif (!$toc_id) { + $toc_id = 0; + } else { + $toc_id = strtolower($toc_id); + } + // To use odd and even pages + // Cannot start table of contents on an even page + if (($this->mpdf->mirrorMargins) && (($this->mpdf->page) % 2 == 0)) { // EVEN + if ($this->mpdf->ColActive) { + if (count($this->mpdf->columnbuffer)) { + $this->mpdf->printcolumnbuffer(); + } + } + $this->mpdf->AddPage($this->mpdf->CurOrientation, '', $resetpagenum, $pagenumstyle, $suppress); + } else { + $this->mpdf->PageNumSubstitutions[] = ['from' => $this->mpdf->page, 'reset' => $resetpagenum, 'type' => $pagenumstyle, 'suppress' => $suppress]; + } + if ($toc_id) { + $this->m_TOC[$toc_id]['TOCmark'] = $this->mpdf->page; + $this->m_TOC[$toc_id]['TOCoutdent'] = $tocoutdent; + $this->m_TOC[$toc_id]['TOCorientation'] = $toc_orientation; + $this->m_TOC[$toc_id]['TOCuseLinking'] = $TOCuseLinking; + $this->m_TOC[$toc_id]['TOCusePaging'] = $TOCusePaging; + $this->m_TOC[$toc_id]['TOC_resetpagenum'] = $toc_resetpagenum; // mPDF 6 + $this->m_TOC[$toc_id]['TOC_pagenumstyle'] = $toc_pagenumstyle; // mPDF 6 + $this->m_TOC[$toc_id]['TOC_suppress'] = $toc_suppress; // mPDF 6 + } else { + $this->TOCmark = $this->mpdf->page; + $this->TOCoutdent = $tocoutdent; + $this->TOCorientation = $toc_orientation; + $this->TOCuseLinking = $TOCuseLinking; + $this->TOCusePaging = $TOCusePaging; + $this->TOC_resetpagenum = $toc_resetpagenum; // mPDF 6 + $this->TOC_pagenumstyle = $toc_pagenumstyle; // mPDF 6 + $this->TOC_suppress = $toc_suppress; // mPDF 6 + } + } + + public function insertTOC() + { + /* + * Fix the TOC page numbering problem + * + * To do this, the current class is deep cloned and then the TOC functionality run. The correct page + * numbers are calculated when the TOC pages are moved into position in the cloned object (see Mpdf::MovePages). + * It's then a matter of copying the correct page numbers to the original object and letting the TOC functionality + * run as per normal. + * + * See https://github.com/mpdf/mpdf/issues/642 + */ + if (!$this->tocTocPaintBegun) { + $copier = new DeepCopy(true); + $tocClassClone = $copier->copy($this); + $tocClassClone->beginTocPaint(); + $tocClassClone->insertTOC(); + $this->_toc = $tocClassClone->_toc; + } + + $notocs = 0; + if ($this->TOCmark) { + $notocs = 1; + } + $notocs += count($this->m_TOC); + + if ($notocs == 0) { + return; + } + + if (count($this->m_TOC)) { + reset($this->m_TOC); + } + $added_toc_pages = 0; + + if ($this->mpdf->ColActive) { + $this->mpdf->SetColumns(0); + } + if (($this->mpdf->mirrorMargins) && (($this->mpdf->page) % 2 == 1)) { // ODD + $this->mpdf->AddPage($this->mpdf->CurOrientation); + $extrapage = true; + } else { + $extrapage = false; + } + + for ($toci = 0; $toci < $notocs; $toci++) { + if ($toci == 0 && $this->TOCmark) { + $toc_id = 0; + $toc_page = $this->TOCmark; + $tocoutdent = $this->TOCoutdent; + $toc_orientation = $this->TOCorientation; + $TOCuseLinking = $this->TOCuseLinking; + $TOCusePaging = $this->TOCusePaging; + $toc_preHTML = $this->TOCpreHTML; + $toc_postHTML = $this->TOCpostHTML; + $toc_bookmarkText = $this->TOCbookmarkText; + $toc_mgl = $this->TOC_margin_left; + $toc_mgr = $this->TOC_margin_right; + $toc_mgt = $this->TOC_margin_top; + $toc_mgb = $this->TOC_margin_bottom; + $toc_mgh = $this->TOC_margin_header; + $toc_mgf = $this->TOC_margin_footer; + $toc_ohname = $this->TOC_odd_header_name; + $toc_ehname = $this->TOC_even_header_name; + $toc_ofname = $this->TOC_odd_footer_name; + $toc_efname = $this->TOC_even_footer_name; + $toc_ohvalue = $this->TOC_odd_header_value; + $toc_ehvalue = $this->TOC_even_header_value; + $toc_ofvalue = $this->TOC_odd_footer_value; + $toc_efvalue = $this->TOC_even_footer_value; + $toc_page_selector = $this->TOC_page_selector; + $toc_resetpagenum = $this->TOC_resetpagenum; // mPDF 6 + $toc_pagenumstyle = $this->TOC_pagenumstyle; // mPDF 6 + $toc_suppress = $this->TOC_suppress; // mPDF 6 + $toc_sheet_size = (isset($this->TOCsheetsize) ? $this->TOCsheetsize : ''); + } else { + $arr = current($this->m_TOC); + + $toc_id = key($this->m_TOC); + $toc_page = $this->m_TOC[$toc_id]['TOCmark']; + $tocoutdent = $this->m_TOC[$toc_id]['TOCoutdent']; + $toc_orientation = $this->m_TOC[$toc_id]['TOCorientation']; + $TOCuseLinking = $this->m_TOC[$toc_id]['TOCuseLinking']; + $TOCusePaging = $this->m_TOC[$toc_id]['TOCusePaging']; + if (isset($this->m_TOC[$toc_id]['TOCpreHTML'])) { + $toc_preHTML = $this->m_TOC[$toc_id]['TOCpreHTML']; + } else { + $toc_preHTML = ''; + } + if (isset($this->m_TOC[$toc_id]['TOCpostHTML'])) { + $toc_postHTML = $this->m_TOC[$toc_id]['TOCpostHTML']; + } else { + $toc_postHTML = ''; + } + if (isset($this->m_TOC[$toc_id]['TOCbookmarkText'])) { + $toc_bookmarkText = $this->m_TOC[$toc_id]['TOCbookmarkText']; + } else { + $toc_bookmarkText = ''; + } // *BOOKMARKS* + $toc_mgl = $this->m_TOC[$toc_id]['TOC_margin_left']; + $toc_mgr = $this->m_TOC[$toc_id]['TOC_margin_right']; + $toc_mgt = $this->m_TOC[$toc_id]['TOC_margin_top']; + $toc_mgb = $this->m_TOC[$toc_id]['TOC_margin_bottom']; + $toc_mgh = $this->m_TOC[$toc_id]['TOC_margin_header']; + $toc_mgf = $this->m_TOC[$toc_id]['TOC_margin_footer']; + $toc_ohname = $this->m_TOC[$toc_id]['TOC_odd_header_name']; + $toc_ehname = $this->m_TOC[$toc_id]['TOC_even_header_name']; + $toc_ofname = $this->m_TOC[$toc_id]['TOC_odd_footer_name']; + $toc_efname = $this->m_TOC[$toc_id]['TOC_even_footer_name']; + $toc_ohvalue = $this->m_TOC[$toc_id]['TOC_odd_header_value']; + $toc_ehvalue = $this->m_TOC[$toc_id]['TOC_even_header_value']; + $toc_ofvalue = $this->m_TOC[$toc_id]['TOC_odd_footer_value']; + $toc_efvalue = $this->m_TOC[$toc_id]['TOC_even_footer_value']; + $toc_page_selector = $this->m_TOC[$toc_id]['TOC_page_selector']; + $toc_resetpagenum = $this->m_TOC[$toc_id]['TOC_resetpagenum']; // mPDF 6 + $toc_pagenumstyle = $this->m_TOC[$toc_id]['TOC_pagenumstyle']; // mPDF 6 + $toc_suppress = $this->m_TOC[$toc_id]['TOC_suppress']; // mPDF 6 + $toc_sheet_size = (isset($this->m_TOC[$toc_id]['TOCsheetsize']) ? $this->m_TOC[$toc_id]['TOCsheetsize'] : ''); + next($this->m_TOC); + } + + // mPDF 5.6.31 + if (!$toc_orientation) { + $toc_orientation = $this->mpdf->DefOrientation; + } + + // mPDF 6 number style and suppress now picked up from section preceding ToC + list($tp_pagenumstyle, $tp_suppress, $tp_reset) = $this->mpdf->docPageSettings($toc_page - 1); + + if ($toc_resetpagenum) { + $tp_reset = $toc_resetpagenum; // mPDF 6 + } + if ($toc_pagenumstyle) { + $tp_pagenumstyle = $toc_pagenumstyle; // mPDF 6 + } + if ($toc_suppress || $toc_suppress === '0') { + $tp_suppress = $toc_suppress; // mPDF 6 + } + + $this->mpdf->AddPage($toc_orientation, '', $tp_reset, $tp_pagenumstyle, $tp_suppress, $toc_mgl, $toc_mgr, $toc_mgt, $toc_mgb, $toc_mgh, $toc_mgf, $toc_ohname, $toc_ehname, $toc_ofname, $toc_efname, $toc_ohvalue, $toc_ehvalue, $toc_ofvalue, $toc_efvalue, $toc_page_selector, $toc_sheet_size); // mPDF 6 + + $this->mpdf->writingToC = true; // mPDF 5.6.38 + + /* + * Ensure the TOC Page Number Style doesn't effect the TOC Numbering (added automatically in `AddPage()` above) + * Ensure the page numbers show in the TOC when the 'suppress' setting is enabled + * @see https://github.com/mpdf/mpdf/issues/792 + * @see https://github.com/mpdf/mpdf/issues/777 + */ + if (isset($tocClassClone)) { + $this->mpdf->PageNumSubstitutions = array_map(function ($sub) { + $sub['suppress'] = ''; + return $sub; + }, $tocClassClone->mpdf->PageNumSubstitutions); + } + + // mPDF 5.6.31 + $tocstart = count($this->mpdf->pages); + if (isset($toc_preHTML) && $toc_preHTML) { + $this->mpdf->WriteHTML($toc_preHTML); + } + + // mPDF 5.6.19 + $html = '<div class="mpdf_toc" id="mpdf_toc_' . $toc_id . '">'; + foreach ($this->_toc as $t) { + if ($t['toc_id'] === '_mpdf_all' || $t['toc_id'] === $toc_id) { + $html .= '<div class="mpdf_toc_level_' . $t['l'] . '">'; + if ($TOCuseLinking) { + $html .= '<a class="mpdf_toc_a" href="#__mpdfinternallink_' . $t['link'] . '">'; + } + $html .= '<span class="mpdf_toc_t_level_' . $t['l'] . '">' . $t['t'] . '</span>'; + if ($TOCuseLinking) { + $html .= '</a>'; + } + if (!$tocoutdent) { + $tocoutdent = '0'; + } + if ($TOCusePaging) { + $html .= ' <dottab outdent="' . $tocoutdent . '" /> '; + if ($TOCuseLinking) { + $html .= '<a class="mpdf_toc_a" href="#__mpdfinternallink_' . $t['link'] . '">'; + } + $html .= '<span class="mpdf_toc_p_level_' . $t['l'] . '">' . $this->mpdf->docPageNum($t['p']) . '</span>'; + if ($TOCuseLinking) { + $html .= '</a>'; + } + } + $html .= '</div>'; + } + } + $html .= '</div>'; + $this->mpdf->WriteHTML($html); + + if (isset($toc_postHTML) && $toc_postHTML) { + $this->mpdf->WriteHTML($toc_postHTML); + } + $this->mpdf->writingToC = false; // mPDF 5.6.38 + $this->mpdf->AddPage($toc_orientation, 'E'); + + $n_toc = $this->mpdf->page - $tocstart + 1; + + if ($toci == 0 && $this->TOCmark) { + $TOC_start = $tocstart; + $TOC_end = $this->mpdf->page; + $TOC_npages = $n_toc; + } else { + $this->m_TOC[$toc_id]['start'] = $tocstart; + $this->m_TOC[$toc_id]['end'] = $this->mpdf->page; + $this->m_TOC[$toc_id]['npages'] = $n_toc; + } + } + + $s = ''; + + $s .= $this->mpdf->PrintBodyBackgrounds(); + + $s .= $this->mpdf->PrintPageBackgrounds(); + $this->mpdf->pages[$this->mpdf->page] = preg_replace('/(___BACKGROUND___PATTERNS' . $this->mpdf->uniqstr . ')/', "\n" . $s . "\n" . '\\1', $this->mpdf->pages[$this->mpdf->page]); + $this->mpdf->pageBackgrounds = []; + + //Page footer + $this->mpdf->InFooter = true; + $this->mpdf->Footer(); + $this->mpdf->InFooter = false; + + // 2nd time through to move pages etc. + $added_toc_pages = 0; + if (count($this->m_TOC)) { + reset($this->m_TOC); + } + + for ($toci = 0; $toci < $notocs; $toci++) { + if ($toci == 0 && $this->TOCmark) { + $toc_id = 0; + $toc_page = $this->TOCmark + $added_toc_pages; + $toc_orientation = $this->TOCorientation; + $TOCuseLinking = $this->TOCuseLinking; + $TOCusePaging = $this->TOCusePaging; + $toc_bookmarkText = $this->TOCbookmarkText; // *BOOKMARKS* + + $tocstart = $TOC_start; + $tocend = $n = $TOC_end; + $n_toc = $TOC_npages; + } else { + $arr = current($this->m_TOC); + + $toc_id = key($this->m_TOC); + $toc_page = $this->m_TOC[$toc_id]['TOCmark'] + $added_toc_pages; + $toc_orientation = $this->m_TOC[$toc_id]['TOCorientation']; + $TOCuseLinking = $this->m_TOC[$toc_id]['TOCuseLinking']; + $TOCusePaging = $this->m_TOC[$toc_id]['TOCusePaging']; + $toc_bookmarkText = Arrays::get($this->m_TOC[$toc_id], 'TOCbookmarkText', null); // *BOOKMARKS* + + $tocstart = $this->m_TOC[$toc_id]['start']; + $tocend = $n = $this->m_TOC[$toc_id]['end']; + $n_toc = $this->m_TOC[$toc_id]['npages']; + + next($this->m_TOC); + } + + // Now pages moved + $added_toc_pages += $n_toc; + + $this->mpdf->MovePages($toc_page, $tocstart, $tocend); + $this->mpdf->pgsIns[$toc_page] = $tocend - $tocstart + 1; + + /* -- BOOKMARKS -- */ + // Insert new Bookmark for Bookmark + if ($toc_bookmarkText) { + $insert = -1; + foreach ($this->mpdf->BMoutlines as $i => $o) { + if ($o['p'] < $toc_page) { // i.e. before point of insertion + $insert = $i; + } + } + $txt = $this->mpdf->purify_utf8_text($toc_bookmarkText); + if ($this->mpdf->text_input_as_HTML) { + $txt = $this->mpdf->all_entities_to_utf8($txt); + } + $newBookmark[0] = ['t' => $txt, 'l' => 0, 'y' => 0, 'p' => $toc_page]; + array_splice($this->mpdf->BMoutlines, ($insert + 1), 0, $newBookmark); + } + /* -- END BOOKMARKS -- */ + } + + // Delete empty page that was inserted earlier + if ($extrapage) { + unset($this->mpdf->pages[count($this->mpdf->pages)]); + $this->mpdf->page--; // Reset page pointer + } + + /* Fix the over adjustment of the TOC and Page Substitutions values */ + if (isset($tocClassClone)) { + $this->_toc = $tocClassClone->_toc; + $this->mpdf->PageNumSubstitutions = $tocClassClone->mpdf->PageNumSubstitutions; + unset($tocClassClone); + } + } + + public function openTagTOC($attr) + { + if (isset($attr['OUTDENT']) && $attr['OUTDENT']) { + $tocoutdent = $attr['OUTDENT']; + } else { + $tocoutdent = ''; + } // mPDF 5.6.19 + if (isset($attr['RESETPAGENUM']) && $attr['RESETPAGENUM']) { + $resetpagenum = $attr['RESETPAGENUM']; + } else { + $resetpagenum = ''; + } + if (isset($attr['PAGENUMSTYLE']) && $attr['PAGENUMSTYLE']) { + $pagenumstyle = $attr['PAGENUMSTYLE']; + } else { + $pagenumstyle = ''; + } + if (isset($attr['SUPPRESS']) && $attr['SUPPRESS']) { + $suppress = $attr['SUPPRESS']; + } else { + $suppress = ''; + } + if (isset($attr['TOC-ORIENTATION']) && $attr['TOC-ORIENTATION']) { + $toc_orientation = $attr['TOC-ORIENTATION']; + } else { + $toc_orientation = ''; + } + if (isset($attr['PAGING']) && (strtoupper($attr['PAGING']) == 'OFF' || $attr['PAGING'] === '0')) { + $paging = false; + } else { + $paging = true; + } + if (isset($attr['LINKS']) && (strtoupper($attr['LINKS']) == 'ON' || $attr['LINKS'] == 1)) { + $links = true; + } else { + $links = false; + } + if (isset($attr['NAME']) && $attr['NAME']) { + $toc_id = strtolower($attr['NAME']); + } else { + $toc_id = 0; + } + $this->TOC('', 0, 0, $resetpagenum, $pagenumstyle, $suppress, $toc_orientation, $paging, $links, $toc_id, $tocoutdent); // mPDF 5.6.19 5.6.31 + } + + public function openTagTOCPAGEBREAK($attr) + { + if (isset($attr['NAME']) && $attr['NAME']) { + $toc_id = strtolower($attr['NAME']); + } else { + $toc_id = 0; + } + if ($toc_id) { + if (isset($attr['OUTDENT']) && $attr['OUTDENT']) { + $this->m_TOC[$toc_id]['TOCoutdent'] = $attr['OUTDENT']; + } else { + $this->m_TOC[$toc_id]['TOCoutdent'] = ''; + } // mPDF 5.6.19 + if (isset($attr['TOC-ORIENTATION']) && $attr['TOC-ORIENTATION']) { + $this->m_TOC[$toc_id]['TOCorientation'] = $attr['TOC-ORIENTATION']; + } else { + $this->m_TOC[$toc_id]['TOCorientation'] = ''; + } + if (isset($attr['PAGING']) && (strtoupper($attr['PAGING']) == 'OFF' || $attr['PAGING'] === '0')) { + $this->m_TOC[$toc_id]['TOCusePaging'] = false; + } else { + $this->m_TOC[$toc_id]['TOCusePaging'] = true; + } + if (isset($attr['LINKS']) && (strtoupper($attr['LINKS']) == 'ON' || $attr['LINKS'] == 1)) { + $this->m_TOC[$toc_id]['TOCuseLinking'] = true; + } else { + $this->m_TOC[$toc_id]['TOCuseLinking'] = false; + } + + $this->m_TOC[$toc_id]['TOC_margin_left'] = $this->m_TOC[$toc_id]['TOC_margin_right'] = $this->m_TOC[$toc_id]['TOC_margin_top'] = $this->m_TOC[$toc_id]['TOC_margin_bottom'] = $this->m_TOC[$toc_id]['TOC_margin_header'] = $this->m_TOC[$toc_id]['TOC_margin_footer'] = ''; + if (isset($attr['TOC-MARGIN-RIGHT'])) { + $this->m_TOC[$toc_id]['TOC_margin_right'] = $this->sizeConverter->convert($attr['TOC-MARGIN-RIGHT'], $this->mpdf->w, $this->mpdf->FontSize, false); + } + if (isset($attr['TOC-MARGIN-LEFT'])) { + $this->m_TOC[$toc_id]['TOC_margin_left'] = $this->sizeConverter->convert($attr['TOC-MARGIN-LEFT'], $this->mpdf->w, $this->mpdf->FontSize, false); + } + if (isset($attr['TOC-MARGIN-TOP'])) { + $this->m_TOC[$toc_id]['TOC_margin_top'] = $this->sizeConverter->convert($attr['TOC-MARGIN-TOP'], $this->mpdf->w, $this->mpdf->FontSize, false); + } + if (isset($attr['TOC-MARGIN-BOTTOM'])) { + $this->m_TOC[$toc_id]['TOC_margin_bottom'] = $this->sizeConverter->convert($attr['TOC-MARGIN-BOTTOM'], $this->mpdf->w, $this->mpdf->FontSize, false); + } + if (isset($attr['TOC-MARGIN-HEADER'])) { + $this->m_TOC[$toc_id]['TOC_margin_header'] = $this->sizeConverter->convert($attr['TOC-MARGIN-HEADER'], $this->mpdf->w, $this->mpdf->FontSize, false); + } + if (isset($attr['TOC-MARGIN-FOOTER'])) { + $this->m_TOC[$toc_id]['TOC_margin_footer'] = $this->sizeConverter->convert($attr['TOC-MARGIN-FOOTER'], $this->mpdf->w, $this->mpdf->FontSize, false); + } + $this->m_TOC[$toc_id]['TOC_odd_header_name'] = $this->m_TOC[$toc_id]['TOC_even_header_name'] = $this->m_TOC[$toc_id]['TOC_odd_footer_name'] = $this->m_TOC[$toc_id]['TOC_even_footer_name'] = ''; + if (isset($attr['TOC-ODD-HEADER-NAME']) && $attr['TOC-ODD-HEADER-NAME']) { + $this->m_TOC[$toc_id]['TOC_odd_header_name'] = $attr['TOC-ODD-HEADER-NAME']; + } + if (isset($attr['TOC-EVEN-HEADER-NAME']) && $attr['TOC-EVEN-HEADER-NAME']) { + $this->m_TOC[$toc_id]['TOC_even_header_name'] = $attr['TOC-EVEN-HEADER-NAME']; + } + if (isset($attr['TOC-ODD-FOOTER-NAME']) && $attr['TOC-ODD-FOOTER-NAME']) { + $this->m_TOC[$toc_id]['TOC_odd_footer_name'] = $attr['TOC-ODD-FOOTER-NAME']; + } + if (isset($attr['TOC-EVEN-FOOTER-NAME']) && $attr['TOC-EVEN-FOOTER-NAME']) { + $this->m_TOC[$toc_id]['TOC_even_footer_name'] = $attr['TOC-EVEN-FOOTER-NAME']; + } + $this->m_TOC[$toc_id]['TOC_odd_header_value'] = $this->m_TOC[$toc_id]['TOC_even_header_value'] = $this->m_TOC[$toc_id]['TOC_odd_footer_value'] = $this->m_TOC[$toc_id]['TOC_even_footer_value'] = 0; + if (isset($attr['TOC-ODD-HEADER-VALUE']) && ($attr['TOC-ODD-HEADER-VALUE'] == '1' || strtoupper($attr['TOC-ODD-HEADER-VALUE']) == 'ON')) { + $this->m_TOC[$toc_id]['TOC_odd_header_value'] = 1; + } elseif (isset($attr['TOC-ODD-HEADER-VALUE']) && ($attr['TOC-ODD-HEADER-VALUE'] == '-1' || strtoupper($attr['TOC-ODD-HEADER-VALUE']) == 'OFF')) { + $this->m_TOC[$toc_id]['TOC_odd_header_value'] = -1; + } + if (isset($attr['TOC-EVEN-HEADER-VALUE']) && ($attr['TOC-EVEN-HEADER-VALUE'] == '1' || strtoupper($attr['TOC-EVEN-HEADER-VALUE']) == 'ON')) { + $this->m_TOC[$toc_id]['TOC_even_header_value'] = 1; + } elseif (isset($attr['TOC-EVEN-HEADER-VALUE']) && ($attr['TOC-EVEN-HEADER-VALUE'] == '-1' || strtoupper($attr['TOC-EVEN-HEADER-VALUE']) == 'OFF')) { + $this->m_TOC[$toc_id]['TOC_even_header_value'] = -1; + } + if (isset($attr['TOC-ODD-FOOTER-VALUE']) && ($attr['TOC-ODD-FOOTER-VALUE'] == '1' || strtoupper($attr['TOC-ODD-FOOTER-VALUE']) == 'ON')) { + $this->m_TOC[$toc_id]['TOC_odd_footer_value'] = 1; + } elseif (isset($attr['TOC-ODD-FOOTER-VALUE']) && ($attr['TOC-ODD-FOOTER-VALUE'] == '-1' || strtoupper($attr['TOC-ODD-FOOTER-VALUE']) == 'OFF')) { + $this->m_TOC[$toc_id]['TOC_odd_footer_value'] = -1; + } + if (isset($attr['TOC-EVEN-FOOTER-VALUE']) && ($attr['TOC-EVEN-FOOTER-VALUE'] == '1' || strtoupper($attr['TOC-EVEN-FOOTER-VALUE']) == 'ON')) { + $this->m_TOC[$toc_id]['TOC_even_footer_value'] = 1; + } elseif (isset($attr['TOC-EVEN-FOOTER-VALUE']) && ($attr['TOC-EVEN-FOOTER-VALUE'] == '-1' || strtoupper($attr['TOC-EVEN-FOOTER-VALUE']) == 'OFF')) { + $this->m_TOC[$toc_id]['TOC_even_footer_value'] = -1; + } + if (isset($attr['TOC-RESETPAGENUM']) && $attr['TOC-RESETPAGENUM']) { + $this->m_TOC[$toc_id]['TOC_resetpagenum'] = $attr['TOC-RESETPAGENUM']; + } else { + $this->m_TOC[$toc_id]['TOC_resetpagenum'] = ''; + } // mPDF 6 + if (isset($attr['TOC-PAGENUMSTYLE']) && $attr['TOC-PAGENUMSTYLE']) { + $this->m_TOC[$toc_id]['TOC_pagenumstyle'] = $attr['TOC-PAGENUMSTYLE']; + } else { + $this->m_TOC[$toc_id]['TOC_pagenumstyle'] = ''; + } // mPDF 6 + if (isset($attr['TOC-SUPPRESS']) && ($attr['TOC-SUPPRESS'] || $attr['TOC-SUPPRESS'] === '0')) { + $this->m_TOC[$toc_id]['TOC_suppress'] = $attr['TOC-SUPPRESS']; + } else { + $this->m_TOC[$toc_id]['TOC_suppress'] = ''; + } // mPDF 6 + if (isset($attr['TOC-PAGE-SELECTOR']) && $attr['TOC-PAGE-SELECTOR']) { + $this->m_TOC[$toc_id]['TOC_page_selector'] = $attr['TOC-PAGE-SELECTOR']; + } else { + $this->m_TOC[$toc_id]['TOC_page_selector'] = ''; + } + if (isset($attr['TOC-SHEET-SIZE']) && $attr['TOC-SHEET-SIZE']) { + $this->m_TOC[$toc_id]['TOCsheetsize'] = $attr['TOC-SHEET-SIZE']; + } else { + $this->m_TOC[$toc_id]['TOCsheetsize'] = ''; + } + + + if (isset($attr['TOC-PREHTML']) && $attr['TOC-PREHTML']) { + $this->m_TOC[$toc_id]['TOCpreHTML'] = htmlspecialchars_decode($attr['TOC-PREHTML'], ENT_QUOTES); + } + if (isset($attr['TOC-POSTHTML']) && $attr['TOC-POSTHTML']) { + $this->m_TOC[$toc_id]['TOCpostHTML'] = htmlspecialchars_decode($attr['TOC-POSTHTML'], ENT_QUOTES); + } + + if (isset($attr['TOC-BOOKMARKTEXT']) && $attr['TOC-BOOKMARKTEXT']) { + $this->m_TOC[$toc_id]['TOCbookmarkText'] = htmlspecialchars_decode($attr['TOC-BOOKMARKTEXT'], ENT_QUOTES); + } // *BOOKMARKS* + } else { + if (isset($attr['OUTDENT']) && $attr['OUTDENT']) { + $this->TOCoutdent = $attr['OUTDENT']; + } else { + $this->TOCoutdent = ''; + } // mPDF 5.6.19 + if (isset($attr['TOC-ORIENTATION']) && $attr['TOC-ORIENTATION']) { + $this->TOCorientation = $attr['TOC-ORIENTATION']; + } else { + $this->TOCorientation = ''; + } + if (isset($attr['PAGING']) && (strtoupper($attr['PAGING']) == 'OFF' || $attr['PAGING'] === '0')) { + $this->TOCusePaging = false; + } else { + $this->TOCusePaging = true; + } + if (isset($attr['LINKS']) && (strtoupper($attr['LINKS']) == 'ON' || $attr['LINKS'] == 1)) { + $this->TOCuseLinking = true; + } else { + $this->TOCuseLinking = false; + } + + $this->TOC_margin_left = $this->TOC_margin_right = $this->TOC_margin_top = $this->TOC_margin_bottom = $this->TOC_margin_header = $this->TOC_margin_footer = ''; + if (isset($attr['TOC-MARGIN-RIGHT'])) { + $this->TOC_margin_right = $this->sizeConverter->convert($attr['TOC-MARGIN-RIGHT'], $this->mpdf->w, $this->mpdf->FontSize, false); + } + if (isset($attr['TOC-MARGIN-LEFT'])) { + $this->TOC_margin_left = $this->sizeConverter->convert($attr['TOC-MARGIN-LEFT'], $this->mpdf->w, $this->mpdf->FontSize, false); + } + if (isset($attr['TOC-MARGIN-TOP'])) { + $this->TOC_margin_top = $this->sizeConverter->convert($attr['TOC-MARGIN-TOP'], $this->mpdf->w, $this->mpdf->FontSize, false); + } + if (isset($attr['TOC-MARGIN-BOTTOM'])) { + $this->TOC_margin_bottom = $this->sizeConverter->convert($attr['TOC-MARGIN-BOTTOM'], $this->mpdf->w, $this->mpdf->FontSize, false); + } + if (isset($attr['TOC-MARGIN-HEADER'])) { + $this->TOC_margin_header = $this->sizeConverter->convert($attr['TOC-MARGIN-HEADER'], $this->mpdf->w, $this->mpdf->FontSize, false); + } + if (isset($attr['TOC-MARGIN-FOOTER'])) { + $this->TOC_margin_footer = $this->sizeConverter->convert($attr['TOC-MARGIN-FOOTER'], $this->mpdf->w, $this->mpdf->FontSize, false); + } + $this->TOC_odd_header_name = $this->TOC_even_header_name = $this->TOC_odd_footer_name = $this->TOC_even_footer_name = ''; + if (isset($attr['TOC-ODD-HEADER-NAME']) && $attr['TOC-ODD-HEADER-NAME']) { + $this->TOC_odd_header_name = $attr['TOC-ODD-HEADER-NAME']; + } + if (isset($attr['TOC-EVEN-HEADER-NAME']) && $attr['TOC-EVEN-HEADER-NAME']) { + $this->TOC_even_header_name = $attr['TOC-EVEN-HEADER-NAME']; + } + if (isset($attr['TOC-ODD-FOOTER-NAME']) && $attr['TOC-ODD-FOOTER-NAME']) { + $this->TOC_odd_footer_name = $attr['TOC-ODD-FOOTER-NAME']; + } + if (isset($attr['TOC-EVEN-FOOTER-NAME']) && $attr['TOC-EVEN-FOOTER-NAME']) { + $this->TOC_even_footer_name = $attr['TOC-EVEN-FOOTER-NAME']; + } + $this->TOC_odd_header_value = $this->TOC_even_header_value = $this->TOC_odd_footer_value = $this->TOC_even_footer_value = 0; + if (isset($attr['TOC-ODD-HEADER-VALUE']) && ($attr['TOC-ODD-HEADER-VALUE'] == '1' || strtoupper($attr['TOC-ODD-HEADER-VALUE']) == 'ON')) { + $this->TOC_odd_header_value = 1; + } elseif (isset($attr['TOC-ODD-HEADER-VALUE']) && ($attr['TOC-ODD-HEADER-VALUE'] == '-1' || strtoupper($attr['TOC-ODD-HEADER-VALUE']) == 'OFF')) { + $this->TOC_odd_header_value = -1; + } + if (isset($attr['TOC-EVEN-HEADER-VALUE']) && ($attr['TOC-EVEN-HEADER-VALUE'] == '1' || strtoupper($attr['TOC-EVEN-HEADER-VALUE']) == 'ON')) { + $this->TOC_even_header_value = 1; + } elseif (isset($attr['TOC-EVEN-HEADER-VALUE']) && ($attr['TOC-EVEN-HEADER-VALUE'] == '-1' || strtoupper($attr['TOC-EVEN-HEADER-VALUE']) == 'OFF')) { + $this->TOC_even_header_value = -1; + } + + if (isset($attr['TOC-ODD-FOOTER-VALUE']) && ($attr['TOC-ODD-FOOTER-VALUE'] == '1' || strtoupper($attr['TOC-ODD-FOOTER-VALUE']) == 'ON')) { + $this->TOC_odd_footer_value = 1; + } elseif (isset($attr['TOC-ODD-FOOTER-VALUE']) && ($attr['TOC-ODD-FOOTER-VALUE'] == '-1' || strtoupper($attr['TOC-ODD-FOOTER-VALUE']) == 'OFF')) { + $this->TOC_odd_footer_value = -1; + } + if (isset($attr['TOC-EVEN-FOOTER-VALUE']) && ($attr['TOC-EVEN-FOOTER-VALUE'] == '1' || strtoupper($attr['TOC-EVEN-FOOTER-VALUE']) == 'ON')) { + $this->TOC_even_footer_value = 1; + } elseif (isset($attr['TOC-EVEN-FOOTER-VALUE']) && ($attr['TOC-EVEN-FOOTER-VALUE'] == '-1' || strtoupper($attr['TOC-EVEN-FOOTER-VALUE']) == 'OFF')) { + $this->TOC_even_footer_value = -1; + } + if (isset($attr['TOC-PAGE-SELECTOR']) && $attr['TOC-PAGE-SELECTOR']) { + $this->TOC_page_selector = $attr['TOC-PAGE-SELECTOR']; + } else { + $this->TOC_page_selector = ''; + } + if (isset($attr['TOC-RESETPAGENUM']) && $attr['TOC-RESETPAGENUM']) { + $this->TOC_resetpagenum = $attr['TOC-RESETPAGENUM']; + } else { + $this->TOC_resetpagenum = ''; + } // mPDF 6 + if (isset($attr['TOC-PAGENUMSTYLE']) && $attr['TOC-PAGENUMSTYLE']) { + $this->TOC_pagenumstyle = $attr['TOC-PAGENUMSTYLE']; + } else { + $this->TOC_pagenumstyle = ''; + } // mPDF 6 + if (isset($attr['TOC-SUPPRESS']) && ($attr['TOC-SUPPRESS'] || $attr['TOC-SUPPRESS'] === '0')) { + $this->TOC_suppress = $attr['TOC-SUPPRESS']; + } else { + $this->TOC_suppress = ''; + } // mPDF 6 + if (isset($attr['TOC-SHEET-SIZE']) && $attr['TOC-SHEET-SIZE']) { + $this->TOCsheetsize = $attr['TOC-SHEET-SIZE']; + } else { + $this->TOCsheetsize = ''; + } + + if (isset($attr['TOC-PREHTML']) && $attr['TOC-PREHTML']) { + $this->TOCpreHTML = htmlspecialchars_decode($attr['TOC-PREHTML'], ENT_QUOTES); + } + if (isset($attr['TOC-POSTHTML']) && $attr['TOC-POSTHTML']) { + $this->TOCpostHTML = htmlspecialchars_decode($attr['TOC-POSTHTML'], ENT_QUOTES); + } + if (isset($attr['TOC-BOOKMARKTEXT']) && $attr['TOC-BOOKMARKTEXT']) { + $this->TOCbookmarkText = htmlspecialchars_decode($attr['TOC-BOOKMARKTEXT'], ENT_QUOTES); + } + } + + if ($this->mpdf->y == $this->mpdf->tMargin && (!$this->mpdf->mirrorMargins || ($this->mpdf->mirrorMargins && $this->mpdf->page % 2 == 1))) { + if ($toc_id) { + $this->m_TOC[$toc_id]['TOCmark'] = $this->mpdf->page; + } else { + $this->TOCmark = $this->mpdf->page; + } + // Don't add a page + if ($this->mpdf->page == 1 && count($this->mpdf->PageNumSubstitutions) == 0) { + $resetpagenum = ''; + $pagenumstyle = ''; + $suppress = ''; + if (isset($attr['RESETPAGENUM'])) { + $resetpagenum = $attr['RESETPAGENUM']; + } + if (isset($attr['PAGENUMSTYLE'])) { + $pagenumstyle = $attr['PAGENUMSTYLE']; + } + if (isset($attr['SUPPRESS'])) { + $suppress = $attr['SUPPRESS']; + } + if (!$suppress) { + $suppress = 'off'; + } + $this->mpdf->PageNumSubstitutions[] = ['from' => 1, 'reset' => $resetpagenum, 'type' => $pagenumstyle, 'suppress' => $suppress]; + } + return [true, $toc_id]; + } + + // No break - continues as PAGEBREAK... + return [false, $toc_id]; + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag.php b/src/bb-vendor/mpdf/mpdf/src/Tag.php new file mode 100644 index 000000000..6886d1c33 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag.php @@ -0,0 +1,253 @@ +<?php + +namespace Mpdf; + +use Mpdf\Strict; + +use Mpdf\Color\ColorConverter; + +use Mpdf\Image\ImageProcessor; + +use Mpdf\Language\LanguageToFontInterface; + +class Tag +{ + + use Strict; + + /** + * @var \Mpdf\Mpdf + */ + private $mpdf; + + /** + * @var \Mpdf\Cache + */ + private $cache; + + /** + * @var \Mpdf\CssManager + */ + private $cssManager; + + /** + * @var \Mpdf\Form + */ + private $form; + + /** + * @var \Mpdf\Otl + */ + private $otl; + + /** + * @var \Mpdf\TableOfContents + */ + private $tableOfContents; + + /** + * @var \Mpdf\SizeConverter + */ + private $sizeConverter; + + /** + * @var \Mpdf\Color\ColorConverter + */ + private $colorConverter; + + /** + * @var \Mpdf\Image\ImageProcessor + */ + private $imageProcessor; + + /** + * @var \Mpdf\Language\LanguageToFontInterface + */ + private $languageToFont; + + /** + * @param \Mpdf\Mpdf $mpdf + * @param \Mpdf\Cache $cache + * @param \Mpdf\CssManager $cssManager + * @param \Mpdf\Form $form + * @param \Mpdf\Otl $otl + * @param \Mpdf\TableOfContents $tableOfContents + * @param \Mpdf\SizeConverter $sizeConverter + * @param \Mpdf\Color\ColorConverter $colorConverter + * @param \Mpdf\Image\ImageProcessor $imageProcessor + * @param \Mpdf\Language\LanguageToFontInterface $languageToFont + */ + public function __construct( + Mpdf $mpdf, + Cache $cache, + CssManager $cssManager, + Form $form, + Otl $otl, + TableOfContents $tableOfContents, + SizeConverter $sizeConverter, + ColorConverter $colorConverter, + ImageProcessor $imageProcessor, + LanguageToFontInterface $languageToFont + ) { + + $this->mpdf = $mpdf; + $this->cache = $cache; + $this->cssManager = $cssManager; + $this->form = $form; + $this->otl = $otl; + $this->tableOfContents = $tableOfContents; + $this->sizeConverter = $sizeConverter; + $this->colorConverter = $colorConverter; + $this->imageProcessor = $imageProcessor; + $this->languageToFont = $languageToFont; + } + + /** + * @param string $tag The tag name + * @return \Mpdf\Tag\Tag + */ + private function getTagInstance($tag) + { + $className = self::getTagClassName($tag); + if (class_exists($className)) { + return new $className( + $this->mpdf, + $this->cache, + $this->cssManager, + $this->form, + $this->otl, + $this->tableOfContents, + $this->sizeConverter, + $this->colorConverter, + $this->imageProcessor, + $this->languageToFont + ); + } + } + + /** + * Returns the fully qualified name of the class handling the rendering of the given tag + * + * @param string $tag The tag name + * @return string The fully qualified name + */ + public static function getTagClassName($tag) + { + static $map = [ + 'BARCODE' => 'BarCode', + 'BLOCKQUOTE' => 'BlockQuote', + 'COLUMN_BREAK' => 'ColumnBreak', + 'COLUMNBREAK' => 'ColumnBreak', + 'DOTTAB' => 'DotTab', + 'FIELDSET' => 'FieldSet', + 'FIGCAPTION' => 'FigCaption', + 'FORMFEED' => 'FormFeed', + 'HGROUP' => 'HGroup', + 'INDEXENTRY' => 'IndexEntry', + 'INDEXINSERT' => 'IndexInsert', + 'NEWCOLUMN' => 'NewColumn', + 'NEWPAGE' => 'NewPage', + 'PAGEFOOTER' => 'PageFooter', + 'PAGEHEADER' => 'PageHeader', + 'PAGE_BREAK' => 'PageBreak', + 'PAGEBREAK' => 'PageBreak', + 'SETHTMLPAGEFOOTER' => 'SetHtmlPageFooter', + 'SETHTMLPAGEHEADER' => 'SetHtmlPageHeader', + 'SETPAGEFOOTER' => 'SetPageFooter', + 'SETPAGEHEADER' => 'SetPageHeader', + 'TBODY' => 'TBody', + 'TFOOT' => 'TFoot', + 'THEAD' => 'THead', + 'TEXTAREA' => 'TextArea', + 'TEXTCIRCLE' => 'TextCircle', + 'TOCENTRY' => 'TocEntry', + 'TOCPAGEBREAK' => 'TocPageBreak', + 'VAR' => 'VarTag', + 'WATERMARKIMAGE' => 'WatermarkImage', + 'WATERMARKTEXT' => 'WatermarkText', + ]; + + $className = 'Mpdf\Tag\\'; + $className .= isset($map[$tag]) ? $map[$tag] : ucfirst(strtolower($tag)); + + return $className; + } + + public function OpenTag($tag, $attr, &$ahtml, &$ihtml) + { + // Correct for tags where HTML5 specifies optional end tags excluding table elements (cf WriteHTML() ) + if ($this->mpdf->allow_html_optional_endtags) { + if (isset($this->mpdf->blk[$this->mpdf->blklvl]['tag'])) { + $closed = false; + // li end tag may be omitted if immediately followed by another li element + if (!$closed && $this->mpdf->blk[$this->mpdf->blklvl]['tag'] == 'LI' && $tag == 'LI') { + $this->CloseTag('LI', $ahtml, $ihtml); + $closed = true; + } + // dt end tag may be omitted if immediately followed by another dt element or a dd element + if (!$closed && $this->mpdf->blk[$this->mpdf->blklvl]['tag'] == 'DT' && ($tag == 'DT' || $tag == 'DD')) { + $this->CloseTag('DT', $ahtml, $ihtml); + $closed = true; + } + // dd end tag may be omitted if immediately followed by another dd element or a dt element + if (!$closed && $this->mpdf->blk[$this->mpdf->blklvl]['tag'] == 'DD' && ($tag == 'DT' || $tag == 'DD')) { + $this->CloseTag('DD', $ahtml, $ihtml); + $closed = true; + } + // p end tag may be omitted if immediately followed by an address, article, aside, blockquote, div, dl, + // fieldset, form, h1, h2, h3, h4, h5, h6, hgroup, hr, main, nav, ol, p, pre, section, table, ul + if (!$closed && $this->mpdf->blk[$this->mpdf->blklvl]['tag'] == 'P' + && ($tag == 'P' || $tag == 'DIV' || $tag == 'H1' || $tag == 'H2' || $tag == 'H3' + || $tag == 'H4' || $tag == 'H5' || $tag == 'H6' || $tag == 'UL' || $tag == 'OL' + || $tag == 'TABLE' || $tag == 'PRE' || $tag == 'FORM' || $tag == 'ADDRESS' || $tag == 'BLOCKQUOTE' + || $tag == 'CENTER' || $tag == 'DL' || $tag == 'HR' || $tag == 'ARTICLE' || $tag == 'ASIDE' + || $tag == 'FIELDSET' || $tag == 'HGROUP' || $tag == 'MAIN' || $tag == 'NAV' || $tag == 'SECTION')) { + $this->CloseTag('P', $ahtml, $ihtml); + $closed = true; + } + // option end tag may be omitted if immediately followed by another option element + // (or if it is immediately followed by an optgroup element) + if (!$closed && $this->mpdf->blk[$this->mpdf->blklvl]['tag'] == 'OPTION' && $tag == 'OPTION') { + $this->CloseTag('OPTION', $ahtml, $ihtml); + $closed = true; + } + // Table elements - see also WriteHTML() + if (!$closed && ($tag == 'TD' || $tag == 'TH') && $this->mpdf->lastoptionaltag == 'TD') { + $this->CloseTag($this->mpdf->lastoptionaltag, $ahtml, $ihtml); + $closed = true; + } // *TABLES* + if (!$closed && ($tag == 'TD' || $tag == 'TH') && $this->mpdf->lastoptionaltag == 'TH') { + $this->CloseTag($this->mpdf->lastoptionaltag, $ahtml, $ihtml); + $closed = true; + } // *TABLES* + if (!$closed && $tag == 'TR' && $this->mpdf->lastoptionaltag == 'TR') { + $this->CloseTag($this->mpdf->lastoptionaltag, $ahtml, $ihtml); + $closed = true; + } // *TABLES* + if (!$closed && $tag == 'TR' && $this->mpdf->lastoptionaltag == 'TD') { + $this->CloseTag($this->mpdf->lastoptionaltag, $ahtml, $ihtml); + $this->CloseTag('TR', $ahtml, $ihtml); + $this->CloseTag('THEAD', $ahtml, $ihtml); + $closed = true; + } // *TABLES* + if (!$closed && $tag == 'TR' && $this->mpdf->lastoptionaltag == 'TH') { + $this->CloseTag($this->mpdf->lastoptionaltag, $ahtml, $ihtml); + $this->CloseTag('TR', $ahtml, $ihtml); + $this->CloseTag('THEAD', $ahtml, $ihtml); + $closed = true; + } // *TABLES* + } + } + + if ($object = $this->getTagInstance($tag)) { + return $object->open($attr, $ahtml, $ihtml); + } + } + + public function CloseTag($tag, &$ahtml, &$ihtml) + { + if ($object = $this->getTagInstance($tag)) { + return $object->close($ahtml, $ihtml); + } + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/A.php b/src/bb-vendor/mpdf/mpdf/src/Tag/A.php new file mode 100644 index 000000000..6a6488b1d --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/A.php @@ -0,0 +1,50 @@ +<?php + +namespace Mpdf\Tag; + +class A extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + if (isset($attr['NAME']) && $attr['NAME'] != '') { + $e = ''; + /* -- BOOKMARKS -- */ + if ($this->mpdf->anchor2Bookmark) { + $objattr = []; + $objattr['CONTENT'] = htmlspecialchars_decode($attr['NAME'], ENT_QUOTES); + $objattr['type'] = 'bookmark'; + if (!empty($attr['LEVEL'])) { + $objattr['bklevel'] = $attr['LEVEL']; + } else { + $objattr['bklevel'] = 0; + } + $e = "\xbb\xa4\xactype=bookmark,objattr=" . serialize($objattr) . "\xbb\xa4\xac"; + } + /* -- END BOOKMARKS -- */ + if ($this->mpdf->tableLevel) { // *TABLES* + $this->mpdf->_saveCellTextBuffer($e, '', $attr['NAME']); // *TABLES* + } // *TABLES* + else { // *TABLES* + $this->mpdf->_saveTextBuffer($e, '', $attr['NAME']); //an internal link (adds a space for recognition) + } // *TABLES* + } + if (isset($attr['HREF'])) { + $this->mpdf->InlineProperties['A'] = $this->mpdf->saveInlineProperties(); + $properties = $this->cssManager->MergeCSS('INLINE', 'A', $attr); + if (!empty($properties)) { + $this->mpdf->setCSS($properties, 'INLINE'); + } + $this->mpdf->HREF = $attr['HREF']; // mPDF 5.7.4 URLs + } + } + + public function close(&$ahtml, &$ihtml) + { + $this->mpdf->HREF = ''; + if (isset($this->mpdf->InlineProperties['A'])) { + $this->mpdf->restoreInlineProperties($this->mpdf->InlineProperties['A']); + } + unset($this->mpdf->InlineProperties['A']); + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Acronym.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Acronym.php new file mode 100644 index 000000000..e33eea53a --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Acronym.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Acronym extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Address.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Address.php new file mode 100644 index 000000000..44b5b3cbb --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Address.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Address extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Annotation.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Annotation.php new file mode 100644 index 000000000..6ed5e0e52 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Annotation.php @@ -0,0 +1,99 @@ +<?php + +namespace Mpdf\Tag; + +class Annotation extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + //if (isset($attr['CONTENT']) && !$this->mpdf->writingHTMLheader && !$this->mpdf->writingHTMLfooter) { // Stops annotations in FixedPos + if (isset($attr['CONTENT'])) { + $objattr = []; + $objattr['margin_top'] = 0; + $objattr['margin_bottom'] = 0; + $objattr['margin_left'] = 0; + $objattr['margin_right'] = 0; + $objattr['width'] = 0; + $objattr['height'] = 0; + $objattr['border_top']['w'] = 0; + $objattr['border_bottom']['w'] = 0; + $objattr['border_left']['w'] = 0; + $objattr['border_right']['w'] = 0; + $objattr['CONTENT'] = htmlspecialchars_decode($attr['CONTENT'], ENT_QUOTES); + $objattr['type'] = 'annot'; + $objattr['POPUP'] = ''; + } else { + return; + } + if (isset($attr['POS-X'])) { + $objattr['POS-X'] = $attr['POS-X']; + } else { + $objattr['POS-X'] = 0; + } + if (isset($attr['POS-Y'])) { + $objattr['POS-Y'] = $attr['POS-Y']; + } else { + $objattr['POS-Y'] = 0; + } + if (isset($attr['ICON'])) { + $objattr['ICON'] = $attr['ICON']; + } else { + $objattr['ICON'] = 'Note'; + } + if (isset($attr['AUTHOR'])) { + $objattr['AUTHOR'] = $attr['AUTHOR']; + } elseif (isset($attr['TITLE'])) { + $objattr['AUTHOR'] = $attr['TITLE']; + } else { + $objattr['AUTHOR'] = ''; + } + if (isset($attr['FILE'])) { + $objattr['FILE'] = $attr['FILE']; + } else { + $objattr['FILE'] = ''; + } + if (isset($attr['SUBJECT'])) { + $objattr['SUBJECT'] = $attr['SUBJECT']; + } else { + $objattr['SUBJECT'] = ''; + } + if (isset($attr['OPACITY']) && $attr['OPACITY'] > 0 && $attr['OPACITY'] <= 1) { + $objattr['OPACITY'] = $attr['OPACITY']; + } elseif ($this->mpdf->annotMargin) { + $objattr['OPACITY'] = 1; + } else { + $objattr['OPACITY'] = $this->mpdf->annotOpacity; + } + if (isset($attr['COLOR'])) { + $cor = $this->colorConverter->convert($attr['COLOR'], $this->mpdf->PDFAXwarnings); + if ($cor) { + $objattr['COLOR'] = $cor; + } else { + $objattr['COLOR'] = $this->colorConverter->convert('yellow', $this->mpdf->PDFAXwarnings); + } + } else { + $objattr['COLOR'] = $this->colorConverter->convert('yellow', $this->mpdf->PDFAXwarnings); + } + + if (isset($attr['POPUP']) && !empty($attr['POPUP'])) { + $pop = preg_split('/\s+/', trim($attr['POPUP'])); + if (count($pop) > 1) { + $objattr['POPUP'] = $pop; + } else { + $objattr['POPUP'] = true; + } + } + $e = "\xbb\xa4\xactype=annot,objattr=" . serialize($objattr) . "\xbb\xa4\xac"; + if ($this->mpdf->tableLevel) { + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['textbuffer'][] = [$e]; + } // *TABLES* + else { // *TABLES* + $this->mpdf->textbuffer[] = [$e]; + } // *TABLES* + } + + public function close(&$ahtml, &$ihtml) + { + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Article.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Article.php new file mode 100644 index 000000000..180d69d8c --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Article.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Article extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Aside.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Aside.php new file mode 100644 index 000000000..fa7e697b3 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Aside.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Aside extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/B.php b/src/bb-vendor/mpdf/mpdf/src/Tag/B.php new file mode 100644 index 000000000..15e2eb3e9 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/B.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class B extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/BarCode.php b/src/bb-vendor/mpdf/mpdf/src/Tag/BarCode.php new file mode 100644 index 000000000..726b16fd6 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/BarCode.php @@ -0,0 +1,256 @@ +<?php + +namespace Mpdf\Tag; + +class BarCode extends Tag +{ + + /** + * @var \Mpdf\Barcode + */ + protected $barcode; + + public function open($attr, &$ahtml, &$ihtml) + { + $this->mpdf->ignorefollowingspaces = false; + if (!empty($attr['CODE'])) { + $objattr = []; + $objattr['margin_top'] = 0; + $objattr['margin_bottom'] = 0; + $objattr['margin_left'] = 0; + $objattr['margin_right'] = 0; + $objattr['padding_top'] = 0; + $objattr['padding_bottom'] = 0; + $objattr['padding_left'] = 0; + $objattr['padding_right'] = 0; + $objattr['width'] = 0; + $objattr['height'] = 0; + $objattr['border_top']['w'] = 0; + $objattr['border_bottom']['w'] = 0; + $objattr['border_left']['w'] = 0; + $objattr['border_right']['w'] = 0; + $objattr['code'] = $attr['CODE']; + + if (isset($attr['TYPE'])) { + $objattr['btype'] = strtoupper(trim($attr['TYPE'])); + } else { + $objattr['btype'] = 'EAN13'; + } // default + if (preg_match('/^(EAN13|ISBN|ISSN|EAN8|UPCA|UPCE)P([25])$/', $objattr['btype'], $m)) { + $objattr['btype'] = $m[1]; + $objattr['bsupp'] = $m[2]; + if (preg_match('/^(\S+)\s+(.*)$/', $objattr['code'], $mm)) { + $objattr['code'] = $mm[1]; + $objattr['bsupp_code'] = $mm[2]; + } + } else { + $objattr['bsupp'] = 0; + } + + if (isset($attr['TEXT']) && $attr['TEXT'] == 1) { + $objattr['showtext'] = 1; + } else { + $objattr['showtext'] = 0; + } + if (isset($attr['SIZE']) && $attr['SIZE'] > 0) { + $objattr['bsize'] = $attr['SIZE']; + } else { + $objattr['bsize'] = 1; + } + if (isset($attr['HEIGHT']) && $attr['HEIGHT'] > 0) { + $objattr['bheight'] = $attr['HEIGHT']; + } else { + $objattr['bheight'] = 1; + } + if (isset($attr['PR']) && $attr['PR'] > 0) { + $objattr['pr_ratio'] = $attr['PR']; + } else { + $objattr['pr_ratio'] = ''; + } + $properties = $this->cssManager->MergeCSS('', 'BARCODE', $attr); + if (isset($properties ['DISPLAY']) && strtolower($properties ['DISPLAY']) === 'none') { + return; + } + if (isset($properties['MARGIN-TOP'])) { + $objattr['margin_top'] = $this->sizeConverter->convert( + $properties['MARGIN-TOP'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['MARGIN-BOTTOM'])) { + $objattr['margin_bottom'] = $this->sizeConverter->convert( + $properties['MARGIN-BOTTOM'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['MARGIN-LEFT'])) { + $objattr['margin_left'] = $this->sizeConverter->convert( + $properties['MARGIN-LEFT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['MARGIN-RIGHT'])) { + $objattr['margin_right'] = $this->sizeConverter->convert( + $properties['MARGIN-RIGHT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + + if (isset($properties['PADDING-TOP'])) { + $objattr['padding_top'] = $this->sizeConverter->convert( + $properties['PADDING-TOP'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['PADDING-BOTTOM'])) { + $objattr['padding_bottom'] = $this->sizeConverter->convert( + $properties['PADDING-BOTTOM'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['PADDING-LEFT'])) { + $objattr['padding_left'] = $this->sizeConverter->convert( + $properties['PADDING-LEFT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['PADDING-RIGHT'])) { + $objattr['padding_right'] = $this->sizeConverter->convert( + $properties['PADDING-RIGHT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + + if (isset($properties['BORDER-TOP'])) { + $objattr['border_top'] = $this->mpdf->border_details($properties['BORDER-TOP']); + } + if (isset($properties['BORDER-BOTTOM'])) { + $objattr['border_bottom'] = $this->mpdf->border_details($properties['BORDER-BOTTOM']); + } + if (isset($properties['BORDER-LEFT'])) { + $objattr['border_left'] = $this->mpdf->border_details($properties['BORDER-LEFT']); + } + if (isset($properties['BORDER-RIGHT'])) { + $objattr['border_right'] = $this->mpdf->border_details($properties['BORDER-RIGHT']); + } + + if (isset($properties['VERTICAL-ALIGN'])) { + $objattr['vertical-align'] = self::ALIGN[strtolower($properties['VERTICAL-ALIGN'])]; + } + if (isset($properties['COLOR']) && $properties['COLOR'] != '') { + $objattr['color'] = $this->colorConverter->convert($properties['COLOR'], $this->mpdf->PDFAXwarnings); + } else { + $objattr['color'] = false; + } + if (isset($properties['BACKGROUND-COLOR']) && $properties['BACKGROUND-COLOR'] != '') { + $objattr['bgcolor'] = $this->colorConverter->convert($properties['BACKGROUND-COLOR'], $this->mpdf->PDFAXwarnings); + } else { + $objattr['bgcolor'] = false; + } + + $this->barcode = new \Mpdf\Barcode(); + + if (in_array($objattr['btype'], ['EAN13', 'ISBN', 'ISSN', 'UPCA', 'UPCE', 'EAN8'])) { + + $code = preg_replace('/\-/', '', $objattr['code']); + $arrcode = $this->barcode->getBarcodeArray($code, $objattr['btype']); + + if ($objattr['bsupp'] == 2 || $objattr['bsupp'] == 5) { // EAN-2 or -5 Supplement + $supparrcode = $this->barcode->getBarcodeArray($objattr['bsupp_code'], 'EAN' . $objattr['bsupp']); + $w = ($arrcode['maxw'] + $arrcode['lightmL'] + $arrcode['lightmR'] + + $supparrcode['maxw'] + $supparrcode['sepM']) * $arrcode['nom-X'] * $objattr['bsize']; + } else { + $w = ($arrcode['maxw'] + $arrcode['lightmL'] + $arrcode['lightmR']) * $arrcode['nom-X'] * $objattr['bsize']; + } + + $h = $arrcode['nom-H'] * $objattr['bsize'] * $objattr['bheight']; + // Add height for ISBN string + margin from top of bars + if (($objattr['showtext'] && $objattr['btype'] === 'EAN13') || $objattr['btype'] === 'ISBN' || $objattr['btype'] === 'ISSN') { + $tisbnm = 1.5 * $objattr['bsize']; // Top margin between TOP TEXT (isbn - if shown) & bars + $isbn_fontsize = 2.1 * $objattr['bsize']; + $h += $isbn_fontsize + $tisbnm; + } + + } elseif ($objattr['btype'] === 'QR') { // QR-code + $w = $h = $objattr['bsize'] * 25; // Factor of 25mm (default) + $objattr['errorlevel'] = 'L'; + if (isset($attr['ERROR'])) { + $objattr['errorlevel'] = $attr['ERROR']; + } + $objattr['disableborder'] = false; + if (isset($attr['DISABLEBORDER'])) { + $objattr['disableborder'] = (bool) $attr['DISABLEBORDER']; + } + + } elseif (in_array($objattr['btype'], ['IMB', 'RM4SCC', 'KIX', 'POSTNET', 'PLANET'])) { + + $arrcode = $this->barcode->getBarcodeArray($objattr['code'], $objattr['btype']); + + $w = ($arrcode['maxw'] * $arrcode['nom-X'] * $objattr['bsize']) + $arrcode['quietL'] + $arrcode['quietR']; + $h = ($arrcode['nom-H'] * $objattr['bsize']) + (2 * $arrcode['quietTB']); + + } elseif (in_array($objattr['btype'], ['C128A', 'C128B', 'C128C', 'C128RAW', 'EAN128A', 'EAN128B', 'EAN128C', + 'C39', 'C39+', 'C39E', 'C39E+', 'S25', 'S25+', 'I25', 'I25+', 'I25B', + 'I25B+', 'C93', 'MSI', 'MSI+', 'CODABAR', 'CODE11'])) { + + $arrcode = $this->barcode->getBarcodeArray($objattr['code'], $objattr['btype'], $objattr['pr_ratio']); + $w = ($arrcode['maxw'] + $arrcode['lightmL'] + $arrcode['lightmR']) * $arrcode['nom-X'] * $objattr['bsize']; + $h = ((2 * $arrcode['lightTB'] * $arrcode['nom-X']) + $arrcode['nom-H']) * $objattr['bsize'] * $objattr['bheight']; + + } else { + return; + } + + $extraheight = $objattr['padding_top'] + $objattr['padding_bottom'] + $objattr['margin_top'] + + $objattr['margin_bottom'] + $objattr['border_top']['w'] + $objattr['border_bottom']['w']; + $extrawidth = $objattr['padding_left'] + $objattr['padding_right'] + $objattr['margin_left'] + + $objattr['margin_right'] + $objattr['border_left']['w'] + $objattr['border_right']['w']; + + $objattr['type'] = 'barcode'; + $objattr['height'] = $h + $extraheight; + $objattr['width'] = $w + $extrawidth; + $objattr['barcode_height'] = $h; + $objattr['barcode_width'] = $w; + + /* -- CSS-IMAGE-FLOAT -- */ + if (!$this->mpdf->ColActive && !$this->mpdf->tableLevel && !$this->mpdf->listlvl && !$this->mpdf->kwt) { + if (isset($properties['FLOAT']) && (strtoupper($properties['FLOAT']) === 'RIGHT' || strtoupper($properties['FLOAT']) === 'LEFT')) { + $objattr['float'] = strtoupper(substr($properties['FLOAT'], 0, 1)); + } + } + /* -- END CSS-IMAGE-FLOAT -- */ + + $e = "\xbb\xa4\xactype=barcode,objattr=" . serialize($objattr) . "\xbb\xa4\xac"; + + /* -- TABLES -- */ + // Output it to buffers + if ($this->mpdf->tableLevel) { + $this->mpdf->_saveCellTextBuffer($e, $this->mpdf->HREF); + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s'] += $objattr['width']; + } else { + /* -- END TABLES -- */ + $this->mpdf->_saveTextBuffer($e, $this->mpdf->HREF); + } // *TABLES* + } + } + + public function close(&$ahtml, &$ihtml) + { + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Bdi.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Bdi.php new file mode 100644 index 000000000..3de3ec5f7 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Bdi.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Bdi extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Bdo.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Bdo.php new file mode 100644 index 000000000..6435d3f17 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Bdo.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Bdo extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Big.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Big.php new file mode 100644 index 000000000..fffd893d1 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Big.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Big extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/BlockQuote.php b/src/bb-vendor/mpdf/mpdf/src/Tag/BlockQuote.php new file mode 100644 index 000000000..44287ca61 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/BlockQuote.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class BlockQuote extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/BlockTag.php b/src/bb-vendor/mpdf/mpdf/src/Tag/BlockTag.php new file mode 100644 index 000000000..0f7df9afb --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/BlockTag.php @@ -0,0 +1,1353 @@ +<?php + +namespace Mpdf\Tag; + +use Mpdf\Conversion\DecToAlpha; +use Mpdf\Conversion\DecToRoman; + +use Mpdf\Utils\Arrays; +use Mpdf\Utils\UtfString; + +abstract class BlockTag extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $tag = $this->getTagName(); + + // mPDF 6 Lists + $this->mpdf->lastoptionaltag = ''; + + // mPDF 6 bidi + // Block + // If unicode-bidi set on current clock, any embedding levels, isolates, or overrides are closed (not inherited) + if (isset($this->mpdf->blk[$this->mpdf->blklvl]['bidicode'])) { + $blockpost = $this->mpdf->_setBidiCodes('end', $this->mpdf->blk[$this->mpdf->blklvl]['bidicode']); + if ($blockpost) { + $this->mpdf->OTLdata = []; + if ($this->mpdf->tableLevel) { + $this->mpdf->_saveCellTextBuffer($blockpost); + } else { + $this->mpdf->_saveTextBuffer($blockpost); + } + } + } + + + $p = $this->cssManager->PreviewBlockCSS($tag, $attr); + if (isset($p['DISPLAY']) && strtolower($p['DISPLAY']) === 'none') { + $this->mpdf->blklvl++; + $this->mpdf->blk[$this->mpdf->blklvl]['hide'] = true; + $this->mpdf->blk[$this->mpdf->blklvl]['tag'] = $tag; // mPDF 6 + return; + } + if ($tag === 'CAPTION') { + // position is written in AdjstHTML + $divpos = 'T'; + if (isset($attr['POSITION']) && strtolower($attr['POSITION']) === 'bottom') { + $divpos = 'B'; + } + + $cappos = 'T'; + if (isset($attr['ALIGN']) && strtolower($attr['ALIGN']) === 'bottom') { + $cappos = 'B'; + } elseif (isset($p['CAPTION-SIDE']) && strtolower($p['CAPTION-SIDE']) === 'bottom') { + $cappos = 'B'; + } + if (isset($attr['ALIGN'])) { + unset($attr['ALIGN']); + } + if ($cappos != $divpos) { + $this->mpdf->blklvl++; + $this->mpdf->blk[$this->mpdf->blklvl]['hide'] = true; + $this->mpdf->blk[$this->mpdf->blklvl]['tag'] = $tag; // mPDF 6 + return; + } + } + + /* -- FORMS -- */ + if ($tag === 'FORM') { + $this->form->formMethod = 'POST'; + if (isset($attr['METHOD']) && strtolower($attr['METHOD']) === 'get') { + $this->form->formMethod = 'GET'; + } + + $this->form->formAction = ''; + if (isset($attr['ACTION'])) { + $this->form->formAction = $attr['ACTION']; + } + } + /* -- END FORMS -- */ + + + /* -- CSS-POSITION -- */ + if ((isset($p['POSITION']) + && (strtolower($p['POSITION']) === 'fixed' + || strtolower($p['POSITION']) === 'absolute')) + && $this->mpdf->blklvl == 0) { + if ($this->mpdf->inFixedPosBlock) { + throw new \Mpdf\MpdfException('Cannot nest block with position:fixed or position:absolute'); + } + $this->mpdf->inFixedPosBlock = true; + return; + } + /* -- END CSS-POSITION -- */ + // Start Block + $this->mpdf->ignorefollowingspaces = true; + + $lastbottommargin = 0; + if ($this->mpdf->blockjustfinished && !count($this->mpdf->textbuffer) + && $this->mpdf->y != $this->mpdf->tMargin + && $this->mpdf->collapseBlockMargins) { + $lastbottommargin = $this->mpdf->lastblockbottommargin; + } + $this->mpdf->lastblockbottommargin = 0; + $this->mpdf->blockjustfinished = false; + + + $this->mpdf->InlineBDF = []; // mPDF 6 + $this->mpdf->InlineBDFctr = 0; // mPDF 6 + $this->mpdf->InlineProperties = []; + $this->mpdf->divbegin = true; + + $this->mpdf->linebreakjustfinished = false; + + /* -- TABLES -- */ + if ($this->mpdf->tableLevel) { + // If already something on the line + if ($this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s'] > 0 && !$this->mpdf->nestedtablejustfinished) { + $this->mpdf->_saveCellTextBuffer("\n"); + if (!isset($this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['maxs'])) { + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['maxs'] = $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s']; + } elseif ($this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['maxs'] < $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s']) { + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['maxs'] = $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s']; + } + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s'] = 0; // reset + } + // Cannot set block properties inside table - use Bold to indicate h1-h6 + if ($tag === 'CENTER' && $this->mpdf->tdbegin) { + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['a'] = self::ALIGN['center']; + } + + $this->mpdf->InlineProperties['BLOCKINTABLE'] = $this->mpdf->saveInlineProperties(); + $properties = $this->cssManager->MergeCSS('', $tag, $attr); + if (!empty($properties)) { + $this->mpdf->setCSS($properties, 'INLINE'); + } + + // mPDF 6 Lists + if ($tag === 'UL' || $tag === 'OL') { + $this->mpdf->listlvl++; + if (isset($attr['START'])) { + $this->mpdf->listcounter[$this->mpdf->listlvl] = (int) $attr['START'] - 1; + } else { + $this->mpdf->listcounter[$this->mpdf->listlvl] = 0; + } + $this->mpdf->listitem = []; + if ($tag === 'OL') { + $this->mpdf->listtype[$this->mpdf->listlvl] = 'decimal'; + } elseif ($tag === 'UL') { + if ($this->mpdf->listlvl % 3 == 1) { + $this->mpdf->listtype[$this->mpdf->listlvl] = 'disc'; + } elseif ($this->mpdf->listlvl % 3 == 2) { + $this->mpdf->listtype[$this->mpdf->listlvl] = 'circle'; + } else { + $this->mpdf->listtype[$this->mpdf->listlvl] = 'square'; + } + } + } + + // mPDF 6 Lists - in Tables + if ($tag === 'LI') { + + if ($this->mpdf->listlvl == 0) { //in case of malformed HTML code. Example:(...)</p><li>Content</li><p>Paragraph1</p>(...) + $this->mpdf->listlvl++; // first depth level + $this->mpdf->listcounter[$this->mpdf->listlvl] = 0; + } + + $this->mpdf->listcounter[$this->mpdf->listlvl]++; + $this->mpdf->listitem = []; + //if in table - output here as a tabletextbuffer + //position:inside OR position:outside (always output in table as position:inside) + + $decToAlpha = new DecToAlpha(); + $decToRoman = new DecToRoman(); + + switch ($this->mpdf->listtype[$this->mpdf->listlvl]) { + case 'upper-alpha': + case 'upper-latin': + case 'A': + $blt = $decToAlpha->convert($this->mpdf->listcounter[$this->mpdf->listlvl]) . $this->mpdf->list_number_suffix; + break; + case 'lower-alpha': + case 'lower-latin': + case 'a': + $blt = $decToAlpha->convert($this->mpdf->listcounter[$this->mpdf->listlvl], false) . $this->mpdf->list_number_suffix; + break; + case 'upper-roman': + case 'I': + $blt = $decToRoman->convert($this->mpdf->listcounter[$this->mpdf->listlvl]) . $this->mpdf->list_number_suffix; + break; + case 'lower-roman': + case 'i': + $blt = $decToRoman->convert($this->mpdf->listcounter[$this->mpdf->listlvl]) . $this->mpdf->list_number_suffix; + break; + case 'decimal': + case '1': + $blt = $this->mpdf->listcounter[$this->mpdf->listlvl] . $this->mpdf->list_number_suffix; + break; + default: + $blt = '-'; + if ($this->mpdf->listlvl % 3 == 1 && $this->mpdf->_charDefined($this->mpdf->CurrentFont['cw'], 8226)) { + $blt = "\xe2\x80\xa2"; + } // • + elseif ($this->mpdf->listlvl % 3 == 2 && $this->mpdf->_charDefined($this->mpdf->CurrentFont['cw'], 9900)) { + $blt = "\xe2\x9a\xac"; + } // ⚬ + elseif ($this->mpdf->listlvl % 3 == 0 && $this->mpdf->_charDefined($this->mpdf->CurrentFont['cw'], 9642)) { + $blt = "\xe2\x96\xaa"; + } // ▪ + break; + } + + // change to   spaces + if ($this->mpdf->usingCoreFont) { + $ls = str_repeat(chr(160) . chr(160), ($this->mpdf->listlvl - 1) * 2) . $blt . ' '; + } else { + $ls = str_repeat("\xc2\xa0\xc2\xa0", ($this->mpdf->listlvl - 1) * 2) . $blt . ' '; + } + $this->mpdf->_saveCellTextBuffer($ls); + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s'] += $this->mpdf->GetStringWidth($ls); + } + + return; + } + /* -- END TABLES -- */ + + if ($this->mpdf->lastblocklevelchange == 1) { + $blockstate = 1; + } // Top margins/padding only + elseif ($this->mpdf->lastblocklevelchange < 1) { + $blockstate = 0; + } // NO margins/padding + + $this->mpdf->printbuffer($this->mpdf->textbuffer, $blockstate); + $this->mpdf->textbuffer = []; + + $save_blklvl = $this->mpdf->blklvl; + $save_blk = $this->mpdf->blk; + + $this->mpdf->Reset(); + + $pagesel = ''; + /* -- CSS-PAGE -- */ + if (isset($p['PAGE'])) { + $pagesel = $p['PAGE']; + } // mPDF 6 (uses $p - preview of properties so blklvl can be incremented after page-break) + /* -- END CSS-PAGE -- */ + + // If page-box has changed AND/OR PAGE-BREAK-BEFORE + // mPDF 6 (uses $p - preview of properties so blklvl can be imcremented after page-break) + if (!$this->mpdf->tableLevel && (($pagesel && (!isset($this->mpdf->page_box['current']) + || $pagesel != $this->mpdf->page_box['current'])) + || (isset($p['PAGE-BREAK-BEFORE']) + && $p['PAGE-BREAK-BEFORE']))) { + // mPDF 6 pagebreaktype + $startpage = $this->mpdf->page; + $pagebreaktype = $this->mpdf->defaultPagebreakType; + $this->mpdf->lastblocklevelchange = -1; + if ($this->mpdf->ColActive) { + $pagebreaktype = 'cloneall'; + } + if ($pagesel && (!isset($this->mpdf->page_box['current']) || $pagesel != $this->mpdf->page_box['current'])) { + $pagebreaktype = 'cloneall'; + } + $this->mpdf->_preForcedPagebreak($pagebreaktype); + + if (isset($p['PAGE-BREAK-BEFORE'])) { + if (strtoupper($p['PAGE-BREAK-BEFORE']) === 'RIGHT') { + $this->mpdf->AddPage( + $this->mpdf->CurOrientation, + 'NEXT-ODD', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + 0, + 0, + 0, + 0, + $pagesel + ); + } elseif (strtoupper($p['PAGE-BREAK-BEFORE']) === 'LEFT') { + $this->mpdf->AddPage( + $this->mpdf->CurOrientation, + 'NEXT-EVEN', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + 0, + 0, + 0, + 0, + $pagesel + ); + } elseif (strtoupper($p['PAGE-BREAK-BEFORE']) === 'ALWAYS') { + $this->mpdf->AddPage($this->mpdf->CurOrientation, '', '', '', '', '', '', '', '', '', '', '', '', '', '', 0, 0, 0, 0, $pagesel); + } elseif ($this->mpdf->page_box['current'] != $pagesel) { + $this->mpdf->AddPage($this->mpdf->CurOrientation, '', '', '', '', '', '', '', '', '', '', '', '', '', '', 0, 0, 0, 0, $pagesel); + } // *CSS-PAGE* + } /* -- CSS-PAGE -- */ + // Must Add new page if changed page properties + elseif (!isset($this->mpdf->page_box['current']) || $pagesel != $this->mpdf->page_box['current']) { + $this->mpdf->AddPage($this->mpdf->CurOrientation, '', '', '', '', '', '', '', '', '', '', '', '', '', '', 0, 0, 0, 0, $pagesel); + } + /* -- END CSS-PAGE -- */ + + // mPDF 6 pagebreaktype + $this->mpdf->_postForcedPagebreak($pagebreaktype, $startpage, $save_blk, $save_blklvl); + } + + // mPDF 6 pagebreaktype - moved after pagebreak + $this->mpdf->blklvl++; + $currblk = & $this->mpdf->blk[$this->mpdf->blklvl]; + $this->mpdf->initialiseBlock($currblk); + $prevblk = & $this->mpdf->blk[$this->mpdf->blklvl - 1]; + $currblk['tag'] = $tag; + $currblk['attr'] = $attr; + + $properties = $this->cssManager->MergeCSS('BLOCK', $tag, $attr); // mPDF 6 - moved to after page-break-before + // mPDF 6 page-break-inside:avoid + if (isset($properties['PAGE-BREAK-INSIDE']) && strtoupper($properties['PAGE-BREAK-INSIDE']) === 'AVOID' + && !$this->mpdf->ColActive && !$this->mpdf->keep_block_together && !isset($attr['PAGEBREAKAVOIDCHECKED'])) { + // avoid re-iterating using PAGEBREAKAVOIDCHECKED; set in CloseTag + $currblk['keep_block_together'] = 1; + $currblk['array_i'] = $ihtml; // mPDF 6 + $this->mpdf->kt_y00 = $this->mpdf->y; + $this->mpdf->kt_p00 = $this->mpdf->page; + $this->mpdf->keep_block_together = 1; + } + if ($lastbottommargin && !empty($properties['MARGIN-TOP']) && empty($properties['FLOAT'])) { + $currblk['lastbottommargin'] = $lastbottommargin; + } + + if (isset($properties['Z-INDEX']) && $this->mpdf->current_layer == 0) { + $v = (int) $properties['Z-INDEX']; + if ($v > 0) { + $currblk['z-index'] = $v; + $this->mpdf->BeginLayer($v); + } + } + + + // mPDF 6 Lists + // List-type set by attribute + if ($tag === 'OL' || $tag === 'UL' || $tag === 'LI') { + if (!empty($attr['TYPE'])) { + $listtype = $attr['TYPE']; + switch ($listtype) { + case 'A': + $listtype = 'upper-latin'; + break; + case 'a': + $listtype = 'lower-latin'; + break; + case 'I': + $listtype = 'upper-roman'; + break; + case 'i': + $listtype = 'lower-roman'; + break; + case '1': + $listtype = 'decimal'; + break; + } + $currblk['list_style_type'] = $listtype; + } + } + + $this->mpdf->setCSS($properties, 'BLOCK', $tag); //name(id/class/style) found in the CSS array! + $currblk['InlineProperties'] = $this->mpdf->saveInlineProperties(); + + if (isset($properties['VISIBILITY'])) { + $v = strtolower($properties['VISIBILITY']); + if (($v === 'hidden' || $v === 'printonly' || $v === 'screenonly') && $this->mpdf->visibility === 'visible' && !$this->mpdf->tableLevel) { + $currblk['visibility'] = $v; + $this->mpdf->SetVisibility($v); + } + } + + // mPDF 6 + if (!empty($attr['ALIGN'])) { + $currblk['block-align'] = self::ALIGN[strtolower($attr['ALIGN'])]; + } + + + if (isset($properties['HEIGHT'])) { + $currblk['css_set_height'] = $this->sizeConverter->convert( + $properties['HEIGHT'], + $this->mpdf->h - $this->mpdf->tMargin - $this->mpdf->bMargin, + $this->mpdf->FontSize, + false + ); + if (($currblk['css_set_height'] + $this->mpdf->y) > $this->mpdf->PageBreakTrigger + && $this->mpdf->y > $this->mpdf->tMargin + 5 + && $currblk['css_set_height'] < ($this->mpdf->h - ($this->mpdf->tMargin + $this->mpdf->bMargin))) { + $this->mpdf->AddPage($this->mpdf->CurOrientation); + } + } else { + $currblk['css_set_height'] = false; + } + + + // Added mPDF 3.0 Float DIV + if (isset($prevblk['blockContext'])) { + $currblk['blockContext'] = $prevblk['blockContext']; + } // *CSS-FLOAT* + + if (isset($properties['CLEAR'])) { + $this->mpdf->ClearFloats(strtoupper($properties['CLEAR']), $this->mpdf->blklvl - 1); + } // *CSS-FLOAT* + + $currblk['padding_left'] = is_numeric($currblk['padding_left']) ? $currblk['padding_left'] : 0; + $currblk['padding_right'] = is_numeric($currblk['padding_right']) ? $currblk['padding_right'] : 0; + + $container_w = $prevblk['inner_width']; + $bdr = $currblk['border_right']['w']; + $bdl = $currblk['border_left']['w']; + $pdr = $currblk['padding_right']; + $pdl = $currblk['padding_left']; + + $setwidth = 0; + if (isset($currblk['css_set_width'])) { + $setwidth = $currblk['css_set_width']; + } + + /* -- CSS-FLOAT -- */ + if (isset($properties['FLOAT']) && strtoupper($properties['FLOAT']) === 'RIGHT' && !$this->mpdf->ColActive) { + + // Cancel Keep-Block-together + $currblk['keep_block_together'] = false; + $this->mpdf->kt_y00 = 0; + $this->mpdf->keep_block_together = 0; + + $this->mpdf->blockContext++; + $currblk['blockContext'] = $this->mpdf->blockContext; + + list($l_exists, $r_exists, $l_max, $r_max, $l_width, $r_width) = $this->mpdf->GetFloatDivInfo($this->mpdf->blklvl - 1); + + // DIV is too narrow for text to fit! + $maxw = $container_w - $l_width - $r_width; + $doubleCharWidth = (2 * $this->mpdf->GetCharWidth('W', false)); + if (($setwidth + $currblk['margin_right'] + $bdl + $pdl + $bdr + $pdr) > $maxw + || ($maxw - ($currblk['margin_right'] + $bdl + $pdl + $bdr + $pdr)) < (2 * $this->mpdf->GetCharWidth('W', false))) { + // Too narrow to fit - try to move down past L or R float + if ($l_max < $r_max && ($setwidth + $currblk['margin_right'] + $bdl + $pdl + $bdr + $pdr) <= ($container_w - $r_width) + && (($container_w - $r_width) - ($currblk['margin_right'] + $bdl + $pdl + $bdr + $pdr)) > $doubleCharWidth) { + $this->mpdf->ClearFloats('LEFT', $this->mpdf->blklvl - 1); + } elseif ($r_max < $l_max && ($setwidth + $currblk['margin_right'] + $bdl + $pdl + $bdr + $pdr) <= ($container_w - $l_width) + && (($container_w - $l_width) - ($currblk['margin_right'] + $bdl + $pdl + $bdr + $pdr)) > $doubleCharWidth) { + $this->mpdf->ClearFloats('RIGHT', $this->mpdf->blklvl - 1); + } else { + $this->mpdf->ClearFloats('BOTH', $this->mpdf->blklvl - 1); + } + list($l_exists, $r_exists, $l_max, $r_max, $l_width, $r_width) = $this->mpdf->GetFloatDivInfo($this->mpdf->blklvl - 1); + } + + if ($r_exists) { + $currblk['margin_right'] += $r_width; + } + + $currblk['float'] = 'R'; + $currblk['float_start_y'] = $this->mpdf->y; + + if (isset($currblk['css_set_width'])) { + $currblk['margin_left'] = $container_w - ($setwidth + $bdl + $pdl + $bdr + $pdr + $currblk['margin_right']); + $currblk['float_width'] = ($setwidth + $bdl + $pdl + $bdr + $pdr + $currblk['margin_right']); + } else { + // *** If no width set - would need to buffer and keep track of max width, then Right-align if not full width + // and do borders and backgrounds - For now - just set to maximum width left + + if ($l_exists) { + $currblk['margin_left'] += $l_width; + } + $currblk['css_set_width'] = $container_w - ($currblk['margin_left'] + $currblk['margin_right'] + $bdl + $pdl + $bdr + $pdr); + + $currblk['float_width'] = ($currblk['css_set_width'] + $bdl + $pdl + $bdr + $pdr + $currblk['margin_right']); + } + + } elseif (isset($properties['FLOAT']) && strtoupper($properties['FLOAT']) === 'LEFT' && !$this->mpdf->ColActive) { + // Cancel Keep-Block-together + $currblk['keep_block_together'] = false; + $this->mpdf->kt_y00 = 0; + $this->mpdf->keep_block_together = 0; + + $this->mpdf->blockContext++; + $currblk['blockContext'] = $this->mpdf->blockContext; + + list($l_exists, $r_exists, $l_max, $r_max, $l_width, $r_width) = $this->mpdf->GetFloatDivInfo($this->mpdf->blklvl - 1); + + // DIV is too narrow for text to fit! + $maxw = $container_w - $l_width - $r_width; + $doubleCharWidth = (2 * $this->mpdf->GetCharWidth('W', false)); + if (($setwidth + $currblk['margin_left'] + $bdl + $pdl + $bdr + $pdr) > $maxw + || ($maxw - ($currblk['margin_left'] + $bdl + $pdl + $bdr + $pdr)) < (2 * $this->mpdf->GetCharWidth('W', false))) { + // Too narrow to fit - try to move down past L or R float + if ($l_max < $r_max && ($setwidth + $currblk['margin_right'] + $bdl + $pdl + $bdr + $pdr) <= ($container_w - $r_width) + && (($container_w - $r_width) - ($currblk['margin_right'] + $bdl + $pdl + $bdr + $pdr)) > $doubleCharWidth) { + $this->mpdf->ClearFloats('LEFT', $this->mpdf->blklvl - 1); + } elseif ($r_max < $l_max && ($setwidth + $currblk['margin_right'] + $bdl + $pdl + $bdr + $pdr) <= ($container_w - $l_width) + && (($container_w - $l_width) - ($currblk['margin_right'] + $bdl + $pdl + $bdr + $pdr)) > $doubleCharWidth) { + $this->mpdf->ClearFloats('RIGHT', $this->mpdf->blklvl - 1); + } else { + $this->mpdf->ClearFloats('BOTH', $this->mpdf->blklvl - 1); + } + list($l_exists, $r_exists, $l_max, $r_max, $l_width, $r_width) = $this->mpdf->GetFloatDivInfo($this->mpdf->blklvl - 1); + } + + if ($l_exists) { + $currblk['margin_left'] += $l_width; + } + + $currblk['float'] = 'L'; + $currblk['float_start_y'] = $this->mpdf->y; + if ($setwidth) { + $currblk['margin_right'] = $container_w - ($setwidth + $bdl + $pdl + $bdr + $pdr + $currblk['margin_left']); + $currblk['float_width'] = ($setwidth + $bdl + $pdl + $bdr + $pdr + $currblk['margin_left']); + } else { + // *** If no width set - would need to buffer and keep track of max width, then Right-align if not full width + // and do borders and backgrounds - For now - just set to maximum width left + + if ($r_exists) { + $currblk['margin_right'] += $r_width; + } + $currblk['css_set_width'] = $container_w - ($currblk['margin_left'] + $currblk['margin_right'] + $bdl + $pdl + $bdr + $pdr); + + $currblk['float_width'] = ($currblk['css_set_width'] + $bdl + $pdl + $bdr + $pdr + $currblk['margin_left']); + } + } else { + // Don't allow overlap - if floats present - adjust padding to avoid overlap with Floats + list($l_exists, $r_exists, $l_max, $r_max, $l_width, $r_width) = $this->mpdf->GetFloatDivInfo($this->mpdf->blklvl - 1); + $maxw = $container_w - $l_width - $r_width; + + $pdl = is_numeric($pdl) ? $pdl : 0; + $pdr = is_numeric($pdr) ? $pdr : 0; + + $doubleCharWidth = (2 * $this->mpdf->GetCharWidth('W', false)); + if (($setwidth + $currblk['margin_left'] + $currblk['margin_right'] + $bdl + $pdl + $bdr + $pdr) > $maxw + || ($maxw - ($currblk['margin_right'] + $currblk['margin_left'] + $bdl + $pdl + $bdr + $pdr)) < $doubleCharWidth) { + // Too narrow to fit - try to move down past L or R float + if ($l_max < $r_max && ($setwidth + $currblk['margin_left'] + $currblk['margin_right'] + $bdl + $pdl + $bdr + $pdr) <= ($container_w - $r_width) + && (($container_w - $r_width) - ($currblk['margin_right'] + $currblk['margin_left'] + $bdl + $pdl + $bdr + $pdr)) > $doubleCharWidth) { + $this->mpdf->ClearFloats('LEFT', $this->mpdf->blklvl - 1); + } elseif ($r_max < $l_max && ($setwidth + $currblk['margin_left'] + $currblk['margin_right'] + $bdl + $pdl + $bdr + $pdr) <= ($container_w - $l_width) + && (($container_w - $l_width) - ($currblk['margin_right'] + $currblk['margin_left'] + $bdl + $pdl + $bdr + $pdr)) > $doubleCharWidth) { + $this->mpdf->ClearFloats('RIGHT', $this->mpdf->blklvl - 1); + } else { + $this->mpdf->ClearFloats('BOTH', $this->mpdf->blklvl - 1); + } + list($l_exists, $r_exists, $l_max, $r_max, $l_width, $r_width) = $this->mpdf->GetFloatDivInfo($this->mpdf->blklvl - 1); + } + if ($r_exists) { + $currblk['padding_right'] = max($r_width - $currblk['margin_right'] - $bdr, $pdr); + } + if ($l_exists) { + $currblk['padding_left'] = max($l_width - $currblk['margin_left'] - $bdl, $pdl); + } + } + /* -- END CSS-FLOAT -- */ + + + /* -- BORDER-RADIUS -- */ + // Automatically increase padding if required for border-radius + if ($this->mpdf->autoPadding && !$this->mpdf->ColActive) { + $currblk['border_radius_TL_H'] = Arrays::get($currblk, 'border_radius_TL_H', 0); + $currblk['border_radius_TL_V'] = Arrays::get($currblk, 'border_radius_TL_V', 0); + $currblk['border_radius_TR_H'] = Arrays::get($currblk, 'border_radius_TR_H', 0); + $currblk['border_radius_TR_V'] = Arrays::get($currblk, 'border_radius_TR_V', 0); + $currblk['border_radius_BL_H'] = Arrays::get($currblk, 'border_radius_BL_H', 0); + $currblk['border_radius_BL_V'] = Arrays::get($currblk, 'border_radius_BL_V', 0); + $currblk['border_radius_BR_H'] = Arrays::get($currblk, 'border_radius_BR_H', 0); + $currblk['border_radius_BR_V'] = Arrays::get($currblk, 'border_radius_BR_V', 0); + + if ($currblk['border_radius_TL_H'] > $currblk['padding_left'] && $currblk['border_radius_TL_V'] > $currblk['padding_top']) { + if ($currblk['border_radius_TL_H'] > $currblk['border_radius_TL_V']) { + $this->mpdf->_borderPadding( + $currblk['border_radius_TL_H'], + $currblk['border_radius_TL_V'], + $currblk['padding_left'], + $currblk['padding_top'] + ); + } else { + $this->mpdf->_borderPadding( + $currblk['border_radius_TL_V'], + $currblk['border_radius_TL_H'], + $currblk['padding_top'], + $currblk['padding_left'] + ); + } + } + if ($currblk['border_radius_TR_H'] > $currblk['padding_right'] && $currblk['border_radius_TR_V'] > $currblk['padding_top']) { + if ($currblk['border_radius_TR_H'] > $currblk['border_radius_TR_V']) { + $this->mpdf->_borderPadding( + $currblk['border_radius_TR_H'], + $currblk['border_radius_TR_V'], + $currblk['padding_right'], + $currblk['padding_top'] + ); + } else { + $this->mpdf->_borderPadding( + $currblk['border_radius_TR_V'], + $currblk['border_radius_TR_H'], + $currblk['padding_top'], + $currblk['padding_right'] + ); + } + } + if ($currblk['border_radius_BL_H'] > $currblk['padding_left'] && $currblk['border_radius_BL_V'] > $currblk['padding_bottom']) { + if ($currblk['border_radius_BL_H'] > $currblk['border_radius_BL_V']) { + $this->mpdf->_borderPadding( + $currblk['border_radius_BL_H'], + $currblk['border_radius_BL_V'], + $currblk['padding_left'], + $currblk['padding_bottom'] + ); + } else { + $this->mpdf->_borderPadding( + $currblk['border_radius_BL_V'], + $currblk['border_radius_BL_H'], + $currblk['padding_bottom'], + $currblk['padding_left'] + ); + } + } + if ($currblk['border_radius_BR_H'] > $currblk['padding_right'] && $currblk['border_radius_BR_V'] > $currblk['padding_bottom']) { + if ($currblk['border_radius_BR_H'] > $currblk['border_radius_BR_V']) { + $this->mpdf->_borderPadding( + $currblk['border_radius_BR_H'], + $currblk['border_radius_BR_V'], + $currblk['padding_right'], + $currblk['padding_bottom'] + ); + } else { + $this->mpdf->_borderPadding( + $currblk['border_radius_BR_V'], + $currblk['border_radius_BR_H'], + $currblk['padding_bottom'], + $currblk['padding_right'] + ); + } + } + } + /* -- END BORDER-RADIUS -- */ + + // Hanging indent - if negative indent: ensure padding is >= indent + if (!isset($currblk['text_indent'])) { + $currblk['text_indent'] = null; + } + if (!isset($currblk['inner_width'])) { + $currblk['inner_width'] = null; + } + $cbti = $this->sizeConverter->convert( + $currblk['text_indent'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + if ($cbti < 0) { + $hangind = -$cbti; + if (isset($currblk['direction']) && $currblk['direction'] === 'rtl') { // *OTL* + $currblk['padding_right'] = max($currblk['padding_right'], $hangind); // *OTL* + } // *OTL* + else { // *OTL* + $currblk['padding_left'] = max($currblk['padding_left'], $hangind); + } // *OTL* + } + + if (isset($currblk['css_set_width'])) { + if (isset($properties['MARGIN-LEFT'], $properties['MARGIN-RIGHT']) + && strtolower($properties['MARGIN-LEFT']) === 'auto' && strtolower($properties['MARGIN-RIGHT']) === 'auto') { + // Try to reduce margins to accomodate - if still too wide, set margin-right/left=0 (reduces width) + $anyextra = $prevblk['inner_width'] - ($currblk['css_set_width'] + $currblk['border_left']['w'] + + $currblk['padding_left'] + $currblk['border_right']['w'] + $currblk['padding_right']); + if ($anyextra > 0) { + $currblk['margin_left'] = $currblk['margin_right'] = $anyextra / 2; + } else { + $currblk['margin_left'] = $currblk['margin_right'] = 0; + } + } elseif (isset($properties['MARGIN-LEFT']) && strtolower($properties['MARGIN-LEFT']) === 'auto') { + // Try to reduce margin-left to accomodate - if still too wide, set margin-left=0 (reduces width) + $currblk['margin_left'] = $prevblk['inner_width'] - ($currblk['css_set_width'] + + $currblk['border_left']['w'] + $currblk['padding_left'] + $currblk['border_right']['w'] + + $currblk['padding_right'] + $currblk['margin_right']); + if ($currblk['margin_left'] < 0) { + $currblk['margin_left'] = 0; + } + } elseif (isset($properties['MARGIN-RIGHT']) && strtolower($properties['MARGIN-RIGHT']) === 'auto') { + // Try to reduce margin-right to accomodate - if still too wide, set margin-right=0 (reduces width) + $currblk['margin_right'] = $prevblk['inner_width'] - ($currblk['css_set_width'] + + $currblk['border_left']['w'] + $currblk['padding_left'] + + $currblk['border_right']['w'] + $currblk['padding_right'] + $currblk['margin_left']); + if ($currblk['margin_right'] < 0) { + $currblk['margin_right'] = 0; + } + } else { + if ($currblk['direction'] === 'rtl') { // *OTL* + // Try to reduce margin-left to accomodate - if still too wide, set margin-left=0 (reduces width) + $currblk['margin_left'] = $prevblk['inner_width'] - ($currblk['css_set_width'] + + $currblk['border_left']['w'] + $currblk['padding_left'] + $currblk['border_right']['w'] + + $currblk['padding_right'] + $currblk['margin_right']); // *OTL* + if ($currblk['margin_left'] < 0) { // *OTL* + $currblk['margin_left'] = 0; // *OTL* + } // *OTL* + } // *OTL* + else { // *OTL* + // Try to reduce margin-right to accomodate - if still too wide, set margin-right=0 (reduces width) + $currblk['margin_right'] = $prevblk['inner_width'] - ($currblk['css_set_width'] + + $currblk['border_left']['w'] + $currblk['padding_left'] + $currblk['border_right']['w'] + + $currblk['padding_right'] + $currblk['margin_left']); + if ($currblk['margin_right'] < 0) { + $currblk['margin_right'] = 0; + } + } // *OTL* + } + } + + $currblk['outer_left_margin'] = $prevblk['outer_left_margin'] + $currblk['margin_left'] + + $prevblk['border_left']['w'] + $prevblk['padding_left']; + + $currblk['outer_right_margin'] = $prevblk['outer_right_margin'] + $currblk['margin_right'] + + $prevblk['border_right']['w'] + $prevblk['padding_right']; + + $currblk['width'] = $this->mpdf->pgwidth - ($currblk['outer_right_margin'] + $currblk['outer_left_margin']); + + $currblk['inner_width'] = $currblk['width'] + - ($currblk['border_left']['w'] + $currblk['padding_left'] + $currblk['border_right']['w'] + $currblk['padding_right']); + + // Check DIV is not now too narrow to fit text + $mw = 2 * $this->mpdf->GetCharWidth('W', false); + if ($currblk['inner_width'] < $mw) { + $currblk['padding_left'] = 0; + $currblk['padding_right'] = 0; + $currblk['border_left']['w'] = 0.2; + $currblk['border_right']['w'] = 0.2; + $currblk['margin_left'] = 0; + $currblk['margin_right'] = 0; + $currblk['outer_left_margin'] = $prevblk['outer_left_margin'] + $currblk['margin_left'] + + $prevblk['border_left']['w'] + $prevblk['padding_left']; + $currblk['outer_right_margin'] = $prevblk['outer_right_margin'] + $currblk['margin_right'] + + $prevblk['border_right']['w'] + $prevblk['padding_right']; + $currblk['width'] = $this->mpdf->pgwidth - ($currblk['outer_right_margin'] + $currblk['outer_left_margin']); + $currblk['inner_width'] = $this->mpdf->pgwidth - ($currblk['outer_right_margin'] + + $currblk['outer_left_margin'] + $currblk['border_left']['w'] + $currblk['padding_left'] + + $currblk['border_right']['w'] + $currblk['padding_right']); + // if ($currblk['inner_width'] < $mw) { throw new \Mpdf\MpdfException("DIV is too narrow for text to fit!"); } + } + + $this->mpdf->x = $this->mpdf->lMargin + $currblk['outer_left_margin']; + + /* -- BACKGROUNDS -- */ + if (!empty($properties['BACKGROUND-IMAGE']) && !$this->mpdf->kwt && !$this->mpdf->ColActive && !$this->mpdf->keep_block_together) { + $ret = $this->mpdf->SetBackground($properties, $currblk['inner_width']); + if ($ret) { + $currblk['background-image'] = $ret; + } + } + /* -- END BACKGROUNDS -- */ + + /* -- TABLES -- */ + if ($this->mpdf->use_kwt && isset($attr['KEEP-WITH-TABLE']) && !$this->mpdf->ColActive && !$this->mpdf->keep_block_together) { + $this->mpdf->kwt = true; + $this->mpdf->kwt_y0 = $this->mpdf->y; + //$this->mpdf->kwt_x0 = $this->mpdf->x; + $this->mpdf->kwt_x0 = $this->mpdf->lMargin; // mPDF 6 + $this->mpdf->kwt_height = 0; + $this->mpdf->kwt_buffer = []; + $this->mpdf->kwt_Links = []; + $this->mpdf->kwt_Annots = []; + $this->mpdf->kwt_moved = false; + $this->mpdf->kwt_saved = false; + $this->mpdf->kwt_Reference = []; + $this->mpdf->kwt_BMoutlines = []; + $this->mpdf->kwt_toc = []; + } else { + /* -- END TABLES -- */ + $this->mpdf->kwt = false; + } // *TABLES* + + // Save x,y coords in case we need to print borders... + $currblk['y0'] = $this->mpdf->y; + $currblk['initial_y0'] = $this->mpdf->y; // mPDF 6 + $currblk['x0'] = $this->mpdf->x; + $currblk['initial_x0'] = $this->mpdf->x; // mPDF 6 + $currblk['initial_startpage'] = $this->mpdf->page; + $currblk['startpage'] = $this->mpdf->page; // mPDF 6 + $this->mpdf->oldy = $this->mpdf->y; + + $this->mpdf->lastblocklevelchange = 1; + + // mPDF 6 Lists + if ($tag === 'OL' || $tag === 'UL') { + $this->mpdf->listlvl++; + if (!empty($attr['START'])) { + $this->mpdf->listcounter[$this->mpdf->listlvl] = (int) $attr['START'] - 1; + } else { + $this->mpdf->listcounter[$this->mpdf->listlvl] = 0; + } + $this->mpdf->listitem = []; + + // List-type + if (empty($currblk['list_style_type'])) { + if ($tag === 'OL') { + $currblk['list_style_type'] = 'decimal'; + } elseif ($tag === 'UL') { + if ($this->mpdf->listlvl % 3 == 1) { + $currblk['list_style_type'] = 'disc'; + } elseif ($this->mpdf->listlvl % 3 == 2) { + $currblk['list_style_type'] = 'circle'; + } else { + $currblk['list_style_type'] = 'square'; + } + } + } + + // List-image + if (empty($currblk['list_style_image'])) { + $currblk['list_style_image'] = 'none'; + } + + // List-position + if (empty($currblk['list_style_position'])) { + $currblk['list_style_position'] = 'outside'; + } + + // Default indentation using padding + if (strtolower($this->mpdf->list_auto_mode) === 'mpdf' && isset($currblk['list_style_position']) + && $currblk['list_style_position'] === 'outside' && isset($currblk['list_style_image']) + && $currblk['list_style_image'] === 'none' && (!isset($currblk['list_style_type']) + || !preg_match('/U\+([a-fA-F0-9]+)/i', $currblk['list_style_type']))) { + $autopadding = $this->mpdf->_getListMarkerWidth($currblk, $ahtml, $ihtml); + if ($this->mpdf->listlvl > 1 || $this->mpdf->list_indent_first_level) { + $autopadding += $this->sizeConverter->convert( + $this->mpdf->list_indent_default, + $currblk['inner_width'], + $this->mpdf->FontSize, + false + ); + } + // autopadding value is applied to left or right according + // to dir of block. Once a CSS value is set for padding it overrides this default value. + if (isset($properties['PADDING-RIGHT']) && $properties['PADDING-RIGHT'] === 'auto' + && isset($currblk['direction']) && $currblk['direction'] === 'rtl') { + $currblk['padding_right'] = $autopadding; + } elseif (isset($properties['PADDING-LEFT']) && $properties['PADDING-LEFT'] === 'auto') { + $currblk['padding_left'] = $autopadding; + } + } else { + // Initial default value is set by $this->mpdf->list_indent_default in config.php; this value is applied to left or right according + // to dir of block. Once a CSS value is set for padding it overrides this default value. + if (isset($properties['PADDING-RIGHT']) && $properties['PADDING-RIGHT'] === 'auto' + && isset($currblk['direction']) && $currblk['direction'] === 'rtl') { + $currblk['padding_right'] = $this->sizeConverter->convert( + $this->mpdf->list_indent_default, + $currblk['inner_width'], + $this->mpdf->FontSize, + false + ); + } elseif (isset($properties['PADDING-LEFT']) && $properties['PADDING-LEFT'] === 'auto') { + $currblk['padding_left'] = $this->sizeConverter->convert( + $this->mpdf->list_indent_default, + $currblk['inner_width'], + $this->mpdf->FontSize, + false + ); + } + } + } + + // mPDF 6 Lists + if ($tag === 'LI') { + if ($this->mpdf->listlvl == 0) { // in case of malformed HTML code. Example:(...)</p><li>Content</li><p>Paragraph1</p>(...) + $this->mpdf->listlvl++; // first depth level + $this->mpdf->listcounter[$this->mpdf->listlvl] = 0; + } + + if (!isset($attr['PAGEBREAKAVOIDCHECKED']) || !$attr['PAGEBREAKAVOIDCHECKED']) { + $this->mpdf->listcounter[$this->mpdf->listlvl]++; + } + + $this->mpdf->listitem = []; + + // Listitem-type + $this->mpdf->_setListMarker($currblk['list_style_type'], $currblk['list_style_image'], $currblk['list_style_position']); + } + + // mPDF 6 Bidirectional formatting for block elements + $bdf = false; + $bdf2 = ''; + $popd = ''; + + // Get current direction + $currdir = 'ltr'; + if (isset($currblk['direction'])) { + $currdir = $currblk['direction']; + } + if (isset($attr['DIR']) && $attr['DIR'] != '') { + $currdir = strtolower($attr['DIR']); + } + if (isset($properties['DIRECTION'])) { + $currdir = strtolower($properties['DIRECTION']); + } + + // mPDF 6 bidi + // cf. http://www.w3.org/TR/css3-writing-modes/#unicode-bidi + if (isset($properties ['UNICODE-BIDI']) + && (strtolower($properties ['UNICODE-BIDI']) === 'bidi-override' || strtolower($properties ['UNICODE-BIDI']) === 'isolate-override')) { + if ($currdir === 'rtl') { + $bdf = 0x202E; + $popd = 'RLOPDF'; + } // U+202E RLO + else { + $bdf = 0x202D; + $popd = 'LROPDF'; + } // U+202D LRO + } elseif (isset($properties ['UNICODE-BIDI']) && strtolower($properties ['UNICODE-BIDI']) === 'plaintext') { + $bdf = 0x2068; + $popd = 'FSIPDI'; // U+2068 FSI + } + if ($bdf) { + if ($bdf2) { + $bdf2 = UtfString::code2utf($bdf); + } + $this->mpdf->OTLdata = []; + if ($this->mpdf->tableLevel) { + $this->mpdf->_saveCellTextBuffer(UtfString::code2utf($bdf) . $bdf2); + } else { + $this->mpdf->_saveTextBuffer(UtfString::code2utf($bdf) . $bdf2); + } + $this->mpdf->biDirectional = true; + $currblk['bidicode'] = $popd; + } + } + + public function close(&$ahtml, &$ihtml) + { + $tag = $this->getTagName(); + + // mPDF 6 bidi + // Block + // If unicode-bidi set, any embedding levels, isolates, or overrides started by this box are closed + if (isset($this->mpdf->blk[$this->mpdf->blklvl]['bidicode'])) { + $blockpost = $this->mpdf->_setBidiCodes('end', $this->mpdf->blk[$this->mpdf->blklvl]['bidicode']); + if ($blockpost) { + $this->mpdf->OTLdata = []; + if ($this->mpdf->tableLevel) { + $this->mpdf->_saveCellTextBuffer($blockpost); + } else { + $this->mpdf->_saveTextBuffer($blockpost); + } + } + } + + $this->mpdf->ignorefollowingspaces = true; //Eliminate exceeding left-side spaces + $this->mpdf->blockjustfinished = true; + + $this->mpdf->lastblockbottommargin = $this->mpdf->blk[$this->mpdf->blklvl]['margin_bottom']; + // mPDF 6 Lists + if ($tag === 'UL' || $tag === 'OL') { + if ($this->mpdf->listlvl > 0 && $this->mpdf->tableLevel) { + if (isset($this->mpdf->listtype[$this->mpdf->listlvl])) { + unset($this->mpdf->listtype[$this->mpdf->listlvl]); + } + } + $this->mpdf->listlvl--; + $this->mpdf->listitem = []; + } + if ($tag === 'LI') { + $this->mpdf->listitem = []; + } + + if (preg_match('/^H\d/', $tag) && !$this->mpdf->tableLevel && !$this->mpdf->writingToC) { + if (isset($this->mpdf->h2toc[$tag]) || isset($this->mpdf->h2bookmarks[$tag])) { + $content = ''; + if (count($this->mpdf->textbuffer) == 1) { + $content = $this->mpdf->textbuffer[0][0]; + } else { + for ($i = 0; $i < count($this->mpdf->textbuffer); $i++) { + if (0 !== strpos($this->mpdf->textbuffer[$i][0], "\xbb\xa4\xac")) { //inline object + $content .= $this->mpdf->textbuffer[$i][0]; + } + } + } + /* -- TOC -- */ + if (isset($this->mpdf->h2toc[$tag])) { + $objattr = []; + $objattr['type'] = 'toc'; + $objattr['toclevel'] = $this->mpdf->h2toc[$tag]; + $objattr['CONTENT'] = htmlspecialchars($content); + $e = "\xbb\xa4\xactype=toc,objattr=" . serialize($objattr) . "\xbb\xa4\xac"; + array_unshift($this->mpdf->textbuffer, [$e]); + } + /* -- END TOC -- */ + /* -- BOOKMARKS -- */ + if (isset($this->mpdf->h2bookmarks[$tag])) { + $objattr = []; + $objattr['type'] = 'bookmark'; + $objattr['bklevel'] = $this->mpdf->h2bookmarks[$tag]; + $objattr['CONTENT'] = $content; + $e = "\xbb\xa4\xactype=toc,objattr=" . serialize($objattr) . "\xbb\xa4\xac"; + array_unshift($this->mpdf->textbuffer, [$e]); + } + /* -- END BOOKMARKS -- */ + } + } + + /* -- TABLES -- */ + if ($this->mpdf->tableLevel) { + if ($this->mpdf->linebreakjustfinished) { + $this->mpdf->blockjustfinished = false; + } + if (isset($this->mpdf->InlineProperties['BLOCKINTABLE'])) { + if ($this->mpdf->InlineProperties['BLOCKINTABLE']) { + $this->mpdf->restoreInlineProperties($this->mpdf->InlineProperties['BLOCKINTABLE']); + } + unset($this->mpdf->InlineProperties['BLOCKINTABLE']); + } + if ($tag === 'PRE') { + $this->mpdf->ispre = false; + } + return; + } + /* -- END TABLES -- */ + $this->mpdf->lastoptionaltag = ''; + $this->mpdf->divbegin = false; + + $this->mpdf->linebreakjustfinished = false; + + $this->mpdf->x = $this->mpdf->lMargin + $this->mpdf->blk[$this->mpdf->blklvl]['outer_left_margin']; + + /* -- CSS-FLOAT -- */ + // If float contained in a float, need to extend bottom to allow for it + $currpos = $this->mpdf->page * 1000 + $this->mpdf->y; + if (isset($this->mpdf->blk[$this->mpdf->blklvl]['float_endpos']) && $this->mpdf->blk[$this->mpdf->blklvl]['float_endpos'] > $currpos) { + $old_page = $this->mpdf->page; + $new_page = (int) ($this->mpdf->blk[$this->mpdf->blklvl]['float_endpos'] / 1000); + if ($old_page != $new_page) { + $s = $this->mpdf->PrintPageBackgrounds(); + // Writes after the marker so not overwritten later by page background etc. + $this->mpdf->pages[$this->mpdf->page] = preg_replace( + '/(___BACKGROUND___PATTERNS' . $this->mpdf->uniqstr . ')/', + '\\1' . "\n" . $s . "\n", + $this->mpdf->pages[$this->mpdf->page] + ); + $this->mpdf->pageBackgrounds = []; + $this->mpdf->page = $new_page; + $this->mpdf->ResetMargins(); + $this->mpdf->Reset(); + $this->mpdf->pageoutput[$this->mpdf->page] = []; + } + // mod changes operands to integers before processing + $this->mpdf->y = (($this->mpdf->blk[$this->mpdf->blklvl]['float_endpos'] * 1000) % 1000000) / 1000; + } + /* -- END CSS-FLOAT -- */ + + + //Print content + $blockstate = 0; + if ($this->mpdf->lastblocklevelchange == 1) { + $blockstate = 3; + } // Top & bottom margins/padding + elseif ($this->mpdf->lastblocklevelchange == -1) { + $blockstate = 2; + } // Bottom margins/padding only + + // called from after e.g. </table> </div> </div> ... Outputs block margin/border and padding + if (count($this->mpdf->textbuffer) && $this->mpdf->textbuffer[count($this->mpdf->textbuffer) - 1]) { + if (0 !== strpos($this->mpdf->textbuffer[count($this->mpdf->textbuffer) - 1][0], "\xbb\xa4\xac")) { // not special content + // Right trim last content and adjust OTLdata + if (preg_match('/[ ]+$/', $this->mpdf->textbuffer[count($this->mpdf->textbuffer) - 1][0], $m)) { + $strip = strlen($m[0]); + $this->mpdf->textbuffer[count($this->mpdf->textbuffer) - 1][0] = substr( + $this->mpdf->textbuffer[count($this->mpdf->textbuffer) - 1][0], + 0, + strlen($this->mpdf->textbuffer[count($this->mpdf->textbuffer) - 1][0]) - $strip + ); + /* -- OTL -- */ + if (!empty($this->mpdf->CurrentFont['useOTL'])) { + $this->otl->trimOTLdata($this->mpdf->textbuffer[count($this->mpdf->textbuffer) - 1][18], false); // mPDF 6 ZZZ99K + } + /* -- END OTL -- */ + } + } + } + + if (count($this->mpdf->textbuffer) == 0 && $this->mpdf->lastblocklevelchange != 0) { + /*$this->mpdf->newFlowingBlock( + $this->mpdf->blk[$this->mpdf->blklvl]['width'], + $this->mpdf->lineheight, + '', + false, + 2, + true, + (isset($this->mpdf->blk[$this->mpdf->blklvl]['direction']) ? $this->mpdf->blk[$this->mpdf->blklvl]['direction'] : 'ltr') + );*/ + + $this->mpdf->newFlowingBlock( + $this->mpdf->blk[$this->mpdf->blklvl]['width'], + $this->mpdf->lineheight, + '', + false, + $blockstate, + true, + (isset($this->mpdf->blk[$this->mpdf->blklvl]['direction']) ? $this->mpdf->blk[$this->mpdf->blklvl]['direction'] : 'ltr') + ); + + $this->mpdf->finishFlowingBlock(true); // true = END of flowing block + $this->mpdf->PaintDivBB('', $blockstate); + } else { + $this->mpdf->printbuffer($this->mpdf->textbuffer, $blockstate); + } + + + $this->mpdf->textbuffer = []; + + if ($this->mpdf->kwt) { + $this->mpdf->kwt_height = $this->mpdf->y - $this->mpdf->kwt_y0; + } + + /* -- CSS-IMAGE-FLOAT -- */ + $this->mpdf->printfloatbuffer(); + /* -- END CSS-IMAGE-FLOAT -- */ + + if ($tag === 'PRE') { + $this->mpdf->ispre = false; + } + + /* -- CSS-FLOAT -- */ + if ($this->mpdf->blk[$this->mpdf->blklvl]['float'] === 'R') { + // If width not set, here would need to adjust and output buffer + $s = $this->mpdf->PrintPageBackgrounds(); + // Writes after the marker so not overwritten later by page background etc. + $this->mpdf->pages[$this->mpdf->page] = preg_replace('/(___BACKGROUND___PATTERNS' . $this->mpdf->uniqstr . ')/', '\\1' . "\n" . $s . "\n", $this->mpdf->pages[$this->mpdf->page]); + $this->mpdf->pageBackgrounds = []; + $this->mpdf->Reset(); + $this->mpdf->pageoutput[$this->mpdf->page] = []; + + for ($i = ($this->mpdf->blklvl - 1); $i >= 0; $i--) { + if (isset($this->mpdf->blk[$i]['float_endpos'])) { + $this->mpdf->blk[$i]['float_endpos'] = max($this->mpdf->blk[$i]['float_endpos'], $this->mpdf->page * 1000 + $this->mpdf->y); + } else { + $this->mpdf->blk[$i]['float_endpos'] = $this->mpdf->page * 1000 + $this->mpdf->y; + } + } + + $this->mpdf->floatDivs[] = [ + 'side' => 'R', + 'startpage' => $this->mpdf->blk[$this->mpdf->blklvl]['startpage'], + 'y0' => $this->mpdf->blk[$this->mpdf->blklvl]['float_start_y'], + 'startpos' => $this->mpdf->blk[$this->mpdf->blklvl]['startpage'] * 1000 + $this->mpdf->blk[$this->mpdf->blklvl]['float_start_y'], + 'endpage' => $this->mpdf->page, + 'y1' => $this->mpdf->y, + 'endpos' => $this->mpdf->page * 1000 + $this->mpdf->y, + 'w' => $this->mpdf->blk[$this->mpdf->blklvl]['float_width'], + 'blklvl' => $this->mpdf->blklvl, + 'blockContext' => $this->mpdf->blk[$this->mpdf->blklvl - 1]['blockContext'] + ]; + + $this->mpdf->y = $this->mpdf->blk[$this->mpdf->blklvl]['float_start_y']; + $this->mpdf->page = $this->mpdf->blk[$this->mpdf->blklvl]['startpage']; + $this->mpdf->ResetMargins(); + $this->mpdf->pageoutput[$this->mpdf->page] = []; + } + if ($this->mpdf->blk[$this->mpdf->blklvl]['float'] === 'L') { + // If width not set, here would need to adjust and output buffer + $s = $this->mpdf->PrintPageBackgrounds(); + // Writes after the marker so not overwritten later by page background etc. + $this->mpdf->pages[$this->mpdf->page] = preg_replace('/(___BACKGROUND___PATTERNS' . $this->mpdf->uniqstr . ')/', '\\1' . "\n" . $s . "\n", $this->mpdf->pages[$this->mpdf->page]); + $this->mpdf->pageBackgrounds = []; + $this->mpdf->Reset(); + $this->mpdf->pageoutput[$this->mpdf->page] = []; + + for ($i = ($this->mpdf->blklvl - 1); $i >= 0; $i--) { + if (isset($this->mpdf->blk[$i]['float_endpos'])) { + $this->mpdf->blk[$i]['float_endpos'] = max($this->mpdf->blk[$i]['float_endpos'], $this->mpdf->page * 1000 + $this->mpdf->y); + } else { + $this->mpdf->blk[$i]['float_endpos'] = $this->mpdf->page * 1000 + $this->mpdf->y; + } + } + + $this->mpdf->floatDivs[] = [ + 'side' => 'L', + 'startpage' => $this->mpdf->blk[$this->mpdf->blklvl]['startpage'], + 'y0' => $this->mpdf->blk[$this->mpdf->blklvl]['float_start_y'], + 'startpos' => $this->mpdf->blk[$this->mpdf->blklvl]['startpage'] * 1000 + $this->mpdf->blk[$this->mpdf->blklvl]['float_start_y'], + 'endpage' => $this->mpdf->page, + 'y1' => $this->mpdf->y, + 'endpos' => $this->mpdf->page * 1000 + $this->mpdf->y, + 'w' => $this->mpdf->blk[$this->mpdf->blklvl]['float_width'], + 'blklvl' => $this->mpdf->blklvl, + 'blockContext' => $this->mpdf->blk[$this->mpdf->blklvl - 1]['blockContext'] + ]; + + $this->mpdf->y = $this->mpdf->blk[$this->mpdf->blklvl]['float_start_y']; + $this->mpdf->page = $this->mpdf->blk[$this->mpdf->blklvl]['startpage']; + $this->mpdf->ResetMargins(); + $this->mpdf->pageoutput[$this->mpdf->page] = []; + } + /* -- END CSS-FLOAT -- */ + + if (isset($this->mpdf->blk[$this->mpdf->blklvl]['visibility']) && $this->mpdf->blk[$this->mpdf->blklvl]['visibility'] !== 'visible') { + $this->mpdf->SetVisibility('visible'); + } + + $page_break_after = ''; + if (isset($this->mpdf->blk[$this->mpdf->blklvl]['page_break_after'])) { + $page_break_after = $this->mpdf->blk[$this->mpdf->blklvl]['page_break_after']; + } + + // Reset values + $this->mpdf->Reset(); + + if (isset($this->mpdf->blk[$this->mpdf->blklvl]['z-index']) && $this->mpdf->blk[$this->mpdf->blklvl]['z-index'] > 0) { + $this->mpdf->EndLayer(); + } + + // mPDF 6 page-break-inside:avoid + if ($this->mpdf->blk[$this->mpdf->blklvl]['keep_block_together']) { + $movepage = false; + // If page-break-inside:avoid section has broken to new page but fits on one side - then move: + if (($this->mpdf->page - $this->mpdf->kt_p00) == 1 && $this->mpdf->y < $this->mpdf->kt_y00) { + $movepage = true; + } + if (($this->mpdf->page - $this->mpdf->kt_p00) > 0) { + for ($i = $this->mpdf->page; $i > $this->mpdf->kt_p00; $i--) { + unset($this->mpdf->pages[$i]); + if (isset($this->mpdf->blk[$this->mpdf->blklvl]['bb_painted'][$i])) { + unset($this->mpdf->blk[$this->mpdf->blklvl]['bb_painted'][$i]); + } + if (isset($this->mpdf->blk[$this->mpdf->blklvl]['marginCorrected'][$i])) { + unset($this->mpdf->blk[$this->mpdf->blklvl]['marginCorrected'][$i]); + } + if (isset($this->mpdf->pageoutput[$i])) { + unset($this->mpdf->pageoutput[$i]); + } + } + $this->mpdf->page = $this->mpdf->kt_p00; + } + $this->mpdf->keep_block_together = 0; + $this->mpdf->pageoutput[$this->mpdf->page] = []; + + $this->mpdf->y = $this->mpdf->kt_y00; + + $ihtml = $this->mpdf->blk[$this->mpdf->blklvl]['array_i'] - 1; + + $ahtml[$ihtml + 1] .= ' pagebreakavoidchecked="true";'; // avoid re-iterating; read in OpenTag() + + unset($this->mpdf->blk[$this->mpdf->blklvl]); + $this->mpdf->blklvl--; + + for ($blklvl = 1; $blklvl <= $this->mpdf->blklvl; $blklvl++) { + $this->mpdf->blk[$blklvl]['y0'] = $this->mpdf->blk[$blklvl]['initial_y0']; + $this->mpdf->blk[$blklvl]['x0'] = $this->mpdf->blk[$blklvl]['initial_x0']; + $this->mpdf->blk[$blklvl]['startpage'] = $this->mpdf->blk[$blklvl]['initial_startpage']; + } + + if (isset($this->mpdf->blk[$this->mpdf->blklvl]['x0'])) { + $this->mpdf->x = $this->mpdf->blk[$this->mpdf->blklvl]['x0']; + } else { + $this->mpdf->x = $this->mpdf->lMargin; + } + + $this->mpdf->lastblocklevelchange = 0; + $this->mpdf->ResetMargins(); + if ($movepage) { + $this->mpdf->AddPage(); + } + return; + } + + if ($this->mpdf->blklvl > 0) { // ==0 SHOULDN'T HAPPEN - NOT XHTML + if ($this->mpdf->blk[$this->mpdf->blklvl]['tag'] == $tag) { + unset($this->mpdf->blk[$this->mpdf->blklvl]); + $this->mpdf->blklvl--; + } + //else { echo $tag; exit; } // debug - forces error if incorrectly nested html tags + } + + $this->mpdf->lastblocklevelchange = -1; + // Reset Inline-type properties + if (isset($this->mpdf->blk[$this->mpdf->blklvl]['InlineProperties'])) { + $this->mpdf->restoreInlineProperties($this->mpdf->blk[$this->mpdf->blklvl]['InlineProperties']); + } + + $this->mpdf->x = $this->mpdf->lMargin + $this->mpdf->blk[$this->mpdf->blklvl]['outer_left_margin']; + + if (!$this->mpdf->tableLevel && $page_break_after) { + $save_blklvl = $this->mpdf->blklvl; + $save_blk = $this->mpdf->blk; + $save_silp = $this->mpdf->saveInlineProperties(); + $save_ilp = $this->mpdf->InlineProperties; + $save_bflp = $this->mpdf->InlineBDF; + $save_bflpc = $this->mpdf->InlineBDFctr; // mPDF 6 + // mPDF 6 pagebreaktype + $startpage = $this->mpdf->page; + $pagebreaktype = $this->mpdf->defaultPagebreakType; + if ($this->mpdf->ColActive) { + $pagebreaktype = 'cloneall'; + } + + // mPDF 6 pagebreaktype + $this->mpdf->_preForcedPagebreak($pagebreaktype); + + if ($page_break_after === 'RIGHT') { + $this->mpdf->AddPage($this->mpdf->CurOrientation, 'NEXT-ODD'); + } elseif ($page_break_after === 'LEFT') { + $this->mpdf->AddPage($this->mpdf->CurOrientation, 'NEXT-EVEN'); + } else { + $this->mpdf->AddPage($this->mpdf->CurOrientation); + } + + // mPDF 6 pagebreaktype + $this->mpdf->_postForcedPagebreak($pagebreaktype, $startpage, $save_blk, $save_blklvl); + + $this->mpdf->InlineProperties = $save_ilp; + $this->mpdf->InlineBDF = $save_bflp; + $this->mpdf->InlineBDFctr = $save_bflpc; // mPDF 6 + $this->mpdf->restoreInlineProperties($save_silp); + } + // mPDF 6 bidi + // Block + // If unicode-bidi set, any embedding levels, isolates, or overrides reopened in the continuing block + if (isset($this->mpdf->blk[$this->mpdf->blklvl]['bidicode'])) { + $blockpre = $this->mpdf->_setBidiCodes('start', $this->mpdf->blk[$this->mpdf->blklvl]['bidicode']); + if ($blockpre) { + $this->mpdf->OTLdata = []; + if ($this->mpdf->tableLevel) { + $this->mpdf->_saveCellTextBuffer($blockpre); + } else { + $this->mpdf->_saveTextBuffer($blockpre); + } + } + } + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Bookmark.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Bookmark.php new file mode 100644 index 000000000..b414cf4ca --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Bookmark.php @@ -0,0 +1,32 @@ +<?php + +namespace Mpdf\Tag; + +class Bookmark extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + if (isset($attr['CONTENT'])) { + $objattr = []; + $objattr['CONTENT'] = htmlspecialchars_decode($attr['CONTENT'], ENT_QUOTES); + $objattr['type'] = 'bookmark'; + if (!empty($attr['LEVEL'])) { + $objattr['bklevel'] = $attr['LEVEL']; + } else { + $objattr['bklevel'] = 0; + } + $e = "\xbb\xa4\xactype=bookmark,objattr=" . serialize($objattr) . "\xbb\xa4\xac"; + if ($this->mpdf->tableLevel) { + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['textbuffer'][] = [$e]; + } // *TABLES* + else { // *TABLES* + $this->mpdf->textbuffer[] = [$e]; + } // *TABLES* + } + } + + public function close(&$ahtml, &$ihtml) + { + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Br.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Br.php new file mode 100644 index 000000000..125a18a7b --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Br.php @@ -0,0 +1,88 @@ +<?php + +namespace Mpdf\Tag; + +class Br extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + // Added mPDF 3.0 Float DIV - CLEAR + if (isset($attr['STYLE'])) { + $properties = $this->cssManager->readInlineCSS($attr['STYLE']); + if (isset($properties['CLEAR'])) { + $this->mpdf->ClearFloats(strtoupper($properties['CLEAR']), $this->mpdf->blklvl); + } // *CSS-FLOAT* + } + + // mPDF 6 bidi + // Inline + // If unicode-bidi set, any embedding levels, isolates, or overrides started by + // the inline box are closed at the br and reopened on the other side + $blockpre = ''; + $blockpost = ''; + if (isset($this->mpdf->blk[$this->mpdf->blklvl]['bidicode'])) { + $blockpre = $this->mpdf->_setBidiCodes('end', $this->mpdf->blk[$this->mpdf->blklvl]['bidicode']); + $blockpost = $this->mpdf->_setBidiCodes('start', $this->mpdf->blk[$this->mpdf->blklvl]['bidicode']); + } + + // Inline + // If unicode-bidi set, any embedding levels, isolates, or overrides started by + // the inline box are closed at the br and reopened on the other side + $inlinepre = ''; + $inlinepost = ''; + $iBDF = []; + if (count($this->mpdf->InlineBDF)) { + foreach ($this->mpdf->InlineBDF as $k => $ib) { + foreach ($ib as $ib2) { + $iBDF[$ib2[1]] = $ib2[0]; + } + } + if (count($iBDF)) { + ksort($iBDF); + for ($i = count($iBDF) - 1; $i >= 0; $i--) { + $inlinepre .= $this->mpdf->_setBidiCodes('end', $iBDF[$i]); + } + for ($i = 0; $i < count($iBDF); $i++) { + $inlinepost .= $this->mpdf->_setBidiCodes('start', $iBDF[$i]); + } + } + } + + /* -- TABLES -- */ + if ($this->mpdf->tableLevel) { + if ($this->mpdf->blockjustfinished) { + $this->mpdf->_saveCellTextBuffer($blockpre . $inlinepre . "\n" . $inlinepost . $blockpost); + } + + $this->mpdf->_saveCellTextBuffer($blockpre . $inlinepre . "\n" . $inlinepost . $blockpost); + if (!isset($this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['maxs'])) { + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['maxs'] = $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s']; + } elseif ($this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['maxs'] < $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s']) { + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['maxs'] = $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s']; + } + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s'] = 0; // reset + } else { + /* -- END TABLES -- */ + if (count($this->mpdf->textbuffer)) { + $this->mpdf->textbuffer[count($this->mpdf->textbuffer) - 1][0] = preg_replace( + '/ $/', + '', + $this->mpdf->textbuffer[count($this->mpdf->textbuffer) - 1][0] + ); + if (!empty($this->mpdf->textbuffer[count($this->mpdf->textbuffer) - 1][18])) { + $this->otl->trimOTLdata($this->mpdf->textbuffer[count($this->mpdf->textbuffer) - 1][18], false); + } // *OTL* + } + $this->mpdf->_saveTextBuffer($blockpre . $inlinepre . "\n" . $inlinepost . $blockpost); + } // *TABLES* + $this->mpdf->ignorefollowingspaces = true; + $this->mpdf->blockjustfinished = false; + + $this->mpdf->linebreakjustfinished = true; + } + + public function close(&$ahtml, &$ihtml) + { + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Caption.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Caption.php new file mode 100644 index 000000000..ffcb99aaf --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Caption.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Caption extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Center.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Center.php new file mode 100644 index 000000000..36fbe774c --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Center.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Center extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Cite.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Cite.php new file mode 100644 index 000000000..869cfc4d0 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Cite.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Cite extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Code.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Code.php new file mode 100644 index 000000000..47776e7fa --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Code.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Code extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/ColumnBreak.php b/src/bb-vendor/mpdf/mpdf/src/Tag/ColumnBreak.php new file mode 100644 index 000000000..5b2ff05e3 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/ColumnBreak.php @@ -0,0 +1,8 @@ +<?php + +namespace Mpdf\Tag; + +class ColumnBreak extends NewColumn +{ + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Columns.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Columns.php new file mode 100644 index 000000000..0e6bed409 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Columns.php @@ -0,0 +1,67 @@ +<?php + +namespace Mpdf\Tag; + +class Columns extends Tag +{ + /** + * @param string $tag + * @return \Mpdf\Tag\Tag + */ + private function getTagInstance($tag) + { + $className = \Mpdf\Tag::getTagClassName($tag); + if (class_exists($className)) { + return new $className( + $this->mpdf, + $this->cache, + $this->cssManager, + $this->form, + $this->otl, + $this->tableOfContents, + $this->sizeConverter, + $this->colorConverter, + $this->imageProcessor, + $this->languageToFont + ); + } + + return null; + } + + public function open($attr, &$ahtml, &$ihtml) + { + if (isset($attr['COLUMN-COUNT']) && ($attr['COLUMN-COUNT'] || $attr['COLUMN-COUNT'] === '0')) { + // Close any open block tags + for ($b = $this->mpdf->blklvl; $b > 0; $b--) { + if ($t = $this->getTagInstance($this->mpdf->blk[$b]['tag'])) { + $t->close($ahtml, $ihtml); + } + } + if (!empty($this->mpdf->textbuffer)) { //Output previously buffered content + $this->mpdf->printbuffer($this->mpdf->textbuffer); + $this->mpdf->textbuffer = []; + } + + if (!empty($attr['VALIGN'])) { + if ($attr['VALIGN'] === 'J') { + $valign = 'J'; + } else { + $valign = self::ALIGN[$attr['VALIGN']]; + } + } else { + $valign = ''; + } + if (!empty($attr['COLUMN-GAP'])) { + $this->mpdf->SetColumns($attr['COLUMN-COUNT'], $valign, $attr['COLUMN-GAP']); + } else { + $this->mpdf->SetColumns($attr['COLUMN-COUNT'], $valign); + } + } + $this->mpdf->ignorefollowingspaces = true; + } + + public function close(&$ahtml, &$ihtml) + { + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Dd.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Dd.php new file mode 100644 index 000000000..ce0ccfb77 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Dd.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Dd extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Del.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Del.php new file mode 100644 index 000000000..8af9cd0a4 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Del.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Del extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Details.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Details.php new file mode 100644 index 000000000..bd81da06a --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Details.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Details extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Div.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Div.php new file mode 100644 index 000000000..30fb2b709 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Div.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Div extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Dl.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Dl.php new file mode 100644 index 000000000..80bafc215 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Dl.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Dl extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/DotTab.php b/src/bb-vendor/mpdf/mpdf/src/Tag/DotTab.php new file mode 100644 index 000000000..278ce38b7 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/DotTab.php @@ -0,0 +1,68 @@ +<?php + +namespace Mpdf\Tag; + +class DotTab extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $objattr = []; + $objattr['type'] = 'dottab'; + $dots = str_repeat('.', 3) . ' '; // minimum number of dots + $objattr['width'] = $this->mpdf->GetStringWidth($dots); + $objattr['margin_top'] = 0; + $objattr['margin_bottom'] = 0; + $objattr['margin_left'] = 0; + $objattr['margin_right'] = 0; + $objattr['height'] = 0; + $objattr['colorarray'] = $this->mpdf->colorarray; + $objattr['border_top']['w'] = 0; + $objattr['border_bottom']['w'] = 0; + $objattr['border_left']['w'] = 0; + $objattr['border_right']['w'] = 0; + $objattr['vertical_align'] = 'BS'; // mPDF 6 DOTTAB + + $properties = $this->cssManager->MergeCSS('INLINE', 'DOTTAB', $attr); + if (isset($properties['OUTDENT'])) { + $objattr['outdent'] = $this->sizeConverter->convert( + $properties['OUTDENT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } elseif (isset($attr['OUTDENT'])) { + $objattr['outdent'] = $this->sizeConverter->convert( + $attr['OUTDENT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } else { + $objattr['outdent'] = 0; + } + + $objattr['fontfamily'] = $this->mpdf->FontFamily; + $objattr['fontsize'] = $this->mpdf->FontSizePt; + + $e = "\xbb\xa4\xactype=dottab,objattr=" . serialize($objattr) . "\xbb\xa4\xac"; + /* -- TABLES -- */ + // Output it to buffers + if ($this->mpdf->tableLevel) { + if (!isset($this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['maxs'])) { + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['maxs'] = $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s']; + } elseif ($this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['maxs'] < $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s']) { + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['maxs'] = $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s']; + } + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s'] = 0; // reset + $this->mpdf->_saveCellTextBuffer($e); + } else { + /* -- END TABLES -- */ + $this->mpdf->_saveTextBuffer($e); + } // *TABLES* + } + + public function close(&$ahtml, &$ihtml) + { + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Dt.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Dt.php new file mode 100644 index 000000000..22492fb35 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Dt.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Dt extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Em.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Em.php new file mode 100644 index 000000000..a353bd22e --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Em.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Em extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/FieldSet.php b/src/bb-vendor/mpdf/mpdf/src/Tag/FieldSet.php new file mode 100644 index 000000000..33356f168 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/FieldSet.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class FieldSet extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/FigCaption.php b/src/bb-vendor/mpdf/mpdf/src/Tag/FigCaption.php new file mode 100644 index 000000000..1e738a546 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/FigCaption.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class FigCaption extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Figure.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Figure.php new file mode 100644 index 000000000..1074a6370 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Figure.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Figure extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Font.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Font.php new file mode 100644 index 000000000..e29041466 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Font.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Font extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Footer.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Footer.php new file mode 100644 index 000000000..46abbc439 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Footer.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Footer extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Form.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Form.php new file mode 100644 index 000000000..588000efd --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Form.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Form extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/FormFeed.php b/src/bb-vendor/mpdf/mpdf/src/Tag/FormFeed.php new file mode 100644 index 000000000..6b2f46b17 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/FormFeed.php @@ -0,0 +1,293 @@ +<?php + +namespace Mpdf\Tag; + +class FormFeed extends Tag +{ + public $toc_id; + + public function open($attr, &$ahtml, &$ihtml) + { + $tag = $this->getTagName(); + if (isset($attr['SHEET-SIZE'])) { + // Convert to same types as accepted in initial mPDF() A4, A4-L, or array(w,h) + $prop = preg_split('/\s+/', trim($attr['SHEET-SIZE'])); + if (count($prop) == 2) { + $newformat = [$this->sizeConverter->convert($prop[0]), $this->sizeConverter->convert($prop[1])]; + } else { + $newformat = $attr['SHEET-SIZE']; + } + } else { + $newformat = ''; + } + + $save_blklvl = $this->mpdf->blklvl; + $save_blk = $this->mpdf->blk; + $save_silp = $this->mpdf->saveInlineProperties(); + $save_ilp = $this->mpdf->InlineProperties; + $save_bflp = $this->mpdf->InlineBDF; + $save_bflpc = $this->mpdf->InlineBDFctr; // mPDF 6 + + $mgr = $mgl = $mgt = $mgb = $mgh = $mgf = ''; + if (isset($attr['MARGIN-RIGHT'])) { + $mgr = $this->sizeConverter->convert($attr['MARGIN-RIGHT'], $this->mpdf->w, $this->mpdf->FontSize, false); + } + if (isset($attr['MARGIN-LEFT'])) { + $mgl = $this->sizeConverter->convert($attr['MARGIN-LEFT'], $this->mpdf->w, $this->mpdf->FontSize, false); + } + if (isset($attr['MARGIN-TOP'])) { + $mgt = $this->sizeConverter->convert($attr['MARGIN-TOP'], $this->mpdf->w, $this->mpdf->FontSize, false); + } + if (isset($attr['MARGIN-BOTTOM'])) { + $mgb = $this->sizeConverter->convert($attr['MARGIN-BOTTOM'], $this->mpdf->w, $this->mpdf->FontSize, false); + } + if (isset($attr['MARGIN-HEADER'])) { + $mgh = $this->sizeConverter->convert($attr['MARGIN-HEADER'], $this->mpdf->w, $this->mpdf->FontSize, false); + } + if (isset($attr['MARGIN-FOOTER'])) { + $mgf = $this->sizeConverter->convert($attr['MARGIN-FOOTER'], $this->mpdf->w, $this->mpdf->FontSize, false); + } + $ohname = $ehname = $ofname = $efname = ''; + if (isset($attr['ODD-HEADER-NAME'])) { + $ohname = $attr['ODD-HEADER-NAME']; + } + if (isset($attr['EVEN-HEADER-NAME'])) { + $ehname = $attr['EVEN-HEADER-NAME']; + } + if (isset($attr['ODD-FOOTER-NAME'])) { + $ofname = $attr['ODD-FOOTER-NAME']; + } + if (isset($attr['EVEN-FOOTER-NAME'])) { + $efname = $attr['EVEN-FOOTER-NAME']; + } + $ohvalue = $ehvalue = $ofvalue = $efvalue = 0; + if (isset($attr['ODD-HEADER-VALUE']) && ($attr['ODD-HEADER-VALUE'] == '1' || strtoupper($attr['ODD-HEADER-VALUE']) === 'ON')) { + $ohvalue = 1; + } elseif (isset($attr['ODD-HEADER-VALUE']) && ($attr['ODD-HEADER-VALUE'] == '-1' || strtoupper($attr['ODD-HEADER-VALUE']) === 'OFF')) { + $ohvalue = -1; + } + if (isset($attr['EVEN-HEADER-VALUE']) && ($attr['EVEN-HEADER-VALUE'] == '1' || strtoupper($attr['EVEN-HEADER-VALUE']) === 'ON')) { + $ehvalue = 1; + } elseif (isset($attr['EVEN-HEADER-VALUE']) && ($attr['EVEN-HEADER-VALUE'] == '-1' || strtoupper($attr['EVEN-HEADER-VALUE']) === 'OFF')) { + $ehvalue = -1; + } + if (isset($attr['ODD-FOOTER-VALUE']) && ($attr['ODD-FOOTER-VALUE'] == '1' || strtoupper($attr['ODD-FOOTER-VALUE']) === 'ON')) { + $ofvalue = 1; + } elseif (isset($attr['ODD-FOOTER-VALUE']) && ($attr['ODD-FOOTER-VALUE'] == '-1' || strtoupper($attr['ODD-FOOTER-VALUE']) === 'OFF')) { + $ofvalue = -1; + } + if (isset($attr['EVEN-FOOTER-VALUE']) && ($attr['EVEN-FOOTER-VALUE'] == '1' || strtoupper($attr['EVEN-FOOTER-VALUE']) === 'ON')) { + $efvalue = 1; + } elseif (isset($attr['EVEN-FOOTER-VALUE']) && ($attr['EVEN-FOOTER-VALUE'] == '-1' || strtoupper($attr['EVEN-FOOTER-VALUE']) === 'OFF')) { + $efvalue = -1; + } + + if (isset($attr['ORIENTATION']) && (strtoupper($attr['ORIENTATION']) === 'L' || strtoupper($attr['ORIENTATION']) === 'LANDSCAPE')) { + $orient = 'L'; + } elseif (isset($attr['ORIENTATION']) && (strtoupper($attr['ORIENTATION']) === 'P' || strtoupper($attr['ORIENTATION']) === 'PORTRAIT')) { + $orient = 'P'; + } else { + $orient = $this->mpdf->CurOrientation; + } + + $pagesel = ''; + if (!empty($attr['PAGE-SELECTOR'])) { + $pagesel = $attr['PAGE-SELECTOR']; + } + + // mPDF 6 pagebreaktype + $pagebreaktype = $this->mpdf->defaultPagebreakType; + if ($tag === 'FORMFEED') { + $pagebreaktype = 'slice'; + } // can be overridden by PAGE-BREAK-TYPE + $startpage = $this->mpdf->page; + if (isset($attr['PAGE-BREAK-TYPE'])) { + if (strtolower($attr['PAGE-BREAK-TYPE']) === 'cloneall' + || strtolower($attr['PAGE-BREAK-TYPE']) === 'clonebycss' + || strtolower($attr['PAGE-BREAK-TYPE']) === 'slice') { + $pagebreaktype = strtolower($attr['PAGE-BREAK-TYPE']); + } + } + if ($tag === 'TOCPAGEBREAK') { + $pagebreaktype = 'cloneall'; + } elseif ($this->mpdf->ColActive) { + $pagebreaktype = 'cloneall'; + } // Any change in headers/footers (may need to _getHtmlHeight), or page size/orientation, @page selector, or margins - force cloneall + elseif ($mgr !== '' || $mgl !== '' || $mgt !== '' || $mgb !== '' || $mgh !== '' || $mgf !== '' || + $ohname !== '' || $ehname !== '' || $ofname !== '' || $efname !== '' || + $ohvalue || $ehvalue || $ofvalue || $efvalue || + $orient != $this->mpdf->CurOrientation || $newformat || $pagesel) { + $pagebreaktype = 'cloneall'; + } + + // mPDF 6 pagebreaktype + $this->mpdf->_preForcedPagebreak($pagebreaktype); + + $this->mpdf->ignorefollowingspaces = true; + + + $resetpagenum = ''; + $pagenumstyle = ''; + $suppress = ''; + if (isset($attr['RESETPAGENUM'])) { + $resetpagenum = $attr['RESETPAGENUM']; + } + if (isset($attr['PAGENUMSTYLE'])) { + $pagenumstyle = $attr['PAGENUMSTYLE']; + } + if (isset($attr['SUPPRESS'])) { + $suppress = $attr['SUPPRESS']; + } + + $type = ''; + if ($tag === 'TOCPAGEBREAK') { + $type = 'NEXT-ODD'; + } elseif (isset($attr['TYPE'])) { + $type = strtoupper($attr['TYPE']); + } + + if ($type === 'E' || $type === 'EVEN') { + $this->mpdf->AddPage( + $orient, + 'E', + $resetpagenum, + $pagenumstyle, + $suppress, + $mgl, + $mgr, + $mgt, + $mgb, + $mgh, + $mgf, + $ohname, + $ehname, + $ofname, + $efname, + $ohvalue, + $ehvalue, + $ofvalue, + $efvalue, + $pagesel, + $newformat + ); + } elseif ($type === 'O' || $type === 'ODD') { + $this->mpdf->AddPage( + $orient, + 'O', + $resetpagenum, + $pagenumstyle, + $suppress, + $mgl, + $mgr, + $mgt, + $mgb, + $mgh, + $mgf, + $ohname, + $ehname, + $ofname, + $efname, + $ohvalue, + $ehvalue, + $ofvalue, + $efvalue, + $pagesel, + $newformat + ); + } elseif ($type === 'NEXT-ODD') { + $this->mpdf->AddPage( + $orient, + 'NEXT-ODD', + $resetpagenum, + $pagenumstyle, + $suppress, + $mgl, + $mgr, + $mgt, + $mgb, + $mgh, + $mgf, + $ohname, + $ehname, + $ofname, + $efname, + $ohvalue, + $ehvalue, + $ofvalue, + $efvalue, + $pagesel, + $newformat + ); + } elseif ($type === 'NEXT-EVEN') { + $this->mpdf->AddPage( + $orient, + 'NEXT-EVEN', + $resetpagenum, + $pagenumstyle, + $suppress, + $mgl, + $mgr, + $mgt, + $mgb, + $mgh, + $mgf, + $ohname, + $ehname, + $ofname, + $efname, + $ohvalue, + $ehvalue, + $ofvalue, + $efvalue, + $pagesel, + $newformat + ); + } else { + $this->mpdf->AddPage( + $orient, + '', + $resetpagenum, + $pagenumstyle, + $suppress, + $mgl, + $mgr, + $mgt, + $mgb, + $mgh, + $mgf, + $ohname, + $ehname, + $ofname, + $efname, + $ohvalue, + $ehvalue, + $ofvalue, + $efvalue, + $pagesel, + $newformat + ); + } + + /* -- TOC -- */ + if ($tag === 'TOCPAGEBREAK') { + if ($this->toc_id) { + $this->tableOfContents->m_TOC[$this->toc_id]['TOCmark'] = $this->mpdf->page; + } else { + $this->tableOfContents->TOCmark = $this->mpdf->page; + } + } + /* -- END TOC -- */ + + // mPDF 6 pagebreaktype + $this->mpdf->_postForcedPagebreak($pagebreaktype, $startpage, $save_blk, $save_blklvl); + + $this->mpdf->InlineProperties = $save_ilp; + $this->mpdf->InlineBDF = $save_bflp; + $this->mpdf->InlineBDFctr = $save_bflpc; // mPDF 6 + $this->mpdf->restoreInlineProperties($save_silp); + } + + public function close(&$ahtml, &$ihtml) + { + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/H1.php b/src/bb-vendor/mpdf/mpdf/src/Tag/H1.php new file mode 100644 index 000000000..5174afbb8 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/H1.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class H1 extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/H2.php b/src/bb-vendor/mpdf/mpdf/src/Tag/H2.php new file mode 100644 index 000000000..199bb55ff --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/H2.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class H2 extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/H3.php b/src/bb-vendor/mpdf/mpdf/src/Tag/H3.php new file mode 100644 index 000000000..b9db924cd --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/H3.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class H3 extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/H4.php b/src/bb-vendor/mpdf/mpdf/src/Tag/H4.php new file mode 100644 index 000000000..3083ba100 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/H4.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class H4 extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/H5.php b/src/bb-vendor/mpdf/mpdf/src/Tag/H5.php new file mode 100644 index 000000000..50b78d746 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/H5.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class H5 extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/H6.php b/src/bb-vendor/mpdf/mpdf/src/Tag/H6.php new file mode 100644 index 000000000..f33dacf34 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/H6.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class H6 extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/HGroup.php b/src/bb-vendor/mpdf/mpdf/src/Tag/HGroup.php new file mode 100644 index 000000000..e519b936e --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/HGroup.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class HGroup extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Header.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Header.php new file mode 100644 index 000000000..f94855915 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Header.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Header extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Hr.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Hr.php new file mode 100644 index 000000000..5155c63ed --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Hr.php @@ -0,0 +1,126 @@ +<?php + +namespace Mpdf\Tag; + +use Mpdf\Utils\NumericString; + +class Hr extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + + // Added mPDF 3.0 Float DIV - CLEAR + if (isset($attr['STYLE'])) { + $properties = $this->cssManager->readInlineCSS($attr['STYLE']); + if (isset($properties['CLEAR'])) { + $this->mpdf->ClearFloats(strtoupper($properties['CLEAR']), $this->mpdf->blklvl); + } // *CSS-FLOAT* + } + + $this->mpdf->ignorefollowingspaces = true; + + $objattr = []; + $objattr['margin_top'] = 0; + $objattr['margin_bottom'] = 0; + $objattr['margin_left'] = 0; + $objattr['margin_right'] = 0; + $objattr['width'] = 0; + $objattr['height'] = 0; + $objattr['border_top']['w'] = 0; + $objattr['border_bottom']['w'] = 0; + $objattr['border_left']['w'] = 0; + $objattr['border_right']['w'] = 0; + $properties = $this->cssManager->MergeCSS('', 'HR', $attr); + if (isset($properties['MARGIN-TOP'])) { + $objattr['margin_top'] = $this->sizeConverter->convert( + $properties['MARGIN-TOP'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['MARGIN-BOTTOM'])) { + $objattr['margin_bottom'] = $this->sizeConverter->convert( + $properties['MARGIN-BOTTOM'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['WIDTH'])) { + $objattr['width'] = $this->sizeConverter->convert($properties['WIDTH'], $this->mpdf->blk[$this->mpdf->blklvl]['inner_width']); + } elseif (isset($attr['WIDTH']) && $attr['WIDTH'] != '') { + $objattr['width'] = $this->sizeConverter->convert($attr['WIDTH'], $this->mpdf->blk[$this->mpdf->blklvl]['inner_width']); + } + if (isset($properties['TEXT-ALIGN'])) { + $objattr['align'] = self::ALIGN[strtolower($properties['TEXT-ALIGN'])]; + } elseif (isset($attr['ALIGN']) && $attr['ALIGN'] != '') { + $objattr['align'] = self::ALIGN[strtolower($attr['ALIGN'])]; + } + + if (isset($properties['MARGIN-LEFT']) && strtolower($properties['MARGIN-LEFT']) === 'auto') { + $objattr['align'] = 'R'; + } + if (isset($properties['MARGIN-RIGHT']) && strtolower($properties['MARGIN-RIGHT']) === 'auto') { + $objattr['align'] = 'L'; + if (isset($properties['MARGIN-RIGHT']) && strtolower($properties['MARGIN-RIGHT']) === 'auto' + && isset($properties['MARGIN-LEFT']) && strtolower($properties['MARGIN-LEFT']) === 'auto') { + $objattr['align'] = 'C'; + } + } + if (isset($properties['COLOR'])) { + $objattr['color'] = $this->colorConverter->convert($properties['COLOR'], $this->mpdf->PDFAXwarnings); + } elseif (isset($attr['COLOR']) && $attr['COLOR'] != '') { + $objattr['color'] = $this->colorConverter->convert($attr['COLOR'], $this->mpdf->PDFAXwarnings); + } + if (isset($properties['HEIGHT'])) { + $objattr['linewidth'] = $this->sizeConverter->convert( + $properties['HEIGHT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + + + /* -- TABLES -- */ + if ($this->mpdf->tableLevel) { + $objattr['W-PERCENT'] = 100; + if (isset($properties['WIDTH']) && NumericString::containsPercentChar($properties['WIDTH'])) { + $properties['WIDTH'] = NumericString::removePercentChar($properties['WIDTH']); // make "90%" become simply "90" + $objattr['W-PERCENT'] = $properties['WIDTH']; + } + if (isset($attr['WIDTH']) && NumericString::containsPercentChar($attr['WIDTH'])) { + $attr['WIDTH'] = NumericString::removePercentChar($attr['WIDTH']); // make "90%" become simply "90" + $objattr['W-PERCENT'] = $attr['WIDTH']; + } + } + /* -- END TABLES -- */ + + $objattr['type'] = 'hr'; + $objattr['height'] = $objattr['linewidth'] + $objattr['margin_top'] + $objattr['margin_bottom']; + $e = "\xbb\xa4\xactype=image,objattr=" . serialize($objattr) . "\xbb\xa4\xac"; + + /* -- TABLES -- */ + // Output it to buffers + if ($this->mpdf->tableLevel) { + if ($this->mpdf->cell) { + if (!isset($this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['maxs'])) { + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['maxs'] = $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s']; + } elseif ($this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['maxs'] < $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s']) { + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['maxs'] = $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s']; + } + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s'] = 0; // reset + $this->mpdf->_saveCellTextBuffer($e, $this->mpdf->HREF); + } + } else { + /* -- END TABLES -- */ + $this->mpdf->_saveTextBuffer($e, $this->mpdf->HREF); + } // *TABLES* + } + + public function close(&$ahtml, &$ihtml) + { + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/I.php b/src/bb-vendor/mpdf/mpdf/src/Tag/I.php new file mode 100644 index 000000000..8c03c2dad --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/I.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class I extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Img.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Img.php new file mode 100644 index 000000000..cd7fc0dd6 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Img.php @@ -0,0 +1,458 @@ +<?php + +namespace Mpdf\Tag; + +use Mpdf\Mpdf; + +class Img extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $this->mpdf->ignorefollowingspaces = false; + $objattr = []; + $objattr['margin_top'] = 0; + $objattr['margin_bottom'] = 0; + $objattr['margin_left'] = 0; + $objattr['margin_right'] = 0; + $objattr['padding_top'] = 0; + $objattr['padding_bottom'] = 0; + $objattr['padding_left'] = 0; + $objattr['padding_right'] = 0; + $objattr['width'] = 0; + $objattr['height'] = 0; + $objattr['border_top']['w'] = 0; + $objattr['border_bottom']['w'] = 0; + $objattr['border_left']['w'] = 0; + $objattr['border_right']['w'] = 0; + if (isset($attr['SRC'])) { + $srcpath = $attr['SRC']; + $orig_srcpath = (isset($attr['ORIG_SRC']) ? $attr['ORIG_SRC'] : ''); + $properties = $this->cssManager->MergeCSS('', 'IMG', $attr); + if (isset($properties ['DISPLAY']) && strtolower($properties ['DISPLAY']) === 'none') { + return; + } + if (isset($properties['Z-INDEX']) && $this->mpdf->current_layer == 0) { + $v = (int) $properties['Z-INDEX']; + if ($v > 0) { + $objattr['z-index'] = $v; + } + } + + $objattr['visibility'] = 'visible'; + if (isset($properties['VISIBILITY'])) { + $v = strtolower($properties['VISIBILITY']); + if (($v === 'hidden' || $v === 'printonly' || $v === 'screenonly') && $this->mpdf->visibility === 'visible') { + $objattr['visibility'] = $v; + } + } + + // VSPACE and HSPACE converted to margins in MergeCSS + if (isset($properties['MARGIN-TOP'])) { + $objattr['margin_top'] = $this->sizeConverter->convert( + $properties['MARGIN-TOP'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['MARGIN-BOTTOM'])) { + $objattr['margin_bottom'] = $this->sizeConverter->convert( + $properties['MARGIN-BOTTOM'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['MARGIN-LEFT'])) { + $objattr['margin_left'] = $this->sizeConverter->convert( + $properties['MARGIN-LEFT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['MARGIN-RIGHT'])) { + $objattr['margin_right'] = $this->sizeConverter->convert( + $properties['MARGIN-RIGHT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + + if (isset($properties['PADDING-TOP'])) { + $objattr['padding_top'] = $this->sizeConverter->convert( + $properties['PADDING-TOP'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['PADDING-BOTTOM'])) { + $objattr['padding_bottom'] = $this->sizeConverter->convert( + $properties['PADDING-BOTTOM'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['PADDING-LEFT'])) { + $objattr['padding_left'] = $this->sizeConverter->convert( + $properties['PADDING-LEFT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['PADDING-RIGHT'])) { + $objattr['padding_right'] = $this->sizeConverter->convert( + $properties['PADDING-RIGHT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + + if (isset($properties['BORDER-TOP'])) { + $objattr['border_top'] = $this->mpdf->border_details($properties['BORDER-TOP']); + } + if (isset($properties['BORDER-BOTTOM'])) { + $objattr['border_bottom'] = $this->mpdf->border_details($properties['BORDER-BOTTOM']); + } + if (isset($properties['BORDER-LEFT'])) { + $objattr['border_left'] = $this->mpdf->border_details($properties['BORDER-LEFT']); + } + if (isset($properties['BORDER-RIGHT'])) { + $objattr['border_right'] = $this->mpdf->border_details($properties['BORDER-RIGHT']); + } + + if (isset($properties['VERTICAL-ALIGN'])) { + $objattr['vertical-align'] = self::ALIGN[strtolower($properties['VERTICAL-ALIGN'])]; + } + $w = 0; + $h = 0; + if (isset($properties['WIDTH'])) { + $w = $this->sizeConverter->convert( + $properties['WIDTH'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } elseif (isset($attr['WIDTH'])) { + $w = $this->sizeConverter->convert( + $attr['WIDTH'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['HEIGHT'])) { + $h = $this->sizeConverter->convert( + $properties['HEIGHT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } elseif (isset($attr['HEIGHT'])) { + $h = $this->sizeConverter->convert( + $attr['HEIGHT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + $maxw = $maxh = $minw = $minh = false; + if (isset($properties['MAX-WIDTH'])) { + $maxw = $this->sizeConverter->convert( + $properties['MAX-WIDTH'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } elseif (isset($attr['MAX-WIDTH'])) { + $maxw = $this->sizeConverter->convert( + $attr['MAX-WIDTH'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['MAX-HEIGHT'])) { + $maxh = $this->sizeConverter->convert( + $properties['MAX-HEIGHT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } elseif (isset($attr['MAX-HEIGHT'])) { + $maxh = $this->sizeConverter->convert( + $attr['MAX-HEIGHT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['MIN-WIDTH'])) { + $minw = $this->sizeConverter->convert( + $properties['MIN-WIDTH'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } elseif (isset($attr['MIN-WIDTH'])) { + $minw = $this->sizeConverter->convert( + $attr['MIN-WIDTH'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['MIN-HEIGHT'])) { + $minh = $this->sizeConverter->convert( + $properties['MIN-HEIGHT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } elseif (isset($attr['MIN-HEIGHT'])) { + $minh = $this->sizeConverter->convert( + $attr['MIN-HEIGHT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + + if (isset($properties['OPACITY']) && $properties['OPACITY'] > 0 && $properties['OPACITY'] <= 1) { + $objattr['opacity'] = $properties['OPACITY']; + } + if ($this->mpdf->HREF) { + if (strpos($this->mpdf->HREF, '.') === false && strpos($this->mpdf->HREF, '@') !== 0) { + $href = $this->mpdf->HREF; + while (array_key_exists($href, $this->mpdf->internallink)) { + $href = '#' . $href; + } + $this->mpdf->internallink[$href] = $this->mpdf->AddLink(); + $objattr['link'] = $this->mpdf->internallink[$href]; + } else { + $objattr['link'] = $this->mpdf->HREF; + } + } + $extraheight = $objattr['padding_top'] + $objattr['padding_bottom'] + $objattr['margin_top'] + + $objattr['margin_bottom'] + $objattr['border_top']['w'] + $objattr['border_bottom']['w']; + + $extrawidth = $objattr['padding_left'] + $objattr['padding_right'] + $objattr['margin_left'] + + $objattr['margin_right'] + $objattr['border_left']['w'] + $objattr['border_right']['w']; + + // mPDF 5.7.3 TRANSFORMS + if (isset($properties['BACKGROUND-COLOR']) && $properties['BACKGROUND-COLOR'] != '') { + $objattr['bgcolor'] = $this->colorConverter->convert($properties['BACKGROUND-COLOR'], $this->mpdf->PDFAXwarnings); + } + + /* -- BACKGROUNDS -- */ + if (isset($properties['GRADIENT-MASK']) && preg_match('/(-moz-)*(repeating-)*(linear|radial)-gradient/', $properties['GRADIENT-MASK'])) { + $objattr['GRADIENT-MASK'] = $properties['GRADIENT-MASK']; + } + /* -- END BACKGROUNDS -- */ + + // mPDF 6 + $interpolation = false; + if (!empty($properties['IMAGE-RENDERING'])) { + $interpolation = false; + if (strtolower($properties['IMAGE-RENDERING']) === 'crisp-edges') { + $interpolation = false; + } elseif (strtolower($properties['IMAGE-RENDERING']) === 'optimizequality') { + $interpolation = true; + } elseif (strtolower($properties['IMAGE-RENDERING']) === 'smooth') { + $interpolation = true; + } elseif (strtolower($properties['IMAGE-RENDERING']) === 'auto') { + $interpolation = $this->mpdf->interpolateImages; + } + $info['interpolation'] = $interpolation; + } + + // Image file + $info = $this->imageProcessor->getImage($srcpath, true, true, $orig_srcpath, $interpolation); // mPDF 6 + if (!$info) { + $info = $this->imageProcessor->getImage($this->mpdf->noImageFile); + if ($info) { + $srcpath = $this->mpdf->noImageFile; + $w = ($info['w'] * (25.4 / $this->mpdf->img_dpi)); + $h = ($info['h'] * (25.4 / $this->mpdf->img_dpi)); + } + } + if (!$info) { + return; + } + + $image_orientation = 0; + if (isset($attr['ROTATE'])) { + $image_orientation = $attr['ROTATE']; + } elseif (isset($properties['IMAGE-ORIENTATION'])) { + $image_orientation = $properties['IMAGE-ORIENTATION']; + } + if ($image_orientation) { + if ($image_orientation == 90 || $image_orientation == -90 || $image_orientation == 270) { + $tmpw = $info['w']; + $info['w'] = $info['h']; + $info['h'] = $tmpw; + } + $objattr['ROTATE'] = $image_orientation; + } + + $objattr['file'] = $srcpath; + //Default width and height calculation if needed + if ($w == 0 && $h == 0) { + /* -- IMAGES-WMF -- */ + if ($info['type'] === 'wmf') { + // WMF units are twips (1/20pt) + // divide by 20 to get points + // divide by k to get user units + $w = abs($info['w']) / (20 * Mpdf::SCALE); + $h = abs($info['h']) / (20 * Mpdf::SCALE); + } else { /* -- END IMAGES-WMF -- */ + if ($info['type'] === 'svg') { + // SVG units are pixels + $w = abs($info['w']) / Mpdf::SCALE; + $h = abs($info['h']) / Mpdf::SCALE; + } else { + //Put image at default image dpi + $w = ($info['w'] / Mpdf::SCALE) * (72 / $this->mpdf->img_dpi); + $h = ($info['h'] / Mpdf::SCALE) * (72 / $this->mpdf->img_dpi); + } + } + if (isset($properties['IMAGE-RESOLUTION'])) { + if (preg_match('/from-image/i', $properties['IMAGE-RESOLUTION']) && isset($info['set-dpi']) && $info['set-dpi'] > 0) { + $w *= $this->mpdf->img_dpi / $info['set-dpi']; + $h *= $this->mpdf->img_dpi / $info['set-dpi']; + } elseif (preg_match('/(\d+)dpi/i', $properties['IMAGE-RESOLUTION'], $m)) { + $dpi = $m[1]; + if ($dpi > 0) { + $w *= $this->mpdf->img_dpi / $dpi; + $h *= $this->mpdf->img_dpi / $dpi; + } + } + } + } + // IF WIDTH OR HEIGHT SPECIFIED + if ($w == 0) { + $w = $info['h'] ? abs($h * $info['w'] / $info['h']) : INF; + } + + if ($h == 0) { + $h = $info['w'] ? abs($w * $info['h'] / $info['w']) : INF; + } + + if ($minw && $w < $minw) { + $w = $minw; + $h = $info['w'] ? abs($w * $info['h'] / $info['w']) : INF; + } + if ($maxw && $w > $maxw) { + $w = $maxw; + $h = $info['w'] ? abs($w * $info['h'] / $info['w']) : INF; + } + if ($minh && $h < $minh) { + $h = $minh; + $w = $info['h'] ? abs($h * $info['w'] / $info['h']) : INF; + } + if ($maxh && $h > $maxh) { + $h = $maxh; + $w = $info['h'] ? abs($h * $info['w'] / $info['h']) : INF; + } + + // Resize to maximum dimensions of page + $maxWidth = $this->mpdf->blk[$this->mpdf->blklvl]['inner_width']; + $maxHeight = $this->mpdf->h - ($this->mpdf->tMargin + $this->mpdf->bMargin + 1); + if ($this->mpdf->fullImageHeight) { + $maxHeight = $this->mpdf->fullImageHeight; + } + if (($w + $extrawidth) > ($maxWidth + 0.0001)) { // mPDF 5.7.4 0.0001 to allow for rounding errors when w==maxWidth + $w = $maxWidth - $extrawidth; + $h = abs($w * $info['h'] / $info['w']); + } + + if ($h + $extraheight > $maxHeight) { + $h = $maxHeight - $extraheight; + $w = abs($h * $info['w'] / $info['h']); + } + $objattr['type'] = 'image'; + $objattr['itype'] = $info['type']; + + $objattr['orig_h'] = $info['h']; + $objattr['orig_w'] = $info['w']; + /* -- IMAGES-WMF -- */ + if ($info['type'] === 'wmf') { + $objattr['wmf_x'] = $info['x']; + $objattr['wmf_y'] = $info['y']; + } else { /* -- END IMAGES-WMF -- */ + if ($info['type'] === 'svg') { + $objattr['wmf_x'] = $info['x']; + $objattr['wmf_y'] = $info['y']; + } + } + $objattr['height'] = $h + $extraheight; + $objattr['width'] = $w + $extrawidth; + $objattr['image_height'] = $h; + $objattr['image_width'] = $w; + /* -- CSS-IMAGE-FLOAT -- */ + if (!$this->mpdf->ColActive && !$this->mpdf->tableLevel && !$this->mpdf->listlvl && !$this->mpdf->kwt) { + if (isset($properties['FLOAT']) && (strtoupper($properties['FLOAT']) === 'RIGHT' || strtoupper($properties['FLOAT']) === 'LEFT')) { + $objattr['float'] = strtoupper(substr($properties['FLOAT'], 0, 1)); + } + } + /* -- END CSS-IMAGE-FLOAT -- */ + // mPDF 5.7.3 TRANSFORMS + if (isset($properties['TRANSFORM']) && !$this->mpdf->ColActive && !$this->mpdf->kwt) { + $objattr['transform'] = $properties['TRANSFORM']; + } + + $e = "\xbb\xa4\xactype=image,objattr=" . serialize($objattr) . "\xbb\xa4\xac"; + + /* -- TABLES -- */ + // Output it to buffers + if ($this->mpdf->tableLevel) { + $this->mpdf->_saveCellTextBuffer($e, $this->mpdf->HREF); + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s'] += $objattr['width']; + } else { + /* -- END TABLES -- */ + $this->mpdf->_saveTextBuffer($e, $this->mpdf->HREF); + } // *TABLES* + /* -- ANNOTATIONS -- */ + if ($this->mpdf->title2annots && isset($attr['TITLE'])) { + $objattr = []; + $objattr['margin_top'] = 0; + $objattr['margin_bottom'] = 0; + $objattr['margin_left'] = 0; + $objattr['margin_right'] = 0; + $objattr['width'] = 0; + $objattr['height'] = 0; + $objattr['border_top']['w'] = 0; + $objattr['border_bottom']['w'] = 0; + $objattr['border_left']['w'] = 0; + $objattr['border_right']['w'] = 0; + $objattr['CONTENT'] = $attr['TITLE']; + $objattr['type'] = 'annot'; + $objattr['POS-X'] = 0; + $objattr['POS-Y'] = 0; + $objattr['ICON'] = 'Comment'; + $objattr['AUTHOR'] = ''; + $objattr['SUBJECT'] = ''; + $objattr['OPACITY'] = $this->mpdf->annotOpacity; + $objattr['COLOR'] = $this->colorConverter->convert('yellow', $this->mpdf->PDFAXwarnings); + $e = "\xbb\xa4\xactype=annot,objattr=" . serialize($objattr) . "\xbb\xa4\xac"; + if ($this->mpdf->tableLevel) { // *TABLES* + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['textbuffer'][] = [$e]; // *TABLES* + } // *TABLES* + else { // *TABLES* + $this->mpdf->textbuffer[] = [$e]; + } // *TABLES* + } + /* -- END ANNOTATIONS -- */ + } + } + + public function close(&$ahtml, &$ihtml) + { + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/IndexEntry.php b/src/bb-vendor/mpdf/mpdf/src/Tag/IndexEntry.php new file mode 100644 index 000000000..2ca06a4e1 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/IndexEntry.php @@ -0,0 +1,32 @@ +<?php + +namespace Mpdf\Tag; + +class IndexEntry extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + if (!empty($attr['CONTENT'])) { + if (!empty($attr['XREF'])) { + $this->mpdf->IndexEntry(htmlspecialchars_decode($attr['CONTENT'], ENT_QUOTES), $attr['XREF']); + return; + } + $objattr = []; + $objattr['CONTENT'] = htmlspecialchars_decode($attr['CONTENT'], ENT_QUOTES); + $objattr['type'] = 'indexentry'; + $objattr['vertical-align'] = 'T'; + $e = "\xbb\xa4\xactype=indexentry,objattr=" . serialize($objattr) . "\xbb\xa4\xac"; + if ($this->mpdf->tableLevel) { + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['textbuffer'][] = [$e]; + } // *TABLES* + else { // *TABLES* + $this->mpdf->textbuffer[] = [$e]; + } // *TABLES* + } + } + + public function close(&$ahtml, &$ihtml) + { + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/IndexInsert.php b/src/bb-vendor/mpdf/mpdf/src/Tag/IndexInsert.php new file mode 100644 index 000000000..2704b4fbf --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/IndexInsert.php @@ -0,0 +1,33 @@ +<?php + +namespace Mpdf\Tag; + +class IndexInsert extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $indexCollationLocale = ''; + if (isset($attr['COLLATION'])) { + $indexCollationLocale = $attr['COLLATION']; + } + + $indexCollationGroup = ''; + if (isset($attr['COLLATION-GROUP'])) { + $indexCollationGroup = $attr['COLLATION-GROUP']; + } + + $usedivletters = 1; + if (isset($attr['USEDIVLETTERS']) && (strtoupper($attr['USEDIVLETTERS']) === 'OFF' + || $attr['USEDIVLETTERS'] == -1 + || $attr['USEDIVLETTERS'] === '0')) { + $usedivletters = 0; + } + $links = isset($attr['LINKS']) && (strtoupper($attr['LINKS']) === 'ON' || $attr['LINKS'] == 1); + $this->mpdf->InsertIndex($usedivletters, $links, $indexCollationLocale, $indexCollationGroup); + } + + public function close(&$ahtml, &$ihtml) + { + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/InlineTag.php b/src/bb-vendor/mpdf/mpdf/src/Tag/InlineTag.php new file mode 100644 index 000000000..69ea5f568 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/InlineTag.php @@ -0,0 +1,232 @@ +<?php + +namespace Mpdf\Tag; + +use Mpdf\Utils\UtfString; + +abstract class InlineTag extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $tag = $this->getTagName(); + + /* -- ANNOTATIONS -- */ + if ($this->mpdf->title2annots && isset($attr['TITLE'])) { + $objattr = []; + $objattr['margin_top'] = 0; + $objattr['margin_bottom'] = 0; + $objattr['margin_left'] = 0; + $objattr['margin_right'] = 0; + $objattr['width'] = 0; + $objattr['height'] = 0; + $objattr['border_top']['w'] = 0; + $objattr['border_bottom']['w'] = 0; + $objattr['border_left']['w'] = 0; + $objattr['border_right']['w'] = 0; + + $objattr['CONTENT'] = $attr['TITLE']; + $objattr['type'] = 'annot'; + $objattr['POS-X'] = 0; + $objattr['POS-Y'] = 0; + $objattr['ICON'] = 'Comment'; + $objattr['AUTHOR'] = ''; + $objattr['SUBJECT'] = ''; + $objattr['OPACITY'] = $this->mpdf->annotOpacity; + $objattr['COLOR'] = $this->colorConverter->convert('yellow', $this->mpdf->PDFAXwarnings); + $annot = "\xbb\xa4\xactype=annot,objattr=" . serialize($objattr) . "\xbb\xa4\xac"; + } + /* -- END ANNOTATIONS -- */ + + // mPDF 5.7.3 Inline tags + if (!isset($this->mpdf->InlineProperties[$tag])) { + $this->mpdf->InlineProperties[$tag] = [$this->mpdf->saveInlineProperties()]; + } else { + $this->mpdf->InlineProperties[$tag][] = $this->mpdf->saveInlineProperties(); + } + if (isset($annot)) { // *ANNOTATIONS* + if (!isset($this->mpdf->InlineAnnots[$tag])) { + $this->mpdf->InlineAnnots[$tag] = []; + } // *ANNOTATIONS* + $this->mpdf->InlineAnnots[$tag][] = $annot; + } // *ANNOTATIONS* + + $properties = $this->cssManager->MergeCSS('INLINE', $tag, $attr); + if (!empty($properties)) { + $this->mpdf->setCSS($properties, 'INLINE'); + } + + // mPDF 6 Bidirectional formatting for inline elements + $bdf = false; + $bdf2 = ''; + $popd = ''; + + // Get current direction + $currdir = 'ltr'; + if (isset($this->mpdf->blk[$this->mpdf->blklvl]['direction'])) { + $currdir = $this->mpdf->blk[$this->mpdf->blklvl]['direction']; + } + if ($this->mpdf->tableLevel + && isset($this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['direction']) + && $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['direction'] === 'rtl') { + $currdir = 'rtl'; + } + if (isset($attr['DIR']) && $attr['DIR'] != '') { + $currdir = strtolower($attr['DIR']); + } + if (isset($properties['DIRECTION'])) { + $currdir = strtolower($properties['DIRECTION']); + } + + // mPDF 6 bidi + // cf. http://www.w3.org/TR/css3-writing-modes/#unicode-bidi + if ($tag === 'BDO') { + if (isset($attr['DIR']) && strtolower($attr['DIR']) === 'rtl') { + $bdf = 0x202E; + $popd = 'RLOPDF'; + } // U+202E RLO + elseif (isset($attr['DIR']) && strtolower($attr['DIR']) === 'ltr') { + $bdf = 0x202D; + $popd = 'LROPDF'; + } // U+202D LRO + } elseif ($tag === 'BDI') { + if (isset($attr['DIR']) && strtolower($attr['DIR']) === 'rtl') { + $bdf = 0x2067; + $popd = 'RLIPDI'; + } // U+2067 RLI + elseif (isset($attr['DIR']) && strtolower($attr['DIR']) === 'ltr') { + $bdf = 0x2066; + $popd = 'LRIPDI'; + } // U+2066 LRI + else { + $bdf = 0x2068; + $popd = 'FSIPDI'; + } // U+2068 FSI + } elseif (isset($properties ['UNICODE-BIDI']) && strtolower($properties ['UNICODE-BIDI']) === 'bidi-override') { + if ($currdir === 'rtl') { + $bdf = 0x202E; + $popd = 'RLOPDF'; + } // U+202E RLO + else { + $bdf = 0x202D; + $popd = 'LROPDF'; + } // U+202D LRO + } elseif (isset($properties ['UNICODE-BIDI']) && strtolower($properties ['UNICODE-BIDI']) === 'embed') { + if ($currdir === 'rtl') { + $bdf = 0x202B; + $popd = 'RLEPDF'; + } // U+202B RLE + else { + $bdf = 0x202A; + $popd = 'LREPDF'; + } // U+202A LRE + } elseif (isset($properties ['UNICODE-BIDI']) && strtolower($properties ['UNICODE-BIDI']) === 'isolate') { + if ($currdir === 'rtl') { + $bdf = 0x2067; + $popd = 'RLIPDI'; + } // U+2067 RLI + else { + $bdf = 0x2066; + $popd = 'LRIPDI'; + } // U+2066 LRI + } elseif (isset($properties ['UNICODE-BIDI']) && strtolower($properties ['UNICODE-BIDI']) === 'isolate-override') { + if ($currdir === 'rtl') { + $bdf = 0x2067; + $bdf2 = 0x202E; + $popd = 'RLIRLOPDFPDI'; + } // U+2067 RLI // U+202E RLO + else { + $bdf = 0x2066; + $bdf2 = 0x202D; + $popd = 'LRILROPDFPDI'; + } // U+2066 LRI // U+202D LRO + } elseif (isset($properties ['UNICODE-BIDI']) && strtolower($properties ['UNICODE-BIDI']) === 'plaintext') { + $bdf = 0x2068; + $popd = 'FSIPDI'; // U+2068 FSI + } else { + if (isset($attr['DIR']) && strtolower($attr['DIR']) === 'rtl') { + $bdf = 0x202B; + $popd = 'RLEPDF'; + } // U+202B RLE + elseif (isset($attr['DIR']) && strtolower($attr['DIR']) === 'ltr') { + $bdf = 0x202A; + $popd = 'LREPDF'; + } // U+202A LRE + } + + if ($bdf) { + // mPDF 5.7.3 Inline tags + if (!isset($this->mpdf->InlineBDF[$tag])) { + $this->mpdf->InlineBDF[$tag] = [[$popd, $this->mpdf->InlineBDFctr]]; + } else { + $this->mpdf->InlineBDF[$tag][] = [$popd, $this->mpdf->InlineBDFctr]; + } + $this->mpdf->InlineBDFctr++; + if ($bdf2) { + $bdf2 = UtfString::code2utf($bdf); + } + $this->mpdf->OTLdata = []; + if ($this->mpdf->tableLevel) { + $this->mpdf->_saveCellTextBuffer(UtfString::code2utf($bdf) . $bdf2); + } else { + $this->mpdf->_saveTextBuffer(UtfString::code2utf($bdf) . $bdf2); + } + $this->mpdf->biDirectional = true; + } + } + + public function close(&$ahtml, &$ihtml) + { + $tag = $this->getTagName(); + + $annot = false; // mPDF 6 + $bdf = false; // mPDF 6 + + // mPDF 5.7.3 Inline tags + if ($tag === 'PROGRESS' || $tag === 'METER') { + if (!empty($this->mpdf->InlineProperties[$tag])) { + $this->mpdf->restoreInlineProperties($this->mpdf->InlineProperties[$tag]); + } + unset($this->mpdf->InlineProperties[$tag]); + if (!empty($this->mpdf->InlineAnnots[$tag])) { + $annot = $this->mpdf->InlineAnnots[$tag]; + } // *ANNOTATIONS* + unset($this->mpdf->InlineAnnots[$tag]); // *ANNOTATIONS* + } else { + if (isset($this->mpdf->InlineProperties[$tag]) && count($this->mpdf->InlineProperties[$tag])) { + $tmpProps = array_pop($this->mpdf->InlineProperties[$tag]); // mPDF 5.7.4 + $this->mpdf->restoreInlineProperties($tmpProps); + } + if (isset($this->mpdf->InlineAnnots[$tag]) && count($this->mpdf->InlineAnnots[$tag])) { // *ANNOTATIONS* + $annot = array_pop($this->mpdf->InlineAnnots[$tag]); // *ANNOTATIONS* + } // *ANNOTATIONS* + if (isset($this->mpdf->InlineBDF[$tag]) && count($this->mpdf->InlineBDF[$tag])) { // mPDF 6 + $bdfarr = array_pop($this->mpdf->InlineBDF[$tag]); + $bdf = $bdfarr[0]; + } + } + + /* -- ANNOTATIONS -- */ + if ($annot) { // mPDF 6 + if ($this->mpdf->tableLevel) { // *TABLES* + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['textbuffer'][] = [$annot]; // *TABLES* + } // *TABLES* + else { // *TABLES* + $this->mpdf->textbuffer[] = [$annot]; + } // *TABLES* + } + /* -- END ANNOTATIONS -- */ + + // mPDF 6 bidi + // mPDF 6 Bidirectional formatting for inline elements + if ($bdf) { + $popf = $this->mpdf->_setBidiCodes('end', $bdf); + $this->mpdf->OTLdata = []; + if ($this->mpdf->tableLevel) { + $this->mpdf->_saveCellTextBuffer($popf); + } else { + $this->mpdf->_saveTextBuffer($popf); + } + } + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Input.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Input.php new file mode 100644 index 000000000..2b5b5348f --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Input.php @@ -0,0 +1,425 @@ +<?php + +namespace Mpdf\Tag; + +use Mpdf\Mpdf; +use Mpdf\Utils\UtfString; + +class Input extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $tag = $this->getTagName(); + $this->mpdf->ignorefollowingspaces = false; + if (!isset($attr['TYPE'])) { + $attr['TYPE'] = 'TEXT'; + } + $objattr = []; + $objattr['margin_top'] = 0; + $objattr['margin_bottom'] = 0; + $objattr['margin_left'] = 0; + $objattr['margin_right'] = 0; + $objattr['width'] = 0; + $objattr['height'] = 0; + $objattr['border_top']['w'] = 0; + $objattr['border_bottom']['w'] = 0; + $objattr['border_left']['w'] = 0; + $objattr['border_right']['w'] = 0; + $objattr['type'] = 'input'; + if (isset($attr['DISABLED'])) { + $objattr['disabled'] = true; + } + if (isset($attr['READONLY'])) { + $objattr['readonly'] = true; + } + if (isset($attr['REQUIRED'])) { + $objattr['required'] = true; + } + if (isset($attr['SPELLCHECK']) && strtolower($attr['SPELLCHECK']) === 'true') { + $objattr['spellcheck'] = true; + } + if (isset($attr['TITLE'])) { + $objattr['title'] = $attr['TITLE']; + } elseif (isset($attr['ALT'])) { + $objattr['title'] = $attr['ALT']; + } else { + $objattr['title'] = ''; + } + $objattr['title'] = UtfString::strcode2utf($objattr['title']); + $objattr['title'] = $this->mpdf->lesser_entity_decode($objattr['title']); + if ($this->mpdf->onlyCoreFonts) { + $objattr['title'] = mb_convert_encoding($objattr['title'], $this->mpdf->mb_enc, 'UTF-8'); + } + if ($this->mpdf->useActiveForms && isset($attr['NAME'])) { + $objattr['fieldname'] = $attr['NAME']; + } + if (isset($attr['VALUE'])) { + $attr['VALUE'] = UtfString::strcode2utf($attr['VALUE']); + $attr['VALUE'] = $this->mpdf->lesser_entity_decode($attr['VALUE']); + if ($this->mpdf->onlyCoreFonts) { + $attr['VALUE'] = mb_convert_encoding($attr['VALUE'], $this->mpdf->mb_enc, 'UTF-8'); + } + $objattr['value'] = $attr['VALUE']; + } + + $this->mpdf->InlineProperties['INPUT'] = $this->mpdf->saveInlineProperties(); + $properties = $this->cssManager->MergeCSS('', 'INPUT', $attr); + $objattr['vertical-align'] = ''; + + if (isset($properties['FONT-FAMILY'])) { + $this->mpdf->SetFont($properties['FONT-FAMILY'], $this->mpdf->FontStyle, 0, false); + } + if (isset($properties['FONT-SIZE'])) { + $mmsize = $this->sizeConverter->convert($properties['FONT-SIZE'], $this->mpdf->default_font_size / Mpdf::SCALE); + $this->mpdf->SetFontSize($mmsize * Mpdf::SCALE, false); + } + if (isset($properties['COLOR'])) { + $objattr['color'] = $this->colorConverter->convert($properties['COLOR'], $this->mpdf->PDFAXwarnings); + } + $objattr['fontfamily'] = $this->mpdf->FontFamily; + $objattr['fontsize'] = $this->mpdf->FontSizePt; + if ($this->mpdf->useActiveForms) { + if (isset($attr['ALIGN'])) { + $objattr['text_align'] = self::ALIGN[strtolower($attr['ALIGN'])]; + } elseif (isset($properties['TEXT-ALIGN'])) { + $objattr['text_align'] = self::ALIGN[strtolower($properties['TEXT-ALIGN'])]; + } + if (isset($properties['BORDER-TOP-COLOR'])) { + $objattr['border-col'] = $this->colorConverter->convert($properties['BORDER-TOP-COLOR'], $this->mpdf->PDFAXwarnings); + } + if (isset($properties['BACKGROUND-COLOR'])) { + $objattr['background-col'] = $this->colorConverter->convert($properties['BACKGROUND-COLOR'], $this->mpdf->PDFAXwarnings); + } + } + + $type = ''; + $texto = ''; + $height = $this->mpdf->FontSize; + $width = 0; + $spacesize = $this->mpdf->GetCharWidth(' ', false); + + $w = 0; + if (isset($properties['WIDTH'])) { + $w = $this->sizeConverter->convert($properties['WIDTH'], $this->mpdf->blk[$this->mpdf->blklvl]['inner_width']); + } + + if ($properties['VERTICAL-ALIGN']) { + $objattr['vertical-align'] = self::ALIGN[strtolower($properties['VERTICAL-ALIGN'])]; + } + + switch (strtoupper($attr['TYPE'])) { + case 'HIDDEN': + $this->mpdf->ignorefollowingspaces = true; //Eliminate exceeding left-side spaces + if ($this->mpdf->useActiveForms) { + $this->form->SetFormText(0, 0, $objattr['fieldname'], $objattr['value'], $objattr['value'], '', 0, '', true); + } + if ($this->mpdf->InlineProperties[$tag]) { + $this->mpdf->restoreInlineProperties($this->mpdf->InlineProperties[$tag]); + } + unset($this->mpdf->InlineProperties[$tag]); + return; + + case 'CHECKBOX': //Draw Checkbox + $type = 'CHECKBOX'; + if (isset($attr['CHECKED'])) { + $objattr['checked'] = true; + } else { + $objattr['checked'] = false; + } + $width = $this->mpdf->FontSize; + $height = $this->mpdf->FontSize; + break; + + case 'RADIO': //Draw Radio button + $type = 'RADIO'; + if (isset($attr['CHECKED'])) { + $objattr['checked'] = true; + } + $width = $this->mpdf->FontSize; + $height = $this->mpdf->FontSize; + break; + + /* -- IMAGES-CORE -- */ + case 'IMAGE': // Draw an Image button + if (isset($attr['SRC'])) { + $type = 'IMAGE'; + $srcpath = $attr['SRC']; + $orig_srcpath = $attr['ORIG_SRC']; + // VSPACE and HSPACE converted to margins in MergeCSS + if (isset($properties['MARGIN-TOP'])) { + $objattr['margin_top'] = $this->sizeConverter->convert( + $properties['MARGIN-TOP'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['MARGIN-BOTTOM'])) { + $objattr['margin_bottom'] = $this->sizeConverter->convert( + $properties['MARGIN-BOTTOM'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['MARGIN-LEFT'])) { + $objattr['margin_left'] = $this->sizeConverter->convert( + $properties['MARGIN-LEFT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['MARGIN-RIGHT'])) { + $objattr['margin_right'] = $this->sizeConverter->convert( + $properties['MARGIN-RIGHT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + + if (isset($properties['BORDER-TOP'])) { + $objattr['border_top'] = $this->mpdf->border_details($properties['BORDER-TOP']); + } + if (isset($properties['BORDER-BOTTOM'])) { + $objattr['border_bottom'] = $this->mpdf->border_details($properties['BORDER-BOTTOM']); + } + if (isset($properties['BORDER-LEFT'])) { + $objattr['border_left'] = $this->mpdf->border_details($properties['BORDER-LEFT']); + } + if (isset($properties['BORDER-RIGHT'])) { + $objattr['border_right'] = $this->mpdf->border_details($properties['BORDER-RIGHT']); + } + + $objattr['padding_top'] = 0; + $objattr['padding_bottom'] = 0; + $objattr['padding_left'] = 0; + $objattr['padding_right'] = 0; + + if (isset($properties['VERTICAL-ALIGN'])) { + $objattr['vertical-align'] = self::ALIGN[strtolower($properties['VERTICAL-ALIGN'])]; + } + + $w = 0; + $h = 0; + if (isset($properties['WIDTH'])) { + $w = $this->sizeConverter->convert($properties['WIDTH'], $this->mpdf->blk[$this->mpdf->blklvl]['inner_width']); + } + if (isset($properties['HEIGHT'])) { + $h = $this->sizeConverter->convert($properties['HEIGHT'], $this->mpdf->blk[$this->mpdf->blklvl]['inner_width']); + } + + $extraheight = $objattr['margin_top'] + $objattr['margin_bottom'] + $objattr['border_top']['w'] + $objattr['border_bottom']['w']; + $extrawidth = $objattr['margin_left'] + $objattr['margin_right'] + $objattr['border_left']['w'] + $objattr['border_right']['w']; + + // Image file + $info = $this->imageProcessor->getImage($srcpath, true, true, $orig_srcpath); + if (!$info) { + $info = $this->imageProcessor->getImage($this->mpdf->noImageFile); + if ($info) { + $srcpath = $this->mpdf->noImageFile; + $w = ($info['w'] * (25.4 / $this->mpdf->img_dpi)); + $h = ($info['h'] * (25.4 / $this->mpdf->img_dpi)); + } + } + if (!$info) { + break; + } + if ($info['cs'] === 'Indexed') { + $objattr['Indexed'] = true; + } + $objattr['file'] = $srcpath; + //Default width and height calculation if needed + if ($w == 0 && $h == 0) { + /* -- IMAGES-WMF -- */ + if ($info['type'] === 'wmf') { + // WMF units are twips (1/20pt) + // divide by 20 to get points + // divide by k to get user units + $w = abs($info['w']) / (20 * Mpdf::SCALE); + $h = abs($info['h']) / (20 * Mpdf::SCALE); + } else { /* -- END IMAGES-WMF -- */ + if ($info['type'] === 'svg') { + // SVG units are pixels + $w = abs($info['w']) / Mpdf::SCALE; + $h = abs($info['h']) / Mpdf::SCALE; + } else { + //Put image at default image dpi + $w = ($info['w'] / Mpdf::SCALE) * (72 / $this->mpdf->img_dpi); + $h = ($info['h'] / Mpdf::SCALE) * (72 / $this->mpdf->img_dpi); + } + } + if (isset($properties['IMAGE-RESOLUTION'])) { + if (preg_match('/from-image/i', $properties['IMAGE-RESOLUTION']) && isset($info['set-dpi']) && $info['set-dpi'] > 0) { + $w *= $this->mpdf->img_dpi / $info['set-dpi']; + $h *= $this->mpdf->img_dpi / $info['set-dpi']; + } elseif (preg_match('/(\d+)dpi/i', $properties['IMAGE-RESOLUTION'], $m)) { + $dpi = $m[1]; + if ($dpi > 0) { + $w *= $this->mpdf->img_dpi / $dpi; + $h *= $this->mpdf->img_dpi / $dpi; + } + } + } + } + // IF WIDTH OR HEIGHT SPECIFIED + if ($w == 0) { + $w = $h * $info['w'] / $info['h']; + } + if ($h == 0) { + $h = $w * $info['h'] / $info['w']; + } + // Resize to maximum dimensions of page + $maxWidth = $this->mpdf->blk[$this->mpdf->blklvl]['inner_width']; + $maxHeight = $this->mpdf->h - ($this->mpdf->tMargin + $this->mpdf->bMargin + 10); + if ($this->mpdf->fullImageHeight) { + $maxHeight = $this->mpdf->fullImageHeight; + } + if (($w + $extrawidth) > ($maxWidth + 0.0001)) { // mPDF 5.7.4 0.0001 to allow for rounding errors when w==maxWidth + $w = $maxWidth - $extrawidth; + $h = $w * $info['h'] / $info['w']; + } + if ($h + $extraheight > $maxHeight) { + $h = $maxHeight - $extraheight; + $w = $h * $info['w'] / $info['h']; + } + $height = $h + $extraheight; + $width = $w + $extrawidth; + $objattr['type'] = 'image'; + $objattr['itype'] = $info['type']; + $objattr['orig_h'] = $info['h']; + $objattr['orig_w'] = $info['w']; + /* -- IMAGES-WMF -- */ + if ($info['type'] === 'wmf') { + $objattr['wmf_x'] = $info['x']; + $objattr['wmf_y'] = $info['y']; + /* -- END IMAGES-WMF -- */ + } else { + if ($info['type'] === 'svg') { + $objattr['wmf_x'] = $info['x']; + $objattr['wmf_y'] = $info['y']; + } + } + $objattr['height'] = $h + $extraheight; + $objattr['width'] = $w + $extrawidth; + + $objattr['image_height'] = $h; + $objattr['image_width'] = $w; + $objattr['ID'] = $info['i']; + $texto = 'X'; + if ($this->mpdf->useActiveForms) { + if (isset($attr['ONCLICK'])) { + $objattr['onClick'] = $attr['ONCLICK']; + } + $objattr['type'] = 'input'; + $type = 'IMAGE'; + } + break; + } + /* -- END IMAGES-CORE -- */ + + case 'BUTTON': // Draw a button + case 'SUBMIT': + case 'RESET': + $type = strtoupper($attr['TYPE']); + if ($type === 'IMAGE') { + $type = 'BUTTON'; + } // src path not found + if (isset($attr['NOPRINT'])) { + $objattr['noprint'] = true; + } + if (!isset($attr['VALUE'])) { + $objattr['value'] = ucfirst(strtolower($type)); + } + + $texto = ' ' . $objattr['value'] . ' '; + + $width = $this->mpdf->GetStringWidth($texto) + ($this->form->form_element_spacing['button']['outer']['h'] * 2) + + ($this->form->form_element_spacing['button']['inner']['h'] * 2); + + $height = $this->mpdf->FontSize + ($this->form->form_element_spacing['button']['outer']['v'] * 2) + + ($this->form->form_element_spacing['button']['inner']['v'] * 2); + + if ($this->mpdf->useActiveForms && isset($attr['ONCLICK'])) { + $objattr['onClick'] = $attr['ONCLICK']; + } + break; + + case 'PASSWORD': + case 'TEXT': + default: + if ($type == '') { + $type = 'TEXT'; + } + if (strtoupper($attr['TYPE']) === 'PASSWORD') { + $type = 'PASSWORD'; + } + if (isset($attr['VALUE'])) { + if ($type === 'PASSWORD') { + $num_stars = mb_strlen($attr['VALUE'], $this->mpdf->mb_enc); + $texto = str_repeat('*', $num_stars); + } else { + $texto = $attr['VALUE']; + } + } + $xw = ($this->form->form_element_spacing['input']['outer']['h'] * 2) + ($this->form->form_element_spacing['input']['inner']['h'] * 2); + $xh = ($this->form->form_element_spacing['input']['outer']['v'] * 2) + ($this->form->form_element_spacing['input']['inner']['v'] * 2); + if ($w) { + $width = $w + $xw; + } else { + $width = (20 * $spacesize) + $xw; + } // Default width in chars + if (isset($attr['SIZE']) && ctype_digit($attr['SIZE'])) { + $width = ($attr['SIZE'] * $spacesize) + $xw; + } + $height = $this->mpdf->FontSize + $xh; + if (isset($attr['MAXLENGTH']) && ctype_digit($attr['MAXLENGTH'])) { + $objattr['maxlength'] = $attr['MAXLENGTH']; + } + if ($this->mpdf->useActiveForms) { + if (isset($attr['ONCALCULATE'])) { + $objattr['onCalculate'] = $attr['ONCALCULATE']; + } elseif (isset($attr['ONCHANGE'])) { + $objattr['onCalculate'] = $attr['ONCHANGE']; + } + if (isset($attr['ONVALIDATE'])) { + $objattr['onValidate'] = $attr['ONVALIDATE']; + } + if (isset($attr['ONKEYSTROKE'])) { + $objattr['onKeystroke'] = $attr['ONKEYSTROKE']; + } + if (isset($attr['ONFORMAT'])) { + $objattr['onFormat'] = $attr['ONFORMAT']; + } + } + break; + } + + $objattr['subtype'] = $type; + $objattr['text'] = $texto; + $objattr['width'] = $width; + $objattr['height'] = $height; + $e = "\xbb\xa4\xactype=input,objattr=" . serialize($objattr) . "\xbb\xa4\xac"; + + /* -- TABLES -- */ + // Output it to buffers + if ($this->mpdf->tableLevel) { + $this->mpdf->_saveCellTextBuffer($e, $this->mpdf->HREF); + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s'] += $objattr['width']; + } else { + /* -- END TABLES -- */ + $this->mpdf->_saveTextBuffer($e, $this->mpdf->HREF); + } // *TABLES* + + if ($this->mpdf->InlineProperties[$tag]) { + $this->mpdf->restoreInlineProperties($this->mpdf->InlineProperties[$tag]); + } + unset($this->mpdf->InlineProperties[$tag]); + } + + public function close(&$ahtml, &$ihtml) + { + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Ins.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Ins.php new file mode 100644 index 000000000..03ec244cc --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Ins.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Ins extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Kbd.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Kbd.php new file mode 100644 index 000000000..10b7880fb --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Kbd.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Kbd extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Legend.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Legend.php new file mode 100644 index 000000000..90308d455 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Legend.php @@ -0,0 +1,35 @@ +<?php + +namespace Mpdf\Tag; + +use Mpdf\Mpdf; + +class Legend extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $this->mpdf->InlineProperties['LEGEND'] = $this->mpdf->saveInlineProperties(); + $properties = $this->cssManager->MergeCSS('INLINE', 'LEGEND', $attr); + if (!empty($properties)) { + $this->mpdf->setCSS($properties, 'INLINE'); + } + } + + public function close(&$ahtml, &$ihtml) + { + if (count($this->mpdf->textbuffer) && !$this->mpdf->tableLevel) { + $leg = $this->mpdf->textbuffer[count($this->mpdf->textbuffer) - 1]; + unset($this->mpdf->textbuffer[count($this->mpdf->textbuffer) - 1]); + $this->mpdf->textbuffer = array_values($this->mpdf->textbuffer); + $this->mpdf->blk[$this->mpdf->blklvl]['border_legend'] = $leg; + $this->mpdf->blk[$this->mpdf->blklvl]['margin_top'] += ($leg[11] / 2) / Mpdf::SCALE; + $this->mpdf->blk[$this->mpdf->blklvl]['padding_top'] += ($leg[11] / 2) / Mpdf::SCALE; + } + if (isset($this->mpdf->InlineProperties['LEGEND'])) { + $this->mpdf->restoreInlineProperties($this->mpdf->InlineProperties['LEGEND']); + } + unset($this->mpdf->InlineProperties['LEGEND']); + $this->mpdf->ignorefollowingspaces = true; //Eliminate exceeding left-side spaces + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Li.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Li.php new file mode 100644 index 000000000..361af06fe --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Li.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Li extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Main.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Main.php new file mode 100644 index 000000000..2e2fe396f --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Main.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Main extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Mark.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Mark.php new file mode 100644 index 000000000..38c14a423 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Mark.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Mark extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Meter.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Meter.php new file mode 100644 index 000000000..e3f9297c4 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Meter.php @@ -0,0 +1,517 @@ +<?php + +namespace Mpdf\Tag; + +use Mpdf\Mpdf; + +class Meter extends InlineTag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $tag = $this->getTagName(); + $this->mpdf->inMeter = true; + + $max = 1; + if (!empty($attr['MAX'])) { + $max = $attr['MAX']; + } + + $min = 0; + if (!empty($attr['MIN']) && $tag === 'METER') { + $min = $attr['MIN']; + } + + if ($max < $min) { + $max = $min; + } + + $value = ''; + if (isset($attr['VALUE']) && ($attr['VALUE'] || $attr['VALUE'] === '0')) { + $value = $attr['VALUE']; + if ($value < $min) { + $value = $min; + } elseif ($value > $max) { + $value = $max; + } + } + + $low = $min; + if (!empty($attr['LOW'])) { + $low = $attr['LOW']; + } + if ($low < $min) { + $low = $min; + } elseif ($low > $max) { + $low = $max; + } + $high = $max; + if (!empty($attr['HIGH'])) { + $high = $attr['HIGH']; + } + if ($high < $low) { + $high = $low; + } elseif ($high > $max) { + $high = $max; + } + if (!empty($attr['OPTIMUM'])) { + $optimum = $attr['OPTIMUM']; + } else { + $optimum = $min + (($max - $min) / 2); + } + if ($optimum < $min) { + $optimum = $min; + } elseif ($optimum > $max) { + $optimum = $max; + } + $type = ''; + if (!empty($attr['TYPE'])) { + $type = $attr['TYPE']; + } + $objattr = []; + $objattr['margin_top'] = 0; + $objattr['margin_bottom'] = 0; + $objattr['margin_left'] = 0; + $objattr['margin_right'] = 0; + $objattr['padding_top'] = 0; + $objattr['padding_bottom'] = 0; + $objattr['padding_left'] = 0; + $objattr['padding_right'] = 0; + $objattr['width'] = 0; + $objattr['height'] = 0; + $objattr['border_top']['w'] = 0; + $objattr['border_bottom']['w'] = 0; + $objattr['border_left']['w'] = 0; + $objattr['border_right']['w'] = 0; + + $properties = $this->cssManager->MergeCSS('INLINE', $tag, $attr); + if (isset($properties ['DISPLAY']) && strtolower($properties ['DISPLAY']) === 'none') { + return; + } + $objattr['visibility'] = 'visible'; + if (isset($properties['VISIBILITY'])) { + $v = strtolower($properties['VISIBILITY']); + if (($v === 'hidden' || $v === 'printonly' || $v === 'screenonly') && $this->mpdf->visibility === 'visible') { + $objattr['visibility'] = $v; + } + } + + if (isset($properties['MARGIN-TOP'])) { + $objattr['margin_top'] = $this->sizeConverter->convert( + $properties['MARGIN-TOP'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['MARGIN-BOTTOM'])) { + $objattr['margin_bottom'] = $this->sizeConverter->convert( + $properties['MARGIN-BOTTOM'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['MARGIN-LEFT'])) { + $objattr['margin_left'] = $this->sizeConverter->convert( + $properties['MARGIN-LEFT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['MARGIN-RIGHT'])) { + $objattr['margin_right'] = $this->sizeConverter->convert( + $properties['MARGIN-RIGHT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + + if (isset($properties['PADDING-TOP'])) { + $objattr['padding_top'] = $this->sizeConverter->convert( + $properties['PADDING-TOP'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['PADDING-BOTTOM'])) { + $objattr['padding_bottom'] = $this->sizeConverter->convert( + $properties['PADDING-BOTTOM'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['PADDING-LEFT'])) { + $objattr['padding_left'] = $this->sizeConverter->convert( + $properties['PADDING-LEFT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['PADDING-RIGHT'])) { + $objattr['padding_right'] = $this->sizeConverter->convert( + $properties['PADDING-RIGHT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + + if (isset($properties['BORDER-TOP'])) { + $objattr['border_top'] = $this->mpdf->border_details($properties['BORDER-TOP']); + } + if (isset($properties['BORDER-BOTTOM'])) { + $objattr['border_bottom'] = $this->mpdf->border_details($properties['BORDER-BOTTOM']); + } + if (isset($properties['BORDER-LEFT'])) { + $objattr['border_left'] = $this->mpdf->border_details($properties['BORDER-LEFT']); + } + if (isset($properties['BORDER-RIGHT'])) { + $objattr['border_right'] = $this->mpdf->border_details($properties['BORDER-RIGHT']); + } + + if (isset($properties['VERTICAL-ALIGN'])) { + $objattr['vertical-align'] = self::ALIGN[strtolower($properties['VERTICAL-ALIGN'])]; + } + $w = 0; + $h = 0; + if (isset($properties['WIDTH'])) { + $w = $this->sizeConverter->convert( + $properties['WIDTH'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } elseif (isset($attr['WIDTH'])) { + $w = $this->sizeConverter->convert($attr['WIDTH'], $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], $this->mpdf->FontSize, false); + } + + if (isset($properties['HEIGHT'])) { + $h = $this->sizeConverter->convert( + $properties['HEIGHT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } elseif (isset($attr['HEIGHT'])) { + $h = $this->sizeConverter->convert($attr['HEIGHT'], $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], $this->mpdf->FontSize, false); + } + + if (isset($properties['OPACITY']) && $properties['OPACITY'] > 0 && $properties['OPACITY'] <= 1) { + $objattr['opacity'] = $properties['OPACITY']; + } + if ($this->mpdf->HREF) { + if (strpos($this->mpdf->HREF, '.') === false && strpos($this->mpdf->HREF, '@') !== 0) { + $href = $this->mpdf->HREF; + while (array_key_exists($href, $this->mpdf->internallink)) { + $href = '#' . $href; + } + $this->mpdf->internallink[$href] = $this->mpdf->AddLink(); + $objattr['link'] = $this->mpdf->internallink[$href]; + } else { + $objattr['link'] = $this->mpdf->HREF; + } + } + $extraheight = $objattr['padding_top'] + $objattr['padding_bottom'] + $objattr['margin_top'] + + $objattr['margin_bottom'] + $objattr['border_top']['w'] + $objattr['border_bottom']['w']; + + $extrawidth = $objattr['padding_left'] + $objattr['padding_right'] + $objattr['margin_left'] + + $objattr['margin_right'] + $objattr['border_left']['w'] + $objattr['border_right']['w']; + + $svg = $this->makeSVG($type, $value, $max, $min, $optimum, $low, $high); + //Save to local file + $srcpath = $this->cache->write('/_tempSVG' . uniqid(random_int(1, 100000), true) . '_' . strtolower($tag) . '.svg', $svg); + $orig_srcpath = $srcpath; + $this->mpdf->GetFullPath($srcpath); + + $info = $this->imageProcessor->getImage($srcpath, true, true, $orig_srcpath); + if (!$info) { + $info = $this->imageProcessor->getImage($this->mpdf->noImageFile); + if ($info) { + $srcpath = $this->mpdf->noImageFile; + $w = ($info['w'] * (25.4 / $this->mpdf->img_dpi)); + $h = ($info['h'] * (25.4 / $this->mpdf->img_dpi)); + } + } + if (!$info) { + return; + } + + $objattr['file'] = $srcpath; + + // Default width and height calculation if needed + if ($w == 0 && $h == 0) { + // SVG units are pixels + $w = $this->mpdf->FontSize / (10 / Mpdf::SCALE) * abs($info['w']) / Mpdf::SCALE; + $h = $this->mpdf->FontSize / (10 / Mpdf::SCALE) * abs($info['h']) / Mpdf::SCALE; + } + + // IF WIDTH OR HEIGHT SPECIFIED + if ($w == 0) { + $w = $info['h'] ? abs($h * $info['w'] / $info['h']) : INF; + } + if ($h == 0) { + $h = $info['w'] ? abs($w * $info['h'] / $info['w']) : INF; + } + + // Resize to maximum dimensions of page + $maxWidth = $this->mpdf->blk[$this->mpdf->blklvl]['inner_width']; + $maxHeight = $this->mpdf->h - ($this->mpdf->tMargin + $this->mpdf->bMargin + 1); + if ($this->mpdf->fullImageHeight) { + $maxHeight = $this->mpdf->fullImageHeight; + } + if (($w + $extrawidth) > ($maxWidth + 0.0001)) { // mPDF 5.7.4 0.0001 to allow for rounding errors when w==maxWidth + $w = $maxWidth - $extrawidth; + $h = abs($w * $info['h'] / $info['w']); + } + + if ($h + $extraheight > $maxHeight) { + $h = $maxHeight - $extraheight; + $w = abs($h * $info['w'] / $info['h']); + } + $objattr['type'] = 'image'; + $objattr['itype'] = $info['type']; + + $objattr['orig_h'] = $info['h']; + $objattr['orig_w'] = $info['w']; + $objattr['wmf_x'] = $info['x']; + $objattr['wmf_y'] = $info['y']; + $objattr['height'] = $h + $extraheight; + $objattr['width'] = $w + $extrawidth; + $objattr['image_height'] = $h; + $objattr['image_width'] = $w; + $e = "\xbb\xa4\xactype=image,objattr=" . serialize($objattr) . "\xbb\xa4\xac"; + if ($this->mpdf->tableLevel) { + $this->mpdf->_saveCellTextBuffer($e, $this->mpdf->HREF); + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s'] += $objattr['width']; + } else { + $this->mpdf->_saveTextBuffer($e, $this->mpdf->HREF); + } + } + + public function close(&$ahtml, &$ihtml) + { + parent::close($ahtml, $ihtml); + $this->mpdf->ignorefollowingspaces = false; + $this->mpdf->inMeter = false; + } + + protected function makeSVG($type, $value, $max, $min, $optimum, $low, $high) + { + if ($type == '2') { + ///////////////////////////////////////////////////////////////////////////////////// + ///////// CUSTOM <meter type="2"> + ///////////////////////////////////////////////////////////////////////////////////// + $h = 10; + $w = 160; + $border_radius = 0.143; // Factor of Height + + $svg = '<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> +<svg width="' . $w . 'px" height="' . $h . 'px" viewBox="0 0 ' . $w . ' ' . $h . '" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" ><g> + + +<defs> +<linearGradient id="GrGRAY" x1="0" y1="0" x2="0" y2="1" gradientUnits="boundingBox"> +<stop offset="0%" stop-color="rgb(222, 222, 222)" /> +<stop offset="20%" stop-color="rgb(232, 232, 232)" /> +<stop offset="25%" stop-color="rgb(232, 232, 232)" /> +<stop offset="100%" stop-color="rgb(182, 182, 182)" /> +</linearGradient> + +</defs> +'; + $svg .= '<rect x="0" y="0" width="' . $w . '" height="' . $h . '" fill="#f4f4f4" stroke="none" />'; + + // LOW to HIGH region + //if ($low && $high && ($low != $min || $high != $max)) { + if ($low && $high) { + $barx = (($low - $min) / ($max - $min) ) * $w; + $barw = (($high - $low) / ($max - $min) ) * $w; + $svg .= '<rect x="' . $barx . '" y="0" width="' . $barw . '" height="' . $h . '" fill="url(#GrGRAY)" stroke="#888888" stroke-width="0.5px" />'; + } + + // OPTIMUM Marker (? AVERAGE) + if ($optimum) { + $barx = (($optimum - $min) / ($max - $min) ) * $w; + $barw = $h / 2; + $barcol = '#888888'; + $svg .= '<rect x="' . $barx . '" y="0" rx="' . ($h * $border_radius) . 'px" ry="' . ($h * $border_radius) . 'px" width="' . $barw . '" height="' . $h . '" fill="' . $barcol . '" stroke="none" />'; + } + + // VALUE Marker + if ($value) { + if ($min != $low && $value < $low) { + $col = 'orange'; + } elseif ($max != $high && $value > $high) { + $col = 'orange'; + } else { + $col = '#008800'; + } + $cx = (($value - $min) / ($max - $min) ) * $w; + $cy = $h / 2; + $rx = $h / 3.5; + $ry = $h / 2.2; + $svg .= '<ellipse fill="' . $col . '" stroke="#000000" stroke-width="0.5px" cx="' . $cx . '" cy="' . $cy . '" rx="' . $rx . '" ry="' . $ry . '"/>'; + } + + // BoRDER + $svg .= '<rect x="0" y="0" width="' . $w . '" height="' . $h . '" fill="none" stroke="#888888" stroke-width="0.5px" />'; + + $svg .= '</g></svg>'; + } elseif ($type == '3') { + ///////////////////////////////////////////////////////////////////////////////////// + ///////// CUSTOM <meter type="2"> + ///////////////////////////////////////////////////////////////////////////////////// + $h = 10; + $w = 100; + $border_radius = 0.143; // Factor of Height + + $svg = '<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> +<svg width="' . $w . 'px" height="' . $h . 'px" viewBox="0 0 ' . $w . ' ' . $h . '" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" ><g> + + +<defs> +<linearGradient id="GrGRAY" x1="0" y1="0" x2="0" y2="1" gradientUnits="boundingBox"> +<stop offset="0%" stop-color="rgb(222, 222, 222)" /> +<stop offset="20%" stop-color="rgb(232, 232, 232)" /> +<stop offset="25%" stop-color="rgb(232, 232, 232)" /> +<stop offset="100%" stop-color="rgb(182, 182, 182)" /> +</linearGradient> + +</defs> +'; + $svg .= '<rect x="0" y="0" width="' . $w . '" height="' . $h . '" fill="#f4f4f4" stroke="none" />'; + + // LOW to HIGH region + if ($low && $high && ($low != $min || $high != $max)) { + //if ($low && $high) { + $barx = (($low - $min) / ($max - $min) ) * $w; + $barw = (($high - $low) / ($max - $min) ) * $w; + $svg .= '<rect x="' . $barx . '" y="0" width="' . $barw . '" height="' . $h . '" fill="url(#GrGRAY)" stroke="#888888" stroke-width="0.5px" />'; + } + + // OPTIMUM Marker (? AVERAGE) + if ($optimum) { + $barx = (($optimum - $min) / ($max - $min) ) * $w; + $barw = $h / 2; + $barcol = '#888888'; + $svg .= '<rect x="' . $barx . '" y="0" rx="' . ($h * $border_radius) . 'px" ry="' . ($h * $border_radius) . 'px" width="' . $barw . '" height="' . $h . '" fill="' . $barcol . '" stroke="none" />'; + } + + // VALUE Marker + if ($value) { + if ($min != $low && $value < $low) { + $col = 'orange'; + } elseif ($max != $high && $value > $high) { + $col = 'orange'; + } else { + $col = 'orange'; + } + $cx = (($value - $min) / ($max - $min) ) * $w; + $cy = $h / 2; + $rx = $h / 2.2; + $ry = $h / 2.2; + $svg .= '<ellipse fill="' . $col . '" stroke="#000000" stroke-width="0.5px" cx="' . $cx . '" cy="' . $cy . '" rx="' . $rx . '" ry="' . $ry . '"/>'; + } + + // BoRDER + $svg .= '<rect x="0" y="0" width="' . $w . '" height="' . $h . '" fill="none" stroke="#888888" stroke-width="0.5px" />'; + + $svg .= '</g></svg>'; + } else { + ///////////////////////////////////////////////////////////////////////////////////// + ///////// DEFAULT <meter> + ///////////////////////////////////////////////////////////////////////////////////// + $h = 10; + $w = 50; + $border_radius = 0.143; // Factor of Height + + $svg = '<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> +<svg width="' . $w . 'px" height="' . $h . 'px" viewBox="0 0 ' . $w . ' ' . $h . '" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" ><g> + +<defs> +<linearGradient id="GrGRAY" x1="0" y1="0" x2="0" y2="1" gradientUnits="boundingBox"> +<stop offset="0%" stop-color="rgb(222, 222, 222)" /> +<stop offset="20%" stop-color="rgb(232, 232, 232)" /> +<stop offset="25%" stop-color="rgb(232, 232, 232)" /> +<stop offset="100%" stop-color="rgb(182, 182, 182)" /> +</linearGradient> + +<linearGradient id="GrRED" x1="0" y1="0" x2="0" y2="1" gradientUnits="boundingBox"> +<stop offset="0%" stop-color="rgb(255, 162, 162)" /> +<stop offset="20%" stop-color="rgb(255, 218, 218)" /> +<stop offset="25%" stop-color="rgb(255, 218, 218)" /> +<stop offset="100%" stop-color="rgb(255, 0, 0)" /> +</linearGradient> + +<linearGradient id="GrGREEN" x1="0" y1="0" x2="0" y2="1" gradientUnits="boundingBox"> +<stop offset="0%" stop-color="rgb(102, 230, 102)" /> +<stop offset="20%" stop-color="rgb(218, 255, 218)" /> +<stop offset="25%" stop-color="rgb(218, 255, 218)" /> +<stop offset="100%" stop-color="rgb(0, 148, 0)" /> +</linearGradient> + +<linearGradient id="GrBLUE" x1="0" y1="0" x2="0" y2="1" gradientUnits="boundingBox"> +<stop offset="0%" stop-color="rgb(102, 102, 230)" /> +<stop offset="20%" stop-color="rgb(238, 238, 238)" /> +<stop offset="25%" stop-color="rgb(238, 238, 238)" /> +<stop offset="100%" stop-color="rgb(0, 0, 128)" /> +</linearGradient> + +<linearGradient id="GrORANGE" x1="0" y1="0" x2="0" y2="1" gradientUnits="boundingBox"> +<stop offset="0%" stop-color="rgb(255, 186, 0)" /> +<stop offset="20%" stop-color="rgb(255, 238, 168)" /> +<stop offset="25%" stop-color="rgb(255, 238, 168)" /> +<stop offset="100%" stop-color="rgb(255, 155, 0)" /> +</linearGradient> +</defs> + +<rect x="0" y="0" rx="' . ($h * $border_radius) . 'px" ry="' . ($h * $border_radius) . 'px" width="' . $w . '" height="' . $h . '" fill="url(#GrGRAY)" stroke="none" /> +'; + + if ($value) { + $barw = (($value - $min) / ($max - $min) ) * $w; + if ($optimum < $low) { + if ($value < $low) { + $barcol = 'url(#GrGREEN)'; + } elseif ($value > $high) { + $barcol = 'url(#GrRED)'; + } else { + $barcol = 'url(#GrORANGE)'; + } + } elseif ($optimum > $high) { + if ($value < $low) { + $barcol = 'url(#GrRED)'; + } elseif ($value > $high) { + $barcol = 'url(#GrGREEN)'; + } else { + $barcol = 'url(#GrORANGE)'; + } + } else { + if ($value < $low) { + $barcol = 'url(#GrORANGE)'; + } elseif ($value > $high) { + $barcol = 'url(#GrORANGE)'; + } else { + $barcol = 'url(#GrGREEN)'; + } + } + $svg .= '<rect x="0" y="0" rx="' . ($h * $border_radius) . 'px" ry="' . ($h * $border_radius) . 'px" width="' . $barw . '" height="' . $h . '" fill="' . $barcol . '" stroke="none" />'; + } + + $svg .= '</g></svg>'; + } + + + return $svg; + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Nav.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Nav.php new file mode 100644 index 000000000..7845cfa5d --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Nav.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Nav extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/NewColumn.php b/src/bb-vendor/mpdf/mpdf/src/Tag/NewColumn.php new file mode 100644 index 000000000..a9ff5a1bf --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/NewColumn.php @@ -0,0 +1,18 @@ +<?php + +namespace Mpdf\Tag; + +class NewColumn extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $this->mpdf->ignorefollowingspaces = true; + $this->mpdf->NewColumn(); + $this->mpdf->ColumnAdjust = false; // disables all column height adjustment for the page. + } + + public function close(&$ahtml, &$ihtml) + { + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/NewPage.php b/src/bb-vendor/mpdf/mpdf/src/Tag/NewPage.php new file mode 100644 index 000000000..3a7f50f22 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/NewPage.php @@ -0,0 +1,8 @@ +<?php + +namespace Mpdf\Tag; + +class NewPage extends FormFeed +{ + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Ol.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Ol.php new file mode 100644 index 000000000..75deba9a3 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Ol.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Ol extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Option.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Option.php new file mode 100644 index 000000000..c5233d1d2 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Option.php @@ -0,0 +1,38 @@ +<?php + +namespace Mpdf\Tag; + +use Mpdf\Utils\UtfString; + +class Option extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $this->mpdf->lastoptionaltag = ''; + $this->mpdf->selectoption['ACTIVE'] = true; + $this->mpdf->selectoption['currentSEL'] = false; + if (empty($this->mpdf->selectoption)) { + $this->mpdf->selectoption['MAXWIDTH'] = ''; + $this->mpdf->selectoption['SELECTED'] = ''; + } + if (isset($attr['SELECTED'])) { + $this->mpdf->selectoption['SELECTED'] = ''; + $this->mpdf->selectoption['currentSEL'] = true; + } + if (isset($attr['VALUE'])) { + $attr['VALUE'] = UtfString::strcode2utf($attr['VALUE']); + $attr['VALUE'] = $this->mpdf->lesser_entity_decode($attr['VALUE']); + if ($this->mpdf->onlyCoreFonts) { + $attr['VALUE'] = mb_convert_encoding($attr['VALUE'], $this->mpdf->mb_enc, 'UTF-8'); + } + } + $this->mpdf->selectoption['currentVAL'] = $attr['VALUE']; + } + + public function close(&$ahtml, &$ihtml) + { + $this->mpdf->selectoption['ACTIVE'] = false; + $this->mpdf->lastoptionaltag = ''; + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/P.php b/src/bb-vendor/mpdf/mpdf/src/Tag/P.php new file mode 100644 index 000000000..61b2a80c0 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/P.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class P extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/PageBreak.php b/src/bb-vendor/mpdf/mpdf/src/Tag/PageBreak.php new file mode 100644 index 000000000..9f721c4b5 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/PageBreak.php @@ -0,0 +1,8 @@ +<?php + +namespace Mpdf\Tag; + +class PageBreak extends FormFeed +{ + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/PageFooter.php b/src/bb-vendor/mpdf/mpdf/src/Tag/PageFooter.php new file mode 100644 index 000000000..7b18a617b --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/PageFooter.php @@ -0,0 +1,153 @@ +<?php + +namespace Mpdf\Tag; + +use Mpdf\Mpdf; + +class PageFooter extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $tag = $this->getTagName(); + $this->mpdf->ignorefollowingspaces = true; + $pname = '_nonhtmldefault'; + if ($attr['NAME']) { + $pname = $attr['NAME']; + } // mPDF 6 + + $p = []; // mPDF 6 + $p['L'] = []; + $p['C'] = []; + $p['R'] = []; + $p['L']['font-style'] = ''; + $p['C']['font-style'] = ''; + $p['R']['font-style'] = ''; + + if (isset($attr['CONTENT-LEFT'])) { + $p['L']['content'] = $attr['CONTENT-LEFT']; + } + if (isset($attr['CONTENT-CENTER'])) { + $p['C']['content'] = $attr['CONTENT-CENTER']; + } + if (isset($attr['CONTENT-RIGHT'])) { + $p['R']['content'] = $attr['CONTENT-RIGHT']; + } + + if (isset($attr['HEADER-STYLE']) || isset($attr['FOOTER-STYLE'])) { // font-family,size,weight,style,color + if ($tag === 'PAGEHEADER') { + $properties = $this->cssManager->readInlineCSS($attr['HEADER-STYLE']); + } else { + $properties = $this->cssManager->readInlineCSS($attr['FOOTER-STYLE']); + } + if (isset($properties['FONT-FAMILY'])) { + $p['L']['font-family'] = $properties['FONT-FAMILY']; + $p['C']['font-family'] = $properties['FONT-FAMILY']; + $p['R']['font-family'] = $properties['FONT-FAMILY']; + } + if (isset($properties['FONT-SIZE'])) { + $p['L']['font-size'] = $this->sizeConverter->convert($properties['FONT-SIZE']) * Mpdf::SCALE; + $p['C']['font-size'] = $this->sizeConverter->convert($properties['FONT-SIZE']) * Mpdf::SCALE; + $p['R']['font-size'] = $this->sizeConverter->convert($properties['FONT-SIZE']) * Mpdf::SCALE; + } + if (isset($properties['FONT-WEIGHT']) && $properties['FONT-WEIGHT'] === 'bold') { + $p['L']['font-style'] = 'B'; + $p['C']['font-style'] = 'B'; + $p['R']['font-style'] = 'B'; + } + if (isset($properties['FONT-STYLE']) && $properties['FONT-STYLE'] === 'italic') { + $p['L']['font-style'] .= 'I'; + $p['C']['font-style'] .= 'I'; + $p['R']['font-style'] .= 'I'; + } + if (isset($properties['COLOR'])) { + $p['L']['color'] = $properties['COLOR']; + $p['C']['color'] = $properties['COLOR']; + $p['R']['color'] = $properties['COLOR']; + } + } + if (isset($attr['HEADER-STYLE-LEFT']) || isset($attr['FOOTER-STYLE-LEFT'])) { + if ($tag === 'PAGEHEADER') { + $properties = $this->cssManager->readInlineCSS($attr['HEADER-STYLE-LEFT']); + } else { + $properties = $this->cssManager->readInlineCSS($attr['FOOTER-STYLE-LEFT']); + } + if (isset($properties['FONT-FAMILY'])) { + $p['L']['font-family'] = $properties['FONT-FAMILY']; + } + if (isset($properties['FONT-SIZE'])) { + $p['L']['font-size'] = $this->sizeConverter->convert($properties['FONT-SIZE']) * Mpdf::SCALE; + } + if (isset($properties['FONT-WEIGHT']) && $properties['FONT-WEIGHT'] === 'bold') { + $p['L']['font-style'] = 'B'; + } + if (isset($properties['FONT-STYLE']) && $properties['FONT-STYLE'] === 'italic') { + $p['L']['font-style'] .='I'; + } + if (isset($properties['COLOR'])) { + $p['L']['color'] = $properties['COLOR']; + } + } + if (isset($attr['HEADER-STYLE-CENTER']) || isset($attr['FOOTER-STYLE-CENTER'])) { + if ($tag === 'PAGEHEADER') { + $properties = $this->cssManager->readInlineCSS($attr['HEADER-STYLE-CENTER']); + } else { + $properties = $this->cssManager->readInlineCSS($attr['FOOTER-STYLE-CENTER']); + } + if (isset($properties['FONT-FAMILY'])) { + $p['C']['font-family'] = $properties['FONT-FAMILY']; + } + if (isset($properties['FONT-SIZE'])) { + $p['C']['font-size'] = $this->sizeConverter->convert($properties['FONT-SIZE']) * Mpdf::SCALE; + } + if (isset($properties['FONT-WEIGHT']) && $properties['FONT-WEIGHT'] === 'bold') { + $p['C']['font-style'] = 'B'; + } + if (isset($properties['FONT-STYLE']) && $properties['FONT-STYLE'] === 'italic') { + $p['C']['font-style'] .= 'I'; + } + if (isset($properties['COLOR'])) { + $p['C']['color'] = $properties['COLOR']; + } + } + if (isset($attr['HEADER-STYLE-RIGHT']) || isset($attr['FOOTER-STYLE-RIGHT'])) { + if ($tag === 'PAGEHEADER') { + $properties = $this->cssManager->readInlineCSS($attr['HEADER-STYLE-RIGHT']); + } else { + $properties = $this->cssManager->readInlineCSS($attr['FOOTER-STYLE-RIGHT']); + } + if (isset($properties['FONT-FAMILY'])) { + $p['R']['font-family'] = $properties['FONT-FAMILY']; + } + if (isset($properties['FONT-SIZE'])) { + $p['R']['font-size'] = $this->sizeConverter->convert($properties['FONT-SIZE']) * Mpdf::SCALE; + } + if (isset($properties['FONT-WEIGHT']) && $properties['FONT-WEIGHT'] === 'bold') { + $p['R']['font-style'] = 'B'; + } + if (isset($properties['FONT-STYLE']) && $properties['FONT-STYLE'] === 'italic') { + $p['R']['font-style'] .= 'I'; + } + if (isset($properties['COLOR'])) { + $p['R']['color'] = $properties['COLOR']; + } + } + if (!empty($attr['LINE'])) { // 0|1|on|off + $lineset = 0; + if ($attr['LINE'] == '1' || strtoupper($attr['LINE']) === 'ON') { + $lineset = 1; + } + $p['line'] = $lineset; + } + // mPDF 6 + if ($tag === 'PAGEHEADER') { + $this->mpdf->DefHeaderByName($pname, $p); + } else { + $this->mpdf->DefFooterByName($pname, $p); + } + } + + public function close(&$ahtml, &$ihtml) + { + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/PageHeader.php b/src/bb-vendor/mpdf/mpdf/src/Tag/PageHeader.php new file mode 100644 index 000000000..9920ee789 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/PageHeader.php @@ -0,0 +1,8 @@ +<?php + +namespace Mpdf\Tag; + +class PageHeader extends PageFooter +{ + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Pre.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Pre.php new file mode 100644 index 000000000..ef21606ea --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Pre.php @@ -0,0 +1,13 @@ +<?php + +namespace Mpdf\Tag; + +class Pre extends BlockTag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $this->mpdf->ispre = true; // ADDED - Prevents left trim of textbuffer in printbuffer() + parent::open($attr, $ahtml, $ihtml); // TODO: Change the autogenerated stub + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Progress.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Progress.php new file mode 100644 index 000000000..32e22daa0 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Progress.php @@ -0,0 +1,72 @@ +<?php + +namespace Mpdf\Tag; + +class Progress extends Meter +{ + protected function makeSVG($type, $value, $max, $min, $optimum, $low, $high) + { + $svg = ''; + + if ($type == '2') { + ///////////////////////////////////////////////////////////////////////////////////// + ///////// CUSTOM <progress type="2"> + ///////////////////////////////////////////////////////////////////////////////////// + } else { + ///////////////////////////////////////////////////////////////////////////////////// + ///////// DEFAULT <progress> + ///////////////////////////////////////////////////////////////////////////////////// + $h = 10; + $w = 100; + $border_radius = 0.143; // Factor of Height + + if ($value or $value === '0') { + $fill = 'url(#GrGRAY)'; + } else { + $fill = '#f8f8f8'; + } + + $svg = '<svg width="' . $w . 'px" height="' . $h . 'px" viewBox="0 0 ' . $w . ' ' . $h . '"><g> + +<defs> +<linearGradient id="GrGRAY" x1="0" y1="0" x2="0" y2="1" gradientUnits="boundingBox"> +<stop offset="0%" stop-color="rgb(222, 222, 222)" /> +<stop offset="20%" stop-color="rgb(232, 232, 232)" /> +<stop offset="25%" stop-color="rgb(232, 232, 232)" /> +<stop offset="100%" stop-color="rgb(182, 182, 182)" /> +</linearGradient> + +<linearGradient id="GrGREEN" x1="0" y1="0" x2="0" y2="1" gradientUnits="boundingBox"> +<stop offset="0%" stop-color="rgb(102, 230, 102)" /> +<stop offset="20%" stop-color="rgb(218, 255, 218)" /> +<stop offset="25%" stop-color="rgb(218, 255, 218)" /> +<stop offset="100%" stop-color="rgb(0, 148, 0)" /> +</linearGradient> + +</defs> + +<rect x="0" y="0" rx="' . ($h * $border_radius) . 'px" ry="' . ($h * $border_radius) . 'px" width="' . $w . '" height="' . $h . '" fill="' . $fill . '" stroke="none" /> +'; + + if ($value) { + $barw = (($value - $min) / ($max - $min) ) * $w; + $barcol = 'url(#GrGREEN)'; + $svg .= '<rect x="0" y="0" rx="' . ($h * $border_radius) . 'px" ry="' . ($h * $border_radius) . 'px" width="' . $barw . '" height="' . $h . '" fill="' . $barcol . '" stroke="none" />'; + } + + + // Borders + $svg .= '<rect x="0" y="0" rx="' . ($h * $border_radius) . 'px" ry="' . ($h * $border_radius) . 'px" width="' . $w . '" height="' . $h . '" fill="none" stroke="#888888" stroke-width="0.5px" />'; + if ($value) { + // $svg .= '<rect x="0" y="0" rx="'.($h*$border_radius).'px" ry="'.($h*$border_radius).'px" width="'.$barw.'" height="'.$h.'" fill="none" stroke="#888888" stroke-width="0.5px" />'; + } + + + $svg .= '</g></svg>'; + } + + + return $svg; + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Q.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Q.php new file mode 100644 index 000000000..3e0567412 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Q.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Q extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/S.php b/src/bb-vendor/mpdf/mpdf/src/Tag/S.php new file mode 100644 index 000000000..37aa8327b --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/S.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class S extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Samp.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Samp.php new file mode 100644 index 000000000..c541cdd8e --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Samp.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Samp extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Section.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Section.php new file mode 100644 index 000000000..1c41a7b0c --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Section.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Section extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Select.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Select.php new file mode 100644 index 000000000..1d3c131ac --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Select.php @@ -0,0 +1,154 @@ +<?php + +namespace Mpdf\Tag; + +use Mpdf\Mpdf; + +class Select extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $this->mpdf->lastoptionaltag = ''; // Save current HTML specified optional endtag + $this->mpdf->InlineProperties['SELECT'] = $this->mpdf->saveInlineProperties(); + $properties = $this->cssManager->MergeCSS('', 'SELECT', $attr); + if (isset($properties['FONT-FAMILY'])) { + $this->mpdf->SetFont($properties['FONT-FAMILY'], $this->mpdf->FontStyle, 0, false); + } + if (isset($properties['FONT-SIZE'])) { + $mmsize = $this->sizeConverter->convert($properties['FONT-SIZE'], $this->mpdf->default_font_size / Mpdf::SCALE); + $this->mpdf->SetFontSize($mmsize * Mpdf::SCALE, false); + } + if (isset($attr['SPELLCHECK']) && strtolower($attr['SPELLCHECK']) === 'true') { + $this->mpdf->selectoption['SPELLCHECK'] = true; + } + + if (isset($properties['COLOR'])) { + $this->mpdf->selectoption['COLOR'] = $this->colorConverter->convert($properties['COLOR'], $this->mpdf->PDFAXwarnings); + } + $this->mpdf->specialcontent = 'type=select'; + if (isset($attr['DISABLED'])) { + $this->mpdf->selectoption['DISABLED'] = $attr['DISABLED']; + } + if (isset($attr['READONLY'])) { + $this->mpdf->selectoption['READONLY'] = $attr['READONLY']; + } + if (isset($attr['REQUIRED'])) { + $this->mpdf->selectoption['REQUIRED'] = $attr['REQUIRED']; + } + if (isset($attr['EDITABLE'])) { + $this->mpdf->selectoption['EDITABLE'] = $attr['EDITABLE']; + } + if (isset($attr['TITLE'])) { + $this->mpdf->selectoption['TITLE'] = $attr['TITLE']; + } + if (isset($attr['MULTIPLE'])) { + $this->mpdf->selectoption['MULTIPLE'] = $attr['MULTIPLE']; + } + if (isset($attr['SIZE']) && $attr['SIZE'] > 1) { + $this->mpdf->selectoption['SIZE'] = $attr['SIZE']; + } + if ($this->mpdf->useActiveForms) { + if (isset($attr['NAME'])) { + $this->mpdf->selectoption['NAME'] = $attr['NAME']; + } + if (isset($attr['ONCHANGE'])) { + $this->mpdf->selectoption['ONCHANGE'] = $attr['ONCHANGE']; + } + } + } + + public function close(&$ahtml, &$ihtml) + { + $this->mpdf->ignorefollowingspaces = false; + $this->mpdf->lastoptionaltag = ''; + $texto = ''; + $OTLdata = false; + if (isset($this->mpdf->selectoption['SELECTED'])) { + $texto = $this->mpdf->selectoption['SELECTED']; + } + if (isset($this->mpdf->selectoption['SELECTED-OTLDATA'])) { + $OTLdata = $this->mpdf->selectoption['SELECTED-OTLDATA']; + } + + if ($this->mpdf->useActiveForms) { + $w = $this->mpdf->selectoption['MAXWIDTH']; + } else { + $w = $this->mpdf->GetStringWidth($texto, true, $OTLdata); + } + if ($w == 0) { + $w = 5; + } + $objattr['type'] = 'select'; + $objattr['text'] = $texto; + $objattr['OTLdata'] = $OTLdata; + if (isset($this->mpdf->selectoption['NAME'])) { + $objattr['fieldname'] = $this->mpdf->selectoption['NAME']; + } + if (isset($this->mpdf->selectoption['READONLY'])) { + $objattr['readonly'] = true; + } + if (isset($this->mpdf->selectoption['REQUIRED'])) { + $objattr['required'] = true; + } + if (isset($this->mpdf->selectoption['SPELLCHECK'])) { + $objattr['spellcheck'] = true; + } + if (isset($this->mpdf->selectoption['EDITABLE'])) { + $objattr['editable'] = true; + } + if (isset($this->mpdf->selectoption['ONCHANGE'])) { + $objattr['onChange'] = $this->mpdf->selectoption['ONCHANGE']; + } + if (isset($this->mpdf->selectoption['ITEMS'])) { + $objattr['items'] = $this->mpdf->selectoption['ITEMS']; + } + if (isset($this->mpdf->selectoption['MULTIPLE'])) { + $objattr['multiple'] = $this->mpdf->selectoption['MULTIPLE']; + } + if (isset($this->mpdf->selectoption['DISABLED'])) { + $objattr['disabled'] = $this->mpdf->selectoption['DISABLED']; + } + if (isset($this->mpdf->selectoption['TITLE'])) { + $objattr['title'] = $this->mpdf->selectoption['TITLE']; + } + if (isset($this->mpdf->selectoption['COLOR'])) { + $objattr['color'] = $this->mpdf->selectoption['COLOR']; + } + if (isset($this->mpdf->selectoption['SIZE'])) { + $objattr['size'] = $this->mpdf->selectoption['SIZE']; + } + $rows = 1; + if (isset($objattr['size']) && $objattr['size'] > 1) { + $rows = $objattr['size']; + } + + $objattr['fontfamily'] = $this->mpdf->FontFamily; + $objattr['fontsize'] = $this->mpdf->FontSizePt; + + $objattr['width'] = $w + ($this->form->form_element_spacing['select']['outer']['h'] * 2) + + ($this->form->form_element_spacing['select']['inner']['h'] * 2) + ($this->mpdf->FontSize * 1.4); + + $objattr['height'] = ($this->mpdf->FontSize * $rows) + ($this->form->form_element_spacing['select']['outer']['v'] * 2) + + ($this->form->form_element_spacing['select']['inner']['v'] * 2); + + $e = "\xbb\xa4\xactype=select,objattr=" . serialize($objattr) . "\xbb\xa4\xac"; + + // Output it to buffers + if ($this->mpdf->tableLevel) { // *TABLES* + $this->mpdf->_saveCellTextBuffer($e, $this->mpdf->HREF); + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s'] += $objattr['width']; // *TABLES* + } // *TABLES* + else { // *TABLES* + $this->mpdf->_saveTextBuffer($e, $this->mpdf->HREF); + } // *TABLES* + + $this->mpdf->selectoption = []; + $this->mpdf->specialcontent = ''; + + if ($this->mpdf->InlineProperties['SELECT']) { + $this->mpdf->restoreInlineProperties($this->mpdf->InlineProperties['SELECT']); + } + unset($this->mpdf->InlineProperties['SELECT']); + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/SetHtmlPageFooter.php b/src/bb-vendor/mpdf/mpdf/src/Tag/SetHtmlPageFooter.php new file mode 100644 index 000000000..6cb524245 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/SetHtmlPageFooter.php @@ -0,0 +1,73 @@ +<?php + +namespace Mpdf\Tag; + +class SetHtmlPageFooter extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $tag = $this->getTagName(); + $this->mpdf->ignorefollowingspaces = true; + + $pname = '_default'; + if (!empty($attr['NAME'])) { + $pname = $attr['NAME']; + } elseif ($tag === 'SETPAGEHEADER' || $tag === 'SETPAGEFOOTER') { + $pname = '_nonhtmldefault'; + } // mPDF 6 + + if (!empty($attr['PAGE'])) { // O|odd|even|E|ALL|[blank] + $side = 'odd'; + if (strtoupper($attr['PAGE']) === 'O' || strtoupper($attr['PAGE']) === 'ODD') { + $side = 'odd'; + } elseif (strtoupper($attr['PAGE']) === 'E' || strtoupper($attr['PAGE']) === 'EVEN') { + $side = 'even'; + } elseif (strtoupper($attr['PAGE']) === 'ALL') { + $side = 'both'; + } + } else { + $side = 'odd'; + } + if (!empty($attr['VALUE'])) { // -1|1|on|off + $set = 1; + if ($attr['VALUE'] == '1' || strtoupper($attr['VALUE']) === 'ON') { + $set = 1; + } elseif ($attr['VALUE'] == '-1' || strtoupper($attr['VALUE']) === 'OFF') { + $set = 0; + } + } else { + $set = 1; + } + $write = 0; + if (!empty($attr['SHOW-THIS-PAGE']) && ($tag === 'SETHTMLPAGEHEADER' || $tag === 'SETPAGEHEADER')) { + $write = 1; + } + if ($side === 'odd' || $side === 'both') { + if ($set && ($tag === 'SETHTMLPAGEHEADER' || $tag === 'SETPAGEHEADER')) { + $this->mpdf->SetHTMLHeader($this->mpdf->pageHTMLheaders[$pname], 'O', $write); + } elseif ($set && ($tag === 'SETHTMLPAGEFOOTER' || $tag === 'SETPAGEFOOTER')) { + $this->mpdf->SetHTMLFooter($this->mpdf->pageHTMLfooters[$pname], 'O'); + } elseif ($tag === 'SETHTMLPAGEHEADER' || $tag === 'SETPAGEHEADER') { + $this->mpdf->SetHTMLHeader('', 'O'); + } else { + $this->mpdf->SetHTMLFooter('', 'O'); + } + } + if ($side === 'even' || $side === 'both') { + if ($set && ($tag === 'SETHTMLPAGEHEADER' || $tag === 'SETPAGEHEADER')) { + $this->mpdf->SetHTMLHeader($this->mpdf->pageHTMLheaders[$pname], 'E', $write); + } elseif ($set && ($tag === 'SETHTMLPAGEFOOTER' || $tag === 'SETPAGEFOOTER')) { + $this->mpdf->SetHTMLFooter($this->mpdf->pageHTMLfooters[$pname], 'E'); + } elseif ($tag === 'SETHTMLPAGEHEADER' || $tag === 'SETPAGEHEADER') { + $this->mpdf->SetHTMLHeader('', 'E'); + } else { + $this->mpdf->SetHTMLFooter('', 'E'); + } + } + } + + public function close(&$ahtml, &$ihtml) + { + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/SetHtmlPageHeader.php b/src/bb-vendor/mpdf/mpdf/src/Tag/SetHtmlPageHeader.php new file mode 100644 index 000000000..ea987838b --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/SetHtmlPageHeader.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class SetHtmlPageHeader extends SetHtmlPageFooter +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/SetPageFooter.php b/src/bb-vendor/mpdf/mpdf/src/Tag/SetPageFooter.php new file mode 100644 index 000000000..7596c80a7 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/SetPageFooter.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class SetPageFooter extends SetHtmlPageFooter +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/SetPageHeader.php b/src/bb-vendor/mpdf/mpdf/src/Tag/SetPageHeader.php new file mode 100644 index 000000000..ff83dbc3c --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/SetPageHeader.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class SetPageHeader extends SetHtmlPageFooter +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Small.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Small.php new file mode 100644 index 000000000..686c1ebe4 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Small.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Small extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Span.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Span.php new file mode 100644 index 000000000..eaa3c6a16 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Span.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Span extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Strike.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Strike.php new file mode 100644 index 000000000..65ae0f818 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Strike.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Strike extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Strong.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Strong.php new file mode 100644 index 000000000..5592c3d04 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Strong.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Strong extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Sub.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Sub.php new file mode 100644 index 000000000..66a99e16d --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Sub.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Sub extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/SubstituteTag.php b/src/bb-vendor/mpdf/mpdf/src/Tag/SubstituteTag.php new file mode 100644 index 000000000..602aa5178 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/SubstituteTag.php @@ -0,0 +1,18 @@ +<?php + +namespace Mpdf\Tag; + +abstract class SubstituteTag extends Tag +{ + + public function close(&$ahtml, &$ihtml) + { + $tag = $this->getTagName(); + if ($this->mpdf->InlineProperties[$tag]) { + $this->mpdf->restoreInlineProperties($this->mpdf->InlineProperties[$tag]); + } + unset($this->mpdf->InlineProperties[$tag]); + $ltag = strtolower($tag); + $this->mpdf->$ltag = false; + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Summary.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Summary.php new file mode 100644 index 000000000..977cc44a0 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Summary.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Summary extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Sup.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Sup.php new file mode 100644 index 000000000..97221655a --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Sup.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Sup extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/TBody.php b/src/bb-vendor/mpdf/mpdf/src/Tag/TBody.php new file mode 100644 index 000000000..25b4c4531 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/TBody.php @@ -0,0 +1,23 @@ +<?php + +namespace Mpdf\Tag; + +class TBody extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $this->mpdf->tablethead = 0; + $this->mpdf->tabletfoot = 0; + $this->mpdf->lastoptionaltag = 'TBODY'; // Save current HTML specified optional endtag + $this->cssManager->tbCSSlvl++; + $this->cssManager->MergeCSS('TABLE', 'TBODY', $attr); + } + + public function close(&$ahtml, &$ihtml) + { + $this->mpdf->lastoptionaltag = ''; + unset($this->cssManager->tablecascadeCSS[$this->cssManager->tbCSSlvl]); + $this->cssManager->tbCSSlvl--; + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/TFoot.php b/src/bb-vendor/mpdf/mpdf/src/Tag/TFoot.php new file mode 100644 index 000000000..d3bd8e80a --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/TFoot.php @@ -0,0 +1,59 @@ +<?php + +namespace Mpdf\Tag; + +// TODO: Extend THEAD instead? + +class TFoot extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $this->mpdf->lastoptionaltag = 'TFOOT'; // Save current HTML specified optional endtag + $this->cssManager->tbCSSlvl++; + $this->mpdf->tabletfoot = 1; + $this->mpdf->tablethead = 0; + $properties = $this->cssManager->MergeCSS('TABLE', 'TFOOT', $attr); + if (isset($properties['FONT-WEIGHT'])) { + $this->mpdf->tfoot_font_weight = ''; + if (strtoupper($properties['FONT-WEIGHT']) === 'BOLD') { + $this->mpdf->tfoot_font_weight = 'B'; + } + } + + if (isset($properties['FONT-STYLE'])) { + $this->mpdf->tfoot_font_style = ''; + if (strtoupper($properties['FONT-STYLE']) === 'ITALIC') { + $this->mpdf->tfoot_font_style = 'I'; + } + } + if (isset($properties['FONT-VARIANT'])) { + $this->mpdf->tfoot_font_smCaps = ''; + if (strtoupper($properties['FONT-VARIANT']) === 'SMALL-CAPS') { + $this->mpdf->tfoot_font_smCaps = 'S'; + } + } + + if (isset($properties['VERTICAL-ALIGN'])) { + $this->mpdf->tfoot_valign_default = $properties['VERTICAL-ALIGN']; + } + if (isset($properties['TEXT-ALIGN'])) { + $this->mpdf->tfoot_textalign_default = $properties['TEXT-ALIGN']; + } + } + + public function close(&$ahtml, &$ihtml) + { + $this->mpdf->lastoptionaltag = ''; + unset($this->cssManager->tablecascadeCSS[$this->cssManager->tbCSSlvl]); + $this->cssManager->tbCSSlvl--; + $this->mpdf->tabletfoot = 0; + $this->mpdf->ResetStyles(); + $this->mpdf->tfoot_font_weight = ''; + $this->mpdf->tfoot_font_style = ''; + $this->mpdf->tfoot_font_smCaps = ''; + + $this->mpdf->tfoot_valign_default = ''; + $this->mpdf->tfoot_textalign_default = ''; + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/THead.php b/src/bb-vendor/mpdf/mpdf/src/Tag/THead.php new file mode 100644 index 000000000..acd8015ae --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/THead.php @@ -0,0 +1,58 @@ +<?php + +namespace Mpdf\Tag; + +class THead extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $this->mpdf->lastoptionaltag = 'THEAD'; // Save current HTML specified optional endtag + $this->cssManager->tbCSSlvl++; + $this->mpdf->tablethead = 1; + $this->mpdf->tabletfoot = 0; + $properties = $this->cssManager->MergeCSS('TABLE', 'THEAD', $attr); + if (isset($properties['FONT-WEIGHT'])) { + $this->mpdf->thead_font_weight = ''; + if (strtoupper($properties['FONT-WEIGHT']) === 'BOLD') { + $this->mpdf->thead_font_weight = 'B'; + } + } + + if (isset($properties['FONT-STYLE'])) { + $this->mpdf->thead_font_style = ''; + if (strtoupper($properties['FONT-STYLE']) === 'ITALIC') { + $this->mpdf->thead_font_style = 'I'; + } + } + if (isset($properties['FONT-VARIANT'])) { + $this->mpdf->thead_font_smCaps = ''; + if (strtoupper($properties['FONT-VARIANT']) === 'SMALL-CAPS') { + $this->mpdf->thead_font_smCaps = 'S'; + } + } + + if (isset($properties['VERTICAL-ALIGN'])) { + $this->mpdf->thead_valign_default = $properties['VERTICAL-ALIGN']; + } + if (isset($properties['TEXT-ALIGN'])) { + $this->mpdf->thead_textalign_default = $properties['TEXT-ALIGN']; + } + } + + public function close(&$ahtml, &$ihtml) + { + $this->mpdf->lastoptionaltag = ''; + unset($this->cssManager->tablecascadeCSS[$this->cssManager->tbCSSlvl]); + $this->cssManager->tbCSSlvl--; + $this->mpdf->tablethead = 0; + $this->mpdf->tabletheadjustfinished = true; + $this->mpdf->ResetStyles(); + $this->mpdf->thead_font_weight = ''; + $this->mpdf->thead_font_style = ''; + $this->mpdf->thead_font_smCaps = ''; + + $this->mpdf->thead_valign_default = ''; + $this->mpdf->thead_textalign_default = ''; + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Table.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Table.php new file mode 100644 index 000000000..3261ed67d --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Table.php @@ -0,0 +1,1272 @@ +<?php + +namespace Mpdf\Tag; + +use Mpdf\Css\Border; +use Mpdf\Mpdf; + +class Table extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $this->mpdf->tdbegin = false; + $this->mpdf->lastoptionaltag = ''; + // Disable vertical justification in columns + if ($this->mpdf->ColActive) { + $this->mpdf->colvAlign = ''; + } // *COLUMNS* + if ($this->mpdf->lastblocklevelchange == 1) { + $blockstate = 1; + } // Top margins/padding only + elseif ($this->mpdf->lastblocklevelchange < 1) { + $blockstate = 0; + } // NO margins/padding + // called from block after new div e.g. <div> ... <table> ... Outputs block top margin/border and padding + if (count($this->mpdf->textbuffer) == 0 && $this->mpdf->lastblocklevelchange == 1 && !$this->mpdf->tableLevel && !$this->mpdf->kwt) { + $this->mpdf->newFlowingBlock($this->mpdf->blk[$this->mpdf->blklvl]['width'], $this->mpdf->lineheight, '', false, 1, true, $this->mpdf->blk[$this->mpdf->blklvl]['direction']); + $this->mpdf->finishFlowingBlock(true); // true = END of flowing block + } elseif (!$this->mpdf->tableLevel && count($this->mpdf->textbuffer)) { + $this->mpdf->printbuffer($this->mpdf->textbuffer, $blockstate); + } + + $this->mpdf->textbuffer = []; + $this->mpdf->lastblocklevelchange = -1; + + + + if ($this->mpdf->tableLevel) { // i.e. now a nested table coming... + // Save current level table + $this->mpdf->cell['PARENTCELL'] = $this->mpdf->saveInlineProperties(); + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['baseProperties'] = $this->mpdf->base_table_properties; + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['cells'] = $this->mpdf->cell; + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['currrow'] = $this->mpdf->row; + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['currcol'] = $this->mpdf->col; + } + $this->mpdf->tableLevel++; + $this->cssManager->tbCSSlvl++; + + if ($this->mpdf->tableLevel > 1) { // inherit table properties from cell in which nested + //$this->mpdf->base_table_properties['FONT-KERNING'] = ($this->mpdf->textvar & TextVars::FC_KERNING); // mPDF 6 + $this->mpdf->base_table_properties['LETTER-SPACING'] = $this->mpdf->lSpacingCSS; + $this->mpdf->base_table_properties['WORD-SPACING'] = $this->mpdf->wSpacingCSS; + // mPDF 6 + $direction = $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['direction']; + $txta = $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['a']; + $cellLineHeight = $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['cellLineHeight']; + $cellLineStackingStrategy = $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['cellLineStackingStrategy']; + $cellLineStackingShift = $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['cellLineStackingShift']; + } + + if (isset($this->mpdf->tbctr[$this->mpdf->tableLevel])) { + $this->mpdf->tbctr[$this->mpdf->tableLevel] ++; + } else { + $this->mpdf->tbctr[$this->mpdf->tableLevel] = 1; + } + + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['level'] = $this->mpdf->tableLevel; + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['levelid'] = $this->mpdf->tbctr[$this->mpdf->tableLevel]; + + if ($this->mpdf->tableLevel > $this->mpdf->innermostTableLevel) { + $this->mpdf->innermostTableLevel = $this->mpdf->tableLevel; + } + if ($this->mpdf->tableLevel > 1) { + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['nestedpos'] = [ + $this->mpdf->row, + $this->mpdf->col, + $this->mpdf->tbctr[$this->mpdf->tableLevel - 1], + ]; + } + //++++++++++++++++++++++++++++ + + $this->mpdf->cell = []; + $this->mpdf->col = -1; //int + $this->mpdf->row = -1; //int + $table = &$this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]; + + // New table - any level + $table['direction'] = $this->mpdf->directionality; + $table['bgcolor'] = false; + $table['va'] = false; + $table['txta'] = false; + $table['topntail'] = false; + $table['thead-underline'] = false; + $table['border'] = false; + $table['border_details']['R']['w'] = 0; + $table['border_details']['L']['w'] = 0; + $table['border_details']['T']['w'] = 0; + $table['border_details']['B']['w'] = 0; + $table['border_details']['R']['style'] = ''; + $table['border_details']['L']['style'] = ''; + $table['border_details']['T']['style'] = ''; + $table['border_details']['B']['style'] = ''; + $table['max_cell_border_width']['R'] = 0; + $table['max_cell_border_width']['L'] = 0; + $table['max_cell_border_width']['T'] = 0; + $table['max_cell_border_width']['B'] = 0; + $table['padding']['L'] = false; + $table['padding']['R'] = false; + $table['padding']['T'] = false; + $table['padding']['B'] = false; + $table['margin']['L'] = false; + $table['margin']['R'] = false; + $table['margin']['T'] = false; + $table['margin']['B'] = false; + $table['a'] = false; + $table['border_spacing_H'] = false; + $table['border_spacing_V'] = false; + $table['decimal_align'] = false; + $this->mpdf->Reset(); + $this->mpdf->InlineProperties = []; + $this->mpdf->InlineBDF = []; // mPDF 6 + $this->mpdf->InlineBDFctr = 0; // mPDF 6 + $table['nc'] = $table['nr'] = 0; + $this->mpdf->tablethead = 0; + $this->mpdf->tabletfoot = 0; + $this->mpdf->tabletheadjustfinished = false; + + // mPDF 6 + if ($this->mpdf->tableLevel > 1) { // inherit table properties from cell in which nested + $table['direction'] = $direction; + $table['txta'] = $txta; + $table['cellLineHeight'] = $cellLineHeight; + $table['cellLineStackingStrategy'] = $cellLineStackingStrategy; + $table['cellLineStackingShift'] = $cellLineStackingShift; + } + + + $lastbottommargin = 0; + if ($this->mpdf->blockjustfinished && !count($this->mpdf->textbuffer) && $this->mpdf->y != $this->mpdf->tMargin && $this->mpdf->collapseBlockMargins && $this->mpdf->tableLevel == 1) { + $lastbottommargin = $this->mpdf->lastblockbottommargin; + } + $this->mpdf->lastblockbottommargin = 0; + $this->mpdf->blockjustfinished = false; + + if ($this->mpdf->tableLevel == 1) { + $table['headernrows'] = 0; + $table['footernrows'] = 0; + $this->mpdf->base_table_properties = []; + } + + // ADDED CSS FUNCIONS FOR TABLE + if ($this->cssManager->tbCSSlvl == 1) { + $properties = $this->cssManager->MergeCSS('TOPTABLE', 'TABLE', $attr); + } else { + $properties = $this->cssManager->MergeCSS('TABLE', 'TABLE', $attr); + } + + $w = ''; + if (isset($properties['WIDTH'])) { + $w = $properties['WIDTH']; + } elseif (!empty($attr['WIDTH'])) { + $w = $attr['WIDTH']; + } + + if (isset($attr['ALIGN']) && array_key_exists(strtolower($attr['ALIGN']), self::ALIGN)) { + $table['a'] = self::ALIGN[strtolower($attr['ALIGN'])]; + } + if (!$table['a']) { + if ($table['direction'] === 'rtl') { + $table['a'] = 'R'; + } else { + $table['a'] = 'L'; + } + } + + if (!empty($properties['DIRECTION'])) { + $table['direction'] = strtolower($properties['DIRECTION']); + } elseif (!empty($attr['DIR'])) { + $table['direction'] = strtolower($attr['DIR']); + } elseif ($this->mpdf->tableLevel == 1) { + $table['direction'] = $this->mpdf->blk[$this->mpdf->blklvl]['direction']; + } + + if (isset($properties['BACKGROUND-COLOR'])) { + $table['bgcolor'][-1] = $properties['BACKGROUND-COLOR']; + } elseif (isset($properties['BACKGROUND'])) { + $table['bgcolor'][-1] = $properties['BACKGROUND']; + } elseif (isset($attr['BGCOLOR'])) { + $table['bgcolor'][-1] = $attr['BGCOLOR']; + } + + if (isset($properties['VERTICAL-ALIGN']) && array_key_exists(strtolower($properties['VERTICAL-ALIGN']), self::ALIGN)) { + $table['va'] = self::ALIGN[strtolower($properties['VERTICAL-ALIGN'])]; + } + if (isset($properties['TEXT-ALIGN']) && array_key_exists(strtolower($properties['TEXT-ALIGN']), self::ALIGN)) { + $table['txta'] = self::ALIGN[strtolower($properties['TEXT-ALIGN'])]; + } + + if (!empty($properties['AUTOSIZE']) && $this->mpdf->tableLevel == 1) { + $this->mpdf->shrink_this_table_to_fit = $properties['AUTOSIZE']; + if ($this->mpdf->shrink_this_table_to_fit < 1) { + $this->mpdf->shrink_this_table_to_fit = 0; + } + } + if (!empty($properties['ROTATE']) && $this->mpdf->tableLevel == 1) { + $this->mpdf->table_rotate = $properties['ROTATE']; + } + if (isset($properties['TOPNTAIL'])) { + $table['topntail'] = $properties['TOPNTAIL']; + } + if (isset($properties['THEAD-UNDERLINE'])) { + $table['thead-underline'] = $properties['THEAD-UNDERLINE']; + } + + if (isset($properties['BORDER'])) { + $bord = $this->mpdf->border_details($properties['BORDER']); + if ($bord['s']) { + $table['border'] = Border::ALL; + $table['border_details']['R'] = $bord; + $table['border_details']['L'] = $bord; + $table['border_details']['T'] = $bord; + $table['border_details']['B'] = $bord; + } + } + if (isset($properties['BORDER-RIGHT'])) { + if ($table['direction'] === 'rtl') { // *OTL* + $table['border_details']['R'] = $this->mpdf->border_details($properties['BORDER-LEFT']); // *OTL* + } // *OTL* + else { // *OTL* + $table['border_details']['R'] = $this->mpdf->border_details($properties['BORDER-RIGHT']); + } // *OTL* + $this->mpdf->setBorder($table['border'], Border::RIGHT, $table['border_details']['R']['s']); + } + if (isset($properties['BORDER-LEFT'])) { + if ($table['direction'] === 'rtl') { // *OTL* + $table['border_details']['L'] = $this->mpdf->border_details($properties['BORDER-RIGHT']); // *OTL* + } // *OTL* + else { // *OTL* + $table['border_details']['L'] = $this->mpdf->border_details($properties['BORDER-LEFT']); + } // *OTL* + $this->mpdf->setBorder($table['border'], Border::LEFT, $table['border_details']['L']['s']); + } + if (isset($properties['BORDER-BOTTOM'])) { + $table['border_details']['B'] = $this->mpdf->border_details($properties['BORDER-BOTTOM']); + $this->mpdf->setBorder($table['border'], Border::BOTTOM, $table['border_details']['B']['s']); + } + if (isset($properties['BORDER-TOP'])) { + $table['border_details']['T'] = $this->mpdf->border_details($properties['BORDER-TOP']); + $this->mpdf->setBorder($table['border'], Border::TOP, $table['border_details']['T']['s']); + } + + $this->mpdf->table_border_css_set = 0; + if ($table['border']) { + $this->mpdf->table_border_css_set = 1; + } + + // mPDF 6 + if (!empty($properties['LANG'])) { + if ($this->mpdf->autoLangToFont && !$this->mpdf->usingCoreFont) { + if ($properties['LANG'] != $this->mpdf->default_lang && $properties['LANG'] !== 'UTF-8') { + list ($coreSuitable, $mpdf_pdf_unifont) = $this->languageToFont->getLanguageOptions($properties['LANG'], $this->mpdf->useAdobeCJK); + if ($mpdf_pdf_unifont) { + $properties['FONT-FAMILY'] = $mpdf_pdf_unifont; + } + } + } + $this->mpdf->currentLang = $properties['LANG']; + } + + + if (isset($properties['FONT-FAMILY'])) { + $this->mpdf->default_font = $properties['FONT-FAMILY']; + $this->mpdf->SetFont($this->mpdf->default_font, '', 0, false); + } + $this->mpdf->base_table_properties['FONT-FAMILY'] = $this->mpdf->FontFamily; + + if (isset($properties['FONT-SIZE'])) { + if ($this->mpdf->tableLevel > 1) { + $tableFontSize = $this->sizeConverter->convert($this->mpdf->base_table_properties['FONT-SIZE']); + $mmsize = $this->sizeConverter->convert($properties['FONT-SIZE'], $tableFontSize); + } else { + $mmsize = $this->sizeConverter->convert($properties['FONT-SIZE'], $this->mpdf->default_font_size / Mpdf::SCALE); + } + if ($mmsize) { + $this->mpdf->default_font_size = $mmsize * Mpdf::SCALE; + $this->mpdf->SetFontSize($this->mpdf->default_font_size, false); + } + } + $this->mpdf->base_table_properties['FONT-SIZE'] = $this->mpdf->FontSize . 'mm'; + + if (isset($properties['FONT-WEIGHT'])) { + if (strtoupper($properties['FONT-WEIGHT']) === 'BOLD') { + $this->mpdf->base_table_properties['FONT-WEIGHT'] = 'BOLD'; + } + } + if (isset($properties['FONT-STYLE'])) { + if (strtoupper($properties['FONT-STYLE']) === 'ITALIC') { + $this->mpdf->base_table_properties['FONT-STYLE'] = 'ITALIC'; + } + } + if (isset($properties['COLOR'])) { + $this->mpdf->base_table_properties['COLOR'] = $properties['COLOR']; + } + if (isset($properties['FONT-KERNING'])) { + $this->mpdf->base_table_properties['FONT-KERNING'] = $properties['FONT-KERNING']; + } + if (isset($properties['LETTER-SPACING'])) { + $this->mpdf->base_table_properties['LETTER-SPACING'] = $properties['LETTER-SPACING']; + } + if (isset($properties['WORD-SPACING'])) { + $this->mpdf->base_table_properties['WORD-SPACING'] = $properties['WORD-SPACING']; + } + // mPDF 6 + if (isset($properties['HYPHENS'])) { + $this->mpdf->base_table_properties['HYPHENS'] = $properties['HYPHENS']; + } + if (!empty($properties['LINE-HEIGHT'])) { + $table['cellLineHeight'] = $this->mpdf->fixLineheight($properties['LINE-HEIGHT']); + } elseif ($this->mpdf->tableLevel == 1) { + $table['cellLineHeight'] = $this->mpdf->blk[$this->mpdf->blklvl]['line_height']; + } + + if (!empty($properties['LINE-STACKING-STRATEGY'])) { + $table['cellLineStackingStrategy'] = strtolower($properties['LINE-STACKING-STRATEGY']); + } elseif ($this->mpdf->tableLevel == 1 && isset($this->mpdf->blk[$this->mpdf->blklvl]['line_stacking_strategy'])) { + $table['cellLineStackingStrategy'] = $this->mpdf->blk[$this->mpdf->blklvl]['line_stacking_strategy']; + } else { + $table['cellLineStackingStrategy'] = 'inline-line-height'; + } + + if (!empty($properties['LINE-STACKING-SHIFT'])) { + $table['cellLineStackingShift'] = strtolower($properties['LINE-STACKING-SHIFT']); + } elseif ($this->mpdf->tableLevel == 1 && isset($this->mpdf->blk[$this->mpdf->blklvl]['line_stacking_shift'])) { + $table['cellLineStackingShift'] = $this->mpdf->blk[$this->mpdf->blklvl]['line_stacking_shift']; + } else { + $table['cellLineStackingShift'] = 'consider-shifts'; + } + + if (isset($properties['PADDING-LEFT'])) { + $table['padding']['L'] = $this->sizeConverter->convert($properties['PADDING-LEFT'], $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], $this->mpdf->FontSize, false); + } + if (isset($properties['PADDING-RIGHT'])) { + $table['padding']['R'] = $this->sizeConverter->convert($properties['PADDING-RIGHT'], $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], $this->mpdf->FontSize, false); + } + if (isset($properties['PADDING-TOP'])) { + $table['padding']['T'] = $this->sizeConverter->convert($properties['PADDING-TOP'], $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], $this->mpdf->FontSize, false); + } + if (isset($properties['PADDING-BOTTOM'])) { + $table['padding']['B'] = $this->sizeConverter->convert($properties['PADDING-BOTTOM'], $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], $this->mpdf->FontSize, false); + } + + if (isset($properties['MARGIN-TOP'])) { + if ($lastbottommargin) { + $tmp = $this->sizeConverter->convert($properties['MARGIN-TOP'], $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], $this->mpdf->FontSize, false); + if ($tmp > $lastbottommargin) { + $properties['MARGIN-TOP'] = (int) $properties['MARGIN-TOP'] - $lastbottommargin; + } else { + $properties['MARGIN-TOP'] = 0; + } + } + $table['margin']['T'] = $this->sizeConverter->convert($properties['MARGIN-TOP'], $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], $this->mpdf->FontSize, false); + } + + if (isset($properties['MARGIN-BOTTOM'])) { + $table['margin']['B'] = $this->sizeConverter->convert($properties['MARGIN-BOTTOM'], $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], $this->mpdf->FontSize, false); + } + if (isset($properties['MARGIN-LEFT'])) { + $table['margin']['L'] = $this->sizeConverter->convert($properties['MARGIN-LEFT'], $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], $this->mpdf->FontSize, false); + } + + if (isset($properties['MARGIN-RIGHT'])) { + $table['margin']['R'] = $this->sizeConverter->convert($properties['MARGIN-RIGHT'], $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], $this->mpdf->FontSize, false); + } + if (isset($properties['MARGIN-LEFT'], $properties['MARGIN-RIGHT']) && strtolower($properties['MARGIN-LEFT']) === 'auto' && strtolower($properties['MARGIN-RIGHT']) === 'auto') { + $table['a'] = 'C'; + } elseif (isset($properties['MARGIN-LEFT']) && strtolower($properties['MARGIN-LEFT']) === 'auto') { + $table['a'] = 'R'; + } elseif (isset($properties['MARGIN-RIGHT']) && strtolower($properties['MARGIN-RIGHT']) === 'auto') { + $table['a'] = 'L'; + } + + if (isset($properties['BORDER-COLLAPSE']) && strtoupper($properties['BORDER-COLLAPSE']) === 'SEPARATE') { + $table['borders_separate'] = true; + } else { + $table['borders_separate'] = false; + } + + // mPDF 5.7.3 + + if (isset($properties['BORDER-SPACING-H'])) { + $table['border_spacing_H'] = $this->sizeConverter->convert($properties['BORDER-SPACING-H'], $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], $this->mpdf->FontSize, false); + } + if (isset($properties['BORDER-SPACING-V'])) { + $table['border_spacing_V'] = $this->sizeConverter->convert($properties['BORDER-SPACING-V'], $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], $this->mpdf->FontSize, false); + } + // mPDF 5.7.3 + if (!$table['borders_separate']) { + $table['border_spacing_H'] = $table['border_spacing_V'] = 0; + } + + if (isset($properties['EMPTY-CELLS'])) { + $table['empty_cells'] = strtolower($properties['EMPTY-CELLS']); // 'hide' or 'show' + } else { + $table['empty_cells'] = ''; + } + + if (isset($properties['PAGE-BREAK-INSIDE']) && strtoupper($properties['PAGE-BREAK-INSIDE']) === 'AVOID' && $this->mpdf->tableLevel == 1 && !$this->mpdf->writingHTMLfooter) { + $this->mpdf->table_keep_together = true; + } elseif ($this->mpdf->tableLevel == 1) { + $this->mpdf->table_keep_together = false; + } + if (isset($properties['PAGE-BREAK-AFTER']) && $this->mpdf->tableLevel == 1) { + $table['page_break_after'] = strtoupper($properties['PAGE-BREAK-AFTER']); + } + + /* -- BACKGROUNDS -- */ + if (isset($properties['BACKGROUND-GRADIENT']) && !$this->mpdf->kwt && !$this->mpdf->ColActive) { + $table['gradient'] = $properties['BACKGROUND-GRADIENT']; + } + + if (!empty($properties['BACKGROUND-IMAGE']) && !$this->mpdf->kwt && !$this->mpdf->ColActive) { + $ret = $this->mpdf->SetBackground($properties, $this->mpdf->blk[$this->mpdf->blklvl]['inner_width']); + if ($ret) { + $table['background-image'] = $ret; + } + } + /* -- END BACKGROUNDS -- */ + + if (isset($properties['OVERFLOW'])) { + $table['overflow'] = strtolower($properties['OVERFLOW']); // 'hidden' 'wrap' or 'visible' or 'auto' + if (($this->mpdf->ColActive || $this->mpdf->tableLevel > 1) && $table['overflow'] === 'visible') { + unset($table['overflow']); + } + } + + if (isset($attr['CELLPADDING'])) { + $table['cell_padding'] = $attr['CELLPADDING']; + } else { + $table['cell_padding'] = false; + } + + if (isset($attr['BORDER']) && $attr['BORDER'] == '1') { + $this->mpdf->table_border_attr_set = 1; + $bord = $this->mpdf->border_details('#000000 1px solid'); + if ($bord['s']) { + $table['border'] = Border::ALL; + $table['border_details']['R'] = $bord; + $table['border_details']['L'] = $bord; + $table['border_details']['T'] = $bord; + $table['border_details']['B'] = $bord; + } + } else { + $this->mpdf->table_border_attr_set = 0; + } + + if ($w) { + $maxwidth = $this->mpdf->blk[$this->mpdf->blklvl]['inner_width']; + if ($table['borders_separate']) { + $tblblw = $table['margin']['L'] + $table['margin']['R'] + $table['border_details']['L']['w'] / 2 + $table['border_details']['R']['w'] / 2; + } else { + $tblblw = $table['margin']['L'] + $table['margin']['R'] + $table['max_cell_border_width']['L'] / 2 + $table['max_cell_border_width']['R'] / 2; + } + if (strpos($w, '%') && $this->mpdf->tableLevel == 1 && !$this->mpdf->ignore_table_percents) { + // % needs to be of inner box without table margins etc. + $maxwidth -= $tblblw; + $wmm = $this->sizeConverter->convert($w, $maxwidth, $this->mpdf->FontSize, false); + $table['w'] = $wmm + $tblblw; + } + if (strpos($w, '%') && $this->mpdf->tableLevel > 1 && !$this->mpdf->ignore_table_percents && $this->mpdf->keep_table_proportions) { + $table['wpercent'] = (int) $w; // makes 80% -> 80 + } + if (!strpos($w, '%') && !$this->mpdf->ignore_table_widths) { + $wmm = $this->sizeConverter->convert($w, $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], $this->mpdf->FontSize, false); + $table['w'] = $wmm + $tblblw; + } + if (!$this->mpdf->keep_table_proportions) { + if (isset($table['w']) && $table['w'] > $this->mpdf->blk[$this->mpdf->blklvl]['inner_width']) { + $table['w'] = $this->mpdf->blk[$this->mpdf->blklvl]['inner_width']; + } + } + } + + if (isset($attr['AUTOSIZE']) && $this->mpdf->tableLevel == 1) { + $this->mpdf->shrink_this_table_to_fit = $attr['AUTOSIZE']; + if ($this->mpdf->shrink_this_table_to_fit < 1) { + $this->mpdf->shrink_this_table_to_fit = 1; + } + } + if (isset($attr['ROTATE']) && $this->mpdf->tableLevel == 1) { + $this->mpdf->table_rotate = $attr['ROTATE']; + } + + //++++++++++++++++++++++++++++ + if ($this->mpdf->table_rotate) { + $this->mpdf->tbrot_Links = []; + $this->mpdf->tbrot_Annots = []; + $this->mpdf->tbrotForms = []; + $this->mpdf->tbrot_BMoutlines = []; + $this->mpdf->tbrot_toc = []; + } + + if ($this->mpdf->kwt) { + if ($this->mpdf->table_rotate) { + $this->mpdf->table_keep_together = true; + } + $this->mpdf->kwt = false; + $this->mpdf->kwt_saved = true; + } + + //++++++++++++++++++++++++++++ + $this->mpdf->plainCell_properties = []; + unset($table); + } + + public function close(&$ahtml, &$ihtml) + { + + $this->mpdf->lastoptionaltag = ''; + unset($this->cssManager->tablecascadeCSS[$this->cssManager->tbCSSlvl]); + $this->cssManager->tbCSSlvl--; + $this->mpdf->ignorefollowingspaces = true; //Eliminate exceeding left-side spaces + // mPDF 5.7.3 + // In case a colspan (on a row after first row) exceeded number of columns in table + for ($k = 0; $k < $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['nr']; $k++) { + for ($l = 0; $l < $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['nc']; $l++) { + if (!isset($this->mpdf->cell[$k][$l])) { + for ($n = $l - 1; $n >= 0; $n--) { + if (isset($this->mpdf->cell[$k][$n]) && $this->mpdf->cell[$k][$n] != 0) { + break; + } + } + $this->mpdf->cell[$k][$l] = [ + 'a' => 'C', + 'va' => 'M', + 'R' => false, + 'nowrap' => false, + 'bgcolor' => false, + 'padding' => ['L' => false, 'R' => false, 'T' => false, 'B' => false], + 'gradient' => false, + 's' => 0, + 'maxs' => 0, + 'textbuffer' => [], + 'dfs' => $this->mpdf->FontSize, + ]; + + if (!$this->mpdf->simpleTables) { + $this->mpdf->cell[$k][$l]['border'] = 0; + $this->mpdf->cell[$k][$l]['border_details']['R'] = ['s' => 0, 'w' => 0, 'c' => false, 'style' => 'none', 'dom' => 0]; + $this->mpdf->cell[$k][$l]['border_details']['L'] = ['s' => 0, 'w' => 0, 'c' => false, 'style' => 'none', 'dom' => 0]; + $this->mpdf->cell[$k][$l]['border_details']['T'] = ['s' => 0, 'w' => 0, 'c' => false, 'style' => 'none', 'dom' => 0]; + $this->mpdf->cell[$k][$l]['border_details']['B'] = ['s' => 0, 'w' => 0, 'c' => false, 'style' => 'none', 'dom' => 0]; + $this->mpdf->cell[$k][$l]['border_details']['mbw'] = ['BL' => 0, 'BR' => 0, 'RT' => 0, 'RB' => 0, 'TL' => 0, 'TR' => 0, 'LT' => 0, 'LB' => 0]; + if ($this->mpdf->packTableData) { + $this->mpdf->cell[$k][$l]['borderbin'] = $this->mpdf->_packCellBorder($this->mpdf->cell[$k][$l]); + unset($this->mpdf->cell[$k][$l]['border'], $this->mpdf->cell[$k][$l]['border_details']); + } + } + } + } + } + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['cells'] = $this->mpdf->cell; + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['wc'] = array_pad( + [], + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['nc'], + ['miw' => 0, 'maw' => 0] + ); + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['hr'] = array_pad( + [], + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['nr'], + 0 + ); + + // Move table footer <tfoot> row to end of table + if (isset($this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['is_tfoot']) + && count($this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['is_tfoot'])) { + $tfrows = []; + foreach ($this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['is_tfoot'] as $r => $val) { + if ($val) { + $tfrows[] = $r; + } + } + $temp = []; + $temptf = []; + foreach ($this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['cells'] as $k => $row) { + if (in_array($k, $tfrows)) { + $temptf[] = $row; + } else { + $temp[] = $row; + } + } + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['is_tfoot'] = []; + for ($i = count($temp); $i < (count($temp) + count($temptf)); $i++) { + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['is_tfoot'][$i] = true; + } + // Update nestedpos row references + if (isset($this->mpdf->table[$this->mpdf->tableLevel + 1]) && count($this->mpdf->table[$this->mpdf->tableLevel + 1])) { + foreach ($this->mpdf->table[$this->mpdf->tableLevel + 1] as $nid => $nested) { + $this->mpdf->table[$this->mpdf->tableLevel + 1][$nid]['nestedpos'][0] -= count($temptf); + } + } + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['cells'] = array_merge($temp, $temptf); + + // Update other arays set on row number + // [trbackground-images] [trgradients] + $temptrbgi = []; + $temptrbgg = []; + $temptrbgc = []; + if (isset($this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['bgcolor'][-1])) { + $temptrbgc[-1] = $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['bgcolor'][-1]; + } + for ($k = 0; $k < $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['nr']; $k++) { + if (!in_array($k, $tfrows)) { + $temptrbgi[] = isset($this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['trbackground-images'][$k]) + ? $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['trbackground-images'][$k] + : null; + $temptrbgg[] = isset($this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['trgradients'][$k]) + ? $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['trgradients'][$k] + : null; + $temptrbgc[] = isset($this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['bgcolor'][$k]) + ? $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['bgcolor'][$k] + : null; + } + } + for ($k = 0; $k < $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['nr']; $k++) { + if (in_array($k, $tfrows)) { + $temptrbgi[] = isset($this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['trbackground-images'][$k]) + ? $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['trbackground-images'][$k] + : null; + $temptrbgg[] = isset($this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['trgradients'][$k]) + ? $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['trgradients'][$k] + : null; + $temptrbgc[] = isset($this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['bgcolor'][$k]) + ? $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['bgcolor'][$k] + : null; + } + } + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['trbackground-images'] = $temptrbgi; + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['trgradients'] = $temptrbgg; + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['bgcolor'] = $temptrbgc; + // Should Update all other arays set on row number, but cell properties have been set so not needed + // [bgcolor] [trborder-left] [trborder-right] [trborder-top] [trborder-bottom] + } + + if ($this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['direction'] === 'rtl') { + $this->mpdf->_reverseTableDir($this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]); + } + + // Fix Borders ********************************************* + $this->mpdf->_fixTableBorders($this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]); + + if ($this->mpdf->ColActive) { + $this->mpdf->table_rotate = 0; + } // *COLUMNS* + if ($this->mpdf->table_rotate <> 0) { + $this->mpdf->tablebuffer = ''; + // Max width for rotated table + $this->mpdf->tbrot_maxw = $this->mpdf->h - ($this->mpdf->y + $this->mpdf->bMargin + 1); + $this->mpdf->tbrot_maxh = $this->mpdf->blk[$this->mpdf->blklvl]['inner_width']; // Max width for rotated table + $this->mpdf->tbrot_align = $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['a']; + } + $this->mpdf->shrin_k = 1; + + if ($this->mpdf->shrink_tables_to_fit < 1) { + $this->mpdf->shrink_tables_to_fit = 1; + } + if (!$this->mpdf->shrink_this_table_to_fit) { + $this->mpdf->shrink_this_table_to_fit = $this->mpdf->shrink_tables_to_fit; + } + + if ($this->mpdf->tableLevel > 1) { + // deal with nested table + + $this->mpdf->_tableColumnWidth($this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]], true); + + $tmiw = $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['miw']; + $tmaw = $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['maw']; + $tl = $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['tl']; + + // Go down to lower table level + $this->mpdf->tableLevel--; + + // Reset lower level table + $this->mpdf->base_table_properties = $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['baseProperties']; + // mPDF 5.7.3 + $this->mpdf->default_font = $this->mpdf->base_table_properties['FONT-FAMILY']; + $this->mpdf->SetFont($this->mpdf->default_font, '', 0, false); + $this->mpdf->default_font_size = $this->sizeConverter->convert($this->mpdf->base_table_properties['FONT-SIZE']) * Mpdf::SCALE; + $this->mpdf->SetFontSize($this->mpdf->default_font_size, false); + + $this->mpdf->cell = $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['cells']; + if (isset($this->mpdf->cell['PARENTCELL'])) { + if ($this->mpdf->cell['PARENTCELL']) { + $this->mpdf->restoreInlineProperties($this->mpdf->cell['PARENTCELL']); + } + unset($this->mpdf->cell['PARENTCELL']); + } + $this->mpdf->row = $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['currrow']; + $this->mpdf->col = $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['currcol']; + $objattr = []; + $objattr['type'] = 'nestedtable'; + $objattr['nestedcontent'] = $this->mpdf->tbctr[$this->mpdf->tableLevel + 1]; + $objattr['table'] = $this->mpdf->tbctr[$this->mpdf->tableLevel]; + $objattr['row'] = $this->mpdf->row; + $objattr['col'] = $this->mpdf->col; + $objattr['level'] = $this->mpdf->tableLevel; + $e = "\xbb\xa4\xactype=nestedtable,objattr=" . serialize($objattr) . "\xbb\xa4\xac"; + $this->mpdf->_saveCellTextBuffer($e); + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s'] += $tl; + if (!isset($this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['maxs'])) { + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['maxs'] = $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s']; + } elseif ($this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['maxs'] < $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s']) { + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['maxs'] = $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s']; + } + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s'] = 0; // reset + if ((isset($this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['nestedmaw']) && $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['nestedmaw'] < $tmaw) + || !isset($this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['nestedmaw'])) { + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['nestedmaw'] = $tmaw; + } + if ((isset($this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['nestedmiw']) && $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['nestedmiw'] < $tmiw) + || !isset($this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['nestedmiw'])) { + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['nestedmiw'] = $tmiw; + } + $this->mpdf->tdbegin = true; + $this->mpdf->nestedtablejustfinished = true; + $this->mpdf->ignorefollowingspaces = true; + return; + } + $this->mpdf->cMarginL = 0; + $this->mpdf->cMarginR = 0; + $this->mpdf->cMarginT = 0; + $this->mpdf->cMarginB = 0; + $this->mpdf->cellPaddingL = 0; + $this->mpdf->cellPaddingR = 0; + $this->mpdf->cellPaddingT = 0; + $this->mpdf->cellPaddingB = 0; + + if (isset($this->mpdf->table[1][1]['overflow']) && $this->mpdf->table[1][1]['overflow'] === 'visible') { + if ($this->mpdf->kwt || $this->mpdf->table_rotate || $this->mpdf->table_keep_together || $this->mpdf->ColActive) { + $this->mpdf->kwt = false; + $this->mpdf->table_rotate = 0; + $this->mpdf->table_keep_together = false; + //throw new \Mpdf\MpdfException("mPDF Warning: You cannot use CSS overflow:visible together with any of these functions: + // 'Keep-with-table', rotated tables, page-break-inside:avoid, or columns"); + } + $this->mpdf->_tableColumnWidth($this->mpdf->table[1][1], true); + $this->mpdf->_tableWidth($this->mpdf->table[1][1]); + } else { + if (!$this->mpdf->kwt_saved) { + $this->mpdf->kwt_height = 0; + } + + list($check, $tablemiw) = $this->mpdf->_tableColumnWidth($this->mpdf->table[1][1], true); + $save_table = $this->mpdf->table; + $reset_to_minimum_width = false; + $added_page = false; + + if ($check > 1) { + if ($check > $this->mpdf->shrink_this_table_to_fit && $this->mpdf->table_rotate) { + if ($this->mpdf->y != $this->mpdf->tMargin) { + $this->mpdf->AddPage($this->mpdf->CurOrientation); + $this->mpdf->kwt_moved = true; + } + $added_page = true; + $this->mpdf->tbrot_maxw = $this->mpdf->h - ($this->mpdf->y + $this->mpdf->bMargin + 5) - $this->mpdf->kwt_height; + //$check = $tablemiw/$this->mpdf->tbrot_maxw; // undo any shrink + $check = 1; // undo any shrink + } + $reset_to_minimum_width = true; + } + + if ($reset_to_minimum_width) { + $this->mpdf->shrin_k = $check; + + $this->mpdf->default_font_size /= $this->mpdf->shrin_k; + $this->mpdf->SetFontSize($this->mpdf->default_font_size, false); + + $this->mpdf->shrinkTable($this->mpdf->table[1][1], $this->mpdf->shrin_k); + + $this->mpdf->_tableColumnWidth($this->mpdf->table[1][1]); // repeat + // Starting at $this->mpdf->innermostTableLevel + // Shrink table values - and redo columnWidth + for ($lvl = 2; $lvl <= $this->mpdf->innermostTableLevel; $lvl++) { + for ($nid = 1; $nid <= $this->mpdf->tbctr[$lvl]; $nid++) { + $this->mpdf->shrinkTable($this->mpdf->table[$lvl][$nid], $this->mpdf->shrin_k); + $this->mpdf->_tableColumnWidth($this->mpdf->table[$lvl][$nid]); + } + } + } + + // Set table cell widths for top level table + // Use $shrin_k to resize but don't change again + $this->mpdf->SetLineHeight('', $this->mpdf->table[1][1]['cellLineHeight']); + + // Top level table + $this->mpdf->_tableWidth($this->mpdf->table[1][1]); + } + + // Now work through any nested tables setting child table[w'] = parent cell['w'] + // Now do nested tables _tableWidth + for ($lvl = 2; $lvl <= $this->mpdf->innermostTableLevel; $lvl++) { + for ($nid = 1; $nid <= $this->mpdf->tbctr[$lvl]; $nid++) { + // HERE set child table width = cell width + + list($parentrow, $parentcol, $parentnid) = $this->mpdf->table[$lvl][$nid]['nestedpos']; + + $c = & $this->mpdf->table[$lvl - 1][$parentnid]['cells'][$parentrow][$parentcol]; + + if (isset($c['colspan']) && $c['colspan'] > 1) { + $parentwidth = 0; + for ($cs = 0; $cs < $c['colspan']; $cs++) { + $parentwidth += $this->mpdf->table[$lvl - 1][$parentnid]['wc'][$parentcol + $cs]; + } + } else { + $parentwidth = $this->mpdf->table[$lvl - 1][$parentnid]['wc'][$parentcol]; + } + + //$parentwidth -= ALLOW FOR PADDING ETC. in parent cell + if (!$this->mpdf->simpleTables) { + if ($this->mpdf->packTableData) { + list($bt, $br, $bb, $bl) = $this->mpdf->_getBorderWidths($c['borderbin']); + } else { + $br = $c['border_details']['R']['w']; + $bl = $c['border_details']['L']['w']; + } + if ($this->mpdf->table[$lvl - 1][$parentnid]['borders_separate']) { + $parentwidth -= $br + $bl + $c['padding']['L'] + $c['padding']['R'] + $this->mpdf->table[$lvl - 1][$parentnid]['border_spacing_H']; + } else { + $parentwidth -= $br / 2 + $bl / 2 + $c['padding']['L'] + $c['padding']['R']; + } + } elseif ($this->mpdf->simpleTables) { + if ($this->mpdf->table[$lvl - 1][$parentnid]['borders_separate']) { + $parentwidth -= $this->mpdf->table[$lvl - 1][$parentnid]['simple']['border_details']['L']['w'] + + $this->mpdf->table[$lvl - 1][$parentnid]['simple']['border_details']['R']['w'] + $c['padding']['L'] + + $c['padding']['R'] + $this->mpdf->table[$lvl - 1][$parentnid]['border_spacing_H']; + } else { + $parentwidth -= $this->mpdf->table[$lvl - 1][$parentnid]['simple']['border_details']['L']['w'] / 2 + + $this->mpdf->table[$lvl - 1][$parentnid]['simple']['border_details']['R']['w'] / 2 + $c['padding']['L'] + $c['padding']['R']; + } + } + if (!empty($this->mpdf->table[$lvl][$nid]['wpercent']) && $lvl > 1) { + $this->mpdf->table[$lvl][$nid]['w'] = $parentwidth; + } elseif ($parentwidth > $this->mpdf->table[$lvl][$nid]['maw']) { + $this->mpdf->table[$lvl][$nid]['w'] = $this->mpdf->table[$lvl][$nid]['maw']; + } else { + $this->mpdf->table[$lvl][$nid]['w'] = $parentwidth; + } + unset($c); + $this->mpdf->_tableWidth($this->mpdf->table[$lvl][$nid]); + } + } + + // Starting at $this->mpdf->innermostTableLevel + // Cascade back up nested tables: setting heights back up the tree + for ($lvl = $this->mpdf->innermostTableLevel; $lvl > 0; $lvl--) { + for ($nid = 1; $nid <= $this->mpdf->tbctr[$lvl]; $nid++) { + list($tableheight, $maxrowheight, $fullpage, $remainingpage, $maxfirstrowheight) = $this->mpdf->_tableHeight($this->mpdf->table[$lvl][$nid]); + } + } + + if ($this->mpdf->table[1][1]['overflow'] === 'visible') { + if ($maxrowheight > $fullpage) { + throw new \Mpdf\MpdfException('mPDF Warning: A Table row is greater than available height. You cannot use CSS overflow:visible'); + } + if ($maxfirstrowheight > $remainingpage) { + $this->mpdf->AddPage($this->mpdf->CurOrientation); + } + $r = 0; + $c = 0; + $p = 0; + $y = 0; + $finished = false; + while (!$finished) { + list($finished, $r, $c, $p, $y, $y0) = $this->mpdf->_tableWrite($this->mpdf->table[1][1], true, $r, $c, $p, $y); + if (!$finished) { + $this->mpdf->AddPage($this->mpdf->CurOrientation); + // If printed something on first spread, set same y + if ($r == 0 && $y0 > -1) { + $this->mpdf->y = $y0; + } + } + } + } else { + $recalculate = 1; + $forcerecalc = false; + // RESIZING ALGORITHM + if ($maxrowheight > $fullpage) { + $recalculate = $this->tbsqrt($maxrowheight / $fullpage, 1); + $forcerecalc = true; + } elseif ($this->mpdf->table_rotate) { // NB $remainingpage == $fullpage == the width of the page + if ($tableheight > $remainingpage) { + // If can fit on remainder of page whilst respecting autsize value.. + if (($this->mpdf->shrin_k * $this->tbsqrt($tableheight / $remainingpage, 1)) <= $this->mpdf->shrink_this_table_to_fit) { + $recalculate = $this->tbsqrt($tableheight / $remainingpage, 1); + } elseif (!$added_page) { + if ($this->mpdf->y != $this->mpdf->tMargin) { + $this->mpdf->AddPage($this->mpdf->CurOrientation); + $this->mpdf->kwt_moved = true; + } + $added_page = true; + $this->mpdf->tbrot_maxw = $this->mpdf->h - ($this->mpdf->y + $this->mpdf->bMargin + 5) - $this->mpdf->kwt_height; + // 0.001 to force it to recalculate + $recalculate = (1 / $this->mpdf->shrin_k) + 0.001; // undo any shrink + } + } else { + $recalculate = 1; + } + } elseif ($this->mpdf->table_keep_together || ($this->mpdf->table[1][1]['nr'] == 1 && !$this->mpdf->writingHTMLfooter)) { + if ($tableheight > $fullpage) { + if (($this->mpdf->shrin_k * $this->tbsqrt($tableheight / $fullpage, 1)) <= $this->mpdf->shrink_this_table_to_fit) { + $recalculate = $this->tbsqrt($tableheight / $fullpage, 1); + } elseif ($this->mpdf->tableMinSizePriority) { + $this->mpdf->table_keep_together = false; + $recalculate = 1.001; + } else { + if ($this->mpdf->y != $this->mpdf->tMargin) { + $this->mpdf->AddPage($this->mpdf->CurOrientation); + $this->mpdf->kwt_moved = true; + } + $added_page = true; + $this->mpdf->tbrot_maxw = $this->mpdf->h - ($this->mpdf->y + $this->mpdf->bMargin + 5) - $this->mpdf->kwt_height; + $recalculate = $this->tbsqrt($tableheight / $fullpage, 1); + } + } elseif ($tableheight > $remainingpage) { + // If can fit on remainder of page whilst respecting autsize value.. + if (($this->mpdf->shrin_k * $this->tbsqrt($tableheight / $remainingpage, 1)) <= $this->mpdf->shrink_this_table_to_fit) { + $recalculate = $this->tbsqrt($tableheight / $remainingpage, 1); + } else { + if ($this->mpdf->y != $this->mpdf->tMargin) { + // mPDF 6 + if ($this->mpdf->AcceptPageBreak()) { + $this->mpdf->AddPage($this->mpdf->CurOrientation); + } elseif ($this->mpdf->ColActive && $tableheight > (($this->mpdf->h - $this->mpdf->bMargin) - $this->mpdf->y0)) { + $this->mpdf->AddPage($this->mpdf->CurOrientation); + } + $this->mpdf->kwt_moved = true; + } + $added_page = true; + $this->mpdf->tbrot_maxw = $this->mpdf->h - ($this->mpdf->y + $this->mpdf->bMargin + 5) - $this->mpdf->kwt_height; + $recalculate = 1.001; + } + } else { + $recalculate = 1; + } + } else { + $recalculate = 1; + } + + if ($recalculate > $this->mpdf->shrink_this_table_to_fit && !$forcerecalc) { + $recalculate = $this->mpdf->shrink_this_table_to_fit; + } + + $iteration = 1; + + // RECALCULATE + while ($recalculate <> 1) { + $this->mpdf->shrin_k1 = $recalculate; + $this->mpdf->shrin_k *= $recalculate; + $this->mpdf->default_font_size /= $this->mpdf->shrin_k1; + $this->mpdf->SetFontSize($this->mpdf->default_font_size, false); + $this->mpdf->SetLineHeight('', $this->mpdf->table[1][1]['cellLineHeight']); + $this->mpdf->table = $save_table; + if ($this->mpdf->shrin_k <> 1) { + $this->mpdf->shrinkTable($this->mpdf->table[1][1], $this->mpdf->shrin_k); + } + $this->mpdf->_tableColumnWidth($this->mpdf->table[1][1]); // repeat + // Starting at $this->mpdf->innermostTableLevel + // Shrink table values - and redo columnWidth + for ($lvl = 2; $lvl <= $this->mpdf->innermostTableLevel; $lvl++) { + for ($nid = 1; $nid <= $this->mpdf->tbctr[$lvl]; $nid++) { + if ($this->mpdf->shrin_k <> 1) { + $this->mpdf->shrinkTable($this->mpdf->table[$lvl][$nid], $this->mpdf->shrin_k); + } + $this->mpdf->_tableColumnWidth($this->mpdf->table[$lvl][$nid]); + } + } + // Set table cell widths for top level table + // Top level table + $this->mpdf->_tableWidth($this->mpdf->table[1][1]); + + // Now work through any nested tables setting child table[w'] = parent cell['w'] + // Now do nested tables _tableWidth + for ($lvl = 2; $lvl <= $this->mpdf->innermostTableLevel; $lvl++) { + for ($nid = 1; $nid <= $this->mpdf->tbctr[$lvl]; $nid++) { + // HERE set child table width = cell width + + list($parentrow, $parentcol, $parentnid) = $this->mpdf->table[$lvl][$nid]['nestedpos']; + $c = & $this->mpdf->table[$lvl - 1][$parentnid]['cells'][$parentrow][$parentcol]; + + if (isset($c['colspan']) && $c['colspan'] > 1) { + $parentwidth = 0; + for ($cs = 0; $cs < $c['colspan']; $cs++) { + $parentwidth += $this->mpdf->table[$lvl - 1][$parentnid]['wc'][$parentcol + $cs]; + } + } else { + $parentwidth = $this->mpdf->table[$lvl - 1][$parentnid]['wc'][$parentcol]; + } + + //$parentwidth -= ALLOW FOR PADDING ETC.in parent cell + if (!$this->mpdf->simpleTables) { + if ($this->mpdf->packTableData) { + list($bt, $br, $bb, $bl) = $this->mpdf->_getBorderWidths($c['borderbin']); + } else { + $br = $c['border_details']['R']['w']; + $bl = $c['border_details']['L']['w']; + } + if ($this->mpdf->table[$lvl - 1][$parentnid]['borders_separate']) { + $parentwidth -= $br + $bl + $c['padding']['L'] + $c['padding']['R'] + $this->mpdf->table[$lvl - 1][$parentnid]['border_spacing_H']; + } else { + $parentwidth -= $br / 2 + $bl / 2 + $c['padding']['L'] + $c['padding']['R']; + } + } elseif ($this->mpdf->simpleTables) { + if ($this->mpdf->table[$lvl - 1][$parentnid]['borders_separate']) { + $parentwidth -= $this->mpdf->table[$lvl - 1][$parentnid]['simple']['border_details']['L']['w'] + + $this->mpdf->table[$lvl - 1][$parentnid]['simple']['border_details']['R']['w'] + $c['padding']['L'] + $c['padding']['R'] + + $this->mpdf->table[$lvl - 1][$parentnid]['border_spacing_H']; + } else { + $parentwidth -= ($this->mpdf->table[$lvl - 1][$parentnid]['simple']['border_details']['L']['w'] + + $this->mpdf->table[$lvl - 1][$parentnid]['simple']['border_details']['R']['w']) / 2 + $c['padding']['L'] + $c['padding']['R']; + } + } + if (!empty($this->mpdf->table[$lvl][$nid]['wpercent']) && $lvl > 1) { + $this->mpdf->table[$lvl][$nid]['w'] = $parentwidth; + } elseif ($parentwidth > $this->mpdf->table[$lvl][$nid]['maw']) { + $this->mpdf->table[$lvl][$nid]['w'] = $this->mpdf->table[$lvl][$nid]['maw']; + } else { + $this->mpdf->table[$lvl][$nid]['w'] = $parentwidth; + } + unset($c); + $this->mpdf->_tableWidth($this->mpdf->table[$lvl][$nid]); + } + } + + // Starting at $this->mpdf->innermostTableLevel + // Cascade back up nested tables: setting heights back up the tree + for ($lvl = $this->mpdf->innermostTableLevel; $lvl > 0; $lvl--) { + for ($nid = 1; $nid <= $this->mpdf->tbctr[$lvl]; $nid++) { + list($tableheight, $maxrowheight, $fullpage, $remainingpage, $maxfirstrowheight) = $this->mpdf->_tableHeight($this->mpdf->table[$lvl][$nid]); + } + } + + // RESIZING ALGORITHM + + if ($maxrowheight > $fullpage) { + $recalculate = $this->tbsqrt($maxrowheight / $fullpage, $iteration); + $iteration++; + } elseif ($this->mpdf->table_rotate && $tableheight > $remainingpage && !$added_page) { + // If can fit on remainder of page whilst respecting autosize value.. + if (($this->mpdf->shrin_k * $this->tbsqrt($tableheight / $remainingpage, $iteration)) <= $this->mpdf->shrink_this_table_to_fit) { + $recalculate = $this->tbsqrt($tableheight / $remainingpage, $iteration); + $iteration++; + } else { + if (!$added_page) { + $this->mpdf->AddPage($this->mpdf->CurOrientation); + $added_page = true; + $this->mpdf->kwt_moved = true; + $this->mpdf->tbrot_maxw = $this->mpdf->h - ($this->mpdf->y + $this->mpdf->bMargin + 5) - $this->mpdf->kwt_height; + } + // 0.001 to force it to recalculate + $recalculate = (1 / $this->mpdf->shrin_k) + 0.001; // undo any shrink + } + } elseif ($this->mpdf->table_keep_together || ($this->mpdf->table[1][1]['nr'] == 1 && !$this->mpdf->writingHTMLfooter)) { + if ($tableheight > $fullpage) { + if (($this->mpdf->shrin_k * $this->tbsqrt($tableheight / $fullpage, $iteration)) <= $this->mpdf->shrink_this_table_to_fit) { + $recalculate = $this->tbsqrt($tableheight / $fullpage, $iteration); + $iteration++; + } elseif ($this->mpdf->tableMinSizePriority) { + $this->mpdf->table_keep_together = false; + $recalculate = (1 / $this->mpdf->shrin_k) + 0.001; + } else { + if (!$added_page && $this->mpdf->y != $this->mpdf->tMargin) { + $this->mpdf->AddPage($this->mpdf->CurOrientation); + $added_page = true; + $this->mpdf->kwt_moved = true; + $this->mpdf->tbrot_maxw = $this->mpdf->h - ($this->mpdf->y + $this->mpdf->bMargin + 5) - $this->mpdf->kwt_height; + } + $recalculate = $this->tbsqrt($tableheight / $fullpage, $iteration); + $iteration++; + } + } elseif ($tableheight > $remainingpage) { + // If can fit on remainder of page whilst respecting autosize value.. + if (($this->mpdf->shrin_k * $this->tbsqrt($tableheight / $remainingpage, $iteration)) <= $this->mpdf->shrink_this_table_to_fit) { + $recalculate = $this->tbsqrt($tableheight / $remainingpage, $iteration); + $iteration++; + } else { + if (!$added_page) { + // mPDF 6 + if ($this->mpdf->AcceptPageBreak()) { + $this->mpdf->AddPage($this->mpdf->CurOrientation); + } elseif ($this->mpdf->ColActive && $tableheight > (($this->mpdf->h - $this->mpdf->bMargin) - $this->mpdf->y0)) { + $this->mpdf->AddPage($this->mpdf->CurOrientation); + } + $added_page = true; + $this->mpdf->kwt_moved = true; + $this->mpdf->tbrot_maxw = $this->mpdf->h - ($this->mpdf->y + $this->mpdf->bMargin + 5) - $this->mpdf->kwt_height; + } + + //$recalculate = $this->tbsqrt($tableheight / $fullpage, $iteration); $iteration++; + $recalculate = (1 / $this->mpdf->shrin_k) + 0.001; // undo any shrink + } + } else { + $recalculate = 1; + } + } else { + $recalculate = 1; + } + } + + if ($maxfirstrowheight > $remainingpage && !$added_page && !$this->mpdf->table_rotate && !$this->mpdf->ColActive + && !$this->mpdf->table_keep_together && !$this->mpdf->writingHTMLheader && !$this->mpdf->writingHTMLfooter) { + $this->mpdf->AddPage($this->mpdf->CurOrientation); + $this->mpdf->kwt_moved = true; + } + + // keep-with-table: if page has advanced, print out buffer now, else done in fn. _Tablewrite() + if ($this->mpdf->kwt_saved && $this->mpdf->kwt_moved) { + $this->mpdf->printkwtbuffer(); + $this->mpdf->kwt_moved = false; + $this->mpdf->kwt_saved = false; + } + + // Recursively writes all tables starting at top level + $this->mpdf->_tableWrite($this->mpdf->table[1][1]); + + if ($this->mpdf->table_rotate && $this->mpdf->tablebuffer) { + $this->mpdf->PageBreakTrigger = $this->mpdf->h - $this->mpdf->bMargin; + $save_tr = $this->mpdf->table_rotate; + $save_y = $this->mpdf->y; + $this->mpdf->table_rotate = 0; + $this->mpdf->y = $this->mpdf->tbrot_y0; + $h = $this->mpdf->tbrot_w; + $this->mpdf->DivLn($h, $this->mpdf->blklvl); + + $this->mpdf->table_rotate = $save_tr; + $this->mpdf->y = $save_y; + + $this->mpdf->printtablebuffer(); + } + $this->mpdf->table_rotate = 0; + } + + + $this->mpdf->x = $this->mpdf->lMargin + $this->mpdf->blk[$this->mpdf->blklvl]['outer_left_margin']; + + $this->mpdf->maxPosR = max($this->mpdf->maxPosR, $this->mpdf->x + $this->mpdf->table[1][1]['w']); + + $this->mpdf->blockjustfinished = true; + $this->mpdf->lastblockbottommargin = $this->mpdf->table[1][1]['margin']['B']; + //Reset values + + $page_break_after = ''; + if (isset($this->mpdf->table[1][1]['page_break_after'])) { + $page_break_after = $this->mpdf->table[1][1]['page_break_after']; + } + + // Keep-with-table + $this->mpdf->kwt = false; + $this->mpdf->kwt_y0 = 0; + $this->mpdf->kwt_x0 = 0; + $this->mpdf->kwt_height = 0; + $this->mpdf->kwt_buffer = []; + $this->mpdf->kwt_Links = []; + $this->mpdf->kwt_Annots = []; + $this->mpdf->kwt_moved = false; + $this->mpdf->kwt_saved = false; + + $this->mpdf->kwt_Reference = []; + $this->mpdf->kwt_BMoutlines = []; + $this->mpdf->kwt_toc = []; + + $this->mpdf->shrin_k = 1; + $this->mpdf->shrink_this_table_to_fit = 0; + + $this->mpdf->table = []; //array + $this->mpdf->tableLevel = 0; + $this->mpdf->tbctr = []; + $this->mpdf->innermostTableLevel = 0; + $this->cssManager->tbCSSlvl = 0; + $this->cssManager->tablecascadeCSS = []; + + $this->mpdf->cell = []; //array + + $this->mpdf->col = -1; //int + $this->mpdf->row = -1; //int + + $this->mpdf->Reset(); + + $this->mpdf->cellPaddingL = 0; + $this->mpdf->cellPaddingT = 0; + $this->mpdf->cellPaddingR = 0; + $this->mpdf->cellPaddingB = 0; + $this->mpdf->cMarginL = 0; + $this->mpdf->cMarginT = 0; + $this->mpdf->cMarginR = 0; + $this->mpdf->cMarginB = 0; + $this->mpdf->default_font_size = $this->mpdf->original_default_font_size; + $this->mpdf->default_font = $this->mpdf->original_default_font; + $this->mpdf->SetFontSize($this->mpdf->default_font_size, false); + $this->mpdf->SetFont($this->mpdf->default_font, '', 0, false); + $this->mpdf->SetLineHeight(); + + if (isset($this->mpdf->blk[$this->mpdf->blklvl]['InlineProperties'])) { + $this->mpdf->restoreInlineProperties($this->mpdf->blk[$this->mpdf->blklvl]['InlineProperties']); + } + + if ($page_break_after) { + $save_blklvl = $this->mpdf->blklvl; + $save_blk = $this->mpdf->blk; + $save_silp = $this->mpdf->saveInlineProperties(); + $save_ilp = $this->mpdf->InlineProperties; + $save_bflp = $this->mpdf->InlineBDF; + $save_bflpc = $this->mpdf->InlineBDFctr; // mPDF 6 + // mPDF 6 pagebreaktype + $startpage = $this->mpdf->page; + $pagebreaktype = $this->mpdf->defaultPagebreakType; + if ($this->mpdf->ColActive) { + $pagebreaktype = 'cloneall'; + } + + // mPDF 6 pagebreaktype + $this->mpdf->_preForcedPagebreak($pagebreaktype); + + if ($page_break_after === 'RIGHT') { + $this->mpdf->AddPage($this->mpdf->CurOrientation, 'NEXT-ODD'); + } elseif ($page_break_after === 'LEFT') { + $this->mpdf->AddPage($this->mpdf->CurOrientation, 'NEXT-EVEN'); + } else { + $this->mpdf->AddPage($this->mpdf->CurOrientation); + } + + // mPDF 6 pagebreaktype + $this->mpdf->_postForcedPagebreak($pagebreaktype, $startpage, $save_blk, $save_blklvl); + + $this->mpdf->InlineProperties = $save_ilp; + $this->mpdf->InlineBDF = $save_bflp; + $this->mpdf->InlineBDFctr = $save_bflpc; // mPDF 6 + $this->mpdf->restoreInlineProperties($save_silp); + } + } + + /** + * This function determines the shrink factor when resizing tables + * val is the table_height / page_height_available + * returns a scaling factor used as $shrin_k to resize the table + * Overcompensating will be quicker but may unnecessarily shrink table too much + * Undercompensating means it will reiterate more times (taking more processing time) + */ + private function tbsqrt($val, $iteration = 3) + { + // Alters number of iterations until it returns $val itself - Must be > 2 + $k = 4; + + // Probably best guess and most accurate + if ($iteration === 1) { + return sqrt($val); + } + + // Faster than using sqrt (because it won't undercompensate), and gives reasonable results + // return 1 + (($val - 1) / 2); + $x = 2 - (($iteration - 2) / ($k - 2)); + + if ($x === 0) { + $ret = $val + 0.00001; + } elseif ($x < 0) { + $ret = 1 + ( pow(2, ($iteration - 2 - $k)) / 1000 ); + } else { + $ret = 1 + (($val - 1) / $x); + } + + return $ret; + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Tag.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Tag.php new file mode 100644 index 000000000..9f7c52ca9 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Tag.php @@ -0,0 +1,121 @@ +<?php + +namespace Mpdf\Tag; + +use Mpdf\Strict; + +use Mpdf\Cache; +use Mpdf\Color\ColorConverter; +use Mpdf\CssManager; +use Mpdf\Form; +use Mpdf\Image\ImageProcessor; +use Mpdf\Language\LanguageToFontInterface; +use Mpdf\Mpdf; +use Mpdf\Otl; +use Mpdf\SizeConverter; +use Mpdf\TableOfContents; + +abstract class Tag +{ + + use Strict; + + /** + * @var \Mpdf\Mpdf + */ + protected $mpdf; + + /** + * @var \Mpdf\Cache + */ + protected $cache; + + /** + * @var \Mpdf\CssManager + */ + protected $cssManager; + + /** + * @var \Mpdf\Form + */ + protected $form; + + /** + * @var \Mpdf\Otl + */ + protected $otl; + + /** + * @var \Mpdf\TableOfContents + */ + protected $tableOfContents; + + /** + * @var \Mpdf\SizeConverter + */ + protected $sizeConverter; + + /** + * @var \Mpdf\Color\ColorConverter + */ + protected $colorConverter; + + /** + * @var \Mpdf\Image\ImageProcessor + */ + protected $imageProcessor; + + /** + * @var \Mpdf\Language\LanguageToFontInterface + */ + protected $languageToFont; + + const ALIGN = [ + 'left' => 'L', + 'center' => 'C', + 'right' => 'R', + 'top' => 'T', + 'text-top' => 'TT', + 'middle' => 'M', + 'baseline' => 'BS', + 'bottom' => 'B', + 'text-bottom' => 'TB', + 'justify' => 'J' + ]; + + public function __construct( + Mpdf $mpdf, + Cache $cache, + CssManager $cssManager, + Form $form, + Otl $otl, + TableOfContents $tableOfContents, + SizeConverter $sizeConverter, + ColorConverter $colorConverter, + ImageProcessor $imageProcessor, + LanguageToFontInterface $languageToFont + ) { + + $this->mpdf = $mpdf; + $this->cache = $cache; + $this->cssManager = $cssManager; + $this->form = $form; + $this->otl = $otl; + $this->tableOfContents = $tableOfContents; + $this->sizeConverter = $sizeConverter; + $this->colorConverter = $colorConverter; + $this->imageProcessor = $imageProcessor; + $this->languageToFont = $languageToFont; + } + + public function getTagName() + { + $tag = get_class($this); + return strtoupper(str_replace('Mpdf\Tag\\', '', $tag)); + } + + abstract public function open($attr, &$ahtml, &$ihtml); + + abstract public function close(&$ahtml, &$ihtml); + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Td.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Td.php new file mode 100644 index 000000000..9f0bb93b1 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Td.php @@ -0,0 +1,473 @@ +<?php + +namespace Mpdf\Tag; + +use Mpdf\Css\Border; +use Mpdf\Css\TextVars; +use Mpdf\Utils\UtfString; + +class Td extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $tag = $this->getTagName(); + + $this->mpdf->ignorefollowingspaces = true; + $this->mpdf->lastoptionaltag = $tag; // Save current HTML specified optional endtag + + $this->cssManager->tbCSSlvl++; + + $this->mpdf->InlineProperties = []; + $this->mpdf->InlineBDF = []; // mPDF 6 + $this->mpdf->InlineBDFctr = 0; // mPDF 6 + $this->mpdf->tdbegin = true; + $this->mpdf->col++; + + while (isset($this->mpdf->cell[$this->mpdf->row][$this->mpdf->col])) { + $this->mpdf->col++; + } + + // Update number column + if ($this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['nc'] < $this->mpdf->col + 1) { + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['nc'] = $this->mpdf->col + 1; + } + + $table = &$this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]; + + $c = ['a' => false, + 'R' => false, + 'nowrap' => false, + 'bgcolor' => false, + 'padding' => ['L' => false, + 'R' => false, + 'T' => false, + 'B' => false + ] + ]; + + if ($this->mpdf->simpleTables && $this->mpdf->row == 0 && $this->mpdf->col == 0) { + $table['simple']['border'] = false; + $table['simple']['border_details']['R']['w'] = 0; + $table['simple']['border_details']['L']['w'] = 0; + $table['simple']['border_details']['T']['w'] = 0; + $table['simple']['border_details']['B']['w'] = 0; + $table['simple']['border_details']['R']['style'] = ''; + $table['simple']['border_details']['L']['style'] = ''; + $table['simple']['border_details']['T']['style'] = ''; + $table['simple']['border_details']['B']['style'] = ''; + } elseif (!$this->mpdf->simpleTables) { + $c['border'] = false; + $c['border_details']['R']['w'] = 0; + $c['border_details']['L']['w'] = 0; + $c['border_details']['T']['w'] = 0; + $c['border_details']['B']['w'] = 0; + $c['border_details']['mbw']['BL'] = 0; + $c['border_details']['mbw']['BR'] = 0; + $c['border_details']['mbw']['RT'] = 0; + $c['border_details']['mbw']['RB'] = 0; + $c['border_details']['mbw']['TL'] = 0; + $c['border_details']['mbw']['TR'] = 0; + $c['border_details']['mbw']['LT'] = 0; + $c['border_details']['mbw']['LB'] = 0; + $c['border_details']['R']['style'] = ''; + $c['border_details']['L']['style'] = ''; + $c['border_details']['T']['style'] = ''; + $c['border_details']['B']['style'] = ''; + $c['border_details']['R']['s'] = 0; + $c['border_details']['L']['s'] = 0; + $c['border_details']['T']['s'] = 0; + $c['border_details']['B']['s'] = 0; + $c['border_details']['R']['c'] = $this->colorConverter->convert(0, $this->mpdf->PDFAXwarnings); + $c['border_details']['L']['c'] = $this->colorConverter->convert(0, $this->mpdf->PDFAXwarnings); + $c['border_details']['T']['c'] = $this->colorConverter->convert(0, $this->mpdf->PDFAXwarnings); + $c['border_details']['B']['c'] = $this->colorConverter->convert(0, $this->mpdf->PDFAXwarnings); + $c['border_details']['R']['dom'] = 0; + $c['border_details']['L']['dom'] = 0; + $c['border_details']['T']['dom'] = 0; + $c['border_details']['B']['dom'] = 0; + $c['border_details']['cellposdom'] = 0; + } + + + if ($table['va']) { + $c['va'] = $table['va']; + } + if ($table['txta']) { + $c['a'] = $table['txta']; + } + if ($this->mpdf->table_border_attr_set && $table['border_details']) { + if (!$this->mpdf->simpleTables) { + $c['border_details']['R'] = $table['border_details']['R']; + $c['border_details']['L'] = $table['border_details']['L']; + $c['border_details']['T'] = $table['border_details']['T']; + $c['border_details']['B'] = $table['border_details']['B']; + $c['border'] = $table['border']; + $c['border_details']['L']['dom'] = 1; + $c['border_details']['R']['dom'] = 1; + $c['border_details']['T']['dom'] = 1; + $c['border_details']['B']['dom'] = 1; + } elseif ($this->mpdf->simpleTables && $this->mpdf->row == 0 && $this->mpdf->col == 0) { + $table['simple']['border_details']['R'] = $table['border_details']['R']; + $table['simple']['border_details']['L'] = $table['border_details']['L']; + $table['simple']['border_details']['T'] = $table['border_details']['T']; + $table['simple']['border_details']['B'] = $table['border_details']['B']; + $table['simple']['border'] = $table['border']; + } + } + // INHERITED THEAD CSS Properties + if ($this->mpdf->tablethead) { + if ($this->mpdf->thead_valign_default) { + $c['va'] = self::ALIGN[strtolower($this->mpdf->thead_valign_default)]; + } + if ($this->mpdf->thead_textalign_default) { + $c['a'] = self::ALIGN[strtolower($this->mpdf->thead_textalign_default)]; + } + if ($this->mpdf->thead_font_weight === 'B') { + $this->mpdf->SetStyle('B', true); + } + if ($this->mpdf->thead_font_style === 'I') { + $this->mpdf->SetStyle('I', true); + } + if ($this->mpdf->thead_font_smCaps === 'S') { + $this->mpdf->textvar |= TextVars::FC_SMALLCAPS; + } // mPDF 5.7.1 + } + + // INHERITED TFOOT CSS Properties + if ($this->mpdf->tabletfoot) { + if ($this->mpdf->tfoot_valign_default) { + $c['va'] = self::ALIGN[strtolower($this->mpdf->tfoot_valign_default)]; + } + if ($this->mpdf->tfoot_textalign_default) { + $c['a'] = self::ALIGN[strtolower($this->mpdf->tfoot_textalign_default)]; + } + if ($this->mpdf->tfoot_font_weight === 'B') { + $this->mpdf->SetStyle('B', true); + } + if ($this->mpdf->tfoot_font_style === 'I') { + $this->mpdf->SetStyle('I', true); + } + if ($this->mpdf->tfoot_font_style === 'S') { + $this->mpdf->textvar |= TextVars::FC_SMALLCAPS; + } // mPDF 5.7.1 + } + + + if ($this->mpdf->trow_text_rotate) { + $c['R'] = $this->mpdf->trow_text_rotate; + } + + $this->mpdf->cell_border_dominance_L = 0; + $this->mpdf->cell_border_dominance_R = 0; + $this->mpdf->cell_border_dominance_T = 0; + $this->mpdf->cell_border_dominance_B = 0; + + $properties = $this->cssManager->MergeCSS('TABLE', $tag, $attr); + + $properties = $this->cssManager->array_merge_recursive_unique($this->mpdf->base_table_properties, $properties); + + $this->mpdf->Reset(); // mPDF 6 ????????????????????? + + $this->mpdf->setCSS($properties, 'TABLECELL', $tag); + + $c['dfs'] = $this->mpdf->FontSize; // Default Font size + + + if (isset($properties['BACKGROUND-COLOR'])) { + $c['bgcolor'] = $properties['BACKGROUND-COLOR']; + } elseif (isset($properties['BACKGROUND'])) { + $c['bgcolor'] = $properties['BACKGROUND']; + } elseif (isset($attr['BGCOLOR'])) { + $c['bgcolor'] = $attr['BGCOLOR']; + } + + + + /* -- BACKGROUNDS -- */ + if (isset($properties['BACKGROUND-GRADIENT'])) { + $c['gradient'] = $properties['BACKGROUND-GRADIENT']; + } else { + $c['gradient'] = false; + } + + if (!empty($properties['BACKGROUND-IMAGE']) && !$this->mpdf->keep_block_together) { + $ret = $this->mpdf->SetBackground($properties, $this->mpdf->blk[$this->mpdf->blklvl]['inner_width']); + if ($ret) { + $c['background-image'] = $ret; + } + } + /* -- END BACKGROUNDS -- */ + if (isset($properties['VERTICAL-ALIGN'])) { + $c['va'] = self::ALIGN[strtolower($properties['VERTICAL-ALIGN'])]; + } elseif (isset($attr['VALIGN'])) { + $c['va'] = self::ALIGN[strtolower($attr['VALIGN'])]; + } + + + if (!empty($properties['TEXT-ALIGN'])) { + if (0 === strpos($properties['TEXT-ALIGN'], 'D')) { + $c['a'] = $properties['TEXT-ALIGN']; + } else { + $c['a'] = self::ALIGN[strtolower($properties['TEXT-ALIGN'])]; + } + } + if (!empty($attr['ALIGN'])) { + if (strtolower($attr['ALIGN']) === 'char') { + if (!empty($attr['CHAR'])) { + $char = html_entity_decode($attr['CHAR']); + $char = UtfString::strcode2utf($char); + $d = array_search($char, $this->mpdf->decimal_align); + if ($d !== false) { + $c['a'] = $d . 'R'; + } + } else { + $c['a'] = 'DPR'; + } + } else { + $c['a'] = self::ALIGN[strtolower($attr['ALIGN'])]; + } + } + + // mPDF 6 + $c['direction'] = $table['direction']; + if (isset($attr['DIR']) && $attr['DIR'] != '') { + $c['direction'] = strtolower($attr['DIR']); + } + if (isset($properties['DIRECTION'])) { + $c['direction'] = strtolower($properties['DIRECTION']); + } + + if (!$c['a']) { + if (isset($c['direction']) && $c['direction'] === 'rtl') { + $c['a'] = 'R'; + } else { + $c['a'] = 'L'; + } + } + + $c['cellLineHeight'] = $table['cellLineHeight']; + if (isset($properties['LINE-HEIGHT'])) { + $c['cellLineHeight'] = $this->mpdf->fixLineheight($properties['LINE-HEIGHT']); + } + + $c['cellLineStackingStrategy'] = $table['cellLineStackingStrategy']; + if (isset($properties['LINE-STACKING-STRATEGY'])) { + $c['cellLineStackingStrategy'] = strtolower($properties['LINE-STACKING-STRATEGY']); + } + + $c['cellLineStackingShift'] = $table['cellLineStackingShift']; + if (isset($properties['LINE-STACKING-SHIFT'])) { + $c['cellLineStackingShift'] = strtolower($properties['LINE-STACKING-SHIFT']); + } + + if (isset($properties['TEXT-ROTATE']) && ($properties['TEXT-ROTATE'] || $properties['TEXT-ROTATE'] === '0')) { + $c['R'] = $properties['TEXT-ROTATE']; + } + if (isset($properties['BORDER'])) { + $bord = $this->mpdf->border_details($properties['BORDER']); + if ($bord['s']) { + if (!$this->mpdf->simpleTables) { + $c['border'] = Border::ALL; + $c['border_details']['R'] = $bord; + $c['border_details']['L'] = $bord; + $c['border_details']['T'] = $bord; + $c['border_details']['B'] = $bord; + $c['border_details']['L']['dom'] = $this->mpdf->cell_border_dominance_L; + $c['border_details']['R']['dom'] = $this->mpdf->cell_border_dominance_R; + $c['border_details']['T']['dom'] = $this->mpdf->cell_border_dominance_T; + $c['border_details']['B']['dom'] = $this->mpdf->cell_border_dominance_B; + } elseif ($this->mpdf->simpleTables && $this->mpdf->row == 0 && $this->mpdf->col == 0) { + $table['simple']['border'] = Border::ALL; + $table['simple']['border_details']['R'] = $bord; + $table['simple']['border_details']['L'] = $bord; + $table['simple']['border_details']['T'] = $bord; + $table['simple']['border_details']['B'] = $bord; + } + } + } + if (!$this->mpdf->simpleTables) { + if (!empty($properties['BORDER-RIGHT'])) { + $c['border_details']['R'] = $this->mpdf->border_details($properties['BORDER-RIGHT']); + $this->mpdf->setBorder($c['border'], Border::RIGHT, $c['border_details']['R']['s']); + $c['border_details']['R']['dom'] = $this->mpdf->cell_border_dominance_R; + } + if (!empty($properties['BORDER-LEFT'])) { + $c['border_details']['L'] = $this->mpdf->border_details($properties['BORDER-LEFT']); + $this->mpdf->setBorder($c['border'], Border::LEFT, $c['border_details']['L']['s']); + $c['border_details']['L']['dom'] = $this->mpdf->cell_border_dominance_L; + } + if (!empty($properties['BORDER-BOTTOM'])) { + $c['border_details']['B'] = $this->mpdf->border_details($properties['BORDER-BOTTOM']); + $this->mpdf->setBorder($c['border'], Border::BOTTOM, $c['border_details']['B']['s']); + $c['border_details']['B']['dom'] = $this->mpdf->cell_border_dominance_B; + } + if (!empty($properties['BORDER-TOP'])) { + $c['border_details']['T'] = $this->mpdf->border_details($properties['BORDER-TOP']); + $this->mpdf->setBorder($c['border'], Border::TOP, $c['border_details']['T']['s']); + $c['border_details']['T']['dom'] = $this->mpdf->cell_border_dominance_T; + } + } elseif ($this->mpdf->simpleTables && $this->mpdf->row == 0 && $this->mpdf->col == 0) { + if (!empty($properties['BORDER-LEFT'])) { + $bord = $this->mpdf->border_details($properties['BORDER-LEFT']); + if ($bord['s']) { + $table['simple']['border'] = Border::ALL; + } else { + $table['simple']['border'] = 0; + } + $table['simple']['border_details']['R'] = $bord; + $table['simple']['border_details']['L'] = $bord; + $table['simple']['border_details']['T'] = $bord; + $table['simple']['border_details']['B'] = $bord; + } + } + + if ($this->mpdf->simpleTables && $this->mpdf->row == 0 && $this->mpdf->col == 0 && !$table['borders_separate'] && $table['simple']['border']) { + $table['border_details'] = $table['simple']['border_details']; + $table['border'] = $table['simple']['border']; + } + + // Border set on TR (if collapsed only) + if (!$table['borders_separate'] && !$this->mpdf->simpleTables && isset($table['trborder-left'][$this->mpdf->row])) { + if ($this->mpdf->col == 0) { + $left = $this->mpdf->border_details($table['trborder-left'][$this->mpdf->row]); + $c['border_details']['L'] = $left; + $this->mpdf->setBorder($c['border'], Border::LEFT, $c['border_details']['L']['s']); + } + $c['border_details']['B'] = $this->mpdf->border_details($table['trborder-bottom'][$this->mpdf->row]); + $this->mpdf->setBorder($c['border'], Border::BOTTOM, $c['border_details']['B']['s']); + $c['border_details']['T'] = $this->mpdf->border_details($table['trborder-top'][$this->mpdf->row]); + $this->mpdf->setBorder($c['border'], Border::TOP, $c['border_details']['T']['s']); + } + + if ($this->mpdf->packTableData && !$this->mpdf->simpleTables) { + $c['borderbin'] = $this->mpdf->_packCellBorder($c); + unset($c['border'], $c['border_details']); + } + + if (isset($properties['PADDING-LEFT'])) { + $c['padding']['L'] = $this->sizeConverter->convert($properties['PADDING-LEFT'], $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], $this->mpdf->FontSize, false); + } + if (isset($properties['PADDING-RIGHT'])) { + $c['padding']['R'] = $this->sizeConverter->convert($properties['PADDING-RIGHT'], $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], $this->mpdf->FontSize, false); + } + if (isset($properties['PADDING-BOTTOM'])) { + $c['padding']['B'] = $this->sizeConverter->convert($properties['PADDING-BOTTOM'], $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], $this->mpdf->FontSize, false); + } + if (isset($properties['PADDING-TOP'])) { + $c['padding']['T'] = $this->sizeConverter->convert($properties['PADDING-TOP'], $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], $this->mpdf->FontSize, false); + } + + $w = ''; + if (isset($properties['WIDTH'])) { + $w = $properties['WIDTH']; + } elseif (isset($attr['WIDTH'])) { + $w = $attr['WIDTH']; + } + if ($w) { + if (strpos($w, '%') && !$this->mpdf->ignore_table_percents) { + $c['wpercent'] = (float) $w; + } // makes 80% -> 80 + elseif (!strpos($w, '%') && !$this->mpdf->ignore_table_widths) { + $c['w'] = $this->sizeConverter->convert($w, $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], $this->mpdf->FontSize, false); + } + } + + if (isset($properties['HEIGHT']) && !strpos($properties['HEIGHT'], '%')) { + $c['h'] = $this->sizeConverter->convert($properties['HEIGHT'], $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], $this->mpdf->FontSize, false); + } elseif (isset($attr['HEIGHT']) && !strpos($attr['HEIGHT'], '%')) { + $c['h'] = $this->sizeConverter->convert($attr['HEIGHT'], $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], $this->mpdf->FontSize, false); + } + + if (isset($properties['WHITE-SPACE'])) { + if (strtoupper($properties['WHITE-SPACE']) === 'NOWRAP') { + $c['nowrap'] = 1; + } + } + + if (isset($attr['TEXT-ROTATE'])) { + $c['R'] = $attr['TEXT-ROTATE']; + } + if (!empty($attr['NOWRAP'])) { + $c['nowrap'] = 1; + } + + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col] = $c; + unset($c); + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s'] = 0; + + $cs = $rs = 1; + if (isset($attr['COLSPAN']) && $attr['COLSPAN'] > 1) { + $cs = $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['colspan'] = $attr['COLSPAN']; + } + if ($this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['nc'] < $this->mpdf->col + $cs) { + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['nc'] = $this->mpdf->col + $cs; + } // following code moved outside if... + for ($l = $this->mpdf->col; $l < $this->mpdf->col + $cs; $l++) { + if ($l - $this->mpdf->col) { + $this->mpdf->cell[$this->mpdf->row][$l] = 0; + } + } + if (isset($attr['ROWSPAN']) && $attr['ROWSPAN'] > 1) { + $rs = $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['rowspan'] = $attr['ROWSPAN']; + } + for ($k = $this->mpdf->row; $k < $this->mpdf->row + $rs; $k++) { + for ($l = $this->mpdf->col; $l < $this->mpdf->col + $cs; $l++) { + if ($k - $this->mpdf->row || $l - $this->mpdf->col) { + $this->mpdf->cell[$k][$l] = 0; + } + } + } + unset($table); + } + + public function close(&$ahtml, &$ihtml) + { + if ($this->mpdf->tableLevel) { + $this->mpdf->lastoptionaltag = 'TR'; + unset($this->cssManager->tablecascadeCSS[$this->cssManager->tbCSSlvl]); + $this->cssManager->tbCSSlvl--; + if (!$this->mpdf->tdbegin) { + return; + } + $this->mpdf->tdbegin = false; + // Added for correct calculation of cell column width - otherwise misses the last line if not end </p> etc. + if (!isset($this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['maxs'])) { + if (!is_array($this->mpdf->cell[$this->mpdf->row][$this->mpdf->col])) { + throw new \Mpdf\MpdfException('You may have an error in your HTML code e.g. </td></td>'); + } + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['maxs'] = $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s']; + } elseif ($this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['maxs'] < $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s']) { + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['maxs'] = $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s']; + } + + // Remove last <br> if at end of cell + $ntb = 0; + if (isset($this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['textbuffer'])) { + $ntb = count($this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['textbuffer']); + } + if ($ntb > 1 && $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['textbuffer'][$ntb - 1][0] === "\n") { + unset($this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['textbuffer'][$ntb - 1]); + } + + if ($this->mpdf->tablethead) { + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['is_thead'][$this->mpdf->row] = true; + if ($this->mpdf->tableLevel == 1) { + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['headernrows'] + = max($this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['headernrows'], $this->mpdf->row + 1); + } + } + if ($this->mpdf->tabletfoot) { + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['is_tfoot'][$this->mpdf->row] = true; + if ($this->mpdf->tableLevel == 1) { + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['footernrows'] + = max( + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['footernrows'], + $this->mpdf->row + 1 - $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['headernrows'] + ); + } + } + $this->mpdf->Reset(); + } + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/TextArea.php b/src/bb-vendor/mpdf/mpdf/src/Tag/TextArea.php new file mode 100644 index 000000000..8685fab6a --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/TextArea.php @@ -0,0 +1,162 @@ +<?php + +namespace Mpdf\Tag; + +use Mpdf\Mpdf; + +class TextArea extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $objattr = []; + $objattr['margin_top'] = 0; + $objattr['margin_bottom'] = 0; + $objattr['margin_left'] = 0; + $objattr['margin_right'] = 0; + $objattr['width'] = 0; + $objattr['height'] = 0; + $objattr['border_top']['w'] = 0; + $objattr['border_bottom']['w'] = 0; + $objattr['border_left']['w'] = 0; + $objattr['border_right']['w'] = 0; + if (isset($attr['DISABLED'])) { + $objattr['disabled'] = true; + } + if (isset($attr['READONLY'])) { + $objattr['readonly'] = true; + } + if (isset($attr['REQUIRED'])) { + $objattr['required'] = true; + } + if (isset($attr['SPELLCHECK']) && strtolower($attr['SPELLCHECK']) === 'true') { + $objattr['spellcheck'] = true; + } + if (isset($attr['TITLE'])) { + $objattr['title'] = $attr['TITLE']; + if ($this->mpdf->onlyCoreFonts) { + $objattr['title'] = mb_convert_encoding($objattr['title'], $this->mpdf->mb_enc, 'UTF-8'); + } + } + if ($this->mpdf->useActiveForms) { + if (isset($attr['NAME'])) { + $objattr['fieldname'] = $attr['NAME']; + } + $this->form->form_element_spacing['textarea']['outer']['v'] = 0; + $this->form->form_element_spacing['textarea']['inner']['v'] = 0; + if (isset($attr['ONCALCULATE'])) { + $objattr['onCalculate'] = $attr['ONCALCULATE']; + } elseif (isset($attr['ONCHANGE'])) { + $objattr['onCalculate'] = $attr['ONCHANGE']; + } + if (isset($attr['ONVALIDATE'])) { + $objattr['onValidate'] = $attr['ONVALIDATE']; + } + if (isset($attr['ONKEYSTROKE'])) { + $objattr['onKeystroke'] = $attr['ONKEYSTROKE']; + } + if (isset($attr['ONFORMAT'])) { + $objattr['onFormat'] = $attr['ONFORMAT']; + } + } + $this->mpdf->InlineProperties['TEXTAREA'] = $this->mpdf->saveInlineProperties(); + $properties = $this->cssManager->MergeCSS('', 'TEXTAREA', $attr); + if (isset($properties['FONT-FAMILY'])) { + $this->mpdf->SetFont($properties['FONT-FAMILY'], '', 0, false); + } + if (isset($properties['FONT-SIZE'])) { + $mmsize = $this->sizeConverter->convert($properties['FONT-SIZE'], $this->mpdf->default_font_size / Mpdf::SCALE); + $this->mpdf->SetFontSize($mmsize * Mpdf::SCALE, false); + } + if (isset($properties['COLOR'])) { + $objattr['color'] = $this->colorConverter->convert($properties['COLOR'], $this->mpdf->PDFAXwarnings); + } + $objattr['fontfamily'] = $this->mpdf->FontFamily; + $objattr['fontsize'] = $this->mpdf->FontSizePt; + if ($this->mpdf->useActiveForms) { + if (isset($properties['TEXT-ALIGN'])) { + $objattr['text_align'] = self::ALIGN[strtolower($properties['TEXT-ALIGN'])]; + } elseif (isset($attr['ALIGN'])) { + $objattr['text_align'] = self::ALIGN[strtolower($attr['ALIGN'])]; + } + if (isset($properties['OVERFLOW']) && strtolower($properties['OVERFLOW']) === 'hidden') { + $objattr['donotscroll'] = true; + } + if (isset($properties['BORDER-TOP-COLOR'])) { + $objattr['border-col'] = $this->colorConverter->convert($properties['BORDER-TOP-COLOR'], $this->mpdf->PDFAXwarnings); + } + if (isset($properties['BACKGROUND-COLOR'])) { + $objattr['background-col'] = $this->colorConverter->convert($properties['BACKGROUND-COLOR'], $this->mpdf->PDFAXwarnings); + } + } + $this->mpdf->SetLineHeight('', $this->form->textarea_lineheight); + + $w = 0; + $h = 0; + if (isset($properties['WIDTH'])) { + $w = $this->sizeConverter->convert( + $properties['WIDTH'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['HEIGHT'])) { + $h = $this->sizeConverter->convert( + $properties['HEIGHT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['VERTICAL-ALIGN'])) { + $objattr['vertical-align'] = self::ALIGN[strtolower($properties['VERTICAL-ALIGN'])]; + } + + $colsize = 20; //HTML default value + $rowsize = 2; //HTML default value + if (isset($attr['COLS'])) { + $colsize = (int) $attr['COLS']; + } + if (isset($attr['ROWS'])) { + $rowsize = (int) $attr['ROWS']; + } + + $charsize = $this->mpdf->GetCharWidth('w', false); + if ($w) { + $colsize = round(($w - ($this->form->form_element_spacing['textarea']['outer']['h'] * 2) + - ($this->form->form_element_spacing['textarea']['inner']['h'] * 2)) / $charsize); + } + if ($h) { + $rowsize = round(($h - ($this->form->form_element_spacing['textarea']['outer']['v'] * 2) + - ($this->form->form_element_spacing['textarea']['inner']['v'] * 2)) / $this->mpdf->lineheight); + } + + $objattr['type'] = 'textarea'; + $objattr['width'] = ($colsize * $charsize) + ($this->form->form_element_spacing['textarea']['outer']['h'] * 2) + + ($this->form->form_element_spacing['textarea']['inner']['h'] * 2); + + $objattr['height'] = ($rowsize * $this->mpdf->lineheight) + + ($this->form->form_element_spacing['textarea']['outer']['v'] * 2) + + ($this->form->form_element_spacing['textarea']['inner']['v'] * 2); + + $objattr['rows'] = $rowsize; + $objattr['cols'] = $colsize; + + $this->mpdf->specialcontent = serialize($objattr); + + if ($this->mpdf->tableLevel) { // *TABLES* + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s'] += $objattr['width']; // *TABLES* + } // *TABLES* + } + + public function close(&$ahtml, &$ihtml) + { + $this->mpdf->ignorefollowingspaces = false; + $this->mpdf->specialcontent = ''; + if ($this->mpdf->InlineProperties['TEXTAREA']) { + $this->mpdf->restoreInlineProperties($this->mpdf->InlineProperties['TEXTAREA']); + } + unset($this->mpdf->InlineProperties['TEXTAREA']); + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/TextCircle.php b/src/bb-vendor/mpdf/mpdf/src/Tag/TextCircle.php new file mode 100644 index 000000000..6bd531330 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/TextCircle.php @@ -0,0 +1,250 @@ +<?php + +namespace Mpdf\Tag; + +use Mpdf\Mpdf; +use Mpdf\Utils\UtfString; + +class TextCircle extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $objattr = []; + $objattr['margin_top'] = 0; + $objattr['margin_bottom'] = 0; + $objattr['margin_left'] = 0; + $objattr['margin_right'] = 0; + $objattr['padding_top'] = 0; + $objattr['padding_bottom'] = 0; + $objattr['padding_left'] = 0; + $objattr['padding_right'] = 0; + $objattr['width'] = 0; + $objattr['height'] = 0; + $objattr['border_top']['w'] = 0; + $objattr['border_bottom']['w'] = 0; + $objattr['border_left']['w'] = 0; + $objattr['border_right']['w'] = 0; + $objattr['top-text'] = ''; + $objattr['bottom-text'] = ''; + $objattr['r'] = 20; // radius (default value here for safety) + $objattr['space-width'] = 120; + $objattr['char-width'] = 100; + + $this->mpdf->InlineProperties['TEXTCIRCLE'] = $this->mpdf->saveInlineProperties(); + $properties = $this->cssManager->MergeCSS('INLINE', 'TEXTCIRCLE', $attr); + + if (isset($properties ['DISPLAY']) && strtolower($properties ['DISPLAY']) === 'none') { + return; + } + if (isset($attr['R'])) { + $objattr['r'] = $this->sizeConverter->convert( + $attr['R'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($attr['TOP-TEXT'])) { + $objattr['top-text'] = UtfString::strcode2utf($attr['TOP-TEXT']); + $objattr['top-text'] = $this->mpdf->lesser_entity_decode($objattr['top-text']); + if ($this->mpdf->onlyCoreFonts) { + $objattr['top-text'] = mb_convert_encoding($objattr['top-text'], $this->mpdf->mb_enc, 'UTF-8'); + } + } + if (isset($attr['BOTTOM-TEXT'])) { + $objattr['bottom-text'] = UtfString::strcode2utf($attr['BOTTOM-TEXT']); + $objattr['bottom-text'] = $this->mpdf->lesser_entity_decode($objattr['bottom-text']); + if ($this->mpdf->onlyCoreFonts) { + $objattr['bottom-text'] = mb_convert_encoding($objattr['bottom-text'], $this->mpdf->mb_enc, 'UTF-8'); + } + } + if (!empty($attr['SPACE-WIDTH'])) { + $objattr['space-width'] = $attr['SPACE-WIDTH']; + } + if (!empty($attr['CHAR-WIDTH'])) { + $objattr['char-width'] = $attr['CHAR-WIDTH']; + } + + // VISIBILITY + $objattr['visibility'] = 'visible'; + if (isset($properties['VISIBILITY'])) { + $v = strtolower($properties['VISIBILITY']); + if (($v === 'hidden' || $v === 'printonly' || $v === 'screenonly') && $this->mpdf->visibility === 'visible') { + $objattr['visibility'] = $v; + } + } + if (isset($properties['FONT-SIZE'])) { + if (strtolower($properties['FONT-SIZE']) === 'auto') { + if ($objattr['top-text'] && $objattr['bottom-text']) { + $objattr['fontsize'] = -2; + } else { + $objattr['fontsize'] = -1; + } + } else { + $mmsize = $this->sizeConverter->convert($properties['FONT-SIZE'], $this->mpdf->default_font_size / Mpdf::SCALE); + $this->mpdf->SetFontSize($mmsize * Mpdf::SCALE, false); + $objattr['fontsize'] = $this->mpdf->FontSizePt; + } + } + if (isset($attr['DIVIDER'])) { + $objattr['divider'] = UtfString::strcode2utf($attr['DIVIDER']); + $objattr['divider'] = $this->mpdf->lesser_entity_decode($objattr['divider']); + if ($this->mpdf->onlyCoreFonts) { + $objattr['divider'] = mb_convert_encoding($objattr['divider'], $this->mpdf->mb_enc, 'UTF-8'); + } + } + + if (isset($properties['COLOR'])) { + $objattr['color'] = $this->colorConverter->convert($properties['COLOR'], $this->mpdf->PDFAXwarnings); + } + + $objattr['fontstyle'] = ''; + if (isset($properties['FONT-WEIGHT'])) { + if (strtoupper($properties['FONT-WEIGHT']) === 'BOLD') { + $objattr['fontstyle'] .= 'B'; + } + } + if (isset($properties['FONT-STYLE'])) { + if (strtoupper($properties['FONT-STYLE']) === 'ITALIC') { + $objattr['fontstyle'] .= 'I'; + } + } + + if (isset($properties['FONT-FAMILY'])) { + $this->mpdf->SetFont($properties['FONT-FAMILY'], $this->mpdf->FontStyle, 0, false); + } + $objattr['fontfamily'] = $this->mpdf->FontFamily; + + // VSPACE and HSPACE converted to margins in MergeCSS + if (isset($properties['MARGIN-TOP'])) { + $objattr['margin_top'] = $this->sizeConverter->convert( + $properties['MARGIN-TOP'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['MARGIN-BOTTOM'])) { + $objattr['margin_bottom'] = $this->sizeConverter->convert( + $properties['MARGIN-BOTTOM'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['MARGIN-LEFT'])) { + $objattr['margin_left'] = $this->sizeConverter->convert( + $properties['MARGIN-LEFT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['MARGIN-RIGHT'])) { + $objattr['margin_right'] = $this->sizeConverter->convert( + $properties['MARGIN-RIGHT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + + if (isset($properties['PADDING-TOP'])) { + $objattr['padding_top'] = $this->sizeConverter->convert( + $properties['PADDING-TOP'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['PADDING-BOTTOM'])) { + $objattr['padding_bottom'] = $this->sizeConverter->convert( + $properties['PADDING-BOTTOM'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['PADDING-LEFT'])) { + $objattr['padding_left'] = $this->sizeConverter->convert( + $properties['PADDING-LEFT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + if (isset($properties['PADDING-RIGHT'])) { + $objattr['padding_right'] = $this->sizeConverter->convert( + $properties['PADDING-RIGHT'], + $this->mpdf->blk[$this->mpdf->blklvl]['inner_width'], + $this->mpdf->FontSize, + false + ); + } + + if (isset($properties['BORDER-TOP'])) { + $objattr['border_top'] = $this->mpdf->border_details($properties['BORDER-TOP']); + } + if (isset($properties['BORDER-BOTTOM'])) { + $objattr['border_bottom'] = $this->mpdf->border_details($properties['BORDER-BOTTOM']); + } + if (isset($properties['BORDER-LEFT'])) { + $objattr['border_left'] = $this->mpdf->border_details($properties['BORDER-LEFT']); + } + if (isset($properties['BORDER-RIGHT'])) { + $objattr['border_right'] = $this->mpdf->border_details($properties['BORDER-RIGHT']); + } + + if (isset($properties['OPACITY']) && $properties['OPACITY'] > 0 && $properties['OPACITY'] <= 1) { + $objattr['opacity'] = $properties['OPACITY']; + } + if (isset($properties['BACKGROUND-COLOR']) && $properties['BACKGROUND-COLOR'] != '') { + $objattr['bgcolor'] = $this->colorConverter->convert($properties['BACKGROUND-COLOR'], $this->mpdf->PDFAXwarnings); + } else { + $objattr['bgcolor'] = false; + } + if ($this->mpdf->HREF) { + if (strpos($this->mpdf->HREF, '.') === false && strpos($this->mpdf->HREF, '@') !== 0) { + $href = $this->mpdf->HREF; + while (array_key_exists($href, $this->mpdf->internallink)) { + $href = '#' . $href; + } + $this->mpdf->internallink[$href] = $this->mpdf->AddLink(); + $objattr['link'] = $this->mpdf->internallink[$href]; + } else { + $objattr['link'] = $this->mpdf->HREF; + } + } + $extraheight = $objattr['padding_top'] + $objattr['padding_bottom'] + $objattr['margin_top'] + $objattr['margin_bottom'] + $objattr['border_top']['w'] + $objattr['border_bottom']['w']; + $extrawidth = $objattr['padding_left'] + $objattr['padding_right'] + $objattr['margin_left'] + $objattr['margin_right'] + $objattr['border_left']['w'] + $objattr['border_right']['w']; + + + $w = $objattr['r'] * 2; + $h = $w; + $objattr['height'] = $h + $extraheight; + $objattr['width'] = $w + $extrawidth; + $objattr['type'] = 'textcircle'; + + $e = "\xbb\xa4\xactype=image,objattr=" . serialize($objattr) . "\xbb\xa4\xac"; + + /* -- TABLES -- */ + // Output it to buffers + if ($this->mpdf->tableLevel) { + $this->mpdf->_saveCellTextBuffer($e, $this->mpdf->HREF); + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['s'] += $objattr['width']; + } else { + /* -- END TABLES -- */ + $this->mpdf->_saveTextBuffer($e, $this->mpdf->HREF); + } // *TABLES* + + if ($this->mpdf->InlineProperties['TEXTCIRCLE']) { + $this->mpdf->restoreInlineProperties($this->mpdf->InlineProperties['TEXTCIRCLE']); + } + unset($this->mpdf->InlineProperties['TEXTCIRCLE']); + } + + public function close(&$ahtml, &$ihtml) + { + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Th.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Th.php new file mode 100644 index 000000000..c0df792cd --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Th.php @@ -0,0 +1,13 @@ +<?php + +namespace Mpdf\Tag; + +class Th extends Td +{ + + public function close(&$ahtml, &$ihtml) + { + $this->mpdf->SetStyle('B', false); + parent::close($ahtml, $ihtml); + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Time.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Time.php new file mode 100644 index 000000000..04ffb6ea7 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Time.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Time extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Toc.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Toc.php new file mode 100644 index 000000000..1afeae861 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Toc.php @@ -0,0 +1,17 @@ +<?php + +namespace Mpdf\Tag; + +class Toc extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + //added custom-tag - set Marker for insertion later of ToC + $this->tableOfContents->openTagTOC($attr); + } + + public function close(&$ahtml, &$ihtml) + { + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/TocEntry.php b/src/bb-vendor/mpdf/mpdf/src/Tag/TocEntry.php new file mode 100644 index 000000000..1b315abeb --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/TocEntry.php @@ -0,0 +1,38 @@ +<?php + +namespace Mpdf\Tag; + +class TocEntry extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + if (!empty($attr['CONTENT'])) { + $objattr = []; + $objattr['CONTENT'] = htmlspecialchars_decode($attr['CONTENT'], ENT_QUOTES); + $objattr['type'] = 'toc'; + $objattr['vertical-align'] = 'T'; + if (!empty($attr['LEVEL'])) { + $objattr['toclevel'] = $attr['LEVEL']; + } else { + $objattr['toclevel'] = 0; + } + if (!empty($attr['NAME'])) { + $objattr['toc_id'] = $attr['NAME']; + } else { + $objattr['toc_id'] = 0; + } + $e = "\xbb\xa4\xactype=toc,objattr=" . serialize($objattr) . "\xbb\xa4\xac"; + if ($this->mpdf->tableLevel) { + $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]['textbuffer'][] = [$e]; + } // *TABLES* + else { // *TABLES* + $this->mpdf->textbuffer[] = [$e]; + } // *TABLES* + } + } + + public function close(&$ahtml, &$ihtml) + { + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/TocPageBreak.php b/src/bb-vendor/mpdf/mpdf/src/Tag/TocPageBreak.php new file mode 100644 index 000000000..19c516763 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/TocPageBreak.php @@ -0,0 +1,16 @@ +<?php + +namespace Mpdf\Tag; + +class TocPageBreak extends FormFeed +{ + public function open($attr, &$ahtml, &$ihtml) + { + list($isbreak, $toc_id) = $this->tableOfContents->openTagTOCPAGEBREAK($attr); + $this->toc_id = $toc_id; + if ($isbreak) { + return; + } + parent::open($attr, $ahtml, $ihtml); + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Tr.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Tr.php new file mode 100644 index 000000000..f891df99b --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Tr.php @@ -0,0 +1,102 @@ +<?php + +namespace Mpdf\Tag; + +use Mpdf\Css\Border; + +class Tr extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + + $this->mpdf->lastoptionaltag = 'TR'; // Save current HTML specified optional endtag + $this->cssManager->tbCSSlvl++; + $this->mpdf->row++; + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['nr'] ++; + $this->mpdf->col = -1; + $properties = $this->cssManager->MergeCSS('TABLE', 'TR', $attr); + + if (!$this->mpdf->simpleTables && (!isset($this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['borders_separate']) + || !$this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['borders_separate'])) { + if (!empty($properties['BORDER-LEFT'])) { + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['trborder-left'][$this->mpdf->row] = $properties['BORDER-LEFT']; + } + if (!empty($properties['BORDER-RIGHT'])) { + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['trborder-right'][$this->mpdf->row] = $properties['BORDER-RIGHT']; + } + if (!empty($properties['BORDER-TOP'])) { + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['trborder-top'][$this->mpdf->row] = $properties['BORDER-TOP']; + } + if (!empty($properties['BORDER-BOTTOM'])) { + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['trborder-bottom'][$this->mpdf->row] = $properties['BORDER-BOTTOM']; + } + } + + if (isset($properties['BACKGROUND-COLOR'])) { + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['bgcolor'][$this->mpdf->row] = $properties['BACKGROUND-COLOR']; + } elseif (isset($attr['BGCOLOR'])) { + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['bgcolor'][$this->mpdf->row] = $attr['BGCOLOR']; + } + + /* -- BACKGROUNDS -- */ + if (isset($properties['BACKGROUND-GRADIENT']) && !$this->mpdf->kwt && !$this->mpdf->ColActive) { + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['trgradients'][$this->mpdf->row] = $properties['BACKGROUND-GRADIENT']; + } + + // FIXME: undefined variable $currblk + if (!empty($properties['BACKGROUND-IMAGE']) && !$this->mpdf->kwt && !$this->mpdf->ColActive) { + $ret = $this->mpdf->SetBackground($properties, $currblk['inner_width']); + if ($ret) { + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['trbackground-images'][$this->mpdf->row] = $ret; + } + } + /* -- END BACKGROUNDS -- */ + + if (isset($properties['TEXT-ROTATE'])) { + $this->mpdf->trow_text_rotate = $properties['TEXT-ROTATE']; + } + if (isset($attr['TEXT-ROTATE'])) { + $this->mpdf->trow_text_rotate = $attr['TEXT-ROTATE']; + } + + if ($this->mpdf->tablethead) { + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['is_thead'][$this->mpdf->row] = true; + } + if ($this->mpdf->tabletfoot) { + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['is_tfoot'][$this->mpdf->row] = true; + } + } + + public function close(&$ahtml, &$ihtml) + { + if ($this->mpdf->tableLevel) { + // If Border set on TR - Update right border + if (isset($this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['trborder-left'][$this->mpdf->row])) { + $c = & $this->mpdf->cell[$this->mpdf->row][$this->mpdf->col]; + if ($c) { + if ($this->mpdf->packTableData) { + $cell = $this->mpdf->_unpackCellBorder($c['borderbin']); + } else { + $cell = $c; + } + $cell['border_details']['R'] = $this->mpdf->border_details( + $this->mpdf->table[$this->mpdf->tableLevel][$this->mpdf->tbctr[$this->mpdf->tableLevel]]['trborder-right'][$this->mpdf->row] + ); + $this->mpdf->setBorder($cell['border'], Border::RIGHT, $cell['border_details']['R']['s']); + if ($this->mpdf->packTableData) { + $c['borderbin'] = $this->mpdf->_packCellBorder($cell); + unset($c['border'], $c['border_details']); + } else { + $c = $cell; + } + } + } + $this->mpdf->lastoptionaltag = ''; + unset($this->cssManager->tablecascadeCSS[$this->cssManager->tbCSSlvl]); + $this->cssManager->tbCSSlvl--; + $this->mpdf->trow_text_rotate = ''; + $this->mpdf->tabletheadjustfinished = false; + } + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Tt.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Tt.php new file mode 100644 index 000000000..078277ad8 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Tt.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Tt extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Tta.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Tta.php new file mode 100644 index 000000000..bac9fb57e --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Tta.php @@ -0,0 +1,22 @@ +<?php + +namespace Mpdf\Tag; + +class Tta extends SubstituteTag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $this->mpdf->tta = true; + $this->mpdf->InlineProperties['TTA'] = $this->mpdf->saveInlineProperties(); + + if (in_array($this->mpdf->FontFamily, $this->mpdf->mono_fonts)) { + $this->mpdf->setCSS(['FONT-FAMILY' => 'ccourier'], 'INLINE'); + } elseif (in_array($this->mpdf->FontFamily, $this->mpdf->serif_fonts)) { + $this->mpdf->setCSS(['FONT-FAMILY' => 'ctimes'], 'INLINE'); + } else { + $this->mpdf->setCSS(['FONT-FAMILY' => 'chelvetica'], 'INLINE'); + } + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Tts.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Tts.php new file mode 100644 index 000000000..f24d722cf --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Tts.php @@ -0,0 +1,15 @@ +<?php + +namespace Mpdf\Tag; + +class Tts extends SubstituteTag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $this->mpdf->tts = true; + $this->mpdf->InlineProperties['TTS'] = $this->mpdf->saveInlineProperties(); + $this->mpdf->setCSS(['FONT-FAMILY' => 'csymbol', 'FONT-WEIGHT' => 'normal', 'FONT-STYLE' => 'normal'], 'INLINE'); + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Ttz.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Ttz.php new file mode 100644 index 000000000..d76d4c553 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Ttz.php @@ -0,0 +1,15 @@ +<?php + +namespace Mpdf\Tag; + +class Ttz extends SubstituteTag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $this->mpdf->ttz = true; + $this->mpdf->InlineProperties['TTZ'] = $this->mpdf->saveInlineProperties(); + $this->mpdf->setCSS(['FONT-FAMILY' => 'czapfdingbats', 'FONT-WEIGHT' => 'normal', 'FONT-STYLE' => 'normal'], 'INLINE'); + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/U.php b/src/bb-vendor/mpdf/mpdf/src/Tag/U.php new file mode 100644 index 000000000..513298d72 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/U.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class U extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/Ul.php b/src/bb-vendor/mpdf/mpdf/src/Tag/Ul.php new file mode 100644 index 000000000..6efa4d6cb --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/Ul.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class Ul extends BlockTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/VarTag.php b/src/bb-vendor/mpdf/mpdf/src/Tag/VarTag.php new file mode 100644 index 000000000..556dd40e1 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/VarTag.php @@ -0,0 +1,9 @@ +<?php + +namespace Mpdf\Tag; + +class VarTag extends InlineTag +{ + + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/WatermarkImage.php b/src/bb-vendor/mpdf/mpdf/src/Tag/WatermarkImage.php new file mode 100644 index 000000000..21f8c48b5 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/WatermarkImage.php @@ -0,0 +1,41 @@ +<?php + +namespace Mpdf\Tag; + +class WatermarkImage extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $src = ''; + if (isset($attr['SRC'])) { + $src = $attr['SRC']; + } + + $alpha = -1; + if (isset($attr['ALPHA']) && $attr['ALPHA'] > 0) { + $alpha = $attr['ALPHA']; + } + + $size = 'D'; + if (!empty($attr['SIZE'])) { + $size = $attr['SIZE']; + if (strpos($size, ',')) { + $size = explode(',', $size); + } + } + + $pos = 'P'; + if (!empty($attr['POSITION'])) { // mPDF 5.7.2 + $pos = $attr['POSITION']; + if (strpos($pos, ',')) { + $pos = explode(',', $pos); + } + } + $this->mpdf->SetWatermarkImage($src, $alpha, $size, $pos); + } + + public function close(&$ahtml, &$ihtml) + { + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Tag/WatermarkText.php b/src/bb-vendor/mpdf/mpdf/src/Tag/WatermarkText.php new file mode 100644 index 000000000..8d6dcc2dc --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Tag/WatermarkText.php @@ -0,0 +1,25 @@ +<?php + +namespace Mpdf\Tag; + +class WatermarkText extends Tag +{ + + public function open($attr, &$ahtml, &$ihtml) + { + $txt = ''; + if (!empty($attr['CONTENT'])) { + $txt = htmlspecialchars_decode($attr['CONTENT'], ENT_QUOTES); + } + + $alpha = -1; + if (isset($attr['ALPHA']) && $attr['ALPHA'] > 0) { + $alpha = $attr['ALPHA']; + } + $this->mpdf->SetWatermarkText($txt, $alpha); + } + + public function close(&$ahtml, &$ihtml) + { + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Ucdn.php b/src/bb-vendor/mpdf/mpdf/src/Ucdn.php new file mode 100644 index 000000000..dbf7caaec --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Ucdn.php @@ -0,0 +1,2921 @@ +<?php + +namespace Mpdf; + +class Ucdn +{ + + /* HarfBuzz ucdn/unicodedata_db.h */ + /* HarfBuzz ucdn/ucdn.c */ + /* HarfBuzz ucdn/ucdn.h */ + + const SCRIPT_COMMON = 0; + const SCRIPT_LATIN = 1; + const SCRIPT_GREEK = 2; + const SCRIPT_CYRILLIC = 3; + const SCRIPT_ARMENIAN = 4; + const SCRIPT_HEBREW = 5; + const SCRIPT_ARABIC = 6; + const SCRIPT_SYRIAC = 7; + const SCRIPT_THAANA = 8; + const SCRIPT_DEVANAGARI = 9; + const SCRIPT_BENGALI = 10; + const SCRIPT_GURMUKHI = 11; + const SCRIPT_GUJARATI = 12; + const SCRIPT_ORIYA = 13; + const SCRIPT_TAMIL = 14; + const SCRIPT_TELUGU = 15; + const SCRIPT_KANNADA = 16; + const SCRIPT_MALAYALAM = 17; + const SCRIPT_SINHALA = 18; + const SCRIPT_THAI = 19; + const SCRIPT_LAO = 20; + const SCRIPT_TIBETAN = 21; + const SCRIPT_MYANMAR = 22; + const SCRIPT_GEORGIAN = 23; + const SCRIPT_HANGUL = 24; + const SCRIPT_ETHIOPIC = 25; + const SCRIPT_CHEROKEE = 26; + const SCRIPT_CANADIAN_ABORIGINAL = 27; + const SCRIPT_OGHAM = 28; + const SCRIPT_RUNIC = 29; + const SCRIPT_KHMER = 30; + const SCRIPT_MONGOLIAN = 31; + const SCRIPT_HIRAGANA = 32; + const SCRIPT_KATAKANA = 33; + const SCRIPT_BOPOMOFO = 34; + const SCRIPT_HAN = 35; + const SCRIPT_YI = 36; + const SCRIPT_OLD_ITALIC = 37; + const SCRIPT_GOTHIC = 38; + const SCRIPT_DESERET = 39; + const SCRIPT_INHERITED = 40; + const SCRIPT_TAGALOG = 41; + const SCRIPT_HANUNOO = 42; + const SCRIPT_BUHID = 43; + const SCRIPT_TAGBANWA = 44; + const SCRIPT_LIMBU = 45; + const SCRIPT_TAI_LE = 46; + const SCRIPT_LINEAR_B = 47; + const SCRIPT_UGARITIC = 48; + const SCRIPT_SHAVIAN = 49; + const SCRIPT_OSMANYA = 50; + const SCRIPT_CYPRIOT = 51; + const SCRIPT_BRAILLE = 52; + const SCRIPT_BUGINESE = 53; + const SCRIPT_COPTIC = 54; + const SCRIPT_NEW_TAI_LUE = 55; + const SCRIPT_GLAGOLITIC = 56; + const SCRIPT_TIFINAGH = 57; + const SCRIPT_SYLOTI_NAGRI = 58; + const SCRIPT_OLD_PERSIAN = 59; + const SCRIPT_KHAROSHTHI = 60; + const SCRIPT_BALINESE = 61; + const SCRIPT_CUNEIFORM = 62; + const SCRIPT_PHOENICIAN = 63; + const SCRIPT_PHAGS_PA = 64; + const SCRIPT_NKO = 65; + const SCRIPT_SUNDANESE = 66; + const SCRIPT_LEPCHA = 67; + const SCRIPT_OL_CHIKI = 68; + const SCRIPT_VAI = 69; + const SCRIPT_SAURASHTRA = 70; + const SCRIPT_KAYAH_LI = 71; + const SCRIPT_REJANG = 72; + const SCRIPT_LYCIAN = 73; + const SCRIPT_CARIAN = 74; + const SCRIPT_LYDIAN = 75; + const SCRIPT_CHAM = 76; + const SCRIPT_TAI_THAM = 77; + const SCRIPT_TAI_VIET = 78; + const SCRIPT_AVESTAN = 79; + const SCRIPT_EGYPTIAN_HIEROGLYPHS = 80; + const SCRIPT_SAMARITAN = 81; + const SCRIPT_LISU = 82; + const SCRIPT_BAMUM = 83; + const SCRIPT_JAVANESE = 84; + const SCRIPT_MEETEI_MAYEK = 85; + const SCRIPT_IMPERIAL_ARAMAIC = 86; + const SCRIPT_OLD_SOUTH_ARABIAN = 87; + const SCRIPT_INSCRIPTIONAL_PARTHIAN = 88; + const SCRIPT_INSCRIPTIONAL_PAHLAVI = 89; + const SCRIPT_OLD_TURKIC = 90; + const SCRIPT_KAITHI = 91; + const SCRIPT_BATAK = 92; + const SCRIPT_BRAHMI = 93; + const SCRIPT_MANDAIC = 94; + const SCRIPT_CHAKMA = 95; + const SCRIPT_MEROITIC_CURSIVE = 96; + const SCRIPT_MEROITIC_HIEROGLYPHS = 97; + const SCRIPT_MIAO = 98; + const SCRIPT_SHARADA = 99; + const SCRIPT_SORA_SOMPENG = 100; + const SCRIPT_TAKRI = 101; + const SCRIPT_UNKNOWN = 102; + + public static function get_ucd_record($code) + { + if ($code >= 0x110000) { + $index = 0; + } else { + $index = self::$index0[$code >> (8)] << 5; + $offset = ($code >> 3) & ((1 << 5) - 1); + $index = self::$index1[$index + $offset] << 3; + $offset = $code & ((1 << 3) - 1); + $index = self::$index2[$index + $offset]; + } + return self::$ucd_records[$index]; + } + + public static function get_general_category($code) + { + $ucd_record = self::get_ucd_record($code); + return $ucd_record[0]; + } + + public static function get_combining_class($code) + { + $ucd_record = self::get_ucd_record($code); + return $ucd_record[1]; + } + + public static function get_bidi_class($code) + { + $ucd_record = self::get_ucd_record($code); + return $ucd_record[2]; + } + + public static function get_mirrored($code) + { + $ucd_record = self::get_ucd_record($code); + return $ucd_record[3]; + } + + public static function get_east_asian_width($code) + { + $ucd_record = self::get_ucd_record($code); + return $ucd_record[4]; + } + + public static function get_normalization_check($code) + { + $ucd_record = self::get_ucd_record($code); + return $ucd_record[5]; + } + + public static function get_script($code) + { + $ucd_record = self::get_ucd_record($code); + return $ucd_record[6]; + } + + // mPDF added + public static $uni_scriptblock = [ + /* SCRIPT_COMMON */ 0 => '', + /* SCRIPT_LATIN */ 1 => 'latn', + /* SCRIPT_GREEK */ 2 => 'grek', + /* SCRIPT_CYRILLIC */ 3 => 'cyrl', + /* SCRIPT_ARMENIAN */ 4 => 'armn', + /* SCRIPT_HEBREW */ 5 => 'hebr', + /* SCRIPT_ARABIC */ 6 => 'arab', + /* SCRIPT_SYRIAC */ 7 => 'syrc', + /* SCRIPT_THAANA */ 8 => 'thaa', + /* SCRIPT_DEVANAGARI */ 9 => 'dev2', + /* SCRIPT_BENGALI */ 10 => 'bng2', + /* SCRIPT_GURMUKHI */ 11 => 'gur2', + /* SCRIPT_GUJARATI */ 12 => 'gjr2', + /* SCRIPT_ORIYA */ 13 => 'ory2', + /* SCRIPT_TAMIL */ 14 => 'tml2', + /* SCRIPT_TELUGU */ 15 => 'tel2', + /* SCRIPT_KANNADA */ 16 => 'knd2', + /* SCRIPT_MALAYALAM */ 17 => 'mlm2', + /* SCRIPT_SINHALA */ 18 => 'sinh', + /* SCRIPT_THAI */ 19 => 'thai', + /* SCRIPT_LAO */ 20 => 'lao ', + /* SCRIPT_TIBETAN */ 21 => 'tibt', + /* SCRIPT_MYANMAR */ 22 => 'mym2', + /* SCRIPT_GEORGIAN */ 23 => 'geor', + /* SCRIPT_HANGUL */ 24 => 'jamo', /* there is also a hang tag, but we want to activate jamo features if present */ + /* SCRIPT_ETHIOPIC */ 25 => 'ethi', + /* SCRIPT_CHEROKEE */ 26 => 'cher', + /* SCRIPT_CANADIAN_ABORIGINAL */ 27 => 'cans', + /* SCRIPT_OGHAM */ 28 => 'ogam', + /* SCRIPT_RUNIC */ 29 => 'runr', + /* SCRIPT_KHMER */ 30 => 'khmr', + /* SCRIPT_MONGOLIAN */ 31 => 'mong', + /* SCRIPT_HIRAGANA */ 32 => 'kana', + /* SCRIPT_KATAKANA */ 33 => 'kana', + /* SCRIPT_BOPOMOFO */ 34 => 'bopo', + /* SCRIPT_HAN */ 35 => 'hani', + /* SCRIPT_YI */ 36 => 'yi ', + /* SCRIPT_OLD_ITALIC */ 37 => 'ital', + /* SCRIPT_GOTHIC */ 38 => 'goth', + /* SCRIPT_DESERET */ 39 => 'dsrt', + /* SCRIPT_INHERITED */ 40 => '', + /* SCRIPT_TAGALOG */ 41 => 'tglg', + /* SCRIPT_HANUNOO */ 42 => 'hano', + /* SCRIPT_BUHID */ 43 => 'buhd', + /* SCRIPT_TAGBANWA */ 44 => 'tagb', + /* SCRIPT_LIMBU */ 45 => 'limb', + /* SCRIPT_TAI_LE */ 46 => 'tale', + /* SCRIPT_LINEAR_B */ 47 => 'linb', + /* SCRIPT_UGARITIC */ 48 => 'ugar', + /* SCRIPT_SHAVIAN */ 49 => 'shaw', + /* SCRIPT_OSMANYA */ 50 => 'osma', + /* SCRIPT_CYPRIOT */ 51 => 'cprt', + /* SCRIPT_BRAILLE */ 52 => 'brai', + /* SCRIPT_BUGINESE */ 53 => 'bugi', + /* SCRIPT_COPTIC */ 54 => 'copt', + /* SCRIPT_NEW_TAI_LUE */ 55 => 'talu', + /* SCRIPT_GLAGOLITIC */ 56 => 'glag', + /* SCRIPT_TIFINAGH */ 57 => 'tfng', + /* SCRIPT_SYLOTI_NAGRI */ 58 => 'sylo', + /* SCRIPT_OLD_PERSIAN */ 59 => 'xpeo', + /* SCRIPT_KHAROSHTHI */ 60 => 'khar', + /* SCRIPT_BALINESE */ 61 => 'bali', + /* SCRIPT_CUNEIFORM */ 62 => 'xsux', + /* SCRIPT_PHOENICIAN */ 63 => 'phnx', + /* SCRIPT_PHAGS_PA */ 64 => 'phag', + /* SCRIPT_NKO */ 65 => 'nko ', + /* SCRIPT_SUNDANESE */ 66 => 'sund', + /* SCRIPT_LEPCHA */ 67 => 'lepc', + /* SCRIPT_OL_CHIKI */ 68 => 'olck', + /* SCRIPT_VAI */ 69 => 'vai ', + /* SCRIPT_SAURASHTRA */ 70 => 'saur', + /* SCRIPT_KAYAH_LI */ 71 => 'kali', + /* SCRIPT_REJANG */ 72 => 'rjng', + /* SCRIPT_LYCIAN */ 73 => 'lyci', + /* SCRIPT_CARIAN */ 74 => 'cari', + /* SCRIPT_LYDIAN */ 75 => 'lydi', + /* SCRIPT_CHAM */ 76 => 'cham', + /* SCRIPT_TAI_THAM */ 77 => 'lana', + /* SCRIPT_TAI_VIET */ 78 => 'tavt', + /* SCRIPT_AVESTAN */ 79 => 'avst', + /* SCRIPT_EGYPTIAN_HIEROGLYPHS */ 80 => 'egyp', + /* SCRIPT_SAMARITAN */ 81 => 'samr', + /* SCRIPT_LISU */ 82 => 'lisu', + /* SCRIPT_BAMUM */ 83 => 'bamu', + /* SCRIPT_JAVANESE */ 84 => 'java', + /* SCRIPT_MEETEI_MAYEK */ 85 => 'mtei', + /* SCRIPT_IMPERIAL_ARAMAIC */ 86 => 'armi', + /* SCRIPT_OLD_SOUTH_ARABIAN */ 87 => 'sarb', + /* SCRIPT_INSCRIPTIONAL_PARTHIAN */ 88 => 'prti', + /* SCRIPT_INSCRIPTIONAL_PAHLAVI */ 89 => 'phli', + /* SCRIPT_OLD_TURKIC */ 90 => 'orkh', + /* SCRIPT_KAITHI */ 91 => 'kthi', + /* SCRIPT_BATAK */ 92 => 'batk', + /* SCRIPT_BRAHMI */ 93 => 'brah', + /* SCRIPT_MANDAIC */ 94 => 'mand', + /* SCRIPT_CHAKMA */ 95 => 'cakm', + /* SCRIPT_MEROITIC_CURSIVE */ 96 => 'merc', + /* SCRIPT_MEROITIC_HIEROGLYPHS */ 97 => 'mero', + /* SCRIPT_MIAO */ 98 => 'plrd', + /* SCRIPT_SHARADA */ 99 => 'shrd', + /* SCRIPT_SORA_SOMPENG */ 100 => 'sora', + /* SCRIPT_TAKRI */ 101 => 'takr', + /* SCRIPT_UNKNOWN */ 102 => '', + ]; + + public static $ot_languages = [ + 'aa' => 'AFR ', /* Afar */ + 'ab' => 'ABK ', /* Abkhazian */ + 'abq' => 'ABA ', /* Abaza */ + 'ada' => 'DNG ', /* Dangme */ + 'ady' => 'ADY ', /* Adyghe */ + 'af' => 'AFK ', /* Afrikaans */ + 'aii' => 'SWA ', /* Swadaya Aramaic */ + 'aiw' => 'ARI ', /* Aari */ + 'alt' => 'ALT ', /* [Southern] Altai */ + 'am' => 'AMH ', /* Amharic */ + 'amf' => 'HBN ', /* Hammer-Banna */ + 'ar' => 'ARA ', /* Arabic */ + 'arn' => 'MAP ', /* Mapudungun */ + 'as' => 'ASM ', /* Assamese */ + 'ath' => 'ATH ', /* Athapaskan [family] */ + 'atv' => 'ALT ', /* [Northern] Altai */ + 'av' => 'AVR ', /* Avaric */ + 'awa' => 'AWA ', /* Awadhi */ + 'ay' => 'AYM ', /* Aymara */ + 'az' => 'AZE ', /* Azerbaijani */ + 'ba' => 'BSH ', /* Bashkir */ + 'bai' => 'BML ', /* Bamileke [family] */ + 'bal' => 'BLI ', /* Baluchi */ + 'bci' => 'BAU ', /* Baule */ + 'bcq' => 'BCH ', /* Bench */ + 'be' => 'BEL ', /* Belarussian */ + 'bem' => 'BEM ', /* Bemba (Zambia) */ + 'ber' => 'BER ', /* Berber [family] */ + 'bfq' => 'BAD ', /* Badaga */ + 'bft' => 'BLT ', /* Balti */ + 'bfy' => 'BAG ', /* Baghelkhandi */ + 'bg' => 'BGR ', /* Bulgarian */ + 'bhb' => 'BHI ', /* Bhili */ + 'bho' => 'BHO ', /* Bhojpuri */ + 'bik' => 'BIK ', /* Bikol */ + 'bin' => 'EDO ', /* Bini */ + 'bjt' => 'BLN ', /* Balanta-Ganja */ + 'bla' => 'BKF ', /* Blackfoot */ + 'ble' => 'BLN ', /* Balanta-Kentohe */ + 'bm' => 'BMB ', /* Bambara */ + 'bn' => 'BEN ', /* Bengali */ + 'bo' => 'TIB ', /* Tibetan */ + 'br' => 'BRE ', /* Breton */ + 'bra' => 'BRI ', /* Braj Bhasha */ + 'brh' => 'BRH ', /* Brahui */ + 'bs' => 'BOS ', /* Bosnian */ + 'btb' => 'BTI ', /* Beti (Cameroon) */ + 'bxr' => 'RBU ', /* Russian Buriat */ + 'byn' => 'BIL ', /* Bilen */ + 'ca' => 'CAT ', /* Catalan */ + 'ce' => 'CHE ', /* Chechen */ + 'ceb' => 'CEB ', /* Cebuano */ + 'chp' => 'CHP ', /* Chipewyan */ + 'chr' => 'CHR ', /* Cherokee */ + 'ckt' => 'CHK ', /* Chukchi */ + 'cop' => 'COP ', /* Coptic */ + 'cr' => 'CRE ', /* Cree */ + 'crh' => 'CRT ', /* Crimean Tatar */ + 'crj' => 'ECR ', /* [Southern] East Cree */ + 'crl' => 'ECR ', /* [Northern] East Cree */ + 'crm' => 'MCR ', /* Moose Cree */ + 'crx' => 'CRR ', /* Carrier */ + 'cs' => 'CSY ', /* Czech */ + 'cu' => 'CSL ', /* Church Slavic */ + 'cv' => 'CHU ', /* Chuvash */ + 'cwd' => 'DCR ', /* Woods Cree */ + 'cy' => 'WEL ', /* Welsh */ + 'da' => 'DAN ', /* Danish */ + 'dap' => 'NIS ', /* Nisi (India) */ + 'dar' => 'DAR ', /* Dargwa */ + 'de' => 'DEU ', /* German */ + 'din' => 'DNK ', /* Dinka */ + 'dje' => 'DJR ', /* Djerma */ + 'dng' => 'DUN ', /* Dungan */ + 'doi' => 'DGR ', /* Dogri */ + 'dsb' => 'LSB ', /* Lower Sorbian */ + 'dv' => 'DIV ', /* Dhivehi */ + 'dyu' => 'JUL ', /* Jula */ + 'dz' => 'DZN ', /* Dzongkha */ + 'ee' => 'EWE ', /* Ewe */ + 'efi' => 'EFI ', /* Efik */ + 'el' => 'ELL ', /* Modern Greek (1453-) */ + 'grc' => 'PGR ', /* Polytonic Greek */ + 'en' => 'ENG ', /* English */ + 'eo' => 'NTO ', /* Esperanto */ + 'eot' => 'BTI ', /* Beti (Côte d'Ivoire) */ + 'es' => 'ESP ', /* Spanish */ + 'et' => 'ETI ', /* Estonian */ + 'eu' => 'EUQ ', /* Basque */ + 'eve' => 'EVN ', /* Even */ + 'evn' => 'EVK ', /* Evenki */ + 'fa' => 'FAR ', /* Persian */ + 'ff' => 'FUL ', /* Fulah */ + 'fi' => 'FIN ', /* Finnish */ + 'fil' => 'PIL ', /* Filipino */ + 'fj' => 'FJI ', /* Fijian */ + 'fo' => 'FOS ', /* Faroese */ + 'fon' => 'FON ', /* Fon */ + 'fr' => 'FRA ', /* French */ + 'fur' => 'FRL ', /* Friulian */ + 'fy' => 'FRI ', /* Western Frisian */ + 'ga' => 'IRI ', /* Irish */ + 'gaa' => 'GAD ', /* Ga */ + 'gag' => 'GAG ', /* Gagauz */ + 'gbm' => 'GAW ', /* Garhwali */ + 'gd' => 'GAE ', /* Scottish Gaelic */ + 'gez' => 'GEZ ', /* Ge'ez */ + 'gl' => 'GAL ', /* Galician */ + 'gld' => 'NAN ', /* Nanai */ + 'gn' => 'GUA ', /* Guarani */ + 'gon' => 'GON ', /* Gondi */ + 'grt' => 'GRO ', /* Garo */ + 'gru' => 'SOG ', /* Sodo Gurage */ + 'gu' => 'GUJ ', /* Gujarati */ + 'guk' => 'GMZ ', /* Gumuz */ + 'gv' => 'MNX ', /* Manx Gaelic */ + 'ha' => 'HAU ', /* Hausa */ + 'har' => 'HRI ', /* Harari */ + 'haw' => 'HAW ', /* Hawaiin */ + 'he' => 'IWR ', /* Hebrew */ + 'hi' => 'HIN ', /* Hindi */ + 'hil' => 'HIL ', /* Hiligaynon */ + 'hnd' => 'HND ', /* [Southern] Hindko */ + 'hne' => 'CHH ', /* Chattisgarhi */ + 'hno' => 'HND ', /* [Northern] Hindko */ + 'hoc' => 'HO ', /* Ho */ + 'hoj' => 'HAR ', /* Harauti */ + 'hr' => 'HRV ', /* Croatian */ + 'hsb' => 'USB ', /* Upper Sorbian */ + 'ht' => 'HAI ', /* Haitian */ + 'hu' => 'HUN ', /* Hungarian */ + 'hy' => 'HYE ', /* Armenian */ + 'id' => 'IND ', /* Indonesian */ + 'ig' => 'IBO ', /* Igbo */ + 'igb' => 'EBI ', /* Ebira */ + 'ijo' => 'IJO ', /* Ijo [family] */ + 'ilo' => 'ILO ', /* Ilokano */ + 'inh' => 'ING ', /* Ingush */ + 'is' => 'ISL ', /* Icelandic */ + 'it' => 'ITA ', /* Italian */ + 'iu' => 'INU ', /* Inuktitut */ + 'ja' => 'JAN ', /* Japanese */ + 'jv' => 'JAV ', /* Javanese */ + 'ka' => 'KAT ', /* Georgian */ + 'kaa' => 'KRK ', /* Karakalpak */ + 'kam' => 'KMB ', /* Kamba (Kenya) */ + 'kar' => 'KRN ', /* Karen [family] */ + 'kbd' => 'KAB ', /* Kabardian */ + 'kdr' => 'KRM ', /* Karaim */ + 'kdt' => 'KUY ', /* Kuy */ + 'kex' => 'KKN ', /* Kokni */ + 'kfr' => 'KAC ', /* Kachchi */ + 'kfy' => 'KMN ', /* Kumaoni */ + 'kha' => 'KSI ', /* Khasi */ + 'khb' => 'XBD ', /* Tai Lue */ + 'khw' => 'KHW ', /* Khowar */ + 'ki' => 'KIK ', /* Kikuyu */ + 'kjh' => 'KHA ', /* Khakass */ + 'kk' => 'KAZ ', /* Kazakh */ + 'kl' => 'GRN ', /* Kalaallisut */ + 'kln' => 'KAL ', /* Kalenjin */ + 'km' => 'KHM ', /* Central Khmer */ + 'kmb' => 'MBN ', /* [North] Mbundu */ + 'kmw' => 'KMO ', /* Komo (Democratic Republic of Congo) */ + 'kn' => 'KAN ', /* Kannada */ + 'ko' => 'KOR ', /* Korean */ + 'koi' => 'KOP ', /* Komi-Permyak */ + 'kok' => 'KOK ', /* Konkani */ + 'kpe' => 'KPL ', /* Kpelle */ + 'kpv' => 'KOZ ', /* Komi-Zyrian */ + 'kpy' => 'KYK ', /* Koryak */ + 'kqy' => 'KRT ', /* Koorete */ + 'kr' => 'KNR ', /* Kanuri */ + 'kri' => 'KRI ', /* Krio */ + 'krl' => 'KRL ', /* Karelian */ + 'kru' => 'KUU ', /* Kurukh */ + 'ks' => 'KSH ', /* Kashmiri */ + 'ku' => 'KUR ', /* Kurdish */ + 'kum' => 'KUM ', /* Kumyk */ + 'kvd' => 'KUI ', /* Kui (Indonesia) */ + 'kxc' => 'KMS ', /* Komso */ + 'kxu' => 'KUI ', /* Kui (India) */ + 'ky' => 'KIR ', /* Kirghiz */ + 'la' => 'LAT ', /* Latin */ + 'lad' => 'JUD ', /* Ladino */ + 'lb' => 'LTZ ', /* Luxembourgish */ + 'lbe' => 'LAK ', /* Lak */ + 'lbj' => 'LDK ', /* Ladakhi */ + 'lez' => 'LEZ ', /* Lezgi */ + 'lg' => 'LUG ', /* Luganda */ + 'lif' => 'LMB ', /* Limbu */ + 'lld' => 'LAD ', /* Ladin */ + 'lmn' => 'LAM ', /* Lambani */ + 'ln' => 'LIN ', /* Lingala */ + 'lo' => 'LAO ', /* Lao */ + 'lt' => 'LTH ', /* Lithuanian */ + 'lu' => 'LUB ', /* Luba-Katanga */ + 'lua' => 'LUB ', /* Luba-Kasai */ + 'luo' => 'LUO ', /* Luo (Kenya and Tanzania) */ + 'lus' => 'MIZ ', /* Mizo */ + 'luy' => 'LUH ', /* Luhya [macrolanguage] */ + 'lv' => 'LVI ', /* Latvian */ + 'lzz' => 'LAZ ', /* Laz */ + 'mai' => 'MTH ', /* Maithili */ + 'mdc' => 'MLE ', /* Male (Papua New Guinea) */ + 'mdf' => 'MOK ', /* Moksha */ + 'mdy' => 'MLE ', /* Male (Ethiopia) */ + 'men' => 'MDE ', /* Mende (Sierra Leone) */ + 'mg' => 'MLG ', /* Malagasy */ + 'mhr' => 'LMA ', /* Low Mari */ + 'mi' => 'MRI ', /* Maori */ + 'mk' => 'MKD ', /* Macedonian */ + 'ml' => 'MLR ', /* Malayalam reformed (MAL is Malayalam Traditional) */ + 'mn' => 'MNG ', /* Mongolian */ + 'mnc' => 'MCH ', /* Manchu */ + 'mni' => 'MNI ', /* Manipuri */ + 'mnk' => 'MND ', /* Mandinka */ + 'mns' => 'MAN ', /* Mansi */ + 'mnw' => 'MON ', /* Mon */ + 'mo' => 'MOL ', /* Moldavian */ + 'moh' => 'MOH ', /* Mohawk */ + 'mpe' => 'MAJ ', /* Majang */ + 'mr' => 'MAR ', /* Marathi */ + 'mrj' => 'HMA ', /* High Mari */ + 'ms' => 'MLY ', /* Malay */ + 'mt' => 'MTS ', /* Maltese */ + 'mwr' => 'MAW ', /* Marwari */ + 'my' => 'BRM ', /* Burmese */ + 'mym' => 'MEN ', /* Me'en */ + 'myv' => 'ERZ ', /* Erzya */ + 'nag' => 'NAG ', /* Naga-Assamese */ + 'nb' => 'NOR ', /* Norwegian Bokmål */ + 'nco' => 'SIB ', /* Sibe */ + 'nd' => 'NDB ', /* [North] Ndebele */ + 'ne' => 'NEP ', /* Nepali */ + 'new' => 'NEW ', /* Newari */ + 'ng' => 'NDG ', /* Ndonga */ + 'ngl' => 'LMW ', /* Lomwe */ + 'niu' => 'NIU ', /* Niuean */ + 'niv' => 'GIL ', /* Gilyak */ + 'nl' => 'NLD ', /* Dutch */ + 'nn' => 'NYN ', /* Norwegian Nynorsk */ + 'no' => 'NOR ', /* Norwegian (deprecated) */ + 'nod' => 'NTA ', /* Northern Tai */ + 'nog' => 'NOG ', /* Nogai */ + 'nqo' => 'NKO ', /* N'Ko */ + 'nr' => 'NDB ', /* [South] Ndebele */ + 'nsk' => 'NAS ', /* Naskapi */ + 'nso' => 'SOT ', /* [Northern] Sotho */ + 'ny' => 'CHI ', /* Nyanja */ + 'nyn' => 'NKL ', /* Nkole */ + 'oc' => 'OCI ', /* Occitan (post 1500) */ + 'oj' => 'OJB ', /* Ojibwa */ + 'ojs' => 'OCR ', /* Oji-Cree */ + 'om' => 'ORO ', /* Oromo */ + 'or' => 'ORI ', /* Oriya */ + 'os' => 'OSS ', /* Ossetian */ + 'pa' => 'PAN ', /* Panjabi */ + 'pce' => 'PLG ', /* [Ruching] Palaung */ + 'pi' => 'PAL ', /* Pali */ + 'pl' => 'PLK ', /* Polish */ + 'pll' => 'PLG ', /* [Shwe] Palaung */ + 'plp' => 'PAP ', /* Palpa */ + 'prs' => 'DRI ', /* Dari */ + 'ps' => 'PAS ', /* Pushto */ + 'pt' => 'PTG ', /* Portuguese */ + 'raj' => 'RAJ ', /* Rajasthani */ + 'rbb' => 'PLG ', /* [Rumai] Palaung */ + 'ria' => 'RIA ', /* Riang (India) */ + 'ril' => 'RIA ', /* Riang (Myanmar) */ + 'rki' => 'ARK ', /* Arakanese */ + 'rm' => 'RMS ', /* Rhaeto-Romanic */ + 'ro' => 'ROM ', /* Romanian */ + 'rom' => 'ROY ', /* Romany */ + 'ru' => 'RUS ', /* Russian */ + 'rue' => 'RSY ', /* Rusyn */ + 'rw' => 'RUA ', /* Ruanda */ + 'sa' => 'SAN ', /* Sanskrit */ + 'sah' => 'YAK ', /* Yakut */ + 'sat' => 'SAT ', /* Santali */ + 'sck' => 'SAD ', /* Sadri */ + 'scs' => 'SLA ', /* [North] Slavey */ + 'sd' => 'SND ', /* Sindhi */ + 'se' => 'NSM ', /* Northern Sami */ + 'seh' => 'SNA ', /* Sena */ + 'sel' => 'SEL ', /* Selkup */ + 'sg' => 'SGO ', /* Sango */ + 'shn' => 'SHN ', /* Shan */ + 'si' => 'SNH ', /* Sinhala */ + 'sid' => 'SID ', /* Sidamo */ + 'sjd' => 'KSM ', /* Kildin Sami */ + 'sk' => 'SKY ', /* Slovak */ + 'skr' => 'SRK ', /* Seraiki */ + 'sl' => 'SLV ', /* Slovenian */ + 'sm' => 'SMO ', /* Samoan */ + 'sma' => 'SSM ', /* Southern Sami */ + 'smj' => 'LSM ', /* Lule Sami */ + 'smn' => 'ISM ', /* Inari Sami */ + 'sms' => 'SKS ', /* Skolt Sami */ + 'snk' => 'SNK ', /* Soninke */ + 'so' => 'SML ', /* Somali */ + 'sq' => 'SQI ', /* Albanian */ + 'sr' => 'SRB ', /* Serbian */ + 'srr' => 'SRR ', /* Serer */ + 'ss' => 'SWZ ', /* Swazi */ + 'st' => 'SOT ', /* [Southern] Sotho */ + 'suq' => 'SUR ', /* Suri */ + 'sv' => 'SVE ', /* Swedish */ + 'sva' => 'SVA ', /* Svan */ + 'sw' => 'SWK ', /* Swahili */ + 'swb' => 'CMR ', /* Comorian */ + 'syr' => 'SYR ', /* Syriac */ + 'ta' => 'TAM ', /* Tamil */ + 'tab' => 'TAB ', /* Tabasaran */ + 'tcy' => 'TUL ', /* Tulu */ + 'te' => 'TEL ', /* Telugu */ + 'tem' => 'TMN ', /* Temne */ + 'tg' => 'TAJ ', /* Tajik */ + 'th' => 'THA ', /* Thai */ + 'ti' => 'TGY ', /* Tigrinya */ + 'tig' => 'TGR ', /* Tigre */ + 'tk' => 'TKM ', /* Turkmen */ + 'tn' => 'TNA ', /* Tswana */ + 'to' => 'TGN ', /* Tonga (Tonga Islands) */ + 'tr' => 'TRK ', /* Turkish */ + 'tru' => 'TUA ', /* Turoyo Aramaic */ + 'ts' => 'TSG ', /* Tsonga */ + 'tt' => 'TAT ', /* Tatar */ + 'tw' => 'TWI ', /* Twi */ + 'ty' => 'THT ', /* Tahitian */ + 'tyv' => 'TUV ', /* Tuvin */ + 'udm' => 'UDM ', /* Udmurt */ + 'ug' => 'UYG ', /* Uighur */ + 'uk' => 'UKR ', /* Ukrainian */ + 'umb' => 'MBN ', /* [South] Mbundu */ + 'unr' => 'MUN ', /* Mundari */ + 'ur' => 'URD ', /* Urdu */ + 'uz' => 'UZB ', /* Uzbek */ + 've' => 'VEN ', /* Venda */ + 'vi' => 'VIT ', /* Vietnamese */ + 'vmw' => 'MAK ', /* Makua */ + 'wbm' => 'WA ', /* Wa */ + 'wbr' => 'WAG ', /* Wagdi */ + 'wo' => 'WLF ', /* Wolof */ + 'xal' => 'KLM ', /* Kalmyk */ + 'xh' => 'XHS ', /* Xhosa */ + 'xom' => 'KMO ', /* Komo (Sudan) */ + 'xsl' => 'SSL ', /* South Slavey */ + 'yi' => 'JII ', /* Yiddish */ + 'yid' => 'JII ', /* Yiddish */ + 'yo' => 'YBA ', /* Yoruba */ + 'yso' => 'NIS ', /* Nisi (China) */ + 'zne' => 'ZND ', /* Zande */ + 'zu' => 'ZUL ', /* Zulu */ + 'zh-cn' => 'ZHS ', /* Chinese (China) */ + 'zh-hk' => 'ZHH ', /* Chinese (Hong Kong) */ + 'zh-mo' => 'ZHT ', /* Chinese (Macao) */ + 'zh-sg' => 'ZHS ', /* Chinese (Singapore) */ + 'zh-tw' => 'ZHT ', /* Chinese (Taiwan) */ + ]; + + // hb-unicode.h + const UNICODE_GENERAL_CATEGORY_CONTROL = 0; /* Cc */ + const UNICODE_GENERAL_CATEGORY_FORMAT = 1; /* Cf */ + const UNICODE_GENERAL_CATEGORY_UNASSIGNED = 2; /* Cn */ + const UNICODE_GENERAL_CATEGORY_PRIVATE_USE = 3; /* Co */ + const UNICODE_GENERAL_CATEGORY_SURROGATE = 4; /* Cs */ + const UNICODE_GENERAL_CATEGORY_LOWERCASE_LETTER = 5; /* Ll */ + const UNICODE_GENERAL_CATEGORY_MODIFIER_LETTER = 6; /* Lm */ + const UNICODE_GENERAL_CATEGORY_OTHER_LETTER = 7; /* Lo */ + const UNICODE_GENERAL_CATEGORY_TITLECASE_LETTER = 8; /* Lt */ + const UNICODE_GENERAL_CATEGORY_UPPERCASE_LETTER = 9; /* Lu */ + const UNICODE_GENERAL_CATEGORY_SPACING_MARK = 10; /* Mc */ + const UNICODE_GENERAL_CATEGORY_ENCLOSING_MARK = 11; /* Me */ + const UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK = 12; /* Mn */ + const UNICODE_GENERAL_CATEGORY_DECIMAL_NUMBER = 13; /* Nd */ + const UNICODE_GENERAL_CATEGORY_LETTER_NUMBER = 14; /* Nl */ + const UNICODE_GENERAL_CATEGORY_OTHER_NUMBER = 15; /* No */ + const UNICODE_GENERAL_CATEGORY_CONNECT_PUNCTUATION = 16; /* Pc */ + const UNICODE_GENERAL_CATEGORY_DASH_PUNCTUATION = 17; /* Pd */ + const UNICODE_GENERAL_CATEGORY_CLOSE_PUNCTUATION = 18; /* Pe */ + const UNICODE_GENERAL_CATEGORY_FINAL_PUNCTUATION = 19; /* Pf */ + const UNICODE_GENERAL_CATEGORY_INITIAL_PUNCTUATION = 20; /* Pi */ + const UNICODE_GENERAL_CATEGORY_OTHER_PUNCTUATION = 21; /* Po */ + const UNICODE_GENERAL_CATEGORY_OPEN_PUNCTUATION = 22; /* Ps */ + const UNICODE_GENERAL_CATEGORY_CURRENCY_SYMBOL = 23; /* Sc */ + const UNICODE_GENERAL_CATEGORY_MODIFIER_SYMBOL = 24; /* Sk */ + const UNICODE_GENERAL_CATEGORY_MATH_SYMBOL = 25; /* Sm */ + const UNICODE_GENERAL_CATEGORY_OTHER_SYMBOL = 26; /* So */ + const UNICODE_GENERAL_CATEGORY_LINE_SEPARATOR = 27; /* Zl */ + const UNICODE_GENERAL_CATEGORY_PARAGRAPH_SEPARATOR = 28; /* Zp */ + const UNICODE_GENERAL_CATEGORY_SPACE_SEPARATOR = 29; /* Zs */ + + function general_category_is_mark($gen_cat) + { + return $gen_cat == self::UNICODE_GENERAL_CATEGORY_SPACING_MARK || $gen_cat == self::UNICODE_GENERAL_CATEGORY_ENCLOSING_MARK || + $gen_cat == self::UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK; + // define UNICODE_GENERAL_CATEGORY_IS_MARK(gen_cat) + //if (FLAG(gen_cat) & (FLAG(UNICODE_GENERAL_CATEGORY_SPACING_MARK) | FLAG(UNICODE_GENERAL_CATEGORY_ENCLOSING_MARK) | FLAG(UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK))) { return true; } + } + + const BIDI_CLASS_L = 0; + const BIDI_CLASS_LRE = 1; + const BIDI_CLASS_LRO = 2; + const BIDI_CLASS_R = 3; + const BIDI_CLASS_AL = 4; + const BIDI_CLASS_RLE = 5; + const BIDI_CLASS_RLO = 6; + const BIDI_CLASS_PDF = 7; + const BIDI_CLASS_EN = 8; + const BIDI_CLASS_ES = 9; + const BIDI_CLASS_ET = 10; + const BIDI_CLASS_AN = 11; + const BIDI_CLASS_CS = 12; + const BIDI_CLASS_NSM = 13; + const BIDI_CLASS_BN = 14; + const BIDI_CLASS_B = 15; + const BIDI_CLASS_S = 16; + const BIDI_CLASS_WS = 17; + const BIDI_CLASS_ON = 18; + + // UNIDATA_VERSION 6.2.0 + /* a list of unique database records */ + /* struct { + category; + combining; + bidi_class; + mirrored; + east_asian_width; + normalization_check; + script; + } + */ + private static $ucd_records = [ + [2, 0, 18, 0, 5, 0, 102], + [0, 0, 14, 0, 5, 0, 0], + [0, 0, 16, 0, 5, 0, 0], + [0, 0, 15, 0, 5, 0, 0], + [0, 0, 17, 0, 5, 0, 0], + [29, 0, 17, 0, 3, 0, 0], + [21, 0, 18, 0, 3, 0, 0], + [21, 0, 10, 0, 3, 0, 0], + [23, 0, 10, 0, 3, 0, 0], + [22, 0, 18, 1, 3, 0, 0], + [18, 0, 18, 1, 3, 0, 0], + [25, 0, 9, 0, 3, 0, 0], + [21, 0, 12, 0, 3, 0, 0], + [17, 0, 9, 0, 3, 0, 0], + [13, 0, 8, 0, 3, 0, 0], + [25, 0, 18, 1, 3, 0, 0], + [25, 0, 18, 0, 3, 0, 0], + [9, 0, 0, 0, 3, 0, 1], + [24, 0, 18, 0, 3, 0, 0], + [16, 0, 18, 0, 3, 0, 0], + [5, 0, 0, 0, 3, 0, 1], + [29, 0, 12, 0, 5, 0, 0], + [21, 0, 18, 0, 4, 0, 0], + [23, 0, 10, 0, 4, 0, 0], + [26, 0, 18, 0, 3, 0, 0], + [24, 0, 18, 0, 4, 0, 0], + [26, 0, 18, 0, 5, 0, 0], + [7, 0, 0, 0, 4, 0, 1], + [20, 0, 18, 1, 5, 0, 0], + [1, 0, 14, 0, 4, 0, 0], + [26, 0, 18, 0, 4, 0, 0], + [26, 0, 10, 0, 4, 0, 0], + [25, 0, 10, 0, 4, 0, 0], + [15, 0, 8, 0, 4, 0, 0], + [5, 0, 0, 0, 5, 0, 0], + [19, 0, 18, 1, 5, 0, 0], + [15, 0, 18, 0, 4, 0, 0], + [9, 0, 0, 0, 5, 0, 1], + [9, 0, 0, 0, 4, 0, 1], + [25, 0, 18, 0, 4, 0, 0], + [5, 0, 0, 0, 4, 0, 1], + [5, 0, 0, 0, 5, 0, 1], + [7, 0, 0, 0, 5, 0, 1], + [8, 0, 0, 0, 5, 0, 1], + [6, 0, 0, 0, 5, 0, 1], + [6, 0, 18, 0, 5, 0, 0], + [6, 0, 0, 0, 5, 0, 0], + [24, 0, 18, 0, 5, 0, 0], + [6, 0, 18, 0, 4, 0, 0], + [6, 0, 0, 0, 4, 0, 0], + [24, 0, 18, 0, 5, 0, 34], + [12, 230, 13, 0, 4, 0, 40], + [12, 232, 13, 0, 4, 0, 40], + [12, 220, 13, 0, 4, 0, 40], + [12, 216, 13, 0, 4, 0, 40], + [12, 202, 13, 0, 4, 0, 40], + [12, 1, 13, 0, 4, 0, 40], + [12, 240, 13, 0, 4, 0, 40], + [12, 0, 13, 0, 4, 0, 40], + [12, 233, 13, 0, 4, 0, 40], + [12, 234, 13, 0, 4, 0, 40], + [9, 0, 0, 0, 5, 0, 2], + [5, 0, 0, 0, 5, 0, 2], + [24, 0, 18, 0, 5, 0, 2], + [2, 0, 18, 0, 5, 0, 102], + [6, 0, 0, 0, 5, 0, 2], + [21, 0, 18, 0, 5, 0, 0], + [9, 0, 0, 0, 4, 0, 2], + [5, 0, 0, 0, 4, 0, 2], + [9, 0, 0, 0, 5, 0, 54], + [5, 0, 0, 0, 5, 0, 54], + [25, 0, 18, 0, 5, 0, 2], + [9, 0, 0, 0, 5, 0, 3], + [9, 0, 0, 0, 4, 0, 3], + [5, 0, 0, 0, 4, 0, 3], + [5, 0, 0, 0, 5, 0, 3], + [26, 0, 0, 0, 5, 0, 3], + [12, 230, 13, 0, 5, 0, 3], + [12, 230, 13, 0, 5, 0, 40], + [11, 0, 13, 0, 5, 0, 3], + [9, 0, 0, 0, 5, 0, 4], + [6, 0, 0, 0, 5, 0, 4], + [21, 0, 0, 0, 5, 0, 4], + [5, 0, 0, 0, 5, 0, 4], + [21, 0, 0, 0, 5, 0, 0], + [17, 0, 18, 0, 5, 0, 4], + [23, 0, 10, 0, 5, 0, 4], + [12, 220, 13, 0, 5, 0, 5], + [12, 230, 13, 0, 5, 0, 5], + [12, 222, 13, 0, 5, 0, 5], + [12, 228, 13, 0, 5, 0, 5], + [12, 10, 13, 0, 5, 0, 5], + [12, 11, 13, 0, 5, 0, 5], + [12, 12, 13, 0, 5, 0, 5], + [12, 13, 13, 0, 5, 0, 5], + [12, 14, 13, 0, 5, 0, 5], + [12, 15, 13, 0, 5, 0, 5], + [12, 16, 13, 0, 5, 0, 5], + [12, 17, 13, 0, 5, 0, 5], + [12, 18, 13, 0, 5, 0, 5], + [12, 19, 13, 0, 5, 0, 5], + [12, 20, 13, 0, 5, 0, 5], + [12, 21, 13, 0, 5, 0, 5], + [12, 22, 13, 0, 5, 0, 5], + [17, 0, 3, 0, 5, 0, 5], + [12, 23, 13, 0, 5, 0, 5], + [21, 0, 3, 0, 5, 0, 5], + [12, 24, 13, 0, 5, 0, 5], + [12, 25, 13, 0, 5, 0, 5], + [7, 0, 3, 0, 5, 0, 5], + [1, 0, 11, 0, 5, 0, 6], + [25, 0, 18, 0, 5, 0, 6], + [25, 0, 4, 0, 5, 0, 6], + [21, 0, 10, 0, 5, 0, 6], + [23, 0, 4, 0, 5, 0, 6], + [21, 0, 12, 0, 5, 0, 0], + [21, 0, 4, 0, 5, 0, 6], + [26, 0, 18, 0, 5, 0, 6], + [12, 230, 13, 0, 5, 0, 6], + [12, 30, 13, 0, 5, 0, 6], + [12, 31, 13, 0, 5, 0, 6], + [12, 32, 13, 0, 5, 0, 6], + [21, 0, 4, 0, 5, 0, 0], + [7, 0, 4, 0, 5, 0, 6], + [6, 0, 4, 0, 5, 0, 0], + [12, 27, 13, 0, 5, 0, 40], + [12, 28, 13, 0, 5, 0, 40], + [12, 29, 13, 0, 5, 0, 40], + [12, 30, 13, 0, 5, 0, 40], + [12, 31, 13, 0, 5, 0, 40], + [12, 32, 13, 0, 5, 0, 40], + [12, 33, 13, 0, 5, 0, 40], + [12, 34, 13, 0, 5, 0, 40], + [12, 220, 13, 0, 5, 0, 40], + [12, 220, 13, 0, 5, 0, 6], + [13, 0, 11, 0, 5, 0, 0], + [21, 0, 11, 0, 5, 0, 6], + [12, 35, 13, 0, 5, 0, 40], + [1, 0, 11, 0, 5, 0, 0], + [6, 0, 4, 0, 5, 0, 6], + [13, 0, 8, 0, 5, 0, 6], + [26, 0, 4, 0, 5, 0, 6], + [21, 0, 4, 0, 5, 0, 7], + [1, 0, 4, 0, 5, 0, 7], + [7, 0, 4, 0, 5, 0, 7], + [12, 36, 13, 0, 5, 0, 7], + [12, 230, 13, 0, 5, 0, 7], + [12, 220, 13, 0, 5, 0, 7], + [7, 0, 4, 0, 5, 0, 8], + [12, 0, 13, 0, 5, 0, 8], + [13, 0, 3, 0, 5, 0, 65], + [7, 0, 3, 0, 5, 0, 65], + [12, 230, 13, 0, 5, 0, 65], + [12, 220, 13, 0, 5, 0, 65], + [6, 0, 3, 0, 5, 0, 65], + [26, 0, 18, 0, 5, 0, 65], + [21, 0, 18, 0, 5, 0, 65], + [7, 0, 3, 0, 5, 0, 81], + [12, 230, 13, 0, 5, 0, 81], + [6, 0, 3, 0, 5, 0, 81], + [21, 0, 3, 0, 5, 0, 81], + [7, 0, 3, 0, 5, 0, 94], + [12, 220, 13, 0, 5, 0, 94], + [21, 0, 3, 0, 5, 0, 94], + [12, 27, 13, 0, 5, 0, 6], + [12, 28, 13, 0, 5, 0, 6], + [12, 29, 13, 0, 5, 0, 6], + [12, 0, 13, 0, 5, 0, 9], + [10, 0, 0, 0, 5, 0, 9], + [7, 0, 0, 0, 5, 0, 9], + [12, 7, 13, 0, 5, 0, 9], + [12, 9, 13, 0, 5, 0, 9], + [12, 230, 13, 0, 5, 0, 9], + [13, 0, 0, 0, 5, 0, 9], + [21, 0, 0, 0, 5, 0, 9], + [6, 0, 0, 0, 5, 0, 9], + [12, 0, 13, 0, 5, 0, 10], + [10, 0, 0, 0, 5, 0, 10], + [7, 0, 0, 0, 5, 0, 10], + [12, 7, 13, 0, 5, 0, 10], + [12, 9, 13, 0, 5, 0, 10], + [13, 0, 0, 0, 5, 0, 10], + [23, 0, 10, 0, 5, 0, 10], + [15, 0, 0, 0, 5, 0, 10], + [26, 0, 0, 0, 5, 0, 10], + [12, 0, 13, 0, 5, 0, 11], + [10, 0, 0, 0, 5, 0, 11], + [7, 0, 0, 0, 5, 0, 11], + [12, 7, 13, 0, 5, 0, 11], + [12, 9, 13, 0, 5, 0, 11], + [13, 0, 0, 0, 5, 0, 11], + [12, 0, 13, 0, 5, 0, 12], + [10, 0, 0, 0, 5, 0, 12], + [7, 0, 0, 0, 5, 0, 12], + [12, 7, 13, 0, 5, 0, 12], + [12, 9, 13, 0, 5, 0, 12], + [13, 0, 0, 0, 5, 0, 12], + [21, 0, 0, 0, 5, 0, 12], + [23, 0, 10, 0, 5, 0, 12], + [12, 0, 13, 0, 5, 0, 13], + [10, 0, 0, 0, 5, 0, 13], + [7, 0, 0, 0, 5, 0, 13], + [12, 7, 13, 0, 5, 0, 13], + [12, 9, 13, 0, 5, 0, 13], + [13, 0, 0, 0, 5, 0, 13], + [26, 0, 0, 0, 5, 0, 13], + [15, 0, 0, 0, 5, 0, 13], + [12, 0, 13, 0, 5, 0, 14], + [7, 0, 0, 0, 5, 0, 14], + [10, 0, 0, 0, 5, 0, 14], + [12, 9, 13, 0, 5, 0, 14], + [13, 0, 0, 0, 5, 0, 14], + [15, 0, 0, 0, 5, 0, 14], + [26, 0, 18, 0, 5, 0, 14], + [23, 0, 10, 0, 5, 0, 14], + [10, 0, 0, 0, 5, 0, 15], + [7, 0, 0, 0, 5, 0, 15], + [12, 0, 13, 0, 5, 0, 15], + [12, 9, 13, 0, 5, 0, 15], + [12, 84, 13, 0, 5, 0, 15], + [12, 91, 13, 0, 5, 0, 15], + [13, 0, 0, 0, 5, 0, 15], + [15, 0, 18, 0, 5, 0, 15], + [26, 0, 0, 0, 5, 0, 15], + [10, 0, 0, 0, 5, 0, 16], + [7, 0, 0, 0, 5, 0, 16], + [12, 7, 13, 0, 5, 0, 16], + [12, 0, 0, 0, 5, 0, 16], + [12, 0, 13, 0, 5, 0, 16], + [12, 9, 13, 0, 5, 0, 16], + [13, 0, 0, 0, 5, 0, 16], + [10, 0, 0, 0, 5, 0, 17], + [7, 0, 0, 0, 5, 0, 17], + [12, 0, 13, 0, 5, 0, 17], + [12, 9, 13, 0, 5, 0, 17], + [13, 0, 0, 0, 5, 0, 17], + [15, 0, 0, 0, 5, 0, 17], + [26, 0, 0, 0, 5, 0, 17], + [10, 0, 0, 0, 5, 0, 18], + [7, 0, 0, 0, 5, 0, 18], + [12, 9, 13, 0, 5, 0, 18], + [12, 0, 13, 0, 5, 0, 18], + [21, 0, 0, 0, 5, 0, 18], + [7, 0, 0, 0, 5, 0, 19], + [12, 0, 13, 0, 5, 0, 19], + [12, 103, 13, 0, 5, 0, 19], + [12, 9, 13, 0, 5, 0, 19], + [23, 0, 10, 0, 5, 0, 0], + [6, 0, 0, 0, 5, 0, 19], + [12, 107, 13, 0, 5, 0, 19], + [21, 0, 0, 0, 5, 0, 19], + [13, 0, 0, 0, 5, 0, 19], + [7, 0, 0, 0, 5, 0, 20], + [12, 0, 13, 0, 5, 0, 20], + [12, 118, 13, 0, 5, 0, 20], + [6, 0, 0, 0, 5, 0, 20], + [12, 122, 13, 0, 5, 0, 20], + [13, 0, 0, 0, 5, 0, 20], + [7, 0, 0, 0, 5, 0, 21], + [26, 0, 0, 0, 5, 0, 21], + [21, 0, 0, 0, 5, 0, 21], + [12, 220, 13, 0, 5, 0, 21], + [13, 0, 0, 0, 5, 0, 21], + [15, 0, 0, 0, 5, 0, 21], + [12, 216, 13, 0, 5, 0, 21], + [22, 0, 18, 1, 5, 0, 21], + [18, 0, 18, 1, 5, 0, 21], + [10, 0, 0, 0, 5, 0, 21], + [12, 129, 13, 0, 5, 0, 21], + [12, 130, 13, 0, 5, 0, 21], + [12, 0, 13, 0, 5, 0, 21], + [12, 132, 13, 0, 5, 0, 21], + [12, 230, 13, 0, 5, 0, 21], + [12, 9, 13, 0, 5, 0, 21], + [26, 0, 0, 0, 5, 0, 0], + [7, 0, 0, 0, 5, 0, 22], + [10, 0, 0, 0, 5, 0, 22], + [12, 0, 13, 0, 5, 0, 22], + [12, 7, 13, 0, 5, 0, 22], + [12, 9, 13, 0, 5, 0, 22], + [13, 0, 0, 0, 5, 0, 22], + [21, 0, 0, 0, 5, 0, 22], + [12, 220, 13, 0, 5, 0, 22], + [26, 0, 0, 0, 5, 0, 22], + [9, 0, 0, 0, 5, 0, 23], + [7, 0, 0, 0, 5, 0, 23], + [6, 0, 0, 0, 5, 0, 23], + [7, 0, 0, 0, 2, 0, 24], + [7, 0, 0, 0, 5, 0, 24], + [7, 0, 0, 0, 5, 0, 25], + [12, 230, 13, 0, 5, 0, 25], + [21, 0, 0, 0, 5, 0, 25], + [15, 0, 0, 0, 5, 0, 25], + [26, 0, 18, 0, 5, 0, 25], + [7, 0, 0, 0, 5, 0, 26], + [17, 0, 18, 0, 5, 0, 27], + [7, 0, 0, 0, 5, 0, 27], + [21, 0, 0, 0, 5, 0, 27], + [29, 0, 17, 0, 5, 0, 28], + [7, 0, 0, 0, 5, 0, 28], + [22, 0, 18, 1, 5, 0, 28], + [18, 0, 18, 1, 5, 0, 28], + [7, 0, 0, 0, 5, 0, 29], + [14, 0, 0, 0, 5, 0, 29], + [7, 0, 0, 0, 5, 0, 41], + [12, 0, 13, 0, 5, 0, 41], + [12, 9, 13, 0, 5, 0, 41], + [7, 0, 0, 0, 5, 0, 42], + [12, 0, 13, 0, 5, 0, 42], + [12, 9, 13, 0, 5, 0, 42], + [7, 0, 0, 0, 5, 0, 43], + [12, 0, 13, 0, 5, 0, 43], + [7, 0, 0, 0, 5, 0, 44], + [12, 0, 13, 0, 5, 0, 44], + [7, 0, 0, 0, 5, 0, 30], + [12, 0, 13, 0, 5, 0, 30], + [10, 0, 0, 0, 5, 0, 30], + [12, 9, 13, 0, 5, 0, 30], + [21, 0, 0, 0, 5, 0, 30], + [6, 0, 0, 0, 5, 0, 30], + [23, 0, 10, 0, 5, 0, 30], + [12, 230, 13, 0, 5, 0, 30], + [13, 0, 0, 0, 5, 0, 30], + [15, 0, 18, 0, 5, 0, 30], + [21, 0, 18, 0, 5, 0, 31], + [17, 0, 18, 0, 5, 0, 31], + [12, 0, 13, 0, 5, 0, 31], + [29, 0, 17, 0, 5, 0, 31], + [13, 0, 0, 0, 5, 0, 31], + [7, 0, 0, 0, 5, 0, 31], + [6, 0, 0, 0, 5, 0, 31], + [12, 228, 13, 0, 5, 0, 31], + [7, 0, 0, 0, 5, 0, 45], + [12, 0, 13, 0, 5, 0, 45], + [10, 0, 0, 0, 5, 0, 45], + [12, 222, 13, 0, 5, 0, 45], + [12, 230, 13, 0, 5, 0, 45], + [12, 220, 13, 0, 5, 0, 45], + [26, 0, 18, 0, 5, 0, 45], + [21, 0, 18, 0, 5, 0, 45], + [13, 0, 0, 0, 5, 0, 45], + [7, 0, 0, 0, 5, 0, 46], + [7, 0, 0, 0, 5, 0, 55], + [10, 0, 0, 0, 5, 0, 55], + [13, 0, 0, 0, 5, 0, 55], + [15, 0, 0, 0, 5, 0, 55], + [26, 0, 18, 0, 5, 0, 55], + [26, 0, 18, 0, 5, 0, 30], + [7, 0, 0, 0, 5, 0, 53], + [12, 230, 13, 0, 5, 0, 53], + [12, 220, 13, 0, 5, 0, 53], + [10, 0, 0, 0, 5, 0, 53], + [21, 0, 0, 0, 5, 0, 53], + [7, 0, 0, 0, 5, 0, 77], + [10, 0, 0, 0, 5, 0, 77], + [12, 0, 13, 0, 5, 0, 77], + [12, 9, 13, 0, 5, 0, 77], + [12, 230, 13, 0, 5, 0, 77], + [12, 220, 13, 0, 5, 0, 77], + [13, 0, 0, 0, 5, 0, 77], + [21, 0, 0, 0, 5, 0, 77], + [6, 0, 0, 0, 5, 0, 77], + [12, 0, 13, 0, 5, 0, 61], + [10, 0, 0, 0, 5, 0, 61], + [7, 0, 0, 0, 5, 0, 61], + [12, 7, 13, 0, 5, 0, 61], + [10, 9, 0, 0, 5, 0, 61], + [13, 0, 0, 0, 5, 0, 61], + [21, 0, 0, 0, 5, 0, 61], + [26, 0, 0, 0, 5, 0, 61], + [12, 230, 13, 0, 5, 0, 61], + [12, 220, 13, 0, 5, 0, 61], + [12, 0, 13, 0, 5, 0, 66], + [10, 0, 0, 0, 5, 0, 66], + [7, 0, 0, 0, 5, 0, 66], + [10, 9, 0, 0, 5, 0, 66], + [12, 9, 13, 0, 5, 0, 66], + [13, 0, 0, 0, 5, 0, 66], + [7, 0, 0, 0, 5, 0, 92], + [12, 7, 13, 0, 5, 0, 92], + [10, 0, 0, 0, 5, 0, 92], + [12, 0, 13, 0, 5, 0, 92], + [10, 9, 0, 0, 5, 0, 92], + [21, 0, 0, 0, 5, 0, 92], + [7, 0, 0, 0, 5, 0, 67], + [10, 0, 0, 0, 5, 0, 67], + [12, 0, 13, 0, 5, 0, 67], + [12, 7, 13, 0, 5, 0, 67], + [21, 0, 0, 0, 5, 0, 67], + [13, 0, 0, 0, 5, 0, 67], + [13, 0, 0, 0, 5, 0, 68], + [7, 0, 0, 0, 5, 0, 68], + [6, 0, 0, 0, 5, 0, 68], + [21, 0, 0, 0, 5, 0, 68], + [21, 0, 0, 0, 5, 0, 66], + [12, 1, 13, 0, 5, 0, 40], + [10, 0, 0, 0, 5, 0, 0], + [7, 0, 0, 0, 5, 0, 0], + [6, 0, 0, 0, 5, 0, 3], + [12, 234, 13, 0, 5, 0, 40], + [12, 214, 13, 0, 5, 0, 40], + [12, 202, 13, 0, 5, 0, 40], + [12, 233, 13, 0, 5, 0, 40], + [8, 0, 0, 0, 5, 0, 2], + [29, 0, 17, 0, 5, 0, 0], + [1, 0, 14, 0, 5, 0, 0], + [1, 0, 14, 0, 5, 0, 40], + [1, 0, 0, 0, 5, 0, 0], + [1, 0, 3, 0, 5, 0, 0], + [17, 0, 18, 0, 4, 0, 0], + [17, 0, 18, 0, 5, 0, 0], + [20, 0, 18, 0, 4, 0, 0], + [19, 0, 18, 0, 4, 0, 0], + [22, 0, 18, 0, 5, 0, 0], + [20, 0, 18, 0, 5, 0, 0], + [27, 0, 17, 0, 5, 0, 0], + [28, 0, 15, 0, 5, 0, 0], + [1, 0, 1, 0, 5, 0, 0], + [1, 0, 5, 0, 5, 0, 0], + [1, 0, 7, 0, 5, 0, 0], + [1, 0, 2, 0, 5, 0, 0], + [1, 0, 6, 0, 5, 0, 0], + [21, 0, 10, 0, 4, 0, 0], + [21, 0, 10, 0, 5, 0, 0], + [16, 0, 18, 0, 5, 0, 0], + [25, 0, 12, 0, 5, 0, 0], + [22, 0, 18, 1, 5, 0, 0], + [18, 0, 18, 1, 5, 0, 0], + [25, 0, 18, 0, 5, 0, 0], + [15, 0, 8, 0, 5, 0, 0], + [25, 0, 9, 0, 5, 0, 0], + [6, 0, 0, 0, 4, 0, 1], + [23, 0, 10, 0, 1, 0, 0], + [11, 0, 13, 0, 5, 0, 40], + [9, 0, 0, 0, 5, 0, 0], + [5, 0, 0, 0, 4, 0, 0], + [26, 0, 10, 0, 5, 0, 0], + [25, 0, 18, 1, 5, 0, 0], + [15, 0, 18, 0, 5, 0, 0], + [14, 0, 0, 0, 4, 0, 1], + [14, 0, 0, 0, 5, 0, 1], + [25, 0, 18, 1, 4, 0, 0], + [25, 0, 10, 0, 5, 0, 0], + [22, 0, 18, 1, 2, 0, 0], + [18, 0, 18, 1, 2, 0, 0], + [26, 0, 0, 0, 4, 0, 0], + [26, 0, 0, 0, 5, 0, 52], + [9, 0, 0, 0, 5, 0, 56], + [5, 0, 0, 0, 5, 0, 56], + [26, 0, 18, 0, 5, 0, 54], + [12, 230, 13, 0, 5, 0, 54], + [21, 0, 18, 0, 5, 0, 54], + [15, 0, 18, 0, 5, 0, 54], + [5, 0, 0, 0, 5, 0, 23], + [7, 0, 0, 0, 5, 0, 57], + [6, 0, 0, 0, 5, 0, 57], + [21, 0, 0, 0, 5, 0, 57], + [12, 9, 13, 0, 5, 0, 57], + [26, 0, 18, 0, 2, 0, 35], + [26, 0, 18, 0, 2, 0, 0], + [29, 0, 17, 0, 0, 0, 0], + [21, 0, 18, 0, 2, 0, 0], + [6, 0, 0, 0, 2, 0, 35], + [7, 0, 0, 0, 2, 0, 0], + [14, 0, 0, 0, 2, 0, 35], + [17, 0, 18, 0, 2, 0, 0], + [22, 0, 18, 0, 2, 0, 0], + [18, 0, 18, 0, 2, 0, 0], + [12, 218, 13, 0, 2, 0, 40], + [12, 228, 13, 0, 2, 0, 40], + [12, 232, 13, 0, 2, 0, 40], + [12, 222, 13, 0, 2, 0, 40], + [10, 224, 0, 0, 2, 0, 24], + [6, 0, 0, 0, 2, 0, 0], + [7, 0, 0, 0, 2, 0, 32], + [12, 8, 13, 0, 2, 0, 40], + [24, 0, 18, 0, 2, 0, 0], + [6, 0, 0, 0, 2, 0, 32], + [7, 0, 0, 0, 2, 0, 33], + [6, 0, 0, 0, 2, 0, 33], + [7, 0, 0, 0, 2, 0, 34], + [26, 0, 0, 0, 2, 0, 0], + [15, 0, 0, 0, 2, 0, 0], + [26, 0, 0, 0, 2, 0, 24], + [26, 0, 18, 0, 2, 0, 24], + [15, 0, 0, 0, 4, 0, 0], + [15, 0, 18, 0, 2, 0, 0], + [26, 0, 0, 0, 2, 0, 33], + [7, 0, 0, 0, 2, 0, 35], + [2, 0, 18, 0, 2, 0, 35], + [2, 0, 18, 0, 2, 0, 102], + [7, 0, 0, 0, 2, 0, 36], + [6, 0, 0, 0, 2, 0, 36], + [26, 0, 18, 0, 2, 0, 36], + [7, 0, 0, 0, 5, 0, 82], + [6, 0, 0, 0, 5, 0, 82], + [21, 0, 0, 0, 5, 0, 82], + [7, 0, 0, 0, 5, 0, 69], + [6, 0, 0, 0, 5, 0, 69], + [21, 0, 18, 0, 5, 0, 69], + [13, 0, 0, 0, 5, 0, 69], + [7, 0, 0, 0, 5, 0, 3], + [21, 0, 18, 0, 5, 0, 3], + [6, 0, 18, 0, 5, 0, 3], + [7, 0, 0, 0, 5, 0, 83], + [14, 0, 0, 0, 5, 0, 83], + [12, 230, 13, 0, 5, 0, 83], + [21, 0, 0, 0, 5, 0, 83], + [24, 0, 0, 0, 5, 0, 0], + [7, 0, 0, 0, 5, 0, 58], + [12, 0, 13, 0, 5, 0, 58], + [12, 9, 13, 0, 5, 0, 58], + [10, 0, 0, 0, 5, 0, 58], + [26, 0, 18, 0, 5, 0, 58], + [15, 0, 0, 0, 5, 0, 0], + [7, 0, 0, 0, 5, 0, 64], + [21, 0, 18, 0, 5, 0, 64], + [10, 0, 0, 0, 5, 0, 70], + [7, 0, 0, 0, 5, 0, 70], + [12, 9, 13, 0, 5, 0, 70], + [21, 0, 0, 0, 5, 0, 70], + [13, 0, 0, 0, 5, 0, 70], + [13, 0, 0, 0, 5, 0, 71], + [7, 0, 0, 0, 5, 0, 71], + [12, 0, 13, 0, 5, 0, 71], + [12, 220, 13, 0, 5, 0, 71], + [21, 0, 0, 0, 5, 0, 71], + [7, 0, 0, 0, 5, 0, 72], + [12, 0, 13, 0, 5, 0, 72], + [10, 0, 0, 0, 5, 0, 72], + [10, 9, 0, 0, 5, 0, 72], + [21, 0, 0, 0, 5, 0, 72], + [12, 0, 13, 0, 5, 0, 84], + [10, 0, 0, 0, 5, 0, 84], + [7, 0, 0, 0, 5, 0, 84], + [12, 7, 13, 0, 5, 0, 84], + [10, 9, 0, 0, 5, 0, 84], + [21, 0, 0, 0, 5, 0, 84], + [6, 0, 0, 0, 5, 0, 84], + [13, 0, 0, 0, 5, 0, 84], + [7, 0, 0, 0, 5, 0, 76], + [12, 0, 13, 0, 5, 0, 76], + [10, 0, 0, 0, 5, 0, 76], + [13, 0, 0, 0, 5, 0, 76], + [21, 0, 0, 0, 5, 0, 76], + [6, 0, 0, 0, 5, 0, 22], + [7, 0, 0, 0, 5, 0, 78], + [12, 230, 13, 0, 5, 0, 78], + [12, 220, 13, 0, 5, 0, 78], + [6, 0, 0, 0, 5, 0, 78], + [21, 0, 0, 0, 5, 0, 78], + [7, 0, 0, 0, 5, 0, 85], + [10, 0, 0, 0, 5, 0, 85], + [12, 0, 13, 0, 5, 0, 85], + [21, 0, 0, 0, 5, 0, 85], + [6, 0, 0, 0, 5, 0, 85], + [12, 9, 13, 0, 5, 0, 85], + [13, 0, 0, 0, 5, 0, 85], + [2, 0, 18, 0, 2, 0, 24], + [4, 0, 0, 0, 5, 0, 102], + [3, 0, 0, 0, 4, 0, 102], + [2, 0, 18, 0, 4, 0, 102], + [12, 26, 13, 0, 5, 0, 5], + [25, 0, 9, 0, 5, 0, 5], + [24, 0, 4, 0, 5, 0, 6], + [18, 0, 18, 0, 5, 0, 0], + [16, 0, 18, 0, 2, 0, 0], + [21, 0, 12, 0, 2, 0, 0], + [21, 0, 10, 0, 2, 0, 0], + [25, 0, 9, 0, 2, 0, 0], + [17, 0, 9, 0, 2, 0, 0], + [25, 0, 18, 1, 2, 0, 0], + [25, 0, 18, 0, 2, 0, 0], + [23, 0, 10, 0, 2, 0, 0], + [21, 0, 18, 0, 0, 0, 0], + [21, 0, 10, 0, 0, 0, 0], + [23, 0, 10, 0, 0, 0, 0], + [22, 0, 18, 1, 0, 0, 0], + [18, 0, 18, 1, 0, 0, 0], + [25, 0, 9, 0, 0, 0, 0], + [21, 0, 12, 0, 0, 0, 0], + [17, 0, 9, 0, 0, 0, 0], + [13, 0, 8, 0, 0, 0, 0], + [25, 0, 18, 1, 0, 0, 0], + [25, 0, 18, 0, 0, 0, 0], + [9, 0, 0, 0, 0, 0, 1], + [24, 0, 18, 0, 0, 0, 0], + [16, 0, 18, 0, 0, 0, 0], + [5, 0, 0, 0, 0, 0, 1], + [21, 0, 18, 0, 1, 0, 0], + [22, 0, 18, 1, 1, 0, 0], + [18, 0, 18, 1, 1, 0, 0], + [7, 0, 0, 0, 1, 0, 33], + [6, 0, 0, 0, 1, 0, 0], + [7, 0, 0, 0, 1, 0, 24], + [26, 0, 18, 0, 0, 0, 0], + [26, 0, 18, 0, 1, 0, 0], + [25, 0, 18, 0, 1, 0, 0], + [1, 0, 18, 0, 5, 0, 0], + [7, 0, 0, 0, 5, 0, 47], + [14, 0, 18, 0, 5, 0, 2], + [15, 0, 18, 0, 5, 0, 2], + [26, 0, 18, 0, 5, 0, 2], + [7, 0, 0, 0, 5, 0, 73], + [7, 0, 0, 0, 5, 0, 74], + [7, 0, 0, 0, 5, 0, 37], + [15, 0, 0, 0, 5, 0, 37], + [7, 0, 0, 0, 5, 0, 38], + [14, 0, 0, 0, 5, 0, 38], + [7, 0, 0, 0, 5, 0, 48], + [21, 0, 0, 0, 5, 0, 48], + [7, 0, 0, 0, 5, 0, 59], + [21, 0, 0, 0, 5, 0, 59], + [14, 0, 0, 0, 5, 0, 59], + [9, 0, 0, 0, 5, 0, 39], + [5, 0, 0, 0, 5, 0, 39], + [7, 0, 0, 0, 5, 0, 49], + [7, 0, 0, 0, 5, 0, 50], + [13, 0, 0, 0, 5, 0, 50], + [7, 0, 3, 0, 5, 0, 51], + [7, 0, 3, 0, 5, 0, 86], + [21, 0, 3, 0, 5, 0, 86], + [15, 0, 3, 0, 5, 0, 86], + [7, 0, 3, 0, 5, 0, 63], + [15, 0, 3, 0, 5, 0, 63], + [21, 0, 18, 0, 5, 0, 63], + [7, 0, 3, 0, 5, 0, 75], + [21, 0, 3, 0, 5, 0, 75], + [7, 0, 3, 0, 5, 0, 97], + [7, 0, 3, 0, 5, 0, 96], + [7, 0, 3, 0, 5, 0, 60], + [12, 0, 13, 0, 5, 0, 60], + [12, 220, 13, 0, 5, 0, 60], + [12, 230, 13, 0, 5, 0, 60], + [12, 1, 13, 0, 5, 0, 60], + [12, 9, 13, 0, 5, 0, 60], + [15, 0, 3, 0, 5, 0, 60], + [21, 0, 3, 0, 5, 0, 60], + [7, 0, 3, 0, 5, 0, 87], + [15, 0, 3, 0, 5, 0, 87], + [21, 0, 3, 0, 5, 0, 87], + [7, 0, 3, 0, 5, 0, 79], + [21, 0, 18, 0, 5, 0, 79], + [7, 0, 3, 0, 5, 0, 88], + [15, 0, 3, 0, 5, 0, 88], + [7, 0, 3, 0, 5, 0, 89], + [15, 0, 3, 0, 5, 0, 89], + [7, 0, 3, 0, 5, 0, 90], + [15, 0, 11, 0, 5, 0, 6], + [10, 0, 0, 0, 5, 0, 93], + [12, 0, 13, 0, 5, 0, 93], + [7, 0, 0, 0, 5, 0, 93], + [12, 9, 13, 0, 5, 0, 93], + [21, 0, 0, 0, 5, 0, 93], + [15, 0, 18, 0, 5, 0, 93], + [13, 0, 0, 0, 5, 0, 93], + [12, 0, 13, 0, 5, 0, 91], + [10, 0, 0, 0, 5, 0, 91], + [7, 0, 0, 0, 5, 0, 91], + [12, 9, 13, 0, 5, 0, 91], + [12, 7, 13, 0, 5, 0, 91], + [21, 0, 0, 0, 5, 0, 91], + [1, 0, 0, 0, 5, 0, 91], + [7, 0, 0, 0, 5, 0, 100], + [13, 0, 0, 0, 5, 0, 100], + [12, 230, 13, 0, 5, 0, 95], + [7, 0, 0, 0, 5, 0, 95], + [12, 0, 13, 0, 5, 0, 95], + [10, 0, 0, 0, 5, 0, 95], + [12, 9, 13, 0, 5, 0, 95], + [13, 0, 0, 0, 5, 0, 95], + [21, 0, 0, 0, 5, 0, 95], + [12, 0, 13, 0, 5, 0, 99], + [10, 0, 0, 0, 5, 0, 99], + [7, 0, 0, 0, 5, 0, 99], + [10, 9, 0, 0, 5, 0, 99], + [21, 0, 0, 0, 5, 0, 99], + [13, 0, 0, 0, 5, 0, 99], + [7, 0, 0, 0, 5, 0, 101], + [12, 0, 13, 0, 5, 0, 101], + [10, 0, 0, 0, 5, 0, 101], + [10, 9, 0, 0, 5, 0, 101], + [12, 7, 13, 0, 5, 0, 101], + [13, 0, 0, 0, 5, 0, 101], + [7, 0, 0, 0, 5, 0, 62], + [14, 0, 0, 0, 5, 0, 62], + [21, 0, 0, 0, 5, 0, 62], + [7, 0, 0, 0, 5, 0, 80], + [7, 0, 0, 0, 5, 0, 98], + [10, 0, 0, 0, 5, 0, 98], + [12, 0, 13, 0, 5, 0, 98], + [6, 0, 0, 0, 5, 0, 98], + [10, 216, 0, 0, 5, 0, 0], + [10, 226, 0, 0, 5, 0, 0], + [12, 230, 13, 0, 5, 0, 2], + [25, 0, 0, 0, 5, 0, 0], + [13, 0, 8, 0, 5, 0, 0], + [26, 0, 0, 0, 2, 0, 32], + ]; + + /* Mirror unicode characters. Bidirectional Algorithm, at http://www.unicode.org/unicode/reports/tr9/ */ + + public static $mirror_pairs = [ + 40 => 41, + 41 => 40, + 60 => 62, + 62 => 60, + 91 => 93, + 93 => 91, + 123 => 125, + 125 => 123, + 171 => 187, + 187 => 171, + 3898 => 3899, + 3899 => 3898, + 3900 => 3901, + 3901 => 3900, + 5787 => 5788, + 5788 => 5787, + 8249 => 8250, + 8250 => 8249, + 8261 => 8262, + 8262 => 8261, + 8317 => 8318, + 8318 => 8317, + 8333 => 8334, + 8334 => 8333, + 8712 => 8715, + 8713 => 8716, + 8714 => 8717, + 8715 => 8712, + 8716 => 8713, + 8717 => 8714, + 8725 => 10741, + 8764 => 8765, + 8765 => 8764, + 8771 => 8909, + 8786 => 8787, + 8787 => 8786, + 8788 => 8789, + 8789 => 8788, + 8804 => 8805, + 8805 => 8804, + 8806 => 8807, + 8807 => 8806, + 8808 => 8809, + 8809 => 8808, + 8810 => 8811, + 8811 => 8810, + 8814 => 8815, + 8815 => 8814, + 8816 => 8817, + 8817 => 8816, + 8818 => 8819, + 8819 => 8818, + 8820 => 8821, + 8821 => 8820, + 8822 => 8823, + 8823 => 8822, + 8824 => 8825, + 8825 => 8824, + 8826 => 8827, + 8827 => 8826, + 8828 => 8829, + 8829 => 8828, + 8830 => 8831, + 8831 => 8830, + 8832 => 8833, + 8833 => 8832, + 8834 => 8835, + 8835 => 8834, + 8836 => 8837, + 8837 => 8836, + 8838 => 8839, + 8839 => 8838, + 8840 => 8841, + 8841 => 8840, + 8842 => 8843, + 8843 => 8842, + 8847 => 8848, + 8848 => 8847, + 8849 => 8850, + 8850 => 8849, + 8856 => 10680, + 8866 => 8867, + 8867 => 8866, + 8870 => 10974, + 8872 => 10980, + 8873 => 10979, + 8875 => 10981, + 8880 => 8881, + 8881 => 8880, + 8882 => 8883, + 8883 => 8882, + 8884 => 8885, + 8885 => 8884, + 8886 => 8887, + 8887 => 8886, + 8905 => 8906, + 8906 => 8905, + 8907 => 8908, + 8908 => 8907, + 8909 => 8771, + 8912 => 8913, + 8913 => 8912, + 8918 => 8919, + 8919 => 8918, + 8920 => 8921, + 8921 => 8920, + 8922 => 8923, + 8923 => 8922, + 8924 => 8925, + 8925 => 8924, + 8926 => 8927, + 8927 => 8926, + 8928 => 8929, + 8929 => 8928, + 8930 => 8931, + 8931 => 8930, + 8932 => 8933, + 8933 => 8932, + 8934 => 8935, + 8935 => 8934, + 8936 => 8937, + 8937 => 8936, + 8938 => 8939, + 8939 => 8938, + 8940 => 8941, + 8941 => 8940, + 8944 => 8945, + 8945 => 8944, + 8946 => 8954, + 8947 => 8955, + 8948 => 8956, + 8950 => 8957, + 8951 => 8958, + 8954 => 8946, + 8955 => 8947, + 8956 => 8948, + 8957 => 8950, + 8958 => 8951, + 8968 => 8969, + 8969 => 8968, + 8970 => 8971, + 8971 => 8970, + 9001 => 9002, + 9002 => 9001, + 10088 => 10089, + 10089 => 10088, + 10090 => 10091, + 10091 => 10090, + 10092 => 10093, + 10093 => 10092, + 10094 => 10095, + 10095 => 10094, + 10096 => 10097, + 10097 => 10096, + 10098 => 10099, + 10099 => 10098, + 10100 => 10101, + 10101 => 10100, + 10179 => 10180, + 10180 => 10179, + 10181 => 10182, + 10182 => 10181, + 10184 => 10185, + 10185 => 10184, + 10187 => 10189, + 10189 => 10187, + 10197 => 10198, + 10198 => 10197, + 10205 => 10206, + 10206 => 10205, + 10210 => 10211, + 10211 => 10210, + 10212 => 10213, + 10213 => 10212, + 10214 => 10215, + 10215 => 10214, + 10216 => 10217, + 10217 => 10216, + 10218 => 10219, + 10219 => 10218, + 10220 => 10221, + 10221 => 10220, + 10222 => 10223, + 10223 => 10222, + 10627 => 10628, + 10628 => 10627, + 10629 => 10630, + 10630 => 10629, + 10631 => 10632, + 10632 => 10631, + 10633 => 10634, + 10634 => 10633, + 10635 => 10636, + 10636 => 10635, + 10637 => 10640, + 10638 => 10639, + 10639 => 10638, + 10640 => 10637, + 10641 => 10642, + 10642 => 10641, + 10643 => 10644, + 10644 => 10643, + 10645 => 10646, + 10646 => 10645, + 10647 => 10648, + 10648 => 10647, + 10680 => 8856, + 10688 => 10689, + 10689 => 10688, + 10692 => 10693, + 10693 => 10692, + 10703 => 10704, + 10704 => 10703, + 10705 => 10706, + 10706 => 10705, + 10708 => 10709, + 10709 => 10708, + 10712 => 10713, + 10713 => 10712, + 10714 => 10715, + 10715 => 10714, + 10741 => 8725, + 10744 => 10745, + 10745 => 10744, + 10748 => 10749, + 10749 => 10748, + 10795 => 10796, + 10796 => 10795, + 10797 => 10798, + 10798 => 10797, + 10804 => 10805, + 10805 => 10804, + 10812 => 10813, + 10813 => 10812, + 10852 => 10853, + 10853 => 10852, + 10873 => 10874, + 10874 => 10873, + 10877 => 10878, + 10878 => 10877, + 10879 => 10880, + 10880 => 10879, + 10881 => 10882, + 10882 => 10881, + 10883 => 10884, + 10884 => 10883, + 10891 => 10892, + 10892 => 10891, + 10897 => 10898, + 10898 => 10897, + 10899 => 10900, + 10900 => 10899, + 10901 => 10902, + 10902 => 10901, + 10903 => 10904, + 10904 => 10903, + 10905 => 10906, + 10906 => 10905, + 10907 => 10908, + 10908 => 10907, + 10913 => 10914, + 10914 => 10913, + 10918 => 10919, + 10919 => 10918, + 10920 => 10921, + 10921 => 10920, + 10922 => 10923, + 10923 => 10922, + 10924 => 10925, + 10925 => 10924, + 10927 => 10928, + 10928 => 10927, + 10931 => 10932, + 10932 => 10931, + 10939 => 10940, + 10940 => 10939, + 10941 => 10942, + 10942 => 10941, + 10943 => 10944, + 10944 => 10943, + 10945 => 10946, + 10946 => 10945, + 10947 => 10948, + 10948 => 10947, + 10949 => 10950, + 10950 => 10949, + 10957 => 10958, + 10958 => 10957, + 10959 => 10960, + 10960 => 10959, + 10961 => 10962, + 10962 => 10961, + 10963 => 10964, + 10964 => 10963, + 10965 => 10966, + 10966 => 10965, + 10974 => 8870, + 10979 => 8873, + 10980 => 8872, + 10981 => 8875, + 10988 => 10989, + 10989 => 10988, + 10999 => 11000, + 11000 => 10999, + 11001 => 11002, + 11002 => 11001, + 11778 => 11779, + 11779 => 11778, + 11780 => 11781, + 11781 => 11780, + 11785 => 11786, + 11786 => 11785, + 11788 => 11789, + 11789 => 11788, + 11804 => 11805, + 11805 => 11804, + 11808 => 11809, + 11809 => 11808, + 11810 => 11811, + 11811 => 11810, + 11812 => 11813, + 11813 => 11812, + 11814 => 11815, + 11815 => 11814, + 11816 => 11817, + 11817 => 11816, + 12296 => 12297, + 12297 => 12296, + 12298 => 12299, + 12299 => 12298, + 12300 => 12301, + 12301 => 12300, + 12302 => 12303, + 12303 => 12302, + 12304 => 12305, + 12305 => 12304, + 12308 => 12309, + 12309 => 12308, + 12310 => 12311, + 12311 => 12310, + 12312 => 12313, + 12313 => 12312, + 12314 => 12315, + 12315 => 12314, + 65113 => 65114, + 65114 => 65113, + 65115 => 65116, + 65116 => 65115, + 65117 => 65118, + 65118 => 65117, + 65124 => 65125, + 65125 => 65124, + 65288 => 65289, + 65289 => 65288, + 65308 => 65310, + 65310 => 65308, + 65339 => 65341, + 65341 => 65339, + 65371 => 65373, + 65373 => 65371, + 65375 => 65376, + 65376 => 65375, + 65378 => 65379, + 65379 => 65378, + ]; + + + /* index tables for the database records */ + + private static $index0 = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 53, 53, 53, + 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, + 53, 53, 54, 52, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, + 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, + 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, + 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, + 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 55, 56, 57, 57, 57, 58, + 59, 60, 61, 62, 63, 64, 65, 66, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, + 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, + 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 68, 69, 70, 70, + 71, 69, 70, 70, 72, 73, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 75, 76, 77, 78, 79, 80, 81, + 82, 83, 84, 85, 86, 87, 70, 70, 70, 88, 89, 90, 91, 92, 70, 93, 70, 94, + 95, 70, 70, 70, 70, 96, 70, 70, 70, 70, 70, 70, 70, 70, 70, 97, 97, 97, + 98, 99, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 100, 100, 100, 100, + 101, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 102, 102, + 103, 70, 70, 70, 70, 104, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 105, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 106, 107, 108, 109, 110, + 111, 112, 113, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 114, 70, 115, 116, 117, 118, 119, 120, + 121, 122, 70, 70, 70, 70, 70, 70, 70, 70, 52, 53, 53, 53, 53, 53, 53, 53, + 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, + 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, + 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, + 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, + 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, + 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, + 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, + 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, + 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 123, 52, 53, 53, + 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 124, 125, 126, 126, + 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, + 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, + 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, + 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, + 126, 126, 126, 126, 126, 76, 76, 127, 126, 126, 126, 126, 128, 126, 126, + 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, + 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, + 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, + 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, + 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, + 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, + 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, + 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, + 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, + 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, + 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, + 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, + 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, + 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, + 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, + 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, + 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, + 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, + 126, 128, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 129, 130, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, + 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 73, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 131, 73, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, + 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 74, 131, + ]; + + private static $index1 = [ + 0, 1, 0, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10, 11, 11, 12, 13, 0, 0, 0, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 29, 31, 32, + 33, 34, 35, 27, 30, 29, 27, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, + 47, 48, 27, 27, 49, 27, 27, 27, 27, 27, 27, 27, 50, 51, 52, 27, 53, 54, + 53, 54, 54, 54, 54, 54, 55, 54, 54, 54, 56, 57, 58, 59, 60, 61, 62, 63, + 64, 64, 65, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 65, 77, 78, + 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, + 97, 97, 97, 97, 98, 98, 98, 98, 99, 100, 101, 101, 101, 101, 102, 103, + 101, 101, 101, 101, 101, 101, 104, 105, 101, 101, 101, 101, 101, 101, + 101, 101, 101, 101, 101, 106, 107, 108, 108, 108, 109, 110, 111, 112, + 112, 112, 112, 113, 114, 115, 116, 117, 118, 119, 120, 106, 121, 121, + 121, 122, 123, 106, 124, 125, 126, 127, 128, 128, 128, 128, 129, 130, + 131, 132, 133, 134, 135, 128, 128, 128, 128, 128, 128, 128, 128, 128, + 128, 128, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 145, 145, + 146, 147, 148, 149, 128, 128, 128, 128, 128, 128, 150, 150, 150, 150, + 151, 152, 153, 106, 154, 155, 156, 156, 156, 157, 158, 159, 160, 160, + 161, 162, 163, 164, 165, 166, 167, 167, 167, 168, 106, 106, 106, 106, + 106, 106, 106, 106, 169, 170, 106, 106, 106, 106, 106, 106, 171, 172, + 173, 174, 175, 176, 176, 176, 176, 176, 176, 177, 178, 179, 180, 176, + 181, 182, 183, 184, 185, 186, 187, 188, 188, 189, 190, 191, 192, 193, + 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 203, 204, 205, 206, + 207, 208, 209, 210, 211, 212, 213, 106, 214, 215, 216, 217, 217, 218, + 219, 220, 221, 222, 223, 106, 224, 225, 226, 106, 227, 228, 229, 230, + 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 106, 241, 242, + 243, 244, 245, 242, 246, 247, 248, 249, 250, 106, 251, 252, 253, 254, + 255, 256, 257, 258, 258, 257, 259, 260, 261, 262, 263, 264, 265, 266, + 106, 267, 268, 269, 270, 271, 271, 270, 272, 273, 274, 275, 276, 277, + 278, 279, 280, 106, 281, 282, 283, 284, 284, 284, 284, 285, 286, 287, + 288, 106, 289, 290, 291, 292, 293, 294, 295, 296, 294, 294, 297, 298, + 295, 299, 300, 301, 106, 106, 302, 106, 303, 304, 304, 304, 304, 304, + 305, 306, 307, 308, 309, 310, 106, 106, 106, 106, 311, 312, 313, 314, + 315, 316, 317, 318, 319, 320, 321, 322, 106, 106, 106, 106, 323, 324, + 325, 326, 327, 328, 329, 330, 331, 332, 331, 331, 331, 333, 334, 335, + 336, 337, 338, 339, 338, 338, 338, 340, 341, 342, 343, 344, 106, 106, + 106, 106, 345, 345, 345, 345, 345, 346, 347, 348, 349, 350, 351, 352, + 353, 354, 355, 345, 356, 357, 349, 358, 359, 359, 359, 359, 360, 361, + 362, 362, 362, 362, 362, 363, 364, 364, 364, 364, 364, 364, 364, 364, + 364, 364, 364, 364, 365, 365, 365, 365, 365, 365, 365, 365, 365, 365, + 365, 365, 365, 365, 365, 365, 365, 365, 365, 365, 366, 366, 366, 366, + 366, 366, 366, 366, 366, 367, 368, 367, 366, 366, 366, 366, 366, 367, + 366, 366, 366, 366, 367, 368, 367, 366, 368, 366, 366, 366, 366, 366, + 366, 366, 367, 366, 366, 366, 366, 366, 366, 366, 366, 369, 370, 371, + 372, 373, 366, 366, 374, 375, 376, 376, 376, 376, 376, 376, 376, 376, + 376, 376, 377, 106, 378, 379, 379, 379, 379, 379, 379, 379, 379, 379, + 379, 379, 379, 379, 379, 379, 379, 379, 379, 379, 379, 379, 379, 379, + 379, 379, 379, 379, 379, 379, 379, 379, 379, 379, 379, 379, 379, 379, + 379, 379, 379, 379, 379, 379, 379, 379, 379, 379, 379, 379, 379, 379, + 379, 379, 379, 379, 379, 379, 379, 379, 379, 379, 379, 379, 379, 379, + 379, 379, 379, 379, 379, 379, 379, 379, 379, 379, 379, 380, 379, 379, + 381, 382, 382, 383, 384, 384, 384, 384, 384, 384, 384, 384, 384, 385, + 386, 106, 387, 388, 389, 106, 390, 390, 391, 106, 392, 392, 393, 106, + 394, 395, 396, 106, 397, 397, 397, 397, 397, 397, 398, 399, 400, 401, + 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 412, 412, 412, + 413, 412, 412, 412, 412, 412, 412, 106, 412, 412, 412, 412, 412, 414, + 379, 379, 379, 379, 379, 379, 379, 379, 415, 106, 416, 416, 416, 417, + 418, 419, 420, 421, 422, 423, 424, 424, 424, 425, 426, 106, 427, 427, + 427, 427, 427, 428, 429, 429, 430, 431, 432, 433, 434, 434, 434, 434, + 435, 435, 436, 437, 438, 438, 438, 438, 438, 438, 439, 440, 441, 442, + 443, 444, 445, 446, 445, 446, 447, 448, 106, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 449, 450, 450, 450, 450, 450, 451, 452, 453, 454, + 455, 456, 457, 458, 459, 460, 461, 462, 462, 462, 463, 464, 465, 466, + 467, 467, 467, 467, 468, 469, 470, 471, 472, 472, 472, 472, 473, 474, + 475, 476, 477, 478, 479, 480, 481, 481, 481, 482, 106, 106, 106, 106, + 106, 106, 106, 106, 483, 106, 484, 485, 486, 487, 488, 106, 54, 54, 54, + 54, 489, 490, 56, 56, 56, 56, 56, 491, 492, 493, 54, 494, 54, 54, 54, + 495, 56, 56, 56, 496, 497, 498, 499, 500, 501, 106, 106, 502, 27, 27, 27, + 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 503, 504, 27, + 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 505, 506, 507, 508, 505, 506, + 505, 506, 507, 508, 505, 509, 505, 506, 505, 507, 505, 510, 505, 510, + 505, 510, 511, 512, 513, 514, 515, 516, 505, 517, 518, 519, 520, 521, + 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, + 536, 537, 56, 538, 539, 540, 539, 541, 106, 106, 542, 543, 544, 545, 546, + 106, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, + 560, 559, 561, 562, 563, 564, 565, 566, 567, 568, 569, 568, 570, 571, + 568, 572, 568, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, + 584, 585, 586, 587, 588, 583, 583, 589, 590, 591, 592, 593, 583, 583, + 594, 574, 595, 596, 583, 583, 597, 583, 583, 568, 598, 599, 568, 600, + 601, 602, 603, 603, 603, 603, 603, 603, 603, 603, 604, 568, 568, 605, + 606, 574, 574, 607, 568, 568, 568, 568, 573, 608, 568, 609, 106, 568, + 568, 568, 568, 610, 106, 106, 106, 568, 611, 106, 106, 612, 612, 612, + 612, 612, 613, 613, 614, 615, 615, 615, 615, 615, 615, 615, 615, 615, + 616, 612, 612, 617, 617, 617, 617, 617, 617, 617, 617, 617, 618, 617, + 617, 617, 617, 618, 568, 617, 617, 619, 568, 620, 569, 621, 622, 623, + 624, 569, 568, 619, 572, 568, 574, 625, 626, 622, 627, 568, 568, 568, + 568, 628, 568, 568, 568, 629, 630, 568, 568, 568, 568, 568, 631, 568, + 632, 568, 631, 633, 634, 617, 617, 635, 617, 617, 617, 636, 568, 568, + 568, 568, 568, 568, 637, 568, 568, 572, 568, 568, 638, 639, 612, 640, + 640, 641, 568, 568, 568, 568, 568, 642, 643, 644, 645, 646, 647, 574, + 574, 648, 648, 648, 648, 648, 648, 648, 648, 648, 648, 648, 648, 648, + 648, 648, 648, 648, 648, 648, 648, 648, 648, 648, 648, 648, 648, 648, + 648, 648, 648, 648, 648, 574, 574, 574, 574, 574, 574, 574, 574, 574, + 574, 574, 574, 574, 574, 574, 574, 649, 650, 650, 651, 583, 583, 574, + 652, 597, 653, 654, 655, 656, 657, 658, 659, 574, 660, 583, 661, 662, + 663, 664, 645, 574, 574, 586, 652, 664, 665, 666, 667, 583, 583, 583, + 583, 668, 669, 583, 583, 583, 583, 670, 671, 672, 645, 673, 674, 568, + 568, 568, 568, 568, 568, 574, 574, 675, 676, 677, 678, 106, 106, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 106, 106, 106, 679, 679, 679, 679, 679, 680, 681, 681, 681, 681, 681, + 682, 683, 684, 685, 686, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, + 687, 688, 689, 690, 691, 691, 691, 691, 692, 693, 694, 694, 694, 694, + 694, 694, 694, 695, 696, 697, 366, 366, 368, 106, 368, 368, 368, 368, + 368, 368, 368, 368, 698, 698, 698, 698, 699, 700, 701, 702, 703, 704, + 529, 705, 106, 106, 106, 106, 106, 106, 106, 106, 706, 706, 706, 707, + 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 708, 106, 706, 706, + 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, + 706, 706, 706, 706, 706, 706, 706, 706, 706, 706, 709, 106, 106, 106, + 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721, 721, 721, + 721, 721, 721, 721, 721, 721, 722, 723, 724, 725, 725, 725, 725, 725, + 725, 725, 725, 725, 725, 726, 727, 728, 728, 728, 728, 729, 730, 364, + 364, 364, 364, 364, 364, 364, 364, 364, 364, 731, 732, 733, 728, 728, + 728, 734, 710, 710, 710, 710, 711, 106, 725, 725, 735, 735, 735, 736, + 737, 738, 733, 733, 733, 739, 740, 741, 735, 735, 735, 742, 737, 738, + 733, 733, 733, 733, 743, 741, 733, 744, 745, 745, 745, 745, 745, 746, + 745, 745, 745, 745, 745, 745, 745, 745, 745, 745, 745, 733, 733, 733, + 747, 748, 733, 733, 733, 733, 733, 733, 733, 733, 733, 733, 733, 749, + 733, 733, 733, 747, 750, 751, 751, 751, 751, 751, 751, 751, 751, 751, + 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, + 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, + 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, + 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, + 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, + 751, 751, 751, 751, 751, 751, 752, 753, 568, 568, 568, 568, 568, 568, + 568, 568, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, + 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 754, + 753, 753, 753, 753, 753, 753, 755, 755, 756, 755, 755, 755, 755, 755, + 755, 755, 755, 755, 755, 755, 755, 755, 755, 755, 755, 755, 755, 755, + 755, 755, 755, 755, 755, 755, 755, 755, 755, 755, 755, 755, 755, 755, + 755, 755, 755, 755, 755, 755, 755, 755, 755, 755, 755, 755, 755, 755, + 755, 755, 755, 755, 755, 755, 755, 755, 755, 755, 755, 755, 755, 755, + 755, 755, 755, 755, 755, 755, 755, 755, 755, 755, 755, 755, 755, 755, + 755, 755, 755, 757, 758, 758, 758, 758, 758, 758, 759, 106, 760, 760, + 760, 760, 760, 761, 762, 762, 762, 762, 762, 762, 762, 762, 762, 762, + 762, 762, 762, 762, 762, 762, 762, 762, 762, 762, 762, 762, 762, 762, + 762, 762, 762, 762, 762, 762, 762, 762, 762, 763, 762, 762, 764, 765, + 106, 106, 101, 101, 101, 101, 101, 766, 767, 768, 101, 101, 101, 769, + 770, 770, 770, 770, 770, 770, 770, 770, 771, 772, 773, 106, 64, 64, 774, + 775, 776, 27, 777, 27, 27, 27, 27, 27, 27, 27, 778, 779, 27, 780, 781, + 106, 27, 782, 106, 106, 106, 106, 106, 106, 106, 106, 106, 783, 784, 785, + 786, 786, 787, 788, 789, 790, 791, 791, 791, 791, 791, 791, 792, 106, + 793, 794, 794, 794, 794, 794, 795, 796, 797, 798, 799, 800, 801, 801, + 802, 803, 804, 805, 806, 806, 807, 808, 809, 809, 810, 811, 812, 813, + 364, 364, 364, 814, 815, 816, 816, 816, 816, 816, 817, 818, 819, 820, + 821, 822, 106, 106, 106, 106, 823, 823, 823, 823, 823, 824, 825, 106, + 826, 827, 828, 829, 345, 345, 830, 831, 832, 832, 832, 832, 832, 832, + 833, 834, 835, 106, 106, 836, 837, 838, 839, 106, 840, 840, 840, 106, + 368, 368, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 106, 106, 837, 837, 837, 837, 841, 842, 843, 844, + 845, 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, + 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, + 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, + 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, + 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, + 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, 846, + 847, 106, 365, 365, 848, 849, 365, 365, 365, 365, 365, 850, 851, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 106, 106, 106, 852, 851, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 106, 852, 106, 106, 106, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 852, + 853, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, + 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, + 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, + 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, + 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, + 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, + 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 855, 856, 856, + 856, 856, 856, 856, 856, 856, 856, 856, 856, 856, 856, 856, 856, 856, + 856, 856, 856, 856, 856, 856, 856, 856, 856, 856, 856, 856, 856, 856, + 856, 856, 856, 856, 856, 856, 856, 856, 856, 856, 856, 856, 856, 856, + 856, 857, 856, 856, 856, 856, 856, 856, 856, 856, 856, 856, 856, 856, + 856, 858, 753, 753, 753, 753, 859, 106, 860, 861, 121, 862, 863, 864, + 865, 121, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, + 866, 867, 868, 106, 869, 128, 128, 128, 128, 128, 128, 128, 128, 128, + 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, + 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, + 128, 128, 128, 128, 128, 128, 128, 870, 106, 106, 128, 128, 128, 128, + 128, 128, 128, 128, 871, 128, 128, 128, 128, 128, 128, 106, 106, 106, + 106, 106, 128, 872, 873, 873, 874, 875, 501, 106, 876, 877, 878, 879, + 880, 881, 882, 883, 884, 128, 128, 128, 128, 128, 128, 128, 128, 128, + 128, 128, 128, 128, 128, 128, 128, 885, 886, 887, 888, 889, 890, 891, + 891, 892, 893, 894, 894, 895, 896, 897, 898, 897, 897, 897, 897, 899, + 900, 900, 900, 901, 902, 902, 902, 903, 904, 905, 106, 906, 907, 908, + 907, 907, 909, 907, 907, 910, 907, 911, 907, 911, 106, 106, 106, 106, + 907, 907, 907, 907, 907, 907, 907, 907, 907, 907, 907, 907, 907, 907, + 907, 912, 913, 914, 914, 914, 914, 914, 915, 603, 916, 916, 916, 916, + 916, 916, 917, 918, 919, 920, 568, 609, 106, 106, 106, 106, 106, 106, + 603, 603, 603, 603, 603, 921, 106, 106, 106, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 922, 922, 922, 923, 924, 924, + 924, 924, 924, 924, 925, 106, 106, 106, 106, 106, 926, 926, 926, 927, + 928, 106, 929, 929, 930, 931, 106, 106, 106, 106, 106, 106, 932, 932, + 932, 933, 934, 934, 934, 934, 935, 934, 936, 106, 106, 106, 106, 106, + 937, 937, 937, 937, 937, 938, 938, 938, 938, 938, 939, 939, 939, 939, + 939, 939, 940, 940, 940, 941, 942, 943, 106, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 944, 945, 946, 946, 946, 946, 947, 948, 949, 949, + 950, 951, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 952, 952, 953, 954, 955, 955, + 955, 956, 106, 106, 106, 106, 106, 106, 106, 106, 957, 957, 957, 957, + 958, 958, 958, 959, 106, 106, 106, 106, 106, 106, 106, 106, 960, 961, + 962, 963, 964, 964, 965, 966, 967, 106, 968, 969, 970, 970, 970, 971, + 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 106, 106, 972, 972, 972, 972, 972, 972, 973, 974, 975, 975, 976, 977, + 978, 978, 979, 980, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 106, 106, 981, 981, 981, 981, 981, 981, 981, 981, + 981, 982, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 983, 983, 983, 984, 106, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 985, 986, 986, 986, 986, 986, 986, 987, 988, 989, 990, 991, 992, 993, + 106, 106, 994, 995, 995, 995, 995, 995, 996, 997, 998, 106, 999, 999, + 999, 1000, 1001, 1002, 1003, 1004, 1004, 1004, 1005, 1006, 1007, 1008, + 1009, 106, 106, 106, 106, 106, 106, 106, 1010, 1011, 1011, 1011, 1011, + 1011, 1012, 1013, 1014, 1015, 1016, 1017, 106, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 1018, 1018, 1018, 1018, 1018, 1019, 1020, 106, 1021, 1022, 106, 106, 106, + 106, 106, 106, 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023, + 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023, + 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023, + 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023, + 1024, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 106, 1025, 1025, 1025, 1025, 1025, 1025, 1025, 1025, + 1025, 1025, 1025, 1025, 1026, 106, 1027, 106, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 1028, 1028, 1028, + 1028, 1028, 1028, 1028, 1028, 1028, 1028, 1028, 1028, 1028, 1028, 1028, + 1028, 1028, 1028, 1028, 1028, 1028, 1028, 1028, 1028, 1028, 1028, 1028, + 1028, 1028, 1028, 1028, 1028, 1028, 1028, 1028, 1028, 1028, 1029, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 770, 770, 770, + 770, 770, 770, 770, 770, 770, 770, 770, 770, 770, 770, 770, 770, 770, + 770, 770, 770, 770, 770, 770, 770, 770, 770, 770, 770, 770, 770, 770, + 770, 770, 770, 770, 770, 770, 770, 770, 1030, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 106, 1031, 1031, 1031, 1031, 1031, 1031, 1031, 1031, + 1032, 106, 1033, 1034, 1034, 1034, 1034, 1035, 106, 1036, 1037, 1038, + 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 1039, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 106, 106, 603, 603, 603, 603, 603, 603, 603, 603, 603, 603, 603, 603, + 603, 603, 603, 603, 603, 603, 603, 603, 603, 603, 603, 603, 603, 603, + 603, 603, 603, 603, 1040, 106, 603, 603, 603, 603, 1041, 1042, 603, 603, + 603, 603, 603, 603, 1043, 1044, 1045, 1046, 1047, 1048, 603, 603, 603, + 1049, 603, 603, 603, 603, 603, 1040, 106, 106, 106, 106, 919, 919, 919, + 919, 919, 919, 919, 919, 1050, 106, 106, 106, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 106, 568, 568, 568, 568, 568, 568, 568, 568, 568, 568, 610, 106, 914, + 914, 1051, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 106, 1052, 1052, 1052, 1053, 1054, 1054, 1055, 1052, + 1052, 1056, 1057, 1054, 1054, 1052, 1052, 1052, 1053, 1054, 1054, 1058, + 1059, 1060, 1056, 1061, 1062, 1054, 1052, 1052, 1052, 1053, 1054, 1054, + 1063, 1064, 1065, 1066, 1054, 1054, 1054, 1067, 1068, 1069, 1070, 1054, + 1054, 1055, 1052, 1052, 1056, 1054, 1054, 1054, 1052, 1052, 1052, 1053, + 1054, 1054, 1055, 1052, 1052, 1056, 1054, 1054, 1054, 1052, 1052, 1052, + 1053, 1054, 1054, 1055, 1052, 1052, 1056, 1054, 1054, 1054, 1052, 1052, + 1052, 1053, 1054, 1054, 1071, 1052, 1052, 1052, 1072, 1054, 1054, 1073, + 1074, 1052, 1052, 1075, 1054, 1054, 1076, 1055, 1052, 1052, 1077, 1054, + 1054, 1078, 1079, 1052, 1052, 1080, 1054, 1054, 1054, 1081, 1052, 1052, + 1052, 1072, 1054, 1054, 1073, 1082, 1083, 1083, 1083, 1083, 1083, 1083, + 1084, 128, 128, 128, 1085, 1086, 1087, 1088, 1089, 1090, 1085, 1091, + 1085, 1087, 1087, 1092, 128, 1093, 128, 1094, 1095, 1093, 128, 1094, 106, + 106, 106, 106, 106, 106, 1096, 106, 568, 568, 568, 568, 568, 609, 568, + 568, 568, 568, 568, 568, 568, 568, 568, 568, 568, 568, 609, 106, 568, + 610, 636, 610, 636, 568, 636, 568, 106, 106, 106, 106, 613, 1097, 615, + 615, 615, 1098, 615, 615, 615, 615, 615, 615, 615, 1099, 615, 615, 615, + 615, 615, 1100, 106, 106, 106, 106, 106, 106, 106, 106, 1101, 603, 603, + 603, 1102, 106, 733, 733, 733, 733, 733, 1103, 733, 1104, 1105, 106, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 106, 568, 568, 568, 568, 1106, 106, 1107, 568, 568, + 568, 568, 568, 568, 568, 568, 1108, 568, 568, 609, 106, 568, 568, 568, + 568, 1109, 611, 106, 106, 568, 568, 1106, 106, 568, 568, 568, 568, 568, + 568, 568, 610, 1110, 568, 568, 568, 568, 568, 568, 568, 568, 568, 568, + 568, 568, 568, 568, 568, 568, 568, 568, 568, 568, 568, 568, 1111, 568, + 568, 568, 568, 568, 568, 568, 1112, 609, 106, 568, 568, 568, 106, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 106, 106, 1113, 568, 568, 568, 568, 568, 568, 568, 568, 1114, 568, 106, + 106, 106, 106, 106, 106, 568, 568, 568, 568, 568, 568, 568, 568, 1112, + 106, 106, 106, 106, 106, 106, 106, 568, 568, 568, 568, 568, 568, 568, + 568, 568, 568, 568, 568, 568, 568, 609, 106, 106, 106, 106, 106, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 751, 751, 751, + 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, + 751, 751, 751, 751, 751, 751, 751, 751, 751, 1115, 753, 753, 753, 753, + 753, 751, 751, 751, 751, 751, 751, 754, 753, 750, 751, 751, 751, 751, + 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, 751, + 751, 751, 751, 751, 751, 751, 751, 751, 752, 753, 753, 753, 753, 753, + 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, + 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, + 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, + 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 856, + 856, 856, 857, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, + 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, + 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, + 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, 753, + 753, 753, 753, 753, 753, 753, 1116, 1117, 106, 106, 106, 1118, 1118, + 1118, 1118, 1118, 1118, 1118, 1118, 1118, 1118, 1118, 1118, 106, 106, + 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 873, 873, 873, 873, 873, 873, 873, 873, 873, 873, 873, 873, 873, 873, + 873, 873, 873, 873, 873, 873, 873, 873, 873, 873, 873, 873, 873, 873, + 873, 873, 106, 106, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, + 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, 854, + 854, 854, 854, 854, 854, 854, 854, 1119, + ]; + + private static $index2 = [ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 2, 4, 3, 1, 1, 1, 1, 1, 1, 3, 3, 3, 2, + 5, 6, 6, 7, 8, 7, 6, 6, 9, 10, 6, 11, 12, 13, 12, 12, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 12, 6, 15, 16, 15, 6, 6, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 9, 6, 10, 18, 19, 18, 20, 20, + 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 9, 16, + 10, 16, 1, 1, 1, 1, 1, 1, 3, 1, 1, 21, 22, 8, 8, 23, 8, 24, 22, 25, 26, + 27, 28, 16, 29, 30, 18, 31, 32, 33, 33, 25, 34, 22, 22, 25, 33, 27, 35, + 36, 36, 36, 22, 37, 37, 37, 37, 37, 37, 38, 37, 37, 37, 37, 37, 37, 37, + 37, 37, 38, 37, 37, 37, 37, 37, 37, 39, 38, 37, 37, 37, 37, 37, 38, 40, + 40, 40, 41, 41, 41, 41, 40, 41, 40, 40, 40, 41, 40, 40, 41, 41, 40, 41, + 40, 40, 41, 41, 41, 39, 40, 40, 40, 41, 40, 41, 40, 41, 37, 40, 37, 41, + 37, 41, 37, 41, 37, 41, 37, 41, 37, 41, 37, 41, 37, 40, 37, 40, 37, 41, + 37, 41, 37, 41, 37, 40, 37, 41, 37, 41, 37, 41, 37, 41, 37, 41, 38, 40, + 37, 40, 38, 40, 37, 41, 37, 41, 40, 37, 41, 37, 41, 37, 41, 38, 40, 38, + 40, 37, 40, 37, 41, 37, 40, 40, 38, 40, 37, 40, 37, 41, 37, 41, 38, 40, + 37, 41, 37, 41, 37, 37, 41, 37, 41, 37, 41, 41, 41, 37, 37, 41, 37, 41, + 37, 37, 41, 37, 37, 37, 41, 41, 37, 37, 37, 37, 41, 37, 37, 41, 37, 37, + 37, 41, 41, 41, 37, 37, 41, 37, 37, 41, 37, 41, 37, 41, 37, 37, 41, 37, + 41, 41, 37, 41, 37, 37, 41, 37, 37, 37, 41, 37, 41, 37, 37, 41, 41, 42, + 37, 41, 41, 41, 42, 42, 42, 42, 37, 43, 41, 37, 43, 41, 37, 43, 41, 37, + 40, 37, 40, 37, 40, 37, 40, 37, 40, 37, 40, 37, 40, 37, 40, 41, 37, 41, + 41, 37, 43, 41, 37, 41, 37, 37, 37, 41, 37, 41, 41, 41, 41, 41, 41, 41, + 37, 37, 41, 37, 37, 41, 41, 37, 41, 37, 37, 37, 37, 41, 41, 40, 41, 41, + 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 42, 41, + 41, 41, 44, 44, 44, 44, 44, 44, 44, 44, 44, 45, 45, 46, 46, 46, 46, 46, + 46, 46, 47, 47, 25, 47, 45, 48, 45, 48, 48, 48, 45, 48, 45, 45, 49, 46, + 47, 47, 47, 47, 47, 47, 25, 25, 25, 25, 47, 25, 47, 25, 44, 44, 44, 44, + 44, 47, 47, 47, 47, 47, 50, 50, 45, 47, 46, 47, 47, 47, 47, 47, 47, 47, + 47, 47, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 52, 53, 53, + 53, 53, 52, 54, 53, 53, 53, 53, 53, 55, 55, 53, 53, 53, 53, 55, 55, 53, + 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 56, 56, 56, 56, 56, 53, 53, 53, + 53, 51, 51, 51, 51, 51, 51, 51, 51, 57, 51, 53, 53, 53, 51, 51, 51, 53, + 53, 58, 51, 51, 51, 53, 53, 53, 53, 51, 52, 53, 53, 51, 59, 60, 60, 59, + 60, 60, 59, 51, 51, 51, 51, 51, 61, 62, 61, 62, 45, 63, 61, 62, 64, 64, + 65, 62, 62, 62, 66, 64, 64, 64, 64, 64, 63, 47, 61, 66, 61, 61, 61, 64, + 61, 64, 61, 61, 62, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, + 67, 67, 67, 67, 64, 67, 67, 67, 67, 67, 67, 67, 61, 61, 62, 62, 62, 62, + 62, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, + 62, 68, 68, 68, 68, 68, 68, 68, 62, 62, 62, 62, 62, 61, 62, 62, 61, 61, + 61, 62, 62, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 69, 70, 69, 70, + 69, 70, 69, 70, 69, 70, 69, 70, 69, 70, 62, 62, 62, 62, 61, 62, 71, 61, + 62, 61, 61, 62, 62, 61, 61, 61, 72, 73, 72, 72, 72, 72, 72, 72, 72, 72, + 72, 72, 72, 72, 72, 72, 73, 73, 73, 73, 73, 73, 73, 73, 74, 74, 74, 74, + 74, 74, 74, 74, 75, 74, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 75, + 75, 75, 72, 75, 72, 75, 72, 75, 72, 75, 72, 75, 76, 77, 77, 78, 78, 77, + 79, 79, 72, 75, 72, 75, 72, 75, 72, 72, 75, 72, 75, 72, 75, 72, 75, 72, + 75, 72, 75, 72, 75, 75, 64, 64, 64, 64, 64, 64, 64, 64, 64, 80, 80, 80, + 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, + 80, 64, 64, 81, 82, 82, 82, 82, 82, 82, 64, 83, 83, 83, 83, 83, 83, 83, + 83, 83, 83, 83, 83, 83, 83, 83, 64, 84, 85, 64, 64, 64, 64, 86, 64, 87, + 88, 88, 88, 88, 87, 88, 88, 88, 89, 87, 88, 88, 88, 88, 88, 88, 87, 87, + 87, 87, 87, 87, 88, 88, 87, 88, 88, 89, 90, 88, 91, 92, 93, 94, 95, 96, + 97, 98, 99, 100, 100, 101, 102, 103, 104, 105, 106, 107, 108, 106, 88, + 87, 106, 99, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 64, + 64, 64, 64, 64, 109, 109, 109, 106, 106, 64, 64, 64, 110, 110, 110, 110, + 110, 64, 111, 111, 112, 113, 113, 114, 115, 116, 117, 117, 118, 118, 118, + 118, 118, 118, 118, 118, 119, 120, 121, 122, 64, 64, 116, 122, 123, 123, + 123, 123, 123, 123, 123, 123, 124, 123, 123, 123, 123, 123, 123, 123, + 123, 123, 123, 125, 126, 127, 128, 129, 130, 131, 132, 78, 78, 133, 134, + 118, 118, 118, 118, 118, 134, 118, 118, 134, 135, 135, 135, 135, 135, + 135, 135, 135, 135, 135, 113, 136, 136, 116, 123, 123, 137, 123, 123, + 123, 123, 123, 123, 123, 123, 123, 123, 123, 116, 123, 118, 118, 118, + 118, 118, 118, 118, 138, 117, 118, 118, 118, 118, 134, 118, 139, 139, + 118, 118, 117, 134, 118, 118, 134, 123, 123, 140, 140, 140, 140, 140, + 140, 140, 140, 140, 140, 123, 123, 123, 141, 141, 123, 142, 142, 142, + 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 64, 143, 144, 145, + 144, 144, 144, 144, 144, 144, 144, 144, 144, 144, 144, 144, 144, 144, + 146, 147, 146, 146, 147, 146, 146, 147, 147, 147, 146, 147, 147, 146, + 147, 146, 146, 146, 147, 146, 147, 146, 147, 146, 147, 146, 146, 64, 64, + 144, 144, 144, 148, 148, 148, 148, 148, 148, 148, 148, 148, 148, 148, + 148, 148, 148, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, + 148, 64, 64, 64, 64, 64, 64, 150, 150, 150, 150, 150, 150, 150, 150, 150, + 150, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, + 151, 151, 151, 151, 152, 152, 152, 152, 152, 152, 152, 153, 152, 154, + 154, 155, 156, 156, 156, 154, 64, 64, 64, 64, 64, 157, 157, 157, 157, + 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, 158, 158, 158, 158, + 159, 158, 158, 158, 158, 158, 158, 158, 158, 158, 159, 158, 158, 158, + 159, 158, 158, 158, 158, 158, 64, 64, 160, 160, 160, 160, 160, 160, 160, + 160, 160, 160, 160, 160, 160, 160, 160, 64, 161, 161, 161, 161, 161, 161, + 161, 161, 161, 162, 162, 162, 64, 64, 163, 64, 123, 64, 123, 123, 123, + 123, 123, 123, 123, 123, 123, 123, 123, 64, 64, 64, 64, 64, 64, 64, 118, + 118, 134, 118, 118, 134, 118, 118, 118, 134, 134, 134, 164, 165, 166, + 118, 118, 118, 134, 118, 118, 134, 134, 118, 118, 118, 118, 64, 167, 167, + 167, 168, 169, 169, 169, 169, 169, 169, 169, 169, 169, 169, 169, 169, + 169, 169, 167, 168, 170, 169, 168, 168, 168, 167, 167, 167, 167, 167, + 167, 167, 167, 168, 168, 168, 168, 171, 168, 168, 169, 78, 133, 172, 172, + 167, 167, 167, 169, 169, 167, 167, 84, 84, 173, 173, 173, 173, 173, 173, + 173, 173, 173, 173, 174, 175, 169, 169, 169, 169, 169, 169, 64, 169, 169, + 169, 169, 169, 169, 169, 64, 176, 177, 177, 64, 178, 178, 178, 178, 178, + 178, 178, 178, 64, 64, 178, 178, 64, 64, 178, 178, 178, 178, 178, 178, + 178, 178, 178, 178, 178, 178, 178, 178, 64, 178, 178, 178, 178, 178, 178, + 178, 64, 178, 64, 64, 64, 178, 178, 178, 178, 64, 64, 179, 178, 177, 177, + 177, 176, 176, 176, 176, 64, 64, 177, 177, 64, 64, 177, 177, 180, 178, + 64, 64, 64, 64, 64, 64, 64, 64, 177, 64, 64, 64, 64, 178, 178, 64, 178, + 178, 178, 176, 176, 64, 64, 181, 181, 181, 181, 181, 181, 181, 181, 181, + 181, 178, 178, 182, 182, 183, 183, 183, 183, 183, 183, 184, 182, 64, 64, + 64, 64, 64, 185, 185, 186, 64, 187, 187, 187, 187, 187, 187, 64, 64, 64, + 64, 187, 187, 64, 64, 187, 187, 187, 187, 187, 187, 187, 187, 187, 187, + 187, 187, 187, 187, 64, 187, 187, 187, 187, 187, 187, 187, 64, 187, 187, + 64, 187, 187, 64, 187, 187, 64, 64, 188, 64, 186, 186, 186, 185, 185, 64, + 64, 64, 64, 185, 185, 64, 64, 185, 185, 189, 64, 64, 64, 185, 64, 64, 64, + 64, 64, 64, 64, 187, 187, 187, 187, 64, 187, 64, 64, 64, 64, 64, 64, 64, + 190, 190, 190, 190, 190, 190, 190, 190, 190, 190, 185, 185, 187, 187, + 187, 185, 64, 64, 64, 191, 191, 192, 64, 193, 193, 193, 193, 193, 193, + 193, 193, 193, 64, 193, 193, 193, 64, 193, 193, 193, 193, 193, 193, 193, + 193, 193, 193, 193, 193, 193, 193, 64, 193, 193, 193, 193, 193, 193, 193, + 64, 193, 193, 64, 193, 193, 193, 193, 193, 64, 64, 194, 193, 192, 192, + 192, 191, 191, 191, 191, 191, 64, 191, 191, 192, 64, 192, 192, 195, 64, + 64, 193, 64, 64, 64, 64, 64, 64, 64, 193, 193, 191, 191, 64, 64, 196, + 196, 196, 196, 196, 196, 196, 196, 196, 196, 197, 198, 64, 64, 64, 64, + 64, 64, 64, 199, 200, 200, 64, 201, 201, 201, 201, 201, 201, 201, 201, + 64, 64, 201, 201, 64, 64, 201, 201, 201, 201, 201, 201, 201, 201, 201, + 201, 201, 201, 201, 201, 64, 201, 201, 201, 201, 201, 201, 201, 64, 201, + 201, 64, 201, 201, 201, 201, 201, 64, 64, 202, 201, 200, 199, 200, 199, + 199, 199, 199, 64, 64, 200, 200, 64, 64, 200, 200, 203, 64, 64, 64, 64, + 64, 64, 64, 64, 199, 200, 64, 64, 64, 64, 201, 201, 64, 201, 201, 201, + 199, 199, 64, 64, 204, 204, 204, 204, 204, 204, 204, 204, 204, 204, 205, + 201, 206, 206, 206, 206, 206, 206, 64, 64, 207, 208, 64, 208, 208, 208, + 208, 208, 208, 64, 64, 64, 208, 208, 208, 64, 208, 208, 208, 208, 64, 64, + 64, 208, 208, 64, 208, 64, 208, 208, 64, 64, 64, 208, 208, 64, 64, 64, + 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 64, 64, 64, 64, 209, + 209, 207, 209, 209, 64, 64, 64, 209, 209, 209, 64, 209, 209, 209, 210, + 64, 64, 208, 64, 64, 64, 64, 64, 64, 209, 64, 64, 64, 64, 64, 64, 211, + 211, 211, 211, 211, 211, 211, 211, 211, 211, 212, 212, 212, 213, 213, + 213, 213, 213, 213, 214, 213, 64, 64, 64, 64, 64, 64, 215, 215, 215, 64, + 216, 216, 216, 216, 216, 216, 216, 216, 64, 216, 216, 216, 64, 216, 216, + 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, 216, + 216, 216, 64, 216, 216, 216, 216, 216, 64, 64, 64, 216, 217, 217, 217, + 215, 215, 215, 215, 64, 217, 217, 217, 64, 217, 217, 217, 218, 64, 64, + 64, 64, 64, 64, 64, 219, 220, 64, 216, 216, 64, 64, 64, 64, 64, 64, 216, + 216, 217, 217, 64, 64, 221, 221, 221, 221, 221, 221, 221, 221, 221, 221, + 222, 222, 222, 222, 222, 222, 222, 223, 64, 64, 224, 224, 64, 225, 225, + 225, 225, 225, 225, 225, 225, 64, 225, 225, 225, 64, 225, 225, 225, 225, + 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 64, + 225, 225, 225, 225, 225, 64, 64, 226, 225, 224, 227, 224, 224, 224, 224, + 224, 64, 227, 224, 224, 64, 224, 224, 228, 229, 64, 64, 64, 64, 64, 64, + 64, 224, 224, 64, 64, 64, 64, 64, 64, 64, 225, 64, 225, 225, 228, 228, + 64, 64, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 64, 225, 225, + 64, 64, 64, 64, 64, 64, 64, 231, 231, 64, 232, 232, 232, 232, 232, 232, + 232, 232, 64, 232, 232, 232, 64, 232, 232, 232, 232, 232, 232, 232, 232, + 232, 232, 232, 232, 232, 232, 232, 232, 232, 64, 64, 232, 231, 231, 231, + 233, 233, 233, 233, 64, 231, 231, 231, 64, 231, 231, 231, 234, 232, 64, + 64, 64, 64, 64, 64, 64, 64, 231, 232, 232, 233, 233, 64, 64, 235, 235, + 235, 235, 235, 235, 235, 235, 235, 235, 236, 236, 236, 236, 236, 236, 64, + 64, 64, 237, 232, 232, 232, 232, 232, 232, 64, 64, 238, 238, 64, 239, + 239, 239, 239, 239, 239, 239, 239, 239, 239, 239, 239, 239, 239, 239, + 239, 239, 239, 64, 64, 64, 239, 239, 239, 239, 239, 239, 239, 239, 64, + 239, 239, 239, 239, 239, 239, 239, 239, 239, 64, 239, 64, 64, 64, 64, + 240, 64, 64, 64, 64, 238, 238, 238, 241, 241, 241, 64, 241, 64, 238, 238, + 238, 238, 238, 238, 238, 238, 64, 64, 238, 238, 242, 64, 64, 64, 64, 243, + 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, + 243, 244, 243, 243, 244, 244, 244, 244, 245, 245, 246, 64, 64, 64, 64, + 247, 243, 243, 243, 243, 243, 243, 248, 244, 249, 249, 249, 249, 244, + 244, 244, 250, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 250, + 250, 64, 64, 64, 64, 64, 252, 252, 64, 252, 64, 64, 252, 252, 64, 252, + 64, 64, 252, 64, 64, 64, 64, 64, 64, 252, 252, 252, 252, 64, 252, 252, + 252, 252, 252, 252, 252, 64, 252, 252, 252, 64, 252, 64, 252, 64, 64, + 252, 252, 64, 252, 252, 252, 252, 253, 252, 252, 253, 253, 253, 253, 254, + 254, 64, 253, 253, 252, 64, 64, 252, 252, 252, 252, 252, 64, 255, 64, + 256, 256, 256, 256, 253, 253, 64, 64, 257, 257, 257, 257, 257, 257, 257, + 257, 257, 257, 64, 64, 252, 252, 252, 252, 258, 259, 259, 259, 260, 260, + 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 260, 259, + 260, 259, 259, 259, 261, 261, 259, 259, 259, 259, 259, 259, 262, 262, + 262, 262, 262, 262, 262, 262, 262, 262, 263, 263, 263, 263, 263, 263, + 263, 263, 263, 263, 259, 261, 259, 261, 259, 264, 265, 266, 265, 266, + 267, 267, 258, 258, 258, 258, 258, 258, 258, 258, 64, 258, 258, 258, 258, + 258, 258, 258, 258, 258, 258, 258, 258, 64, 64, 64, 64, 268, 269, 270, + 271, 270, 270, 270, 270, 270, 269, 269, 269, 269, 270, 267, 269, 270, + 272, 272, 273, 260, 272, 272, 258, 258, 258, 258, 258, 270, 270, 270, + 270, 270, 270, 270, 270, 270, 270, 270, 64, 270, 270, 270, 270, 270, 270, + 270, 270, 270, 270, 270, 270, 64, 259, 259, 259, 259, 259, 259, 259, 259, + 261, 259, 259, 259, 259, 259, 259, 64, 259, 259, 260, 260, 260, 260, 260, + 274, 274, 274, 274, 260, 260, 64, 64, 64, 64, 64, 275, 275, 275, 275, + 275, 275, 275, 275, 275, 275, 275, 276, 276, 277, 277, 277, 277, 276, + 277, 277, 277, 277, 277, 278, 276, 279, 279, 276, 276, 277, 277, 275, + 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 281, 281, 281, 281, + 281, 281, 275, 275, 275, 275, 275, 275, 276, 276, 277, 277, 275, 275, + 275, 275, 277, 277, 277, 275, 276, 276, 276, 275, 275, 276, 276, 276, + 276, 276, 276, 276, 275, 275, 275, 277, 277, 277, 277, 275, 275, 275, + 275, 275, 277, 276, 276, 277, 277, 276, 276, 276, 276, 276, 276, 282, + 275, 276, 280, 280, 276, 276, 276, 277, 283, 283, 284, 284, 284, 284, + 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 64, 284, 64, 64, 64, + 64, 64, 284, 64, 64, 285, 285, 285, 285, 285, 285, 285, 285, 285, 285, + 285, 84, 286, 285, 285, 285, 287, 287, 287, 287, 287, 287, 287, 287, 288, + 288, 288, 288, 288, 288, 288, 288, 289, 289, 289, 289, 289, 289, 289, + 289, 289, 64, 289, 289, 289, 289, 64, 64, 289, 289, 289, 289, 289, 289, + 289, 64, 289, 289, 289, 64, 64, 290, 290, 290, 291, 291, 291, 291, 291, + 291, 291, 291, 291, 292, 292, 292, 292, 292, 292, 292, 292, 292, 292, + 292, 292, 292, 292, 292, 292, 292, 292, 292, 292, 64, 64, 64, 293, 293, + 293, 293, 293, 293, 293, 293, 293, 293, 64, 64, 64, 64, 64, 64, 294, 294, + 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 294, 64, 64, 64, 295, + 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, 296, + 296, 296, 296, 296, 296, 296, 297, 297, 296, 298, 299, 299, 299, 299, + 299, 299, 299, 299, 299, 299, 299, 299, 299, 299, 299, 299, 299, 299, + 300, 301, 64, 64, 64, 302, 302, 302, 302, 302, 302, 302, 302, 302, 302, + 302, 84, 84, 84, 303, 303, 303, 64, 64, 64, 64, 64, 64, 64, 304, 304, + 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 304, 64, 304, 304, 304, + 304, 305, 305, 306, 64, 64, 64, 307, 307, 307, 307, 307, 307, 307, 307, + 307, 307, 308, 308, 309, 84, 84, 64, 310, 310, 310, 310, 310, 310, 310, + 310, 310, 310, 311, 311, 64, 64, 64, 64, 312, 312, 312, 312, 312, 312, + 312, 312, 312, 312, 312, 312, 312, 64, 312, 312, 312, 64, 313, 313, 64, + 64, 64, 64, 314, 314, 314, 314, 314, 314, 314, 314, 314, 314, 314, 314, + 315, 315, 316, 315, 315, 315, 315, 315, 315, 315, 316, 316, 316, 316, + 316, 316, 316, 316, 315, 316, 316, 315, 315, 315, 315, 315, 315, 315, + 315, 315, 317, 315, 318, 318, 318, 319, 318, 318, 318, 320, 314, 321, 64, + 64, 322, 322, 322, 322, 322, 322, 322, 322, 322, 322, 64, 64, 64, 64, 64, + 64, 323, 323, 323, 323, 323, 323, 323, 323, 323, 323, 64, 64, 64, 64, 64, + 64, 324, 324, 66, 66, 324, 66, 325, 324, 324, 324, 324, 326, 326, 326, + 327, 64, 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, 64, 64, 64, + 64, 64, 64, 329, 329, 329, 329, 329, 329, 329, 329, 329, 329, 329, 330, + 329, 329, 329, 329, 329, 331, 329, 64, 64, 64, 64, 64, 296, 296, 296, + 296, 296, 296, 64, 64, 332, 332, 332, 332, 332, 332, 332, 332, 332, 332, + 332, 332, 332, 64, 64, 64, 333, 333, 333, 334, 334, 334, 334, 333, 333, + 334, 334, 334, 64, 64, 64, 64, 334, 334, 333, 334, 334, 334, 334, 334, + 334, 335, 336, 337, 64, 64, 64, 64, 338, 64, 64, 64, 339, 339, 340, 340, + 340, 340, 340, 340, 340, 340, 340, 340, 341, 341, 341, 341, 341, 341, + 341, 341, 341, 341, 341, 341, 341, 341, 64, 64, 341, 341, 341, 341, 341, + 64, 64, 64, 342, 342, 342, 342, 342, 342, 342, 342, 342, 342, 342, 342, + 64, 64, 64, 64, 343, 343, 343, 343, 343, 343, 343, 343, 343, 342, 342, + 342, 342, 342, 342, 342, 343, 343, 64, 64, 64, 64, 64, 64, 344, 344, 344, + 344, 344, 344, 344, 344, 344, 344, 345, 64, 64, 64, 346, 346, 347, 347, + 347, 347, 347, 347, 347, 347, 348, 348, 348, 348, 348, 348, 348, 348, + 348, 348, 348, 348, 348, 348, 348, 349, 350, 351, 351, 351, 64, 64, 352, + 352, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, 353, + 354, 355, 354, 355, 355, 355, 355, 355, 355, 355, 64, 356, 354, 355, 354, + 354, 355, 355, 355, 355, 355, 355, 355, 355, 354, 354, 354, 354, 354, + 354, 355, 355, 357, 357, 357, 357, 357, 357, 357, 357, 64, 64, 358, 359, + 359, 359, 359, 359, 359, 359, 359, 359, 359, 64, 64, 64, 64, 64, 64, 360, + 360, 360, 360, 360, 360, 360, 361, 360, 360, 360, 360, 360, 360, 64, 64, + 362, 362, 362, 362, 363, 364, 364, 364, 364, 364, 364, 364, 364, 364, + 364, 364, 364, 364, 364, 364, 365, 363, 362, 362, 362, 362, 362, 363, + 362, 363, 363, 363, 363, 363, 362, 363, 366, 364, 364, 364, 364, 364, + 364, 364, 64, 64, 64, 64, 367, 367, 367, 367, 367, 367, 367, 367, 367, + 367, 368, 368, 368, 368, 368, 368, 368, 369, 369, 369, 369, 369, 369, + 369, 369, 369, 369, 370, 371, 370, 370, 370, 370, 370, 370, 370, 369, + 369, 369, 369, 369, 369, 369, 369, 369, 64, 64, 64, 372, 372, 373, 374, + 374, 374, 374, 374, 374, 374, 374, 374, 374, 374, 374, 374, 374, 373, + 372, 372, 372, 372, 373, 373, 372, 372, 375, 376, 373, 373, 374, 374, + 377, 377, 377, 377, 377, 377, 377, 377, 377, 377, 374, 374, 374, 374, + 374, 374, 378, 378, 378, 378, 378, 378, 378, 378, 378, 378, 378, 378, + 378, 378, 379, 380, 381, 381, 380, 380, 380, 381, 380, 381, 381, 381, + 382, 382, 64, 64, 64, 64, 64, 64, 64, 64, 383, 383, 383, 383, 384, 384, + 384, 384, 384, 384, 384, 384, 384, 384, 384, 384, 385, 385, 385, 385, + 385, 385, 385, 385, 386, 386, 386, 386, 386, 386, 386, 386, 385, 385, + 386, 387, 64, 64, 64, 388, 388, 388, 388, 388, 389, 389, 389, 389, 389, + 389, 389, 389, 389, 389, 64, 64, 64, 384, 384, 384, 390, 390, 390, 390, + 390, 390, 390, 390, 390, 390, 391, 391, 391, 391, 391, 391, 391, 391, + 391, 391, 391, 391, 391, 391, 392, 392, 392, 392, 392, 392, 393, 393, + 394, 394, 394, 394, 394, 394, 394, 394, 78, 78, 78, 84, 395, 133, 133, + 133, 133, 133, 78, 78, 133, 133, 133, 133, 78, 396, 395, 395, 395, 395, + 395, 395, 395, 397, 397, 397, 397, 133, 397, 397, 397, 397, 396, 396, 78, + 397, 397, 64, 41, 41, 41, 41, 41, 41, 62, 62, 62, 62, 62, 75, 44, 44, 44, + 44, 44, 44, 44, 44, 44, 65, 65, 65, 65, 65, 44, 44, 44, 44, 65, 65, 65, + 65, 65, 41, 41, 41, 41, 41, 398, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, + 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 44, 65, 78, 78, 133, 78, 78, + 78, 78, 78, 78, 78, 133, 78, 78, 399, 400, 133, 401, 78, 78, 78, 78, 78, + 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 64, + 64, 64, 64, 64, 402, 133, 78, 133, 37, 41, 37, 41, 37, 41, 41, 41, 41, + 41, 41, 41, 41, 41, 37, 41, 62, 62, 62, 62, 62, 62, 62, 62, 61, 61, 61, + 61, 61, 61, 61, 61, 62, 62, 62, 62, 62, 62, 64, 64, 61, 61, 61, 61, 61, + 61, 64, 64, 64, 61, 64, 61, 64, 61, 64, 61, 403, 403, 403, 403, 403, 403, + 403, 403, 62, 62, 62, 62, 62, 64, 62, 62, 61, 61, 61, 61, 403, 63, 62, + 63, 63, 63, 62, 62, 62, 64, 62, 62, 61, 61, 61, 61, 403, 63, 63, 63, 62, + 62, 62, 62, 64, 64, 62, 62, 61, 61, 61, 61, 64, 63, 63, 63, 61, 61, 61, + 61, 61, 63, 63, 63, 64, 64, 62, 62, 62, 64, 62, 62, 61, 61, 61, 61, 403, + 63, 63, 64, 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, 405, + 406, 406, 407, 408, 409, 410, 410, 409, 409, 409, 22, 66, 411, 412, 413, + 414, 411, 412, 413, 414, 22, 22, 22, 66, 22, 22, 22, 22, 415, 416, 417, + 418, 419, 420, 421, 21, 422, 423, 422, 422, 423, 22, 66, 66, 66, 28, 35, + 22, 66, 66, 22, 424, 424, 66, 66, 66, 425, 426, 427, 66, 66, 66, 66, 66, + 66, 66, 66, 66, 66, 66, 428, 66, 424, 66, 66, 66, 66, 66, 66, 66, 66, 66, + 66, 404, 405, 405, 405, 405, 405, 64, 64, 64, 64, 64, 405, 405, 405, 405, + 405, 405, 429, 44, 64, 64, 33, 429, 429, 429, 429, 429, 430, 430, 428, + 426, 427, 431, 429, 33, 33, 33, 33, 429, 429, 429, 429, 429, 430, 430, + 428, 426, 427, 64, 44, 44, 44, 44, 44, 64, 64, 64, 247, 247, 247, 247, + 247, 247, 247, 247, 247, 432, 247, 247, 23, 247, 247, 247, 247, 247, 247, + 64, 64, 64, 64, 64, 78, 78, 395, 395, 78, 78, 78, 78, 395, 395, 395, 78, + 78, 433, 433, 433, 433, 78, 433, 433, 433, 395, 395, 78, 133, 78, 395, + 395, 133, 133, 133, 133, 78, 64, 64, 64, 64, 64, 64, 64, 26, 26, 434, 30, + 26, 30, 26, 434, 26, 30, 34, 434, 434, 434, 34, 34, 434, 434, 434, 435, + 26, 434, 30, 26, 428, 434, 434, 434, 434, 434, 26, 26, 26, 30, 30, 26, + 434, 26, 67, 26, 434, 26, 37, 38, 434, 434, 436, 34, 434, 434, 37, 434, + 34, 397, 397, 397, 397, 34, 26, 26, 34, 34, 434, 434, 437, 428, 428, 428, + 428, 434, 34, 34, 34, 34, 26, 428, 26, 26, 41, 274, 438, 438, 438, 36, + 36, 438, 438, 438, 438, 438, 438, 36, 36, 36, 36, 438, 439, 439, 439, + 439, 439, 439, 439, 439, 439, 439, 439, 439, 440, 440, 440, 440, 439, + 439, 440, 440, 440, 440, 440, 440, 440, 440, 440, 37, 41, 440, 440, 440, + 440, 36, 64, 64, 64, 64, 64, 64, 39, 39, 39, 39, 39, 30, 30, 30, 30, 30, + 428, 428, 26, 26, 26, 26, 428, 26, 26, 428, 26, 26, 428, 26, 26, 26, 26, + 26, 26, 26, 428, 26, 26, 26, 26, 26, 26, 26, 26, 26, 30, 30, 26, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 26, 26, 428, 428, 26, 26, 39, 26, 39, 26, 26, + 26, 26, 26, 26, 26, 26, 26, 26, 30, 26, 26, 26, 26, 428, 428, 428, 428, + 428, 428, 428, 428, 428, 428, 428, 428, 39, 437, 441, 441, 437, 428, 428, + 39, 441, 437, 437, 441, 437, 437, 428, 39, 428, 441, 430, 442, 428, 441, + 437, 428, 428, 428, 441, 437, 437, 441, 39, 441, 441, 437, 437, 39, 437, + 39, 437, 39, 39, 39, 39, 441, 441, 437, 441, 437, 437, 437, 437, 437, 39, + 39, 39, 39, 428, 437, 428, 437, 441, 441, 437, 437, 437, 437, 437, 437, + 437, 437, 437, 437, 441, 437, 437, 437, 441, 428, 428, 428, 428, 428, + 441, 437, 437, 437, 428, 428, 428, 428, 428, 428, 428, 428, 428, 437, + 441, 39, 437, 428, 441, 441, 441, 441, 437, 437, 441, 441, 428, 428, 441, + 441, 437, 437, 441, 441, 437, 437, 441, 441, 437, 437, 437, 437, 437, + 428, 428, 437, 437, 437, 437, 428, 428, 39, 428, 428, 437, 39, 428, 428, + 428, 428, 428, 428, 428, 428, 437, 437, 428, 39, 437, 437, 437, 428, 428, + 428, 428, 428, 437, 441, 428, 437, 437, 437, 437, 437, 428, 428, 437, + 437, 428, 428, 428, 428, 437, 437, 437, 437, 437, 437, 437, 437, 428, + 428, 437, 437, 437, 437, 26, 26, 26, 26, 26, 26, 30, 26, 26, 26, 26, 26, + 437, 437, 26, 26, 26, 26, 26, 26, 26, 443, 444, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 26, 274, 274, 274, 274, 274, 274, 274, 274, 274, 274, + 274, 274, 274, 26, 428, 26, 26, 26, 26, 26, 26, 26, 26, 274, 26, 26, 26, + 26, 26, 428, 428, 428, 428, 428, 428, 428, 428, 428, 26, 26, 26, 26, 428, + 428, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 64, 64, 64, 64, 26, 26, 26, + 26, 26, 26, 26, 64, 26, 26, 26, 64, 64, 64, 64, 64, 36, 36, 36, 36, 36, + 36, 36, 36, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 445, 445, + 445, 445, 445, 445, 445, 445, 445, 445, 445, 445, 445, 445, 438, 36, 36, + 36, 36, 36, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 26, 26, 26, + 26, 26, 26, 30, 30, 30, 30, 26, 26, 30, 30, 26, 30, 30, 30, 30, 30, 26, + 26, 30, 30, 26, 26, 30, 39, 26, 26, 26, 26, 30, 30, 26, 26, 30, 39, 26, + 26, 26, 26, 30, 30, 30, 26, 26, 30, 26, 26, 30, 30, 26, 26, 26, 26, 26, + 30, 30, 26, 26, 30, 26, 26, 26, 26, 30, 30, 26, 26, 26, 26, 30, 26, 30, + 26, 30, 26, 30, 26, 26, 26, 26, 26, 30, 30, 26, 30, 30, 30, 26, 30, 30, + 30, 30, 26, 30, 30, 26, 39, 26, 26, 26, 26, 26, 26, 30, 30, 26, 26, 26, + 26, 274, 26, 26, 26, 26, 26, 26, 26, 30, 30, 30, 30, 30, 30, 30, 30, 30, + 30, 26, 30, 30, 30, 26, 30, 26, 26, 26, 26, 64, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 26, 26, 30, 26, 26, 426, 427, 426, 427, 426, 427, 426, + 427, 426, 427, 426, 427, 426, 427, 36, 36, 438, 438, 438, 438, 438, 438, + 438, 438, 438, 438, 438, 438, 26, 26, 26, 26, 437, 428, 428, 437, 437, + 426, 427, 428, 437, 437, 428, 437, 437, 437, 428, 428, 428, 428, 428, + 437, 437, 437, 437, 428, 428, 428, 428, 428, 437, 437, 437, 428, 428, + 428, 437, 437, 437, 437, 9, 10, 9, 10, 9, 10, 9, 10, 426, 427, 446, 446, + 446, 446, 446, 446, 446, 446, 428, 428, 428, 426, 427, 9, 10, 426, 427, + 426, 427, 426, 427, 426, 427, 426, 427, 428, 428, 437, 437, 437, 437, + 437, 437, 428, 428, 428, 428, 428, 428, 428, 428, 437, 428, 428, 428, + 428, 437, 437, 437, 437, 437, 428, 437, 437, 428, 428, 426, 427, 426, + 427, 437, 428, 428, 428, 428, 437, 428, 437, 437, 437, 428, 428, 437, + 437, 428, 428, 428, 428, 428, 428, 428, 428, 428, 428, 437, 437, 437, + 437, 437, 437, 428, 428, 426, 427, 428, 428, 428, 428, 437, 437, 437, + 437, 437, 437, 437, 437, 437, 437, 437, 428, 437, 437, 437, 437, 428, + 428, 437, 428, 437, 428, 428, 437, 428, 437, 437, 437, 437, 428, 428, + 428, 428, 428, 437, 437, 428, 428, 428, 428, 437, 437, 437, 437, 428, + 437, 437, 428, 428, 437, 437, 428, 428, 428, 428, 437, 437, 437, 437, + 437, 437, 437, 437, 437, 437, 437, 428, 428, 437, 437, 437, 437, 437, + 437, 437, 437, 428, 437, 437, 437, 437, 437, 437, 437, 437, 428, 428, + 428, 428, 428, 437, 428, 437, 428, 428, 428, 437, 437, 437, 437, 437, + 428, 428, 428, 428, 437, 428, 428, 428, 437, 437, 437, 437, 437, 428, + 437, 428, 428, 428, 428, 428, 428, 428, 26, 26, 428, 428, 428, 428, 428, + 428, 64, 64, 64, 26, 26, 26, 26, 26, 30, 30, 30, 30, 30, 64, 64, 64, 64, + 64, 64, 447, 447, 447, 447, 447, 447, 447, 447, 447, 447, 447, 447, 447, + 447, 447, 64, 448, 448, 448, 448, 448, 448, 448, 448, 448, 448, 448, 448, + 448, 448, 448, 64, 37, 41, 37, 37, 37, 41, 41, 37, 41, 37, 41, 37, 41, + 37, 37, 37, 37, 41, 37, 41, 41, 37, 41, 41, 41, 41, 41, 41, 44, 44, 37, + 37, 69, 70, 69, 70, 70, 449, 449, 449, 449, 449, 449, 69, 70, 69, 70, + 450, 450, 450, 69, 70, 64, 64, 64, 64, 64, 451, 451, 451, 451, 452, 451, + 451, 453, 453, 453, 453, 453, 453, 453, 453, 453, 453, 453, 453, 453, + 453, 64, 453, 64, 64, 64, 64, 64, 453, 64, 64, 454, 454, 454, 454, 454, + 454, 454, 454, 64, 64, 64, 64, 64, 64, 64, 455, 456, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 457, 77, 77, 77, 77, 77, 77, 77, 77, + 66, 66, 28, 35, 28, 35, 66, 66, 66, 28, 35, 66, 28, 35, 66, 66, 66, 66, + 66, 66, 66, 66, 66, 410, 66, 66, 410, 66, 28, 35, 66, 66, 28, 35, 426, + 427, 426, 427, 426, 427, 426, 427, 66, 66, 66, 66, 66, 45, 66, 66, 410, + 410, 64, 64, 64, 64, 458, 458, 458, 458, 458, 458, 458, 458, 458, 458, + 64, 458, 458, 458, 458, 458, 458, 458, 458, 458, 64, 64, 64, 64, 458, + 458, 458, 458, 458, 458, 64, 64, 459, 459, 459, 459, 459, 459, 459, 459, + 459, 459, 459, 459, 64, 64, 64, 64, 460, 461, 461, 461, 459, 462, 463, + 464, 443, 444, 443, 444, 443, 444, 443, 444, 443, 444, 459, 459, 443, + 444, 443, 444, 443, 444, 443, 444, 465, 466, 467, 467, 459, 464, 464, + 464, 464, 464, 464, 464, 464, 464, 468, 469, 470, 471, 472, 472, 465, + 473, 473, 473, 473, 473, 459, 459, 464, 464, 464, 462, 463, 461, 459, 26, + 64, 474, 474, 474, 474, 474, 474, 474, 474, 474, 474, 474, 474, 474, 474, + 474, 474, 474, 474, 474, 474, 474, 474, 64, 64, 475, 475, 476, 476, 477, + 477, 474, 465, 478, 478, 478, 478, 478, 478, 478, 478, 478, 478, 478, + 478, 478, 478, 478, 478, 478, 478, 461, 473, 479, 479, 478, 64, 64, 64, + 64, 64, 480, 480, 480, 480, 480, 480, 480, 480, 480, 480, 480, 480, 480, + 480, 480, 480, 480, 64, 64, 64, 287, 287, 287, 287, 287, 287, 287, 287, + 287, 287, 287, 287, 287, 287, 64, 481, 481, 482, 482, 482, 482, 481, 481, + 481, 481, 481, 481, 481, 481, 481, 481, 480, 480, 480, 64, 64, 64, 64, + 64, 483, 483, 483, 483, 483, 483, 483, 483, 483, 483, 483, 483, 483, 484, + 484, 64, 482, 482, 482, 482, 482, 482, 482, 482, 482, 482, 481, 481, 481, + 481, 481, 481, 485, 485, 485, 485, 485, 485, 485, 485, 459, 486, 486, + 486, 486, 486, 486, 486, 486, 486, 486, 486, 486, 486, 486, 486, 483, + 483, 483, 483, 484, 484, 484, 481, 481, 486, 486, 486, 486, 486, 486, + 486, 481, 481, 481, 481, 459, 459, 459, 459, 487, 487, 487, 487, 487, + 487, 487, 487, 487, 487, 487, 487, 487, 487, 487, 64, 481, 481, 481, 481, + 481, 481, 481, 459, 459, 459, 459, 481, 481, 481, 481, 481, 481, 481, + 481, 481, 481, 481, 459, 459, 488, 489, 489, 489, 489, 489, 489, 489, + 489, 489, 489, 489, 489, 489, 489, 489, 489, 489, 489, 489, 489, 488, + 490, 490, 490, 490, 490, 490, 490, 490, 490, 490, 489, 489, 489, 489, + 488, 490, 490, 490, 491, 491, 491, 491, 491, 491, 491, 491, 491, 491, + 491, 491, 491, 492, 491, 491, 491, 491, 491, 491, 491, 64, 64, 64, 493, + 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 493, 64, + 494, 494, 494, 494, 494, 494, 494, 494, 495, 495, 495, 495, 495, 495, + 496, 496, 497, 497, 497, 497, 497, 497, 497, 497, 497, 497, 497, 497, + 498, 499, 499, 499, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, + 497, 497, 64, 64, 64, 64, 72, 75, 72, 75, 72, 75, 501, 77, 79, 79, 79, + 502, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 502, 503, 64, 64, 64, 64, + 64, 64, 64, 77, 504, 504, 504, 504, 504, 504, 504, 504, 504, 504, 504, + 504, 504, 504, 505, 505, 505, 505, 505, 505, 505, 505, 505, 505, 506, + 506, 507, 507, 507, 507, 507, 507, 47, 47, 47, 47, 47, 47, 47, 45, 45, + 45, 45, 45, 45, 45, 45, 45, 47, 47, 37, 41, 37, 41, 37, 41, 41, 41, 37, + 41, 37, 41, 37, 41, 44, 41, 41, 41, 41, 41, 41, 41, 41, 37, 41, 37, 41, + 37, 37, 41, 45, 508, 508, 37, 41, 37, 41, 64, 37, 41, 37, 41, 64, 64, 64, + 64, 37, 41, 37, 64, 64, 64, 64, 64, 44, 44, 41, 42, 42, 42, 42, 42, 509, + 509, 510, 509, 509, 509, 511, 509, 509, 509, 509, 510, 509, 509, 509, + 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 509, 512, 512, + 510, 510, 512, 513, 513, 513, 513, 64, 64, 64, 64, 514, 514, 514, 514, + 514, 514, 274, 274, 247, 436, 64, 64, 64, 64, 64, 64, 515, 515, 515, 515, + 515, 515, 515, 515, 515, 515, 515, 515, 516, 516, 516, 516, 517, 517, + 518, 518, 518, 518, 518, 518, 518, 518, 518, 518, 518, 518, 518, 518, + 518, 518, 518, 518, 517, 517, 517, 517, 517, 517, 517, 517, 517, 517, + 517, 517, 517, 517, 517, 517, 519, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 520, 520, 521, 521, 521, 521, 521, 521, 521, 521, 521, 521, 64, 64, 64, + 64, 64, 64, 172, 172, 172, 172, 172, 172, 172, 172, 172, 172, 169, 169, + 169, 169, 169, 169, 174, 174, 174, 169, 64, 64, 64, 64, 522, 522, 522, + 522, 522, 522, 522, 522, 522, 522, 523, 523, 523, 523, 523, 523, 523, + 523, 523, 523, 523, 523, 523, 523, 523, 523, 523, 523, 523, 523, 524, + 524, 524, 524, 524, 525, 525, 525, 526, 526, 527, 527, 527, 527, 527, + 527, 527, 527, 527, 527, 527, 527, 527, 527, 527, 528, 528, 528, 528, + 528, 528, 528, 528, 528, 528, 528, 529, 530, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 531, 287, 287, 287, 287, 287, 64, 64, 64, 532, 532, 532, + 533, 534, 534, 534, 534, 534, 534, 534, 534, 534, 534, 534, 534, 534, + 534, 534, 535, 533, 533, 532, 532, 532, 532, 533, 533, 532, 533, 533, + 533, 536, 537, 537, 537, 537, 537, 537, 537, 537, 537, 537, 537, 537, + 537, 64, 538, 539, 539, 539, 539, 539, 539, 539, 539, 539, 539, 64, 64, + 64, 64, 537, 537, 540, 540, 540, 540, 540, 540, 540, 540, 540, 541, 541, + 541, 541, 541, 541, 542, 542, 541, 541, 542, 542, 541, 541, 64, 540, 540, + 540, 541, 540, 540, 540, 540, 540, 540, 540, 540, 541, 542, 64, 64, 543, + 543, 543, 543, 543, 543, 543, 543, 543, 543, 64, 64, 544, 544, 544, 544, + 545, 275, 275, 275, 275, 275, 275, 283, 283, 283, 275, 276, 64, 64, 64, + 64, 546, 546, 546, 546, 546, 546, 546, 546, 547, 546, 547, 547, 548, 546, + 546, 547, 547, 546, 546, 546, 546, 546, 547, 547, 546, 547, 546, 64, 64, + 64, 64, 64, 64, 64, 64, 546, 546, 549, 550, 550, 551, 551, 551, 551, 551, + 551, 551, 551, 551, 551, 551, 552, 553, 553, 552, 552, 554, 554, 551, + 555, 555, 552, 556, 64, 64, 289, 289, 289, 289, 289, 289, 64, 551, 551, + 551, 552, 552, 553, 552, 552, 553, 552, 552, 554, 552, 556, 64, 64, 557, + 557, 557, 557, 557, 557, 557, 557, 557, 557, 64, 64, 64, 64, 64, 64, 287, + 558, 558, 558, 558, 558, 558, 558, 558, 558, 558, 558, 558, 558, 558, + 558, 558, 558, 558, 287, 64, 64, 64, 64, 288, 288, 288, 288, 288, 288, + 288, 64, 64, 64, 64, 288, 288, 288, 288, 288, 288, 288, 288, 288, 64, 64, + 64, 64, 559, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 559, + 560, 561, 561, 561, 561, 561, 561, 561, 561, 561, 561, 561, 561, 561, + 561, 561, 561, 561, 561, 561, 561, 561, 561, 560, 488, 488, 488, 488, + 488, 488, 488, 488, 488, 488, 488, 488, 488, 488, 490, 490, 488, 488, + 490, 490, 490, 490, 490, 490, 41, 41, 41, 41, 41, 41, 41, 64, 64, 64, 64, + 83, 83, 83, 83, 83, 64, 64, 64, 64, 64, 109, 562, 109, 109, 563, 109, + 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 109, 64, 109, 109, + 109, 109, 109, 64, 109, 64, 109, 109, 64, 109, 109, 64, 109, 109, 123, + 123, 564, 564, 564, 564, 564, 564, 564, 564, 564, 564, 564, 564, 564, + 564, 564, 564, 64, 64, 64, 64, 64, 64, 64, 64, 64, 123, 123, 123, 123, + 123, 123, 123, 123, 123, 123, 123, 413, 565, 64, 64, 123, 123, 123, 123, + 123, 123, 123, 123, 123, 123, 114, 26, 64, 64, 58, 58, 58, 58, 58, 58, + 58, 58, 461, 461, 461, 461, 461, 461, 461, 466, 467, 461, 64, 64, 64, 64, + 64, 64, 461, 465, 465, 566, 566, 466, 467, 466, 467, 466, 467, 466, 467, + 466, 467, 466, 467, 466, 467, 466, 467, 461, 461, 466, 467, 461, 461, + 461, 461, 566, 566, 566, 567, 461, 567, 64, 461, 567, 461, 461, 465, 443, + 444, 443, 444, 443, 444, 568, 461, 461, 569, 570, 571, 571, 572, 64, 461, + 573, 568, 461, 64, 64, 64, 64, 123, 123, 123, 123, 123, 64, 123, 123, + 123, 123, 123, 123, 123, 64, 64, 405, 64, 574, 574, 575, 576, 575, 574, + 574, 577, 578, 574, 579, 580, 581, 580, 580, 582, 582, 582, 582, 582, + 582, 582, 582, 582, 582, 580, 574, 583, 584, 583, 574, 574, 585, 585, + 585, 585, 585, 585, 585, 585, 585, 585, 585, 585, 585, 585, 585, 585, + 585, 585, 577, 574, 578, 586, 587, 586, 588, 588, 588, 588, 588, 588, + 588, 588, 588, 588, 588, 588, 588, 588, 588, 588, 588, 588, 577, 584, + 578, 584, 577, 578, 589, 590, 591, 589, 589, 592, 592, 592, 592, 592, + 592, 592, 592, 592, 592, 593, 592, 592, 592, 592, 592, 592, 592, 592, + 592, 592, 592, 592, 592, 593, 593, 594, 594, 594, 594, 594, 594, 594, + 594, 594, 594, 594, 594, 594, 594, 594, 64, 64, 64, 594, 594, 594, 594, + 594, 594, 64, 64, 594, 594, 594, 64, 64, 64, 576, 576, 584, 586, 595, + 576, 576, 64, 596, 597, 597, 597, 597, 596, 596, 64, 64, 598, 598, 598, + 26, 30, 64, 64, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, + 599, 64, 599, 599, 599, 599, 599, 599, 599, 599, 599, 599, 64, 599, 599, + 599, 64, 599, 599, 64, 599, 599, 599, 599, 599, 599, 599, 64, 64, 599, + 599, 599, 64, 64, 64, 64, 64, 84, 66, 84, 64, 64, 64, 64, 514, 514, 514, + 514, 514, 514, 514, 514, 514, 514, 514, 514, 514, 64, 64, 64, 274, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 601, 601, + 601, 601, 602, 602, 602, 602, 602, 602, 602, 602, 602, 602, 602, 602, + 602, 602, 602, 602, 602, 601, 64, 64, 64, 64, 64, 274, 274, 274, 274, + 274, 133, 64, 64, 603, 603, 603, 603, 603, 603, 603, 603, 603, 603, 603, + 603, 603, 64, 64, 64, 604, 604, 604, 604, 604, 604, 604, 604, 604, 64, + 64, 64, 64, 64, 64, 64, 605, 605, 605, 605, 605, 605, 605, 605, 605, 605, + 605, 605, 605, 605, 605, 64, 606, 606, 606, 606, 64, 64, 64, 64, 607, + 607, 607, 607, 607, 607, 607, 607, 607, 608, 607, 607, 607, 607, 607, + 607, 607, 607, 608, 64, 64, 64, 64, 64, 609, 609, 609, 609, 609, 609, + 609, 609, 609, 609, 609, 609, 609, 609, 64, 610, 611, 611, 611, 611, 611, + 611, 611, 611, 611, 611, 611, 611, 64, 64, 64, 64, 612, 613, 613, 613, + 613, 613, 64, 64, 614, 614, 614, 614, 614, 614, 614, 614, 615, 615, 615, + 615, 615, 615, 615, 615, 616, 616, 616, 616, 616, 616, 616, 616, 617, + 617, 617, 617, 617, 617, 617, 617, 617, 617, 617, 617, 617, 617, 64, 64, + 618, 618, 618, 618, 618, 618, 618, 618, 618, 618, 64, 64, 64, 64, 64, 64, + 619, 619, 619, 619, 619, 619, 64, 64, 619, 64, 619, 619, 619, 619, 619, + 619, 619, 619, 619, 619, 619, 619, 619, 619, 619, 619, 619, 619, 619, + 619, 64, 619, 619, 64, 64, 64, 619, 64, 64, 619, 620, 620, 620, 620, 620, + 620, 620, 620, 620, 620, 620, 620, 620, 620, 64, 621, 622, 622, 622, 622, + 622, 622, 622, 622, 623, 623, 623, 623, 623, 623, 623, 623, 623, 623, + 623, 623, 623, 623, 624, 624, 624, 624, 624, 624, 64, 64, 64, 625, 626, + 626, 626, 626, 626, 626, 626, 626, 626, 626, 64, 64, 64, 64, 64, 627, + 628, 628, 628, 628, 628, 628, 628, 628, 629, 629, 629, 629, 629, 629, + 629, 629, 64, 64, 64, 64, 64, 64, 629, 629, 630, 631, 631, 631, 64, 631, + 631, 64, 64, 64, 64, 64, 631, 632, 631, 633, 630, 630, 630, 630, 64, 630, + 630, 630, 64, 630, 630, 630, 630, 630, 630, 630, 630, 630, 630, 630, 630, + 630, 630, 630, 630, 630, 630, 630, 64, 64, 64, 64, 633, 634, 632, 64, 64, + 64, 64, 635, 636, 636, 636, 636, 636, 636, 636, 636, 637, 637, 637, 637, + 637, 637, 637, 637, 637, 64, 64, 64, 64, 64, 64, 64, 638, 638, 638, 638, + 638, 638, 638, 638, 638, 638, 638, 638, 638, 639, 639, 640, 641, 641, + 641, 641, 641, 641, 641, 641, 641, 641, 641, 641, 641, 641, 64, 64, 64, + 642, 642, 642, 642, 642, 642, 642, 643, 643, 643, 643, 643, 643, 643, + 643, 643, 643, 643, 643, 643, 643, 64, 64, 644, 644, 644, 644, 644, 644, + 644, 644, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 645, 64, 64, + 64, 64, 64, 646, 646, 646, 646, 646, 646, 646, 646, 647, 647, 647, 647, + 647, 647, 647, 647, 647, 64, 64, 64, 64, 64, 64, 64, 648, 648, 648, 648, + 648, 648, 648, 648, 648, 648, 648, 648, 648, 648, 648, 64, 649, 650, 649, + 651, 651, 651, 651, 651, 651, 651, 651, 651, 651, 651, 651, 651, 650, + 650, 650, 650, 650, 650, 650, 650, 650, 650, 650, 650, 650, 650, 652, + 653, 653, 653, 653, 653, 653, 653, 64, 64, 64, 64, 654, 654, 654, 654, + 654, 654, 654, 654, 654, 654, 654, 654, 654, 654, 654, 654, 654, 654, + 654, 654, 655, 655, 655, 655, 655, 655, 655, 655, 655, 655, 656, 656, + 657, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, 658, + 657, 657, 657, 656, 656, 656, 656, 657, 657, 659, 660, 661, 661, 662, + 661, 661, 661, 661, 64, 64, 64, 64, 64, 64, 663, 663, 663, 663, 663, 663, + 663, 663, 663, 64, 64, 64, 64, 64, 64, 64, 664, 664, 664, 664, 664, 664, + 664, 664, 664, 664, 64, 64, 64, 64, 64, 64, 665, 665, 665, 666, 666, 666, + 666, 666, 666, 666, 666, 666, 666, 666, 666, 666, 666, 666, 666, 666, + 666, 666, 666, 667, 667, 667, 667, 667, 668, 667, 667, 667, 667, 667, + 667, 669, 669, 64, 670, 670, 670, 670, 670, 670, 670, 670, 670, 670, 671, + 671, 671, 671, 64, 64, 64, 64, 672, 672, 673, 674, 674, 674, 674, 674, + 674, 674, 674, 674, 674, 674, 674, 674, 674, 674, 674, 673, 673, 673, + 672, 672, 672, 672, 672, 672, 672, 672, 672, 673, 675, 674, 674, 674, + 674, 676, 676, 676, 676, 64, 64, 64, 64, 64, 64, 64, 677, 677, 677, 677, + 677, 677, 677, 677, 677, 677, 64, 64, 64, 64, 64, 64, 678, 678, 678, 678, + 678, 678, 678, 678, 678, 678, 678, 679, 680, 679, 680, 680, 679, 679, + 679, 679, 679, 679, 681, 682, 683, 683, 683, 683, 683, 683, 683, 683, + 683, 683, 64, 64, 64, 64, 64, 64, 684, 684, 684, 684, 684, 684, 684, 684, + 684, 684, 684, 684, 684, 684, 684, 64, 685, 685, 685, 685, 685, 685, 685, + 685, 685, 685, 685, 64, 64, 64, 64, 64, 686, 686, 686, 686, 64, 64, 64, + 64, 687, 687, 687, 687, 687, 687, 687, 687, 687, 687, 687, 687, 687, 687, + 687, 64, 504, 64, 64, 64, 64, 64, 64, 64, 688, 688, 688, 688, 688, 688, + 688, 688, 688, 688, 688, 688, 688, 64, 64, 64, 688, 689, 689, 689, 689, + 689, 689, 689, 689, 689, 689, 689, 689, 689, 689, 689, 689, 689, 689, + 689, 689, 689, 689, 64, 64, 64, 64, 64, 64, 64, 64, 690, 690, 690, 690, + 691, 691, 691, 691, 691, 691, 691, 691, 691, 691, 691, 691, 691, 478, + 474, 64, 64, 64, 64, 64, 64, 274, 274, 274, 274, 274, 274, 64, 64, 274, + 274, 274, 274, 274, 274, 274, 64, 64, 274, 274, 274, 274, 274, 274, 274, + 274, 274, 274, 274, 274, 692, 692, 395, 395, 395, 274, 274, 274, 693, + 692, 692, 692, 692, 692, 405, 405, 405, 405, 405, 405, 405, 405, 133, + 133, 133, 133, 133, 133, 133, 133, 274, 274, 78, 78, 78, 78, 78, 133, + 133, 274, 274, 274, 274, 274, 274, 78, 78, 78, 78, 274, 274, 602, 602, + 694, 694, 694, 602, 64, 64, 514, 514, 64, 64, 64, 64, 64, 64, 434, 434, + 434, 434, 434, 434, 434, 434, 434, 434, 34, 34, 34, 34, 34, 34, 34, 34, + 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 434, 434, 434, 434, 434, 434, + 434, 434, 434, 434, 34, 34, 34, 34, 34, 34, 34, 64, 34, 34, 34, 34, 34, + 34, 434, 64, 434, 434, 64, 64, 434, 64, 64, 434, 434, 64, 64, 434, 434, + 434, 434, 64, 434, 434, 34, 34, 64, 34, 64, 34, 34, 34, 34, 34, 34, 34, + 64, 34, 34, 34, 34, 34, 34, 34, 434, 434, 64, 434, 434, 434, 434, 64, 64, + 434, 434, 434, 434, 434, 434, 434, 434, 64, 434, 434, 434, 434, 434, 434, + 434, 64, 34, 34, 434, 434, 64, 434, 434, 434, 434, 64, 434, 434, 434, + 434, 434, 64, 434, 64, 64, 64, 434, 434, 434, 434, 434, 434, 434, 64, 34, + 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 64, 64, 434, 695, 34, 34, 34, + 34, 34, 34, 34, 34, 34, 437, 34, 34, 34, 34, 34, 34, 434, 434, 434, 434, + 434, 434, 434, 434, 434, 695, 34, 34, 34, 34, 34, 34, 34, 34, 34, 437, + 34, 34, 434, 434, 434, 434, 434, 695, 34, 34, 34, 34, 34, 34, 34, 34, 34, + 437, 34, 34, 34, 34, 34, 34, 434, 434, 434, 434, 434, 434, 434, 434, 434, + 695, 34, 437, 34, 34, 34, 34, 34, 34, 34, 34, 434, 34, 64, 64, 696, 696, + 696, 696, 696, 696, 696, 696, 696, 696, 123, 123, 123, 123, 64, 123, 123, + 123, 64, 123, 123, 64, 123, 64, 64, 123, 64, 123, 123, 123, 123, 123, + 123, 123, 123, 123, 123, 64, 123, 123, 123, 123, 64, 123, 64, 123, 64, + 64, 64, 64, 64, 64, 123, 64, 64, 64, 64, 123, 64, 123, 64, 123, 64, 123, + 123, 123, 64, 123, 64, 123, 64, 123, 64, 123, 64, 123, 123, 123, 123, 64, + 123, 64, 123, 123, 64, 123, 123, 123, 123, 123, 123, 123, 123, 123, 64, + 64, 64, 64, 64, 123, 123, 123, 64, 123, 123, 123, 111, 111, 64, 64, 64, + 64, 64, 64, 33, 33, 33, 64, 64, 64, 64, 64, 445, 445, 445, 445, 445, 445, + 274, 64, 445, 445, 26, 26, 64, 64, 64, 64, 445, 445, 445, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 274, 274, 697, 481, 481, 64, 64, 64, 64, 64, + 481, 481, 481, 64, 64, 64, 64, 64, 481, 64, 64, 64, 64, 64, 64, 64, 481, + 481, 64, 64, 64, 64, 64, 64, 26, 64, 64, 64, 64, 64, 64, 64, 26, 26, 26, + 26, 26, 26, 64, 26, 26, 26, 26, 26, 26, 64, 64, 64, 26, 26, 26, 26, 26, + 64, 26, 26, 26, 64, 26, 26, 26, 26, 26, 26, 64, 26, 26, 26, 26, 64, 64, + 64, 26, 26, 26, 26, 26, 26, 64, 64, 64, 64, 64, 26, 26, 26, 26, 26, 26, + 64, 64, 64, 64, 26, 26, 26, 489, 489, 489, 489, 489, 489, 488, 490, 490, + 490, 490, 490, 490, 490, 64, 64, 64, 405, 64, 64, 64, 64, 64, 64, 405, + 405, 405, 405, 405, 405, 405, 405, 561, 561, 561, 561, 561, 560, 64, 64, + ]; +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Utils/Arrays.php b/src/bb-vendor/mpdf/mpdf/src/Utils/Arrays.php new file mode 100644 index 000000000..f27c83a42 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Utils/Arrays.php @@ -0,0 +1,92 @@ +<?php + +namespace Mpdf\Utils; + +class Arrays +{ + + public static function get($array, $key, $default = null) + { + if (is_array($array) && array_key_exists($key, $array)) { + return $array[$key]; + } + + if (func_num_args() < 3) { + throw new \InvalidArgumentException(sprintf('Array does not contain key "%s"', $key)); + } + + return $default; + } + + /** + * Returns an array of all k-combinations from an input array of n elements, where k equals 1..n. + * Elements will be sorted and unique in every combination. + * + * Example: array[one, two] will give: + * [ + * [one], + * [two], + * [one, two] + * ] + * @param array $array + * @return array + */ + public static function allUniqueSortedCombinations($array) + { + $input = array_unique($array); + if (count($input) <= 1) { + return [$input]; + } + + sort($input); + $combinations = []; + foreach ($input as $value) { + $combinations[] = [$value]; + } + + $n = count($input); + for ($k = 2; $k <= $n; $k++) { + $combinations = array_merge($combinations, self::combinations($input, $k)); + } + + return $combinations; + } + + /** + * Returns an array of unique k-combinations from an input array. + * + * Example: array=[one, two, three] and k=2 will give: + * [ + * [one, two], + * [one, three] + * ] + * @param array $array + * @param int $k + * @return array + */ + public static function combinations($array, $k) + { + $n = count($array); + $combinations = []; + $indexes = range(0, $k - 1); + $maxIndexes = range($n - $k, $n - 1); + do { + $combination = []; + foreach ($indexes as $index) { + $combination[] = $array[$index]; + } + $combinations[] = $combination; + + $anotherCombination = false; + for ($i = $k - 1; $i >= 0; $i--) { + if ($indexes[$i] < $maxIndexes[$i]) { + $indexes[$i]++; + $anotherCombination = true; + break; + } + } + } while ($anotherCombination); + + return $combinations; + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Utils/NumericString.php b/src/bb-vendor/mpdf/mpdf/src/Utils/NumericString.php new file mode 100644 index 000000000..db10287d3 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Utils/NumericString.php @@ -0,0 +1,18 @@ +<?php + +namespace Mpdf\Utils; + +class NumericString +{ + + public static function containsPercentChar($string) + { + return strstr($string, '%'); + } + + public static function removePercentChar($string) + { + return str_replace('%', '', $string); + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Utils/PdfDate.php b/src/bb-vendor/mpdf/mpdf/src/Utils/PdfDate.php new file mode 100644 index 000000000..1fc390058 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Utils/PdfDate.php @@ -0,0 +1,30 @@ +<?php + +namespace Mpdf\Utils; + +class PdfDate +{ + + /** + * PDF documents use the internal date format: (D:YYYYMMDDHHmmSSOHH'mm'). The date format has these parts: + * + * YYYY The full four-digit year. (For example, 2004) + * MM The month from 01 to 12. + * DD The day from 01 to 31. + * HH The hour from 00 to 23. + * mm The minute from 00 to 59. + * SS The seconds from 00 to 59. + * O The relationship of local time to Universal Time (UT), as denoted by one of the characters +, -, or Z. + * HH The absolute value of the offset from UT in hours specified as 00 to 23. + * mm The absolute value of the offset from UT in minutes specified as 00 to 59. + * + * @return string + */ + public static function format($date) + { + $z = date('O'); // +0200 + $offset = substr($z, 0, 3) . "'" . substr($z, 3, 2) . "'"; // +02'00' + return date('YmdHis', $date) . $offset; + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Utils/UtfString.php b/src/bb-vendor/mpdf/mpdf/src/Utils/UtfString.php new file mode 100644 index 000000000..8b5c8c940 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Utils/UtfString.php @@ -0,0 +1,67 @@ +<?php + +namespace Mpdf\Utils; + +class UtfString +{ + + /** + * Converts all the &#nnn; and &#xhhh; in a string to Unicode + * + * @since mPDF 5.7 + * @param string $str + * @param bool $lo + * + * @return string + */ + public static function strcode2utf($str, $lo = true) + { + $str = preg_replace_callback('/\&\#(\d+)\;/m', function ($matches) use ($lo) { + return static::code2utf($matches[1], $lo ? 1 : 0); + }, $str); + $str = preg_replace_callback('/\&\#x([0-9a-fA-F]+)\;/m', function ($matches) use ($lo) { + return static::codeHex2utf($matches[1], $lo ? 1 : 0); + }, $str); + + return $str; + } + + /** + * @param int $num + * @param bool $lo + * + * @return string + */ + public static function code2utf($num, $lo = true) + { + // Returns the utf string corresponding to the unicode value + if ($num < 128) { + if ($lo) { + return chr($num); + } + return '&#' . $num . ';'; + } + if ($num < 2048) { + return chr(($num >> 6) + 192) . chr(($num & 63) + 128); + } + if ($num < 65536) { + return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128); + } + if ($num < 2097152) { + return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128); + } + + return '?'; + } + + public static function codeHex2utf($hex, $lo = true) + { + $num = hexdec($hex); + if (($num < 128) && !$lo) { + return '&#x' . $hex . ';'; + } + + return static::code2utf($num, $lo); + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Writer/BackgroundWriter.php b/src/bb-vendor/mpdf/mpdf/src/Writer/BackgroundWriter.php new file mode 100644 index 000000000..6dbce84d3 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Writer/BackgroundWriter.php @@ -0,0 +1,451 @@ +<?php + +namespace Mpdf\Writer; + +use Mpdf\Strict; +use Mpdf\Mpdf; + +final class BackgroundWriter +{ + + use Strict; + + /** + * @var \Mpdf\Mpdf + */ + private $mpdf; + + /** + * @var \Mpdf\Writer\BaseWriter + */ + private $writer; + + public function __construct(Mpdf $mpdf, BaseWriter $writer) + { + $this->mpdf = $mpdf; + $this->writer = $writer; + } + + public function writePatterns() // _putpatterns + { + $patternCount = count($this->mpdf->patterns); + + for ($i = 1; $i <= $patternCount; $i++) { + + $x = $this->mpdf->patterns[$i]['x']; + $y = $this->mpdf->patterns[$i]['y']; + $w = $this->mpdf->patterns[$i]['w']; + $h = $this->mpdf->patterns[$i]['h']; + $pgh = $this->mpdf->patterns[$i]['pgh']; + $orig_w = $this->mpdf->patterns[$i]['orig_w']; + $orig_h = $this->mpdf->patterns[$i]['orig_h']; + $image_id = $this->mpdf->patterns[$i]['image_id']; + $itype = $this->mpdf->patterns[$i]['itype']; + + if (isset($this->mpdf->patterns[$i]['bpa'])) { + $bpa = $this->mpdf->patterns[$i]['bpa']; + } else { + $bpa = []; // background positioning area + } + + if ($this->mpdf->patterns[$i]['x_repeat']) { + $x_repeat = true; + } else { + $x_repeat = false; + } + + if ($this->mpdf->patterns[$i]['y_repeat']) { + $y_repeat = true; + } else { + $y_repeat = false; + } + + $x_pos = $this->mpdf->patterns[$i]['x_pos']; + + if (false !== strpos($x_pos, '%')) { + $x_pos = (float) $x_pos; + $x_pos /= 100; + + if (isset($bpa['w']) && $bpa['w']) { + $x_pos = ($bpa['w'] * $x_pos) - ($orig_w / Mpdf::SCALE * $x_pos); + } else { + $x_pos = ($w * $x_pos) - ($orig_w / Mpdf::SCALE * $x_pos); + } + } + + $y_pos = $this->mpdf->patterns[$i]['y_pos']; + + if (false !== strpos($y_pos, '%')) { + $y_pos = (float) $y_pos; + $y_pos /= 100; + + if (isset($bpa['h']) && $bpa['h']) { + $y_pos = ($bpa['h'] * $y_pos) - ($orig_h / Mpdf::SCALE * $y_pos); + } else { + $y_pos = ($h * $y_pos) - ($orig_h / Mpdf::SCALE * $y_pos); + } + } + + if (isset($bpa['x']) && $bpa['x']) { + $adj_x = ($x_pos + $bpa['x']) * Mpdf::SCALE; + } else { + $adj_x = ($x_pos + $x) * Mpdf::SCALE; + } + + if (isset($bpa['y']) && $bpa['y']) { + $adj_y = (($pgh - $y_pos - $bpa['y']) * Mpdf::SCALE) - $orig_h; + } else { + $adj_y = (($pgh - $y_pos - $y) * Mpdf::SCALE) - $orig_h; + } + + $img_obj = false; + + if ($itype === 'svg' || $itype === 'wmf') { + foreach ($this->mpdf->formobjects as $fo) { + if ($fo['i'] == $image_id) { + $img_obj = $fo['n']; + $fo_w = $fo['w']; + $fo_h = -$fo['h']; + $wmf_x = $fo['x']; + $wmf_y = $fo['y']; + break; + } + } + } else { + foreach ($this->mpdf->images as $img) { + if ($img['i'] == $image_id) { + $img_obj = $img['n']; + break; + } + } + } + + if (!$img_obj) { + throw new \Mpdf\MpdfException('Problem: Image object not found for background pattern ' . $img['i']); + } + + $this->writer->object(); + $this->writer->write('<</ProcSet [/PDF /Text /ImageB /ImageC /ImageI]'); + + if ($itype === 'svg' || $itype === 'wmf') { + $this->writer->write('/XObject <</FO' . $image_id . ' ' . $img_obj . ' 0 R >>'); + + // ******* ADD ANY ExtGStates, Shading AND Fonts needed for the FormObject + // Set in classes/svg array['fo'] = true + // Required that _putshaders comes before _putpatterns in _putresources + // This adds any resources associated with any FormObject to every Formobject - overkill but works! + if (count($this->mpdf->extgstates)) { + $this->writer->write('/ExtGState <<'); + foreach ($this->mpdf->extgstates as $k => $extgstate) { + if (isset($extgstate['fo']) && $extgstate['fo']) { + if (isset($extgstate['trans'])) { + $this->writer->write('/' . $extgstate['trans'] . ' ' . $extgstate['n'] . ' 0 R'); + } else { + $this->writer->write('/GS' . $k . ' ' . $extgstate['n'] . ' 0 R'); + } + } + } + $this->writer->write('>>'); + } + + /* -- BACKGROUNDS -- */ + if (isset($this->mpdf->gradients) && ( count($this->mpdf->gradients) > 0)) { + $this->writer->write('/Shading <<'); + foreach ($this->mpdf->gradients as $id => $grad) { + if (isset($grad['fo']) && $grad['fo']) { + $this->writer->write('/Sh' . $id . ' ' . $grad['id'] . ' 0 R'); + } + } + $this->writer->write('>>'); + } + + /* -- END BACKGROUNDS -- */ + $this->writer->write('/Font <<'); + + foreach ($this->mpdf->fonts as $font) { + if (!$font['used'] && $font['type'] === 'TTF') { + continue; + } + if (isset($font['fo']) && $font['fo']) { + if ($font['type'] === 'TTF' && ($font['sip'] || $font['smp'])) { + foreach ($font['n'] as $k => $fid) { + $this->writer->write('/F' . $font['subsetfontids'][$k] . ' ' . $font['n'][$k] . ' 0 R'); + } + } else { + $this->writer->write('/F' . $font['i'] . ' ' . $font['n'] . ' 0 R'); + } + } + } + $this->writer->write('>>'); + } else { + $this->writer->write('/XObject <</I' . $image_id . ' ' . $img_obj . ' 0 R >>'); + } + + $this->writer->write('>>'); + $this->writer->write('endobj'); + + $this->writer->object(); + $this->mpdf->patterns[$i]['n'] = $this->mpdf->n; + $this->writer->write('<< /Type /Pattern /PatternType 1 /PaintType 1 /TilingType 2'); + $this->writer->write('/Resources ' . ($this->mpdf->n - 1) . ' 0 R'); + + $this->writer->write(sprintf('/BBox [0 0 %.3F %.3F]', $orig_w, $orig_h)); + + if ($x_repeat) { + $this->writer->write(sprintf('/XStep %.3F', $orig_w)); + } else { + $this->writer->write(sprintf('/XStep %d', 99999)); + } + + if ($y_repeat) { + $this->writer->write(sprintf('/YStep %.3F', $orig_h)); + } else { + $this->writer->write(sprintf('/YStep %d', 99999)); + } + + if ($itype === 'svg' || $itype === 'wmf') { + $this->writer->write(sprintf('/Matrix [1 0 0 -1 %.3F %.3F]', $adj_x, $adj_y + $orig_h)); + $s = sprintf('q %.3F 0 0 %.3F %.3F %.3F cm /FO%d Do Q', $orig_w / $fo_w, -$orig_h / $fo_h, -($orig_w / $fo_w) * $wmf_x, ($orig_w / $fo_w) * $wmf_y, $image_id); + } else { + $this->writer->write(sprintf('/Matrix [1 0 0 1 %.3F %.3F]', $adj_x, $adj_y)); + $s = sprintf('q %.3F 0 0 %.3F 0 0 cm /I%d Do Q', $orig_w, $orig_h, $image_id); + } + + if ($this->mpdf->compress) { + $this->writer->write('/Filter /FlateDecode'); + $s = gzcompress($s); + } + $this->writer->write('/Length ' . strlen($s) . '>>'); + $this->writer->stream($s); + $this->writer->write('endobj'); + } + } + + public function writeShaders() // _putshaders + { + $maxid = count($this->mpdf->gradients); // index for transparency gradients + + foreach ($this->mpdf->gradients as $id => $grad) { + + if (empty($grad['is_mask']) && ($grad['type'] == 2 || $grad['type'] == 3)) { + + $this->writer->object(); + $this->writer->write('<<'); + $this->writer->write('/FunctionType 3'); + $this->writer->write('/Domain [0 1]'); + + $fn = []; + $bd = []; + $en = []; + + for ($i = 0; $i < (count($grad['stops']) - 1); $i++) { + $fn[] = ($this->mpdf->n + 1 + $i) . ' 0 R'; + $en[] = '0 1'; + if ($i > 0) { + $bd[] = sprintf('%.3F', $grad['stops'][$i]['offset']); + } + } + + $this->writer->write('/Functions [' . implode(' ', $fn) . ']'); + $this->writer->write('/Bounds [' . implode(' ', $bd) . ']'); + $this->writer->write('/Encode [' . implode(' ', $en) . ']'); + $this->writer->write('>>'); + $this->writer->write('endobj'); + + $f1 = $this->mpdf->n; + + for ($i = 0; $i < (count($grad['stops']) - 1); $i++) { + $this->writer->object(); + $this->writer->write('<<'); + $this->writer->write('/FunctionType 2'); + $this->writer->write('/Domain [0 1]'); + $this->writer->write('/C0 [' . $grad['stops'][$i]['col'] . ']'); + $this->writer->write('/C1 [' . $grad['stops'][$i + 1]['col'] . ']'); + $this->writer->write('/N 1'); + $this->writer->write('>>'); + $this->writer->write('endobj'); + } + } + + if ($grad['type'] == 2 || $grad['type'] == 3) { + + if (isset($grad['trans']) && $grad['trans']) { + + $this->writer->object(); + $this->writer->write('<<'); + $this->writer->write('/FunctionType 3'); + $this->writer->write('/Domain [0 1]'); + + $fn = []; + $bd = []; + $en = []; + + for ($i = 0; $i < (count($grad['stops']) - 1); $i++) { + $fn[] = ($this->mpdf->n + 1 + $i) . ' 0 R'; + $en[] = '0 1'; + if ($i > 0) { + $bd[] = sprintf('%.3F', $grad['stops'][$i]['offset']); + } + } + + $this->writer->write('/Functions [' . implode(' ', $fn) . ']'); + $this->writer->write('/Bounds [' . implode(' ', $bd) . ']'); + $this->writer->write('/Encode [' . implode(' ', $en) . ']'); + $this->writer->write('>>'); + $this->writer->write('endobj'); + + $f2 = $this->mpdf->n; + + for ($i = 0; $i < (count($grad['stops']) - 1); $i++) { + $this->writer->object(); + $this->writer->write('<<'); + $this->writer->write('/FunctionType 2'); + $this->writer->write('/Domain [0 1]'); + $this->writer->write(sprintf('/C0 [%.3F]', $grad['stops'][$i]['opacity'])); + $this->writer->write(sprintf('/C1 [%.3F]', $grad['stops'][$i + 1]['opacity'])); + $this->writer->write('/N 1'); + $this->writer->write('>>'); + $this->writer->write('endobj'); + } + } + } + + if (empty($grad['is_mask'])) { + + $this->writer->object(); + $this->writer->write('<<'); + $this->writer->write('/ShadingType ' . $grad['type']); + + if (isset($grad['colorspace'])) { + $this->writer->write('/ColorSpace /Device' . $grad['colorspace']); // Can use CMYK if all C0 and C1 above have 4 values + } else { + $this->writer->write('/ColorSpace /DeviceRGB'); + } + + if ($grad['type'] == 2) { + $this->writer->write(sprintf('/Coords [%.3F %.3F %.3F %.3F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3])); + $this->writer->write('/Function ' . $f1 . ' 0 R'); + $this->writer->write('/Extend [' . $grad['extend'][0] . ' ' . $grad['extend'][1] . '] '); + $this->writer->write('>>'); + } elseif ($grad['type'] == 3) { + // x0, y0, r0, x1, y1, r1 + // at this this time radius of inner circle is 0 + $ir = 0; + if (isset($grad['coords'][5]) && $grad['coords'][5]) { + $ir = $grad['coords'][5]; + } + $this->writer->write(sprintf('/Coords [%.3F %.3F %.3F %.3F %.3F %.3F]', $grad['coords'][0], $grad['coords'][1], $ir, $grad['coords'][2], $grad['coords'][3], $grad['coords'][4])); + $this->writer->write('/Function ' . $f1 . ' 0 R'); + $this->writer->write('/Extend [' . $grad['extend'][0] . ' ' . $grad['extend'][1] . '] '); + $this->writer->write('>>'); + } elseif ($grad['type'] == 6) { + $this->writer->write('/BitsPerCoordinate 16'); + $this->writer->write('/BitsPerComponent 8'); + if ($grad['colorspace'] === 'CMYK') { + $this->writer->write('/Decode[0 1 0 1 0 1 0 1 0 1 0 1]'); + } elseif ($grad['colorspace'] === 'Gray') { + $this->writer->write('/Decode[0 1 0 1 0 1]'); + } else { + $this->writer->write('/Decode[0 1 0 1 0 1 0 1 0 1]'); + } + $this->writer->write('/BitsPerFlag 8'); + $this->writer->write('/Length ' . strlen($grad['stream'])); + $this->writer->write('>>'); + $this->writer->stream($grad['stream']); + } + + $this->writer->write('endobj'); + } + + $this->mpdf->gradients[$id]['id'] = $this->mpdf->n; + + // set pattern object + $this->writer->object(); + $out = '<< /Type /Pattern /PatternType 2'; + $out .= ' /Shading ' . $this->mpdf->gradients[$id]['id'] . ' 0 R'; + $out .= ' >>'; + $out .= "\n" . 'endobj'; + $this->writer->write($out); + + + $this->mpdf->gradients[$id]['pattern'] = $this->mpdf->n; + + if (isset($grad['trans']) && $grad['trans']) { + + // luminosity pattern + $transid = $id + $maxid; + + $this->writer->object(); + $this->writer->write('<<'); + $this->writer->write('/ShadingType ' . $grad['type']); + $this->writer->write('/ColorSpace /DeviceGray'); + + if ($grad['type'] == 2) { + $this->writer->write(sprintf('/Coords [%.3F %.3F %.3F %.3F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3])); + $this->writer->write('/Function ' . $f2 . ' 0 R'); + $this->writer->write('/Extend [' . $grad['extend'][0] . ' ' . $grad['extend'][1] . '] '); + $this->writer->write('>>'); + } elseif ($grad['type'] == 3) { + // x0, y0, r0, x1, y1, r1 + // at this this time radius of inner circle is 0 + $ir = 0; + if (isset($grad['coords'][5]) && $grad['coords'][5]) { + $ir = $grad['coords'][5]; + } + $this->writer->write(sprintf('/Coords [%.3F %.3F %.3F %.3F %.3F %.3F]', $grad['coords'][0], $grad['coords'][1], $ir, $grad['coords'][2], $grad['coords'][3], $grad['coords'][4])); + $this->writer->write('/Function ' . $f2 . ' 0 R'); + $this->writer->write('/Extend [' . $grad['extend'][0] . ' ' . $grad['extend'][1] . '] '); + $this->writer->write('>>'); + } elseif ($grad['type'] == 6) { + $this->writer->write('/BitsPerCoordinate 16'); + $this->writer->write('/BitsPerComponent 8'); + $this->writer->write('/Decode[0 1 0 1 0 1]'); + $this->writer->write('/BitsPerFlag 8'); + $this->writer->write('/Length ' . strlen($grad['stream_trans'])); + $this->writer->write('>>'); + $this->writer->stream($grad['stream_trans']); + } + $this->writer->write('endobj'); + + $this->mpdf->gradients[$transid]['id'] = $this->mpdf->n; + + $this->writer->object(); + $this->writer->write('<< /Type /Pattern /PatternType 2'); + $this->writer->write('/Shading ' . $this->mpdf->gradients[$transid]['id'] . ' 0 R'); + $this->writer->write('>>'); + $this->writer->write('endobj'); + + $this->mpdf->gradients[$transid]['pattern'] = $this->mpdf->n; + $this->writer->object(); + + // Need to extend size of viewing box in case of transformations + $str = 'q /a0 gs /Pattern cs /p' . $transid . ' scn -' . ($this->mpdf->wPt / 2) . ' -' . ($this->mpdf->hPt / 2) . ' ' . (2 * $this->mpdf->wPt) . ' ' . (2 * $this->mpdf->hPt) . ' re f Q'; + $filter = ($this->mpdf->compress) ? '/Filter /FlateDecode ' : ''; + $p = ($this->mpdf->compress) ? gzcompress($str) : $str; + + $this->writer->write('<< /Type /XObject /Subtype /Form /FormType 1 ' . $filter); + $this->writer->write('/Length ' . strlen($p)); + $this->writer->write('/BBox [-' . ($this->mpdf->wPt / 2) . ' -' . ($this->mpdf->hPt / 2) . ' ' . (2 * $this->mpdf->wPt) . ' ' . (2 * $this->mpdf->hPt) . ']'); + $this->writer->write('/Group << /Type /Group /S /Transparency /CS /DeviceGray >>'); + $this->writer->write('/Resources <<'); + $this->writer->write('/ExtGState << /a0 << /ca 1 /CA 1 >> >>'); + $this->writer->write('/Pattern << /p' . $transid . ' ' . $this->mpdf->gradients[$transid]['pattern'] . ' 0 R >>'); + $this->writer->write('>>'); + $this->writer->write('>>'); + $this->writer->stream($p); + $this->writer->write('endobj'); + $this->writer->object(); + $this->writer->write('<< /Type /Mask /S /Luminosity /G ' . ($this->mpdf->n - 1) . ' 0 R >>' . "\n" . 'endobj'); + $this->writer->object(); + $this->writer->write('<< /Type /ExtGState /SMask ' . ($this->mpdf->n - 1) . ' 0 R /AIS false >>' . "\n" . 'endobj'); + + if (isset($grad['fo']) && $grad['fo']) { + $this->mpdf->extgstates[] = ['n' => $this->mpdf->n, 'trans' => 'TGS' . $id, 'fo' => true]; + } else { + $this->mpdf->extgstates[] = ['n' => $this->mpdf->n, 'trans' => 'TGS' . $id]; + } + } + } + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Writer/BaseWriter.php b/src/bb-vendor/mpdf/mpdf/src/Writer/BaseWriter.php new file mode 100644 index 000000000..8abff9196 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Writer/BaseWriter.php @@ -0,0 +1,250 @@ +<?php + +namespace Mpdf\Writer; + +use Mpdf\Strict; + +use Mpdf\Mpdf; +use Mpdf\Pdf\Protection; + +final class BaseWriter +{ + + use Strict; + + /** + * @var \Mpdf\Mpdf + */ + private $mpdf; + + /** + * @var \Mpdf\Pdf\Protection + */ + private $protection; + + public function __construct(Mpdf $mpdf, Protection $protection) + { + $this->mpdf = $mpdf; + $this->protection = $protection; + } + + public function write($s, $ln = true) + { + if ($this->mpdf->state === 2) { + $this->endPage($s, $ln); + } else { + $this->mpdf->buffer .= $s . ($ln ? "\n" : ''); + } + } + + public function string($s) + { + if ($this->mpdf->encrypted) { + $s = $this->protection->rc4($this->protection->objectKey($this->mpdf->currentObjectNumber), $s); + } + + return '(' . $this->escape($s) . ')'; + } + + public function object($obj_id = false, $onlynewobj = false) + { + if (!$obj_id) { + $obj_id = ++$this->mpdf->n; + } + + // Begin a new object + if (!$onlynewobj) { + $this->mpdf->offsets[$obj_id] = strlen($this->mpdf->buffer); + $this->write($obj_id . ' 0 obj'); + $this->mpdf->currentObjectNumber = $obj_id; // for later use with encryption + } + } + + public function stream($s) + { + if ($this->mpdf->encrypted) { + $s = $this->protection->rc4($this->protection->objectKey($this->mpdf->currentObjectNumber), $s); + } + + $this->write('stream'); + $this->write($s); + $this->write('endstream'); + } + + public function utf16BigEndianTextString($s) // _UTF16BEtextstring + { + $s = $this->utf8ToUtf16BigEndian($s, true); + if ($this->mpdf->encrypted) { + $s = $this->protection->rc4($this->protection->objectKey($this->mpdf->currentObjectNumber), $s); + } + + return '(' . $this->escape($s) . ')'; + } + + // Converts UTF-8 strings to UTF16-BE. + public function utf8ToUtf16BigEndian($str, $setbom = true) // UTF8ToUTF16BE + { + if ($this->mpdf->checkSIP && preg_match("/([\x{20000}-\x{2FFFF}])/u", $str)) { + if (!in_array($this->mpdf->currentfontfamily, ['gb', 'big5', 'sjis', 'uhc', 'gbB', 'big5B', 'sjisB', 'uhcB', 'gbI', 'big5I', 'sjisI', 'uhcI', + 'gbBI', 'big5BI', 'sjisBI', 'uhcBI'])) { + $str = preg_replace("/[\x{20000}-\x{2FFFF}]/u", chr(0), $str); + } + } + if ($this->mpdf->checkSMP && preg_match("/([\x{10000}-\x{1FFFF}])/u", $str)) { + $str = preg_replace("/[\x{10000}-\x{1FFFF}]/u", chr(0), $str); + } + + $outstr = ''; // string to be returned + if ($setbom) { + $outstr .= "\xFE\xFF"; // Byte Order Mark (BOM) + } + + $outstr .= mb_convert_encoding($str, 'UTF-16BE', 'UTF-8'); + + return $outstr; + } + + public function escape($s) // _escape + { + return strtr($s, [')' => '\\)', '(' => '\\(', '\\' => '\\\\', chr(13) => '\r']); + } + + public function escapeSlashes($s) // _escapeName + { + return strtr($s, ['/' => '#2F']); + } + + /** + * Un-escapes a PDF string + * + * @param string $s + * @return string + */ + public function unescape($s) + { + $out = ''; + for ($count = 0, $n = strlen($s); $count < $n; $count++) { + if ($count === $n - 1 || $s[$count] !== '\\') { + $out .= $s[$count]; + } else { + switch ($s[++$count]) { + case ')': + case '(': + case '\\': + $out .= $s[$count]; + break; + case 'f': + $out .= chr(0x0C); + break; + case 'b': + $out .= chr(0x08); + break; + case 't': + $out .= chr(0x09); + break; + case 'r': + $out .= chr(0x0D); + break; + case 'n': + $out .= chr(0x0A); + break; + case "\r": + if ($count !== $n - 1 && $s[$count + 1] === "\n") { + $count++; + } + break; + case "\n": + break; + default: + // Octal-Values + $ord = ord($s[$count]); + if ($ord >= ord('0') && $ord <= ord('9')) { + $oct = ''. $s[$count]; + $ord = ord($s[$count + 1]); + if ($ord >= ord('0') && $ord <= ord('9')) { + $oct .= $s[++$count]; + $ord = ord($s[$count + 1]); + if ($ord >= ord('0') && $ord <= ord('9')) { + $oct .= $s[++$count]; + } + } + $out .= chr(octdec($oct)); + } else { + $out .= $s[$count]; + } + } + } + } + + return $out; + } + + private function endPage($s, $ln) + { + if ($this->mpdf->bufferoutput) { + + $this->mpdf->headerbuffer.= $s . "\n"; + + } elseif ($this->mpdf->ColActive && !$this->mpdf->processingHeader && !$this->mpdf->processingFooter) { + + // Captures everything in buffer for columns; Almost everything is sent from fn. Cell() except: + // Images sent from Image() or + // later sent as write($textto) in printbuffer + // Line() + + if (preg_match('/q \d+\.\d\d+ 0 0 (\d+\.\d\d+) \d+\.\d\d+ \d+\.\d\d+ cm \/(I|FO)\d+ Do Q/', $s, $m)) { // Image data + + $h = ($m[1] / Mpdf::SCALE); + // Update/overwrite the lowest bottom of printing y value for a column + $this->mpdf->ColDetails[$this->mpdf->CurrCol]['bottom_margin'] = $this->mpdf->y + $h; + + } elseif ($this->mpdf->tableLevel > 0 && preg_match('/\d+\.\d\d+ \d+\.\d\d+ \d+\.\d\d+ ([\-]{0,1}\d+\.\d\d+) re/', $s, $m)) { // Rect in table + + $h = ($m[1] / Mpdf::SCALE); + // Update/overwrite the lowest bottom of printing y value for a column + $this->mpdf->ColDetails[$this->mpdf->CurrCol]['bottom_margin'] = max($this->mpdf->ColDetails[$this->mpdf->CurrCol]['bottom_margin'], $this->mpdf->y + $h); + + } elseif (isset($this->mpdf->ColDetails[$this->mpdf->CurrCol]['bottom_margin'])) { + + $h = $this->mpdf->ColDetails[$this->mpdf->CurrCol]['bottom_margin'] - $this->mpdf->y; + + } else { + + $h = 0; + + } + + if ($h < 0) { + $h = -$h; + } + + $this->mpdf->columnbuffer[] = [ + 's' => $s, // Text string to output + 'col' => $this->mpdf->CurrCol, // Column when printed + 'x' => $this->mpdf->x, // x when printed + 'y' => $this->mpdf->y, // this->y when printed (after column break) + 'h' => $h // actual y at bottom when printed = y+h + ]; + + } elseif ($this->mpdf->table_rotate && !$this->mpdf->processingHeader && !$this->mpdf->processingFooter) { + + // Captures eveything in buffer for rotated tables; + $this->mpdf->tablebuffer .= $s . "\n"; + + } elseif ($this->mpdf->kwt && !$this->mpdf->processingHeader && !$this->mpdf->processingFooter) { + + // Captures eveything in buffer for keep-with-table (h1-6); + $this->mpdf->kwt_buffer[] = [ + 's' => $s, // Text string to output + 'x' => $this->mpdf->x, // x when printed + 'y' => $this->mpdf->y, // y when printed + ]; + + } elseif ($this->mpdf->keep_block_together && !$this->mpdf->processingHeader && !$this->mpdf->processingFooter) { + // do nothing + } else { + $this->mpdf->pages[$this->mpdf->page] .= $s . ($ln ? "\n" : ''); + } + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Writer/BookmarkWriter.php b/src/bb-vendor/mpdf/mpdf/src/Writer/BookmarkWriter.php new file mode 100644 index 000000000..bbec0d767 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Writer/BookmarkWriter.php @@ -0,0 +1,138 @@ +<?php + +namespace Mpdf\Writer; + +use Mpdf\Strict; +use Mpdf\Mpdf; + +final class BookmarkWriter +{ + + use Strict; + + /** + * @var \Mpdf\Mpdf + */ + private $mpdf; + + /** + * @var \Mpdf\Writer\BaseWriter + */ + private $writer; + + public function __construct(Mpdf $mpdf, BaseWriter $writer) + { + $this->mpdf = $mpdf; + $this->writer = $writer; + } + + public function writeBookmarks() // _putbookmarks + { + $nb = count($this->mpdf->BMoutlines); + if ($nb === 0) { + return; + } + + $bmo = $this->mpdf->BMoutlines; + $this->mpdf->BMoutlines = []; + $lastlevel = -1; + for ($i = 0; $i < count($bmo); $i++) { + if ($bmo[$i]['l'] > 0) { + while ($bmo[$i]['l'] - $lastlevel > 1) { // If jump down more than one level, insert a new entry + $new = $bmo[$i]; + $new['t'] = "[" . $new['t'] . "]"; // Put [] around text/title to highlight + $new['l'] = $lastlevel + 1; + $lastlevel++; + $this->mpdf->BMoutlines[] = $new; + } + } + $this->mpdf->BMoutlines[] = $bmo[$i]; + $lastlevel = $bmo[$i]['l']; + } + $nb = count($this->mpdf->BMoutlines); + + $lru = []; + $level = 0; + foreach ($this->mpdf->BMoutlines as $i => $o) { + if ($o['l'] > 0) { + $parent = $lru[$o['l'] - 1]; + // Set parent and last pointers + $this->mpdf->BMoutlines[$i]['parent'] = $parent; + $this->mpdf->BMoutlines[$parent]['last'] = $i; + if ($o['l'] > $level) { + // Level increasing: set first pointer + $this->mpdf->BMoutlines[$parent]['first'] = $i; + } + } else { + $this->mpdf->BMoutlines[$i]['parent'] = $nb; + } + if ($o['l'] <= $level and $i > 0) { + // Set prev and next pointers + $prev = $lru[$o['l']]; + $this->mpdf->BMoutlines[$prev]['next'] = $i; + $this->mpdf->BMoutlines[$i]['prev'] = $prev; + } + $lru[$o['l']] = $i; + $level = $o['l']; + } + + + // Outline items + $n = $this->mpdf->n + 1; + foreach ($this->mpdf->BMoutlines as $i => $o) { + $this->writer->object(); + $this->writer->write('<writer->utf16BigEndianTextString($o['t'])); + $this->writer->write('/Parent ' . ($n + $o['parent']) . ' 0 R'); + if (isset($o['prev'])) { + $this->writer->write('/Prev ' . ($n + $o['prev']) . ' 0 R'); + } + if (isset($o['next'])) { + $this->writer->write('/Next ' . ($n + $o['next']) . ' 0 R'); + } + if (isset($o['first'])) { + $this->writer->write('/First ' . ($n + $o['first']) . ' 0 R'); + } + if (isset($o['last'])) { + $this->writer->write('/Last ' . ($n + $o['last']) . ' 0 R'); + } + + + if (isset($this->mpdf->pageDim[$o['p']]['h'])) { + $h = $this->mpdf->pageDim[$o['p']]['h']; + } else { + $h = 0; + } + + $this->writer->write(sprintf('/Dest [%d 0 R /XYZ 0 %.3F null]', 1 + 2 * ($o['p']), ($h - $o['y']) * Mpdf::SCALE)); + if (isset($this->mpdf->bookmarkStyles) && isset($this->mpdf->bookmarkStyles[$o['l']])) { + // font style + $bms = $this->mpdf->bookmarkStyles[$o['l']]['style']; + $style = 0; + if (strpos($bms, 'B') !== false) { + $style += 2; + } + if (strpos($bms, 'I') !== false) { + $style += 1; + } + $this->writer->write(sprintf('/F %d', $style)); + // Colour + $col = $this->mpdf->bookmarkStyles[$o['l']]['color']; + if (isset($col) && is_array($col) && count($col) == 3) { + $this->writer->write(sprintf('/C [%.3F %.3F %.3F]', ($col[0] / 255), ($col[1] / 255), ($col[2] / 255))); + } + } + + $this->writer->write('/Count 0>>'); + $this->writer->write('endobj'); + } + // Outline root + $this->writer->object(); + + $this->mpdf->OutlineRoot = $this->mpdf->n; + + $this->writer->write('<writer->write('/Last ' . ($n + $lru[0]) . ' 0 R>>'); + $this->writer->write('endobj'); + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Writer/ColorWriter.php b/src/bb-vendor/mpdf/mpdf/src/Writer/ColorWriter.php new file mode 100644 index 000000000..c6ece981b --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Writer/ColorWriter.php @@ -0,0 +1,46 @@ +mpdf = $mpdf; + $this->writer = $writer; + } + + public function writeSpotColors() // _putspotcolors + { + foreach ($this->mpdf->spotColors as $name => $color) { + + $this->writer->object(); + + $this->writer->write('[/Separation /' . str_replace(' ', '#20', $name)); + $this->writer->write('/DeviceCMYK <<'); + $this->writer->write('/Range [0 1 0 1 0 1 0 1] /C0 [0 0 0 0] '); + $this->writer->write(sprintf('/C1 [%.3F %.3F %.3F %.3F] ', $color['c'] / 100, $color['m'] / 100, $color['y'] / 100, $color['k'] / 100)); + $this->writer->write('/FunctionType 2 /Domain [0 1] /N 1>>]'); + $this->writer->write('endobj'); + + $this->mpdf->spotColors[$name]['n'] = $this->mpdf->n; + } + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Writer/FontWriter.php b/src/bb-vendor/mpdf/mpdf/src/Writer/FontWriter.php new file mode 100644 index 000000000..8d6b2cfa5 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Writer/FontWriter.php @@ -0,0 +1,680 @@ +mpdf = $mpdf; + $this->writer = $writer; + $this->fontCache = $fontCache; + $this->fontDescriptor = $fontDescriptor; + } + + public function writeFonts() + { + foreach ($this->mpdf->FontFiles as $fontkey => $info) { + // TrueType embedded + if (isset($info['type']) && $info['type'] === 'TTF' && !$info['sip'] && !$info['smp']) { + $used = true; + $asSubset = false; + foreach ($this->mpdf->fonts as $k => $f) { + if (isset($f['fontkey']) && $f['fontkey'] === $fontkey && $f['type'] === 'TTF') { + $used = $f['used']; + if ($used) { + $nChars = (ord($f['cw'][0]) << 8) + ord($f['cw'][1]); + $usage = (int) (count($f['subset']) * 100 / $nChars); + $fsize = $info['length1']; + // Always subset the very large TTF files + if ($fsize > ($this->mpdf->maxTTFFilesize * 1024)) { + $asSubset = true; + } elseif ($usage < $this->mpdf->percentSubset) { + $asSubset = true; + } + } + if ($this->mpdf->PDFA || $this->mpdf->PDFX) { + $asSubset = false; + } + $this->mpdf->fonts[$k]['asSubset'] = $asSubset; + break; + } + } + if ($used && !$asSubset) { + // Font file embedding + $this->writer->object(); + $this->mpdf->FontFiles[$fontkey]['n'] = $this->mpdf->n; + $originalsize = $info['length1']; + if ($this->mpdf->repackageTTF || $this->mpdf->fonts[$fontkey]['TTCfontID'] > 0 || $this->mpdf->fonts[$fontkey]['useOTL'] > 0) { // mPDF 5.7.1 + // First see if there is a cached compressed file + if ($this->fontCache->has($fontkey . '.ps.z') && $this->fontCache->jsonHas($fontkey . '.ps.json')) { + $font = $this->fontCache->load($fontkey . '.ps.z'); + $originalsize = $this->fontCache->jsonLoad($fontkey . '.ps.json'); // sets $originalsize (of repackaged font) + } else { + $ttf = new TTFontFile($this->fontCache, $this->fontDescriptor); + $font = $ttf->repackageTTF($this->mpdf->FontFiles[$fontkey]['ttffile'], $this->mpdf->fonts[$fontkey]['TTCfontID'], $this->mpdf->debugfonts, $this->mpdf->fonts[$fontkey]['useOTL']); // mPDF 5.7.1 + + $originalsize = strlen($font); + $font = gzcompress($font); + unset($ttf); + + $this->fontCache->binaryWrite($fontkey . '.ps.z', $font); + $this->fontCache->jsonWrite($fontkey . '.ps.json', $originalsize); + } + } elseif ($this->fontCache->has($fontkey . '.z')) { + $font = $this->fontCache->load($fontkey . '.z'); + } else { + $font = file_get_contents($this->mpdf->FontFiles[$fontkey]['ttffile']); + $font = gzcompress($font); + $this->fontCache->binaryWrite($fontkey . '.z', $font); + } + + $this->writer->write('<writer->write('/Filter /FlateDecode'); + $this->writer->write('/Length1 ' . $originalsize); + $this->writer->write('>>'); + $this->writer->stream($font); + $this->writer->write('endobj'); + } + } + } + + foreach ($this->mpdf->fonts as $k => $font) { + + // Font objects + $type = $font['type']; + $name = $font['name']; + + if ($type === 'TTF' && (!isset($font['used']) || !$font['used'])) { + continue; + } + + // @log Writing fonts + + if (isset($font['asSubset'])) { + $asSubset = $font['asSubset']; + } else { + $asSubset = ''; + } + + if ($type === 'Type0') { // Adobe CJK Fonts + + $this->mpdf->fonts[$k]['n'] = $this->mpdf->n + 1; + $this->writer->object(); + $this->writer->write('<writeType0($font); + + } elseif ($type === 'core') { + + // Standard font + $this->mpdf->fonts[$k]['n'] = $this->mpdf->n + 1; + + if ($this->mpdf->PDFA || $this->mpdf->PDFX) { + throw new \Mpdf\MpdfException('Core fonts are not allowed in PDF/A1-b or PDFX/1-a files (Times, Helvetica, Courier etc.)'); + } + + $this->writer->object(); + $this->writer->write('<writer->write('/BaseFont /' . $name); + $this->writer->write('/Subtype /Type1'); + + if ($name !== 'Symbol' && $name !== 'ZapfDingbats') { + $this->writer->write('/Encoding /WinAnsiEncoding'); + } + + $this->writer->write('>>'); + $this->writer->write('endobj'); + + } elseif ($type === 'TTF' && ($font['sip'] || $font['smp'])) { + + // TrueType embedded SUBSETS for SIP (CJK extB containing Supplementary Ideographic Plane 2) + // Or Unicode Plane 1 - Supplementary Multilingual Plane + + if (!$font['used']) { + continue; + } + + $ssfaid = 'AA'; + $ttf = new TTFontFile($this->fontCache, $this->fontDescriptor); + $subsetCount = count($font['subsetfontids']); + for ($sfid = 0; $sfid < $subsetCount; $sfid++) { + $this->mpdf->fonts[$k]['n'][$sfid] = $this->mpdf->n + 1; // NB an array for subset + $subsetname = 'MPDF' . $ssfaid . '+' . $font['name']; + $ssfaid++; + + /* For some strange reason a subset ($sfid > 0) containing less than 97 characters causes an error + so fill up the array */ + for ($j = count($font['subsets'][$sfid]); $j < 98; $j++) { + $font['subsets'][$sfid][$j] = 0; + } + + $subset = $font['subsets'][$sfid]; + unset($subset[0]); + $ttfontstream = $ttf->makeSubsetSIP($font['ttffile'], $subset, $font['TTCfontID'], $this->mpdf->debugfonts, $font['useOTL']); // mPDF 5.7.1 + $ttfontsize = strlen($ttfontstream); + $fontstream = gzcompress($ttfontstream); + $widthstring = ''; + $toUnistring = ''; + + foreach ($font['subsets'][$sfid] as $cp => $u) { + $w = $this->mpdf->_getCharWidth($font['cw'], $u); + if ($w !== false) { + $widthstring .= $w . ' '; + } else { + $widthstring .= round($ttf->defaultWidth) . ' '; + } + if ($u > 65535) { + $utf8 = chr(($u >> 18) + 240) . chr((($u >> 12) & 63) + 128) . chr((($u >> 6) & 63) + 128) . chr(($u & 63) + 128); + $utf16 = mb_convert_encoding($utf8, 'UTF-16BE', 'UTF-8'); + $l1 = ord($utf16[0]); + $h1 = ord($utf16[1]); + $l2 = ord($utf16[2]); + $h2 = ord($utf16[3]); + $toUnistring .= sprintf("<%02s> <%02s%02s%02s%02s>\n", strtoupper(dechex($cp)), strtoupper(dechex($l1)), strtoupper(dechex($h1)), strtoupper(dechex($l2)), strtoupper(dechex($h2))); + } else { + $toUnistring .= sprintf("<%02s> <%04s>\n", strtoupper(dechex($cp)), strtoupper(dechex($u))); + } + } + + // Additional Type1 or TrueType font + $this->writer->object(); + $this->writer->write('<writer->write('/BaseFont /' . $subsetname); + $this->writer->write('/Subtype /TrueType'); + $this->writer->write('/FirstChar 0 /LastChar ' . (count($font['subsets'][$sfid]) - 1)); + $this->writer->write('/Widths ' . ($this->mpdf->n + 1) . ' 0 R'); + $this->writer->write('/FontDescriptor ' . ($this->mpdf->n + 2) . ' 0 R'); + $this->writer->write('/ToUnicode ' . ($this->mpdf->n + 3) . ' 0 R'); + $this->writer->write('>>'); + $this->writer->write('endobj'); + + // Widths + $this->writer->object(); + $this->writer->write('[' . $widthstring . ']'); + $this->writer->write('endobj'); + + // Descriptor + $this->writer->object(); + $s = '< $v) { + if ($kd === 'Flags') { + $v |= 4; + $v &= ~32; + } // SYMBOLIC font flag + $s .= ' /' . $kd . ' ' . $v . "\n"; + } + $s .= '/FontFile2 ' . ($this->mpdf->n + 2) . ' 0 R'; + $this->writer->write($s . '>>'); + $this->writer->write('endobj'); + + // ToUnicode + $this->writer->object(); + $toUni = "/CIDInit /ProcSet findresource begin\n"; + $toUni .= "12 dict begin\n"; + $toUni .= "begincmap\n"; + $toUni .= "/CIDSystemInfo\n"; + $toUni .= "< <%02s>\n", strtoupper(dechex(count($font['subsets'][$sfid])-1))); + $toUni .= "endcodespacerange\n"; + $toUni .= count($font['subsets'][$sfid]) . " beginbfchar\n"; + $toUni .= $toUnistring; + $toUni .= "endbfchar\n"; + $toUni .= "endcmap\n"; + $toUni .= "CMapName currentdict /CMap defineresource pop\n"; + $toUni .= "end\n"; + $toUni .= "end\n"; + $this->writer->write('<>'); + $this->writer->stream($toUni); + $this->writer->write('endobj'); + + // Font file + $this->writer->object(); + $this->writer->write('<writer->write('/Filter /FlateDecode'); + $this->writer->write('/Length1 ' . $ttfontsize); + $this->writer->write('>>'); + $this->writer->stream($fontstream); + $this->writer->write('endobj'); + } // foreach subset + unset($ttf); + + } elseif ($type === 'TTF') { // TrueType embedded SUBSETS or FULL + + $this->mpdf->fonts[$k]['n'] = $this->mpdf->n + 1; + + if ($asSubset) { + $ssfaid = 'A'; + $ttf = new TTFontFile($this->fontCache, $this->fontDescriptor); + $fontname = 'MPDFA' . $ssfaid . '+' . $font['name']; + $subset = $font['subset']; + unset($subset[0]); + $ttfontstream = $ttf->makeSubset($font['ttffile'], $subset, $font['TTCfontID'], $this->mpdf->debugfonts, $font['useOTL']); + $ttfontsize = strlen($ttfontstream); + $fontstream = gzcompress($ttfontstream); + $codeToGlyph = $ttf->codeToGlyph; + unset($codeToGlyph[0]); + } else { + $fontname = $font['name']; + } + + // Type0 Font + // A composite font - a font composed of other fonts, organized hierarchically + $this->writer->object(); + $this->writer->write('<writer->write('/Subtype /Type0'); + $this->writer->write('/BaseFont /' . $fontname . ''); + $this->writer->write('/Encoding /Identity-H'); + $this->writer->write('/DescendantFonts [' . ($this->mpdf->n + 1) . ' 0 R]'); + $this->writer->write('/ToUnicode ' . ($this->mpdf->n + 2) . ' 0 R'); + $this->writer->write('>>'); + $this->writer->write('endobj'); + + // CIDFontType2 + // A CIDFont whose glyph descriptions are based on TrueType font technology + $this->writer->object(); + $this->writer->write('<writer->write('/Subtype /CIDFontType2'); + $this->writer->write('/BaseFont /' . $fontname . ''); + $this->writer->write('/CIDSystemInfo ' . ($this->mpdf->n + 2) . ' 0 R'); + $this->writer->write('/FontDescriptor ' . ($this->mpdf->n + 3) . ' 0 R'); + + if (isset($font['desc']['MissingWidth'])) { + $this->writer->write('/DW ' . $font['desc']['MissingWidth'] . ''); + } + + if (!$asSubset && $this->fontCache->has($font['fontkey'] . '.cw')) { + $w = $this->fontCache->load($font['fontkey'] . '.cw'); + $this->writer->write($w); + } else { + $this->writeTTFontWidths($font, $asSubset, ($asSubset ? $ttf->maxUni : 0)); + } + + $this->writer->write('/CIDToGIDMap ' . ($this->mpdf->n + 4) . ' 0 R'); + $this->writer->write('>>'); + $this->writer->write('endobj'); + + // ToUnicode + $this->writer->object(); + $toUni = "/CIDInit /ProcSet findresource begin\n"; + $toUni .= "12 dict begin\n"; + $toUni .= "begincmap\n"; + $toUni .= "/CIDSystemInfo\n"; + $toUni .= "<writer->write('<>'); + $this->writer->stream($toUni); + $this->writer->write('endobj'); + + // CIDSystemInfo dictionary + $this->writer->object(); + $this->writer->write('<writer->write('/Ordering (UCS)'); + $this->writer->write('/Supplement 0'); + $this->writer->write('>>'); + $this->writer->write('endobj'); + + // Font descriptor + $this->writer->object(); + $this->writer->write('<writer->write('/FontName /' . $fontname); + + foreach ($font['desc'] as $kd => $v) { + if ($asSubset && $kd === 'Flags') { + $v |= 4; + $v &= ~32; + } // SYMBOLIC font flag + $this->writer->write(' /' . $kd . ' ' . $v); + } + + if ($font['panose']) { + $this->writer->write(' /Style << /Panose <' . $font['panose'] . '> >>'); + } + + if ($asSubset) { + $this->writer->write('/FontFile2 ' . ($this->mpdf->n + 2) . ' 0 R'); + } elseif ($font['fontkey']) { + // obj ID of a stream containing a TrueType font program + $this->writer->write('/FontFile2 ' . $this->mpdf->FontFiles[$font['fontkey']]['n'] . ' 0 R'); + } + + $this->writer->write('>>'); + $this->writer->write('endobj'); + + // Embed CIDToGIDMap + // A specification of the mapping from CIDs to glyph indices + if ($asSubset) { + $cidtogidmap = str_pad('', 256 * 256 * 2, "\x00"); + foreach ($codeToGlyph as $cc => $glyph) { + $cidtogidmap[$cc * 2] = chr($glyph >> 8); + $cidtogidmap[$cc * 2 + 1] = chr($glyph & 0xFF); + } + $cidtogidmap = gzcompress($cidtogidmap); + } else { + // First see if there is a cached CIDToGIDMapfile + if ($this->fontCache->has($font['fontkey'] . '.cgm')) { + $cidtogidmap = $this->fontCache->load($font['fontkey'] . '.cgm'); + } else { + $ttf = new TTFontFile($this->fontCache, $this->fontDescriptor); + $charToGlyph = $ttf->getCTG($font['ttffile'], $font['TTCfontID'], $this->mpdf->debugfonts, $font['useOTL']); + $cidtogidmap = str_pad('', 256 * 256 * 2, "\x00"); + foreach ($charToGlyph as $cc => $glyph) { + $cidtogidmap[$cc * 2] = chr($glyph >> 8); + $cidtogidmap[$cc * 2 + 1] = chr($glyph & 0xFF); + } + unset($ttf); + $cidtogidmap = gzcompress($cidtogidmap); + $this->fontCache->binaryWrite($font['fontkey'] . '.cgm', $cidtogidmap); + } + } + $this->writer->object(); + $this->writer->write('<writer->write('/Filter /FlateDecode'); + $this->writer->write('>>'); + $this->writer->stream($cidtogidmap); + $this->writer->write('endobj'); + + // Font file + if ($asSubset) { + $this->writer->object(); + $this->writer->write('<writer->write('/Filter /FlateDecode'); + $this->writer->write('/Length1 ' . $ttfontsize); + $this->writer->write('>>'); + $this->writer->stream($fontstream); + $this->writer->write('endobj'); + unset($ttf); + } + } else { + throw new \Mpdf\MpdfException(sprintf('Unsupported font type: %s (%s)', $type, $name)); + } + } + } + + private function writeTTFontWidths(&$font, $asSubset, $maxUni) // _putTTfontwidths + { + $character = [ + 'startcid' => 1, + 'rangeid' => 0, + 'prevcid' => -2, + 'prevwidth' => -1, + 'interval' => false, + 'range' => [], + ]; + + $fontCacheFilename = $font['fontkey'] . '.cw127.json'; + if ($asSubset && $this->fontCache->jsonHas($fontCacheFilename)) { + $character = $this->fontCache->jsonLoad($fontCacheFilename); + $character['startcid'] = 128; + } + + // for each character + $cwlen = ($asSubset) ? $maxUni + 1 : (strlen($font['cw']) / 2); + for ($cid = $character['startcid']; $cid < $cwlen; $cid++) { + if ($cid == 128 && $asSubset && (!$this->fontCache->has($fontCacheFilename))) { + $character = [ + 'rangeid' => $character['rangeid'], + 'prevcid' => $character['prevcid'], + 'prevwidth' => $character['prevwidth'], + 'interval' => $character['interval'], + 'range' => $character['range'], + ]; + + $this->fontCache->jsonWrite($fontCacheFilename, $character); + } + + $character1 = isset($font['cw'][$cid * 2]) ? $font['cw'][$cid * 2] : ''; + $character2 = isset($font['cw'][$cid * 2 + 1]) ? $font['cw'][$cid * 2 + 1] : ''; + + if ($character1 === "\00" && $character2 === "\00") { + continue; + } + + $width = (ord($character1) << 8) + ord($character2); + + if ($width === 65535) { + $width = 0; + } + + if ($asSubset && $cid > 255 && (!isset($font['subset'][$cid]) || !$font['subset'][$cid])) { + continue; + } + + if ($asSubset && $cid > 0xFFFF) { + continue; + } // mPDF 6 + + if (!isset($font['dw']) || (isset($font['dw']) && $width != $font['dw'])) { + if ($cid === ($character['prevcid'] + 1)) { + // consecutive CID + if ($width === $character['prevwidth']) { + if (isset($character['range'][$character['rangeid']][0]) && $width === $character['range'][$character['rangeid']][0]) { + $character['range'][$character['rangeid']][] = $width; + } else { + array_pop($character['range'][$character['rangeid']]); + // new range + $character['rangeid'] = $character['prevcid']; + $character['range'][$character['rangeid']] = []; + $character['range'][$character['rangeid']][] = $character['prevwidth']; + $character['range'][$character['rangeid']][] = $width; + } + $character['interval'] = true; + $character['range'][$character['rangeid']]['interval'] = true; + } else { + if ($character['interval']) { + // new range + $character['rangeid'] = $cid; + $character['range'][$character['rangeid']] = []; + $character['range'][$character['rangeid']][] = $width; + } else { + $character['range'][$character['rangeid']][] = $width; + } + $character['interval'] = false; + } + } else { + // new range + $character['rangeid'] = $cid; + $character['range'][$character['rangeid']] = []; + $character['range'][$character['rangeid']][] = $width; + $character['interval'] = false; + } + $character['prevcid'] = $cid; + $character['prevwidth'] = $width; + } + } + $w = $this->writeFontRanges($character['range']); + $this->writer->write($w); + if (!$asSubset) { + $this->fontCache->binaryWrite($font['fontkey'] . '.cw', $w); + } + } + + private function writeFontRanges(&$range) // _putfontranges + { + // optimize ranges + $prevk = -1; + $nextk = -1; + $prevint = false; + foreach ($range as $k => $ws) { + $cws = count($ws); + if (($k == $nextk) and ( !$prevint) and ( (!isset($ws['interval'])) or ( $cws < 4))) { + if (isset($range[$k]['interval'])) { + unset($range[$k]['interval']); + } + $range[$prevk] = array_merge($range[$prevk], $range[$k]); + unset($range[$k]); + } else { + $prevk = $k; + } + $nextk = $k + $cws; + if (isset($ws['interval'])) { + if ($cws > 3) { + $prevint = true; + } else { + $prevint = false; + } + unset($range[$k]['interval']); + --$nextk; + } else { + $prevint = false; + } + } + // output data + $w = ''; + foreach ($range as $k => $ws) { + if (count(array_count_values($ws)) === 1) { + // interval mode is more compact + $w .= ' ' . $k . ' ' . ($k + count($ws) - 1) . ' ' . $ws[0]; + } else { + // range mode + $w .= ' ' . $k . ' [ ' . implode(' ', $ws) . ' ]' . "\n"; + } + } + return '/W [' . $w . ' ]'; + } + + private function writeFontWidths(&$font, $cidoffset = 0) // _putfontwidths + { + ksort($font['cw']); + unset($font['cw'][65535]); + $rangeid = 0; + $range = []; + $prevcid = -2; + $prevwidth = -1; + $interval = false; + // for each character + foreach ($font['cw'] as $cid => $width) { + $cid -= $cidoffset; + if (!isset($font['dw']) || (isset($font['dw']) && $width != $font['dw'])) { + if ($cid === ($prevcid + 1)) { + // consecutive CID + if ($width === $prevwidth) { + if ($width === $range[$rangeid][0]) { + $range[$rangeid][] = $width; + } else { + array_pop($range[$rangeid]); + // new range + $rangeid = $prevcid; + $range[$rangeid] = []; + $range[$rangeid][] = $prevwidth; + $range[$rangeid][] = $width; + } + $interval = true; + $range[$rangeid]['interval'] = true; + } else { + if ($interval) { + // new range + $rangeid = $cid; + $range[$rangeid] = []; + $range[$rangeid][] = $width; + } else { + $range[$rangeid][] = $width; + } + $interval = false; + } + } else { + // new range + $rangeid = $cid; + $range[$rangeid] = []; + $range[$rangeid][] = $width; + $interval = false; + } + $prevcid = $cid; + $prevwidth = $width; + } + } + $this->writer->write($this->writeFontRanges($range)); + } + + // from class PDF_Chinese CJK EXTENSIONS + public function writeType0(&$font) // _putType0 + { + // Type0 + $this->writer->write('/Subtype /Type0'); + $this->writer->write('/BaseFont /' . $font['name'] . '-' . $font['CMap']); + $this->writer->write('/Encoding /' . $font['CMap']); + $this->writer->write('/DescendantFonts [' . ($this->mpdf->n + 1) . ' 0 R]'); + $this->writer->write('>>'); + $this->writer->write('endobj'); + // CIDFont + $this->writer->object(); + $this->writer->write('<writer->write('/Subtype /CIDFontType0'); + $this->writer->write('/BaseFont /' . $font['name']); + + $cidinfo = '/Registry ' . $this->writer->string('Adobe'); + $cidinfo .= ' /Ordering ' . $this->writer->string($font['registry']['ordering']); + $cidinfo .= ' /Supplement ' . $font['registry']['supplement']; + $this->writer->write('/CIDSystemInfo <<' . $cidinfo . '>>'); + + $this->writer->write('/FontDescriptor ' . ($this->mpdf->n + 1) . ' 0 R'); + if (isset($font['MissingWidth'])) { + $this->writer->write('/DW ' . $font['MissingWidth'] . ''); + } + $this->writeFontWidths($font, 31); + $this->writer->write('>>'); + $this->writer->write('endobj'); + + // Font descriptor + $this->writer->object(); + $s = '< $v) { + if ($k !== 'Style') { + $s .= ' /' . $k . ' ' . $v . ''; + } + } + $this->writer->write($s . '>>'); + $this->writer->write('endobj'); + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Writer/FormWriter.php b/src/bb-vendor/mpdf/mpdf/src/Writer/FormWriter.php new file mode 100644 index 000000000..609aac5ce --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Writer/FormWriter.php @@ -0,0 +1,63 @@ +mpdf = $mpdf; + $this->writer = $writer; + } + + public function writeFormObjects() // _putformobjects + { + foreach ($this->mpdf->formobjects as $file => $info) { + + $this->writer->object(); + + $this->mpdf->formobjects[$file]['n'] = $this->mpdf->n; + + $this->writer->write('<writer->write('/Subtype /Form'); + $this->writer->write('/Group ' . ($this->mpdf->n + 1) . ' 0 R'); + $this->writer->write('/BBox [' . $info['x'] . ' ' . $info['y'] . ' ' . ($info['w'] + $info['x']) . ' ' . ($info['h'] + $info['y']) . ']'); + + if ($this->mpdf->compress) { + $this->writer->write('/Filter /FlateDecode'); + } + + $data = $this->mpdf->compress ? gzcompress($info['data']) : $info['data']; + $this->writer->write('/Length ' . strlen($data) . '>>'); + $this->writer->stream($data); + + unset($this->mpdf->formobjects[$file]['data']); + + $this->writer->write('endobj'); + + // Required for SVG transparency (opacity) to work + $this->writer->object(); + $this->writer->write('<writer->write('/S /Transparency'); + $this->writer->write('>>'); + $this->writer->write('endobj'); + } + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Writer/ImageWriter.php b/src/bb-vendor/mpdf/mpdf/src/Writer/ImageWriter.php new file mode 100644 index 000000000..b4d3ac857 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Writer/ImageWriter.php @@ -0,0 +1,119 @@ +mpdf = $mpdf; + $this->writer = $writer; + } + + public function writeImages() + { + $filter = $this->mpdf->compress ? '/Filter /FlateDecode ' : ''; + + foreach ($this->mpdf->images as $file => $info) { + + $this->writer->object(); + + $this->mpdf->images[$file]['n'] = $this->mpdf->n; + + $this->writer->write('<writer->write('/Subtype /Image'); + $this->writer->write('/Width ' . $info['w']); + $this->writer->write('/Height ' . $info['h']); + + if (isset($info['interpolation']) && $info['interpolation']) { + $this->writer->write('/Interpolate true'); // mPDF 6 - image interpolation shall be performed by a conforming reader + } + + if (isset($info['masked'])) { + $this->writer->write('/SMask ' . ($this->mpdf->n - 1) . ' 0 R'); + } + + // set color space + $icc = false; + if (isset($info['icc']) && ( $info['icc'] !== false)) { + // ICC Colour Space + $icc = true; + $this->writer->write('/ColorSpace [/ICCBased ' . ($this->mpdf->n + 1) . ' 0 R]'); + } elseif ($info['cs'] === 'Indexed') { + if ($this->mpdf->PDFX || ($this->mpdf->PDFA && $this->mpdf->restrictColorSpace === 3)) { + throw new \Mpdf\MpdfException('PDFA1-b and PDFX/1-a files do not permit using mixed colour space (' . $file . ').'); + } + $this->writer->write('/ColorSpace [/Indexed /DeviceRGB ' . (strlen($info['pal']) / 3 - 1) . ' ' . ($this->mpdf->n + 1) . ' 0 R]'); + } else { + $this->writer->write('/ColorSpace /' . $info['cs']); + if ($info['cs'] === 'DeviceCMYK') { + if ($this->mpdf->PDFA && $this->mpdf->restrictColorSpace !== 3) { + throw new \Mpdf\MpdfException('PDFA1-b does not permit Images using mixed colour space (' . $file . ').'); + } + if ($info['type'] === 'jpg') { + $this->writer->write('/Decode [1 0 1 0 1 0 1 0]'); + } + } elseif (($this->mpdf->PDFX || ($this->mpdf->PDFA && $this->mpdf->restrictColorSpace === 3)) && $info['cs'] === 'DeviceRGB') { + throw new \Mpdf\MpdfException('PDFA1-b and PDFX/1-a files do not permit using mixed colour space (' . $file . ').'); + } + } + + $this->writer->write('/BitsPerComponent ' . $info['bpc']); + + if (isset($info['f']) && $info['f']) { + $this->writer->write('/Filter /' . $info['f']); + } + + if (isset($info['parms'])) { + $this->writer->write($info['parms']); + } + + if (isset($info['trns']) && is_array($info['trns'])) { + $trns = ''; + $maskCount = count($info['trns']); + for ($i = 0; $i < $maskCount; $i++) { + $trns .= $info['trns'][$i] . ' ' . $info['trns'][$i] . ' '; + } + $this->writer->write('/Mask [' . $trns . ']'); + } + + $this->writer->write('/Length ' . strlen($info['data']) . '>>'); + $this->writer->stream($info['data']); + + unset($this->mpdf->images[$file]['data']); + + $this->writer->write('endobj'); + + if ($icc) { // ICC colour profile + $this->writer->object(); + $icc = $this->mpdf->compress ? gzcompress($info['icc']) : $info['icc']; + $this->writer->write('<>'); + $this->writer->stream($icc); + $this->writer->write('endobj'); + } elseif ($info['cs'] === 'Indexed') { // Palette + $this->writer->object(); + $pal = $this->mpdf->compress ? gzcompress($info['pal']) : $info['pal']; + $this->writer->write('<<' . $filter . '/Length ' . strlen($pal) . '>>'); + $this->writer->stream($pal); + $this->writer->write('endobj'); + } + } + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Writer/JavaScriptWriter.php b/src/bb-vendor/mpdf/mpdf/src/Writer/JavaScriptWriter.php new file mode 100644 index 000000000..f3bb290ab --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Writer/JavaScriptWriter.php @@ -0,0 +1,46 @@ +mpdf = $mpdf; + $this->writer = $writer; + } + + public function writeJavascript() // _putjavascript + { + $this->writer->object(); + $this->mpdf->n_js = $this->mpdf->n; + $this->writer->write('<<'); + $this->writer->write('/Names [(EmbeddedJS) ' . (1 + $this->mpdf->n) . ' 0 R ]'); + $this->writer->write('>>'); + $this->writer->write('endobj'); + + $this->writer->object(); + $this->writer->write('<<'); + $this->writer->write('/S /JavaScript'); + $this->writer->write('/JS ' . $this->writer->string($this->mpdf->js)); + $this->writer->write('>>'); + $this->writer->write('endobj'); + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Writer/MetadataWriter.php b/src/bb-vendor/mpdf/mpdf/src/Writer/MetadataWriter.php new file mode 100644 index 000000000..6285d90bf --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Writer/MetadataWriter.php @@ -0,0 +1,821 @@ +mpdf = $mpdf; + $this->writer = $writer; + $this->form = $form; + $this->protection = $protection; + $this->logger = $logger; + } + + public function writeMetadata() // _putmetadata + { + $this->writer->object(); + $this->mpdf->MetadataRoot = $this->mpdf->n; + $Producer = 'mPDF' . ($this->mpdf->exposeVersion ? (' ' . Mpdf::VERSION) : ''); + $z = date('O'); // +0200 + $offset = substr($z, 0, 3) . ':' . substr($z, 3, 2); + $CreationDate = date('Y-m-d\TH:i:s') . $offset; // 2006-03-10T10:47:26-05:00 2006-06-19T09:05:17Z + $uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', random_int(0, 0xffff), random_int(0, 0xffff), random_int(0, 0xffff), random_int(0, 0x0fff) | 0x4000, random_int(0, 0x3fff) | 0x8000, random_int(0, 0xffff), random_int(0, 0xffff), random_int(0, 0xffff)); + + + $m = '' . "\n"; // begin = FEFF BOM + $m .= ' ' . "\n"; + $m .= ' ' . "\n"; + $m .= ' ' . "\n"; + $m .= ' ' . $Producer . '' . "\n"; + if (!empty($this->mpdf->keywords)) { + $m .= ' ' . $this->mpdf->keywords . '' . "\n"; + } + $m .= ' ' . "\n"; + + $m .= ' ' . "\n"; + $m .= ' ' . $CreationDate . '' . "\n"; + $m .= ' ' . $CreationDate . '' . "\n"; + $m .= ' ' . $CreationDate . '' . "\n"; + if (!empty($this->mpdf->creator)) { + $m .= ' ' . $this->mpdf->creator . '' . "\n"; + } + $m .= ' ' . "\n"; + + // DC elements + $m .= ' ' . "\n"; + $m .= ' application/pdf' . "\n"; + if (!empty($this->mpdf->title)) { + $m .= ' + + ' . $this->mpdf->title . ' + + ' . "\n"; + } + if (!empty($this->mpdf->keywords)) { + $m .= ' + + ' . $this->mpdf->keywords . ' + + ' . "\n"; + } + if (!empty($this->mpdf->subject)) { + $m .= ' + + ' . $this->mpdf->subject . ' + + ' . "\n"; + } + if (!empty($this->mpdf->author)) { + $m .= ' + + ' . $this->mpdf->author . ' + + ' . "\n"; + } + $m .= ' ' . "\n"; + + if (!empty($this->mpdf->additionalXmpRdf)) { + $m .= $this->mpdf->additionalXmpRdf; + } + + // This bit is specific to PDFX-1a + if ($this->mpdf->PDFX) { + $m .= ' ' . "\n"; + } // This bit is specific to PDFA-1b + elseif ($this->mpdf->PDFA) { + + if (strpos($this->mpdf->PDFAversion, '-') === false) { + throw new \Mpdf\MpdfException(sprintf('PDFA version (%s) is not valid. (Use: 1-B, 3-B, etc.)', $this->mpdf->PDFAversion)); + } + + list($part, $conformance) = explode('-', strtoupper($this->mpdf->PDFAversion)); + $m .= ' ' . "\n"; + $m .= ' ' . $part . '' . "\n"; + $m .= ' ' . $conformance . '' . "\n"; + if ($part === '1' && $conformance === 'B') { + $m .= ' 2005' . "\n"; + } + $m .= ' ' . "\n"; + } + + $m .= ' ' . "\n"; + $m .= ' uuid:' . $uuid . '' . "\n"; + $m .= ' ' . "\n"; + $m .= ' ' . "\n"; + $m .= ' ' . "\n"; + $m .= str_repeat(str_repeat(' ', 100) . "\n", 20); // 2-4kB whitespace padding required + $m .= ''; // "r" read only + $this->writer->write('<>'); + $this->writer->stream($m); + $this->writer->write('endobj'); + } + + public function writeInfo() // _putinfo + { + $this->writer->write('/Producer ' . $this->writer->utf16BigEndianTextString('mPDF' . ($this->mpdf->exposeVersion ? (' ' . $this->getVersionString()) : ''))); + + if (!empty($this->mpdf->title)) { + $this->writer->write('/Title ' . $this->writer->utf16BigEndianTextString($this->mpdf->title)); + } + + if (!empty($this->mpdf->subject)) { + $this->writer->write('/Subject ' . $this->writer->utf16BigEndianTextString($this->mpdf->subject)); + } + + if (!empty($this->mpdf->author)) { + $this->writer->write('/Author ' . $this->writer->utf16BigEndianTextString($this->mpdf->author)); + } + + if (!empty($this->mpdf->keywords)) { + $this->writer->write('/Keywords ' . $this->writer->utf16BigEndianTextString($this->mpdf->keywords)); + } + + if (!empty($this->mpdf->creator)) { + $this->writer->write('/Creator ' . $this->writer->utf16BigEndianTextString($this->mpdf->creator)); + } + + foreach ($this->mpdf->customProperties as $key => $value) { + $this->writer->write('/' . $key . ' ' . $this->writer->utf16BigEndianTextString($value)); + } + + $now = PdfDate::format(time()); + $this->writer->write('/CreationDate ' . $this->writer->string('D:' . $now)); + $this->writer->write('/ModDate ' . $this->writer->string('D:' . $now)); + if ($this->mpdf->PDFX) { + $this->writer->write('/Trapped/False'); + $this->writer->write('/GTS_PDFXVersion(PDF/X-1a:2003)'); + } + } + + public function writeOutputIntent() // _putoutputintent + { + $this->writer->object(); + $this->mpdf->OutputIntentRoot = $this->mpdf->n; + $this->writer->write('<mpdf->ICCProfile, '.icc')); + + if ($this->mpdf->PDFA) { + $this->writer->write('/S /GTS_PDFA1'); + if ($this->mpdf->ICCProfile) { + $this->writer->write('/Info (' . $ICCProfile . ')'); + $this->writer->write('/OutputConditionIdentifier (Custom)'); + $this->writer->write('/OutputCondition ()'); + } else { + $this->writer->write('/Info (sRGB IEC61966-2.1)'); + $this->writer->write('/OutputConditionIdentifier (sRGB IEC61966-2.1)'); + $this->writer->write('/OutputCondition ()'); + } + $this->writer->write('/DestOutputProfile ' . ($this->mpdf->n + 1) . ' 0 R'); + } elseif ($this->mpdf->PDFX) { // always a CMYK profile + $this->writer->write('/S /GTS_PDFX'); + if ($this->mpdf->ICCProfile) { + $this->writer->write('/Info (' . $ICCProfile . ')'); + $this->writer->write('/OutputConditionIdentifier (Custom)'); + $this->writer->write('/OutputCondition ()'); + $this->writer->write('/DestOutputProfile ' . ($this->mpdf->n + 1) . ' 0 R'); + } else { + $this->writer->write('/Info (CGATS TR 001)'); + $this->writer->write('/OutputConditionIdentifier (CGATS TR 001)'); + $this->writer->write('/OutputCondition (CGATS TR 001 (SWOP))'); + $this->writer->write('/RegistryName (http://www.color.org)'); + } + } + $this->writer->write('>>'); + $this->writer->write('endobj'); + + if ($this->mpdf->PDFX && !$this->mpdf->ICCProfile) { + return; + } + + $this->writer->object(); + + if ($this->mpdf->ICCProfile) { + if (!file_exists($this->mpdf->ICCProfile)) { + throw new \Mpdf\MpdfException(sprintf('Unable to find ICC profile "%s"', $this->mpdf->ICCProfile)); + } + $s = file_get_contents($this->mpdf->ICCProfile); + } else { + $s = file_get_contents(__DIR__ . '/../../data/iccprofiles/sRGB_IEC61966-2-1.icc'); + } + + if ($this->mpdf->compress) { + $s = gzcompress($s); + } + + $this->writer->write('<<'); + + if ($this->mpdf->PDFX || ($this->mpdf->PDFA && $this->mpdf->restrictColorSpace === 3)) { + $this->writer->write('/N 4'); + } else { + $this->writer->write('/N 3'); + } + + if ($this->mpdf->compress) { + $this->writer->write('/Filter /FlateDecode '); + } + + $this->writer->write('/Length ' . strlen($s) . '>>'); + $this->writer->stream($s); + $this->writer->write('endobj'); + } + + public function writeAssociatedFiles() // _putAssociatedFiles + { + if (!function_exists('gzcompress')) { + throw new \Mpdf\MpdfException('ext-zlib is required for compression of associated files'); + } + + // for each file, we create the spec object + the stream object + foreach ($this->mpdf->associatedFiles as $k => $file) { + // spec + $this->writer->object(); + $this->mpdf->associatedFiles[$k]['_root'] = $this->mpdf->n; // we store the root ref of object for future reference (e.g. /EmbeddedFiles catalog) + $this->writer->write('<writer->string($file['name'])); + if ($file['description']) { + $this->writer->write('/Desc ' . $this->writer->string($file['description'])); + } + $this->writer->write('/Type /Filespec'); + $this->writer->write('/EF <<'); + $this->writer->write('/F ' . ($this->mpdf->n + 1) . ' 0 R'); + $this->writer->write('/UF ' . ($this->mpdf->n + 1) . ' 0 R'); + $this->writer->write('>>'); + if ($file['AFRelationship']) { + $this->writer->write('/AFRelationship /' . $file['AFRelationship']); + } + $this->writer->write('/UF ' . $this->writer->string($file['name'])); + $this->writer->write('>>'); + $this->writer->write('endobj'); + + $fileContent = null; + if (isset($file['path'])) { + $fileContent = @file_get_contents($file['path']); + } elseif (isset($file['content'])) { + $fileContent = $file['content']; + } + + if (!$fileContent) { + throw new \Mpdf\MpdfException(sprintf('Cannot access associated file - %s', $file['path'])); + } + + $filestream = gzcompress($fileContent); + $this->writer->object(); + $this->writer->write('<writer->write('/Subtype /' . $this->writer->escapeSlashes($file['mime'])); + } + $this->writer->write('/Length '.strlen($filestream)); + $this->writer->write('/Filter /FlateDecode'); + if (isset($file['path'])) { + $this->writer->write('/Params <writer->string('D:' . PdfDate::format(filemtime($file['path']))).' >>'); + } else { + $this->writer->write('/Params <writer->string('D:' . PdfDate::format(time())).' >>'); + } + + $this->writer->write('>>'); + $this->writer->stream($filestream); + $this->writer->write('endobj'); + } + + // AF array + $this->writer->object(); + $refs = []; + foreach ($this->mpdf->associatedFiles as $file) { + $refs[] = '' . $file['_root'] . ' 0 R'; + } + $this->writer->write('[' . implode(' ', $refs) . ']'); + $this->writer->write('endobj'); + + $this->mpdf->associatedFilesRoot = $this->mpdf->n; + } + + public function writeCatalog() //_putcatalog + { + $this->writer->write('/Type /Catalog'); + $this->writer->write('/Pages 1 0 R'); + + if ($this->mpdf->ZoomMode === 'fullpage') { + $this->writer->write('/OpenAction [3 0 R /Fit]'); + } elseif ($this->mpdf->ZoomMode === 'fullwidth') { + $this->writer->write('/OpenAction [3 0 R /FitH null]'); + } elseif ($this->mpdf->ZoomMode === 'real') { + $this->writer->write('/OpenAction [3 0 R /XYZ null null 1]'); + } elseif (!is_string($this->mpdf->ZoomMode)) { + $this->writer->write('/OpenAction [3 0 R /XYZ null null ' . ($this->mpdf->ZoomMode / 100) . ']'); + } elseif ($this->mpdf->ZoomMode === 'none') { + // do not write any zoom mode / OpenAction + } else { + $this->writer->write('/OpenAction [3 0 R /XYZ null null null]'); + } + + if ($this->mpdf->LayoutMode === 'single') { + $this->writer->write('/PageLayout /SinglePage'); + } elseif ($this->mpdf->LayoutMode === 'continuous') { + $this->writer->write('/PageLayout /OneColumn'); + } elseif ($this->mpdf->LayoutMode === 'twoleft') { + $this->writer->write('/PageLayout /TwoColumnLeft'); + } elseif ($this->mpdf->LayoutMode === 'tworight') { + $this->writer->write('/PageLayout /TwoColumnRight'); + } elseif ($this->mpdf->LayoutMode === 'two') { + if ($this->mpdf->mirrorMargins) { + $this->writer->write('/PageLayout /TwoColumnRight'); + } else { + $this->writer->write('/PageLayout /TwoColumnLeft'); + } + } + + // Bookmarks + if (count($this->mpdf->BMoutlines) > 0) { + $this->writer->write('/Outlines ' . $this->mpdf->OutlineRoot . ' 0 R'); + $this->writer->write('/PageMode /UseOutlines'); + } + + // Fullscreen + if (is_int(strpos($this->mpdf->DisplayPreferences, 'FullScreen'))) { + $this->writer->write('/PageMode /FullScreen'); + } + + // Metadata + if ($this->mpdf->PDFA || $this->mpdf->PDFX) { + $this->writer->write('/Metadata ' . $this->mpdf->MetadataRoot . ' 0 R'); + } + + // OutputIntents + if ($this->mpdf->PDFA || $this->mpdf->PDFX || $this->mpdf->ICCProfile) { + $this->writer->write('/OutputIntents [' . $this->mpdf->OutputIntentRoot . ' 0 R]'); + } + + // Associated files + if ($this->mpdf->associatedFilesRoot) { + $this->writer->write('/AF '. $this->mpdf->associatedFilesRoot .' 0 R'); + + $names = []; + foreach ($this->mpdf->associatedFiles as $file) { + $names[] = $this->writer->string($file['name']) . ' ' . $file['_root'] . ' 0 R'; + } + $this->writer->write('/Names << /EmbeddedFiles << /Names [' . implode(' ', $names) . '] >> >>'); + } + + // Forms + if (count($this->form->forms) > 0) { + $this->form->_putFormsCatalog(); + } + + if ($this->mpdf->js !== null) { + $this->writer->write('/Names << /JavaScript ' . $this->mpdf->n_js . ' 0 R >> '); + } + + if ($this->mpdf->DisplayPreferences || $this->mpdf->directionality === 'rtl' || $this->mpdf->mirrorMargins) { + + $this->writer->write('/ViewerPreferences<<'); + + if (is_int(strpos($this->mpdf->DisplayPreferences, 'HideMenubar'))) { + $this->writer->write('/HideMenubar true'); + } + + if (is_int(strpos($this->mpdf->DisplayPreferences, 'HideToolbar'))) { + $this->writer->write('/HideToolbar true'); + } + + if (is_int(strpos($this->mpdf->DisplayPreferences, 'HideWindowUI'))) { + $this->writer->write('/HideWindowUI true'); + } + + if (is_int(strpos($this->mpdf->DisplayPreferences, 'DisplayDocTitle'))) { + $this->writer->write('/DisplayDocTitle true'); + } + + if (is_int(strpos($this->mpdf->DisplayPreferences, 'CenterWindow'))) { + $this->writer->write('/CenterWindow true'); + } + + if (is_int(strpos($this->mpdf->DisplayPreferences, 'FitWindow'))) { + $this->writer->write('/FitWindow true'); + } + + // PrintScaling is PDF 1.6 spec. + if (!$this->mpdf->PDFA && !$this->mpdf->PDFX && is_int(strpos($this->mpdf->DisplayPreferences, 'NoPrintScaling'))) { + $this->writer->write('/PrintScaling /None'); + } + + if ($this->mpdf->directionality === 'rtl') { + $this->writer->write('/Direction /R2L'); + } + + // Duplex is PDF 1.7 spec. + if ($this->mpdf->mirrorMargins && !$this->mpdf->PDFA && !$this->mpdf->PDFX) { + // if ($this->mpdf->DefOrientation=='P') $this->writer->write('/Duplex /DuplexFlipShortEdge'); + $this->writer->write('/Duplex /DuplexFlipLongEdge'); // PDF v1.7+ + } + + $this->writer->write('>>'); + } + + if ($this->mpdf->open_layer_pane && ($this->mpdf->hasOC || count($this->mpdf->layers))) { + $this->writer->write('/PageMode /UseOC'); + } + + if ($this->mpdf->hasOC || count($this->mpdf->layers)) { + $p = $v = $h = $l = $loff = $lall = $as = ''; + if ($this->mpdf->hasOC) { + if (($this->mpdf->hasOC & 1) === 1) { + $p = $this->mpdf->n_ocg_print . ' 0 R'; + } + if (($this->mpdf->hasOC & 2) === 2) { + $v = $this->mpdf->n_ocg_view . ' 0 R'; + } + if (($this->mpdf->hasOC & 4) === 4) { + $h = $this->mpdf->n_ocg_hidden . ' 0 R'; + } + $as = "<> <>"; + } + + if (count($this->mpdf->layers)) { + foreach ($this->mpdf->layers as $k => $layer) { + if (strtolower($this->mpdf->layerDetails[$k]['state']) === 'hidden') { + $loff .= $layer['n'] . ' 0 R '; + } else { + $l .= $layer['n'] . ' 0 R '; + } + $lall .= $layer['n'] . ' 0 R '; + } + } + $this->writer->write("/OCProperties <writer->write("/Order [$v $p $h $lall] "); + if ($as) { + $this->writer->write("/AS [$as] "); + } + $this->writer->write('>>>>'); + } + } + + /** + * @since 5.7.2 + */ + public function writeAnnotations() // _putannots + { + $nb = $this->mpdf->page; + + for ($n = 1; $n <= $nb; $n++) { + + if (isset($this->mpdf->PageLinks[$n]) || isset($this->mpdf->PageAnnots[$n]) || count($this->form->forms) > 0) { + + $wPt = $this->mpdf->pageDim[$n]['w'] * Mpdf::SCALE; + $hPt = $this->mpdf->pageDim[$n]['h'] * Mpdf::SCALE; + + // Links + if (isset($this->mpdf->PageLinks[$n])) { + + foreach ($this->mpdf->PageLinks[$n] as $key => $pl) { + + $this->writer->object(); + $annot = ''; + + $rect = sprintf('%.3F %.3F %.3F %.3F', $pl[0], $pl[1], $pl[0] + $pl[2], $pl[1] - $pl[3]); + + $annot .= '<writer->utf16BigEndianTextString($pl[4]); + $annot .= ' /NM ' . $this->writer->string(sprintf('%04u-%04u', $n, $key)); + $annot .= ' /M ' . $this->writer->string('D:' . date('YmdHis')); + + $annot .= ' /Border [0 0 0]'; + + // Use this (instead of /Border) to specify border around link + + // $annot .= ' /BS <mpdf->PDFA || $this->mpdf->PDFX) { + $annot .= ' /F 28'; + } + + if (strpos($pl[4], '@') === 0) { + + $p = substr($pl[4], 1); + // $h=isset($this->mpdf->OrientationChanges[$p]) ? $wPt : $hPt; + $htarg = $this->mpdf->pageDim[$p]['h'] * Mpdf::SCALE; + $annot .= sprintf(' /Dest [%d 0 R /XYZ 0 %.3F null]>>', 1 + 2 * $p, $htarg); + + } elseif (is_string($pl[4])) { + + $annot .= ' /A <
    writer->string($pl[4]) . '>> >>'; + + } else { + + $l = $this->mpdf->links[$pl[4]]; + // may not be set if #link points to non-existent target + if (isset($this->mpdf->pageDim[$l[0]]['h'])) { + $htarg = $this->mpdf->pageDim[$l[0]]['h'] * Mpdf::SCALE; + } else { + $htarg = $this->mpdf->h * Mpdf::SCALE; + } // doesn't really matter + + $annot .= sprintf(' /Dest [%d 0 R /XYZ 0 %.3F null]>>', 1 + 2 * $l[0], $htarg - $l[1] * Mpdf::SCALE); + } + + $this->writer->write($annot); + $this->writer->write('endobj'); + + } + } + + /* -- ANNOTATIONS -- */ + if (isset($this->mpdf->PageAnnots[$n])) { + + foreach ($this->mpdf->PageAnnots[$n] as $key => $pl) { + + $fileAttachment = (bool) $pl['opt']['file']; + + if ($fileAttachment && !$this->mpdf->allowAnnotationFiles) { + $this->logger->warning('Embedded files for annotations have to be allowed explicitly with "allowAnnotationFiles" config key'); + $fileAttachment = false; + } + + $this->writer->object(); + + $annot = ''; + $pl['opt'] = array_change_key_case($pl['opt'], CASE_LOWER); + $x = $pl['x']; + + if ($this->mpdf->annotMargin != 0 || $x == 0 || $x < 0) { // Odd page, intentional non-strict comparison + $x = ($wPt / Mpdf::SCALE) - $this->mpdf->annotMargin; + } + + $w = $h = 0; + $a = $x * Mpdf::SCALE; + $b = $hPt - ($pl['y'] * Mpdf::SCALE); + + $annot .= '<mpdf->n + 1) . ' 0 R>>'; + $annot .= '>>'; + + } else { + $annot .= '/Subtype /Text'; + $w = 20; + $h = 20; // mPDF 6 + } + + $rect = sprintf('%.3F %.3F %.3F %.3F', $a, $b - $h, $a + $w, $b); + $annot .= ' /Rect [' . $rect . ']'; + + // contents = description of file in free text + $annot .= ' /Contents ' . $this->writer->utf16BigEndianTextString($pl['txt']); + + $annot .= ' /NM ' . $this->writer->string(sprintf('%04u-%04u', $n, 2000 + $key)); + $annot .= ' /M ' . $this->writer->string('D:' . date('YmdHis')); + $annot .= ' /CreationDate ' . $this->writer->string('D:' . date('YmdHis')); + $annot .= ' /Border [0 0 0]'; + + if ($this->mpdf->PDFA || $this->mpdf->PDFX) { + $annot .= ' /F 28'; + $annot .= ' /CA 1'; + } elseif ($pl['opt']['ca'] > 0) { + $annot .= ' /CA ' . $pl['opt']['ca']; + } + + $annotcolor = ' /C ['; + if (isset($pl['opt']['c']) && $pl['opt']['c']) { + $col = $pl['opt']['c']; + if ($col[0] == 3 || $col[0] == 5) { + $annotcolor .= sprintf('%.3F %.3F %.3F', ord($col[1]) / 255, ord($col[2]) / 255, ord($col[3]) / 255); + } elseif ($col[0] == 1) { + $annotcolor .= sprintf('%.3F', ord($col[1]) / 255); + } elseif ($col[0] == 4 || $col[0] == 6) { + $annotcolor .= sprintf('%.3F %.3F %.3F %.3F', ord($col[1]) / 100, ord($col[2]) / 100, ord($col[3]) / 100, ord($col[4]) / 100); + } else { + $annotcolor .= '1 1 0'; + } + } else { + $annotcolor .= '1 1 0'; + } + $annotcolor .= ']'; + $annot .= $annotcolor; + + // Usually Author + // Use as Title for fileattachment + if (isset($pl['opt']['t']) && is_string($pl['opt']['t'])) { + $annot .= ' /T ' . $this->writer->utf16BigEndianTextString($pl['opt']['t']); + } + + if ($fileAttachment) { + $iconsapp = ['Paperclip', 'Graph', 'PushPin', 'Tag']; + } else { + $iconsapp = ['Comment', 'Help', 'Insert', 'Key', 'NewParagraph', 'Note', 'Paragraph']; + } + + if (isset($pl['opt']['icon']) && in_array($pl['opt']['icon'], $iconsapp)) { + $annot .= ' /Name /' . $pl['opt']['icon']; + } elseif ($fileAttachment) { + $annot .= ' /Name /PushPin'; + } else { + $annot .= ' /Name /Note'; + } + + if (!$fileAttachment) { + // Subj is PDF 1.5 spec. + if (!$this->mpdf->PDFA && !$this->mpdf->PDFX && isset($pl['opt']['subj'])) { + $annot .= ' /Subj ' . $this->writer->utf16BigEndianTextString($pl['opt']['subj']); + } + if (!empty($pl['opt']['popup'])) { + $annot .= ' /Open true'; + $annot .= ' /Popup ' . ($this->mpdf->n + 1) . ' 0 R'; + } else { + $annot .= ' /Open false'; + } + } + + $annot .= ' /P ' . $pl['pageobj'] . ' 0 R'; + $annot .= '>>'; + $this->writer->write($annot); + $this->writer->write('endobj'); + + if ($fileAttachment) { + + $file = @file_get_contents($pl['opt']['file']); + if (!$file) { + throw new \Mpdf\MpdfException('mPDF Error: Cannot access file attachment - ' . $pl['opt']['file']); + } + + $filestream = gzcompress($file); + $this->writer->object(); + $this->writer->write('<writer->write('/Length ' . strlen($filestream)); + $this->writer->write('/Filter /FlateDecode'); + $this->writer->write('>>'); + $this->writer->stream($filestream); + $this->writer->write('endobj'); + + } elseif (!empty($pl['opt']['popup'])) { + $this->writer->object(); + $annot = ''; + if (is_array($pl['opt']['popup']) && isset($pl['opt']['popup'][0])) { + $x = $pl['opt']['popup'][0] * Mpdf::SCALE; + } else { + $x = $pl['x'] * Mpdf::SCALE; + } + if (is_array($pl['opt']['popup']) && isset($pl['opt']['popup'][1])) { + $y = $hPt - ($pl['opt']['popup'][1] * Mpdf::SCALE); + } else { + $y = $hPt - ($pl['y'] * Mpdf::SCALE); + } + if (is_array($pl['opt']['popup']) && isset($pl['opt']['popup'][2])) { + $w = $pl['opt']['popup'][2] * Mpdf::SCALE; + } else { + $w = 180; + } + if (is_array($pl['opt']['popup']) && isset($pl['opt']['popup'][3])) { + $h = $pl['opt']['popup'][3] * Mpdf::SCALE; + } else { + $h = 120; + } + $rect = sprintf('%.3F %.3F %.3F %.3F', $x, $y - $h, $x + $w, $y); + $annot .= '<writer->string('D:' . date('YmdHis')); + if ($this->mpdf->PDFA || $this->mpdf->PDFX) { + $annot .= ' /F 28'; + } + $annot .= ' /Parent ' . ($this->mpdf->n - 1) . ' 0 R'; + $annot .= '>>'; + $this->writer->write($annot); + $this->writer->write('endobj'); + } + } + } + + // Active Forms + if (count($this->form->forms) > 0) { + $this->form->_putFormItems($n, $hPt); + } + } + } + + // Active Forms - Radio Button Group entries + // Output Radio Button Group form entries (radio_on_obj_id already determined) + if (count($this->form->form_radio_groups)) { + $this->form->_putRadioItems($n); + } + } + + public function writeEncryption() // _putencryption + { + $this->writer->write('/Filter /Standard'); + if ($this->protection->getUseRC128Encryption()) { + $this->writer->write('/V 2'); + $this->writer->write('/R 3'); + $this->writer->write('/Length 128'); + } else { + $this->writer->write('/V 1'); + $this->writer->write('/R 2'); + } + $this->writer->write('/O (' . $this->writer->escape($this->protection->getOValue()) . ')'); + $this->writer->write('/U (' . $this->writer->escape($this->protection->getUValue()) . ')'); + $this->writer->write('/P ' . $this->protection->getPValue()); + } + + public function writeTrailer() // _puttrailer + { + $this->writer->write('/Size ' . ($this->mpdf->n + 1)); + $this->writer->write('/Root ' . $this->mpdf->n . ' 0 R'); + $this->writer->write('/Info ' . $this->mpdf->InfoRoot . ' 0 R'); + + if ($this->mpdf->encrypted) { + $this->writer->write('/Encrypt ' . $this->mpdf->enc_obj_id . ' 0 R'); + $this->writer->write('/ID [<' . $this->protection->getUniqid() . '> <' . $this->protection->getUniqid() . '>]'); + } else { + $uniqid = md5(time() . $this->mpdf->buffer); + $this->writer->write('/ID [<' . $uniqid . '> <' . $uniqid . '>]'); + } + } + + public function setLogger(LoggerInterface $logger) + { + $this->logger = $logger; + } + + private function getVersionString() + { + $return = Mpdf::VERSION; + $headFile = __DIR__ . '/../../.git/HEAD'; + if (file_exists($headFile)) { + $ref = file($headFile); + $path = explode('/', $ref[0], 3); + $branch = isset($path[2]) ? trim($path[2]) : ''; + $revFile = __DIR__ . '/../../.git/refs/heads/' . $branch; + if ($branch && file_exists($revFile)) { + $rev = file($revFile); + $rev = substr($rev[0], 0, 7); + $return .= ' (' . $rev . ')'; + } + } + + return $return; + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Writer/ObjectWriter.php b/src/bb-vendor/mpdf/mpdf/src/Writer/ObjectWriter.php new file mode 100644 index 000000000..2e0ad7d01 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Writer/ObjectWriter.php @@ -0,0 +1,64 @@ +mpdf = $mpdf; + $this->writer = $writer; + } + + public function writeImportedObjects() + { + if (is_array($this->mpdf->parsers) && count($this->mpdf->parsers) > 0) { + + foreach ($this->mpdf->parsers as $filename => $p) { + + $this->mpdf->current_parser = $this->mpdf->parsers[$filename]; + + if (is_array($this->mpdf->_obj_stack[$filename])) { + + while ($n = key($this->mpdf->_obj_stack[$filename])) { + + $nObj = $this->mpdf->current_parser->resolveObject($this->mpdf->_obj_stack[$filename][$n][1]); + $this->writer->object($this->mpdf->_obj_stack[$filename][$n][0]); + + if ($nObj[0] == pdf_parser::TYPE_STREAM) { + $this->mpdf->pdf_write_value($nObj); + } else { + $this->mpdf->pdf_write_value($nObj[1]); + } + + $this->writer->write('endobj'); + + $this->mpdf->_obj_stack[$filename][$n] = null; // free memory + + unset($this->mpdf->_obj_stack[$filename][$n]); + + reset($this->mpdf->_obj_stack[$filename]); + } + } + } + } + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Writer/OptionalContentWriter.php b/src/bb-vendor/mpdf/mpdf/src/Writer/OptionalContentWriter.php new file mode 100644 index 000000000..499a77fd7 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Writer/OptionalContentWriter.php @@ -0,0 +1,71 @@ +mpdf = $mpdf; + $this->writer = $writer; + } + + public function writeOptionalContentGroups() // _putocg Optional Content Groups + { + if ($this->mpdf->hasOC) { + + $this->writer->object(); + $this->mpdf->n_ocg_print = $this->mpdf->n; + $this->writer->write('<writer->string('Print only')); + $this->writer->write('/Usage <> /View <>>>>>'); + $this->writer->write('endobj'); + + $this->writer->object(); + $this->mpdf->n_ocg_view = $this->mpdf->n; + $this->writer->write('<writer->string('Screen only')); + $this->writer->write('/Usage <> /View <>>>>>'); + $this->writer->write('endobj'); + + $this->writer->object(); + $this->mpdf->n_ocg_hidden = $this->mpdf->n; + $this->writer->write('<writer->string('Hidden')); + $this->writer->write('/Usage <> /View <>>>>>'); + $this->writer->write('endobj'); + } + + if (count($this->mpdf->layers)) { + + ksort($this->mpdf->layers); + foreach ($this->mpdf->layers as $id => $layer) { + $this->writer->object(); + $this->mpdf->layers[$id]['n'] = $this->mpdf->n; + + if (isset($this->mpdf->layerDetails[$id]['name']) && $this->mpdf->layerDetails[$id]['name']) { + $name = $this->mpdf->layerDetails[$id]['name']; + } else { + $name = $layer['name']; + } + + $this->writer->write('<writer->utf16BigEndianTextString($name) . '>>'); + $this->writer->write('endobj'); + } + } + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Writer/PageWriter.php b/src/bb-vendor/mpdf/mpdf/src/Writer/PageWriter.php new file mode 100644 index 000000000..7e4e21d47 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Writer/PageWriter.php @@ -0,0 +1,285 @@ +mpdf = $mpdf; + $this->form = $form; + $this->writer = $writer; + $this->metadataWriter = $metadataWriter; + } + + public function writePages() // _putpages + { + $nb = $this->mpdf->page; + $filter = $this->mpdf->compress ? '/Filter /FlateDecode ' : ''; + + if ($this->mpdf->DefOrientation === 'P') { + $defwPt = $this->mpdf->fwPt; + $defhPt = $this->mpdf->fhPt; + } else { + $defwPt = $this->mpdf->fhPt; + $defhPt = $this->mpdf->fwPt; + } + + $annotid = (3 + 2 * $nb); + + // Active Forms + $totaladdnum = 0; + for ($n = 1; $n <= $nb; $n++) { + if (isset($this->mpdf->PageLinks[$n])) { + $totaladdnum += count($this->mpdf->PageLinks[$n]); + } + + /* -- ANNOTATIONS -- */ + if (isset($this->mpdf->PageAnnots[$n])) { + foreach ($this->mpdf->PageAnnots[$n] as $k => $pl) { + if (!empty($pl['opt']['popup']) || !empty($pl['opt']['file'])) { + $totaladdnum += 2; + } else { + $totaladdnum++; + } + } + } + /* -- END ANNOTATIONS -- */ + + /* -- FORMS -- */ + if (count($this->form->forms) > 0) { + $this->form->countPageForms($n, $totaladdnum); + } + /* -- END FORMS -- */ + } + + /* -- FORMS -- */ + // Make a note in the radio button group of the obj_id it will have + $ctr = 0; + if (count($this->form->form_radio_groups)) { + foreach ($this->form->form_radio_groups as $name => $frg) { + $this->form->form_radio_groups[$name]['obj_id'] = $annotid + $totaladdnum + $ctr; + $ctr++; + } + } + /* -- END FORMS -- */ + + // Select unused fonts (usually default font) + $unused = []; + foreach ($this->mpdf->fonts as $fk => $font) { + if (isset($font['type']) && $font['type'] === 'TTF' && !$font['used']) { + $unused[] = $fk; + } + } + + for ($n = 1; $n <= $nb; $n++) { + + $thispage = $this->mpdf->pages[$n]; + + if (isset($this->mpdf->OrientationChanges[$n])) { + $hPt = $this->mpdf->pageDim[$n]['w'] * Mpdf::SCALE; + $wPt = $this->mpdf->pageDim[$n]['h'] * Mpdf::SCALE; + $owidthPt_LR = $this->mpdf->pageDim[$n]['outer_width_TB'] * Mpdf::SCALE; + $owidthPt_TB = $this->mpdf->pageDim[$n]['outer_width_LR'] * Mpdf::SCALE; + } else { + $wPt = $this->mpdf->pageDim[$n]['w'] * Mpdf::SCALE; + $hPt = $this->mpdf->pageDim[$n]['h'] * Mpdf::SCALE; + $owidthPt_LR = $this->mpdf->pageDim[$n]['outer_width_LR'] * Mpdf::SCALE; + $owidthPt_TB = $this->mpdf->pageDim[$n]['outer_width_TB'] * Mpdf::SCALE; + } + + // Remove references to unused fonts (usually default font) + foreach ($unused as $fk) { + if ($this->mpdf->fonts[$fk]['sip'] || $this->mpdf->fonts[$fk]['smp']) { + foreach ($this->mpdf->fonts[$fk]['subsetfontids'] as $k => $fid) { + $thispage = preg_replace('/\s\/F' . $fid . ' \d[\d.]* Tf\s/is', ' ', $thispage); + } + } else { + $thispage = preg_replace('/\s\/F' . $this->mpdf->fonts[$fk]['i'] . ' \d[\d.]* Tf\s/is', ' ', $thispage); + } + } + + // Clean up repeated /GS1 gs statements + // For some reason using + for repetition instead of {2,20} crashes PHP Script Interpreter ??? + $thispage = preg_replace('/(\/GS1 gs\n){2,20}/', "/GS1 gs\n", $thispage); + + $thispage = preg_replace('/(\s*___BACKGROUND___PATTERNS' . $this->mpdf->uniqstr . '\s*)/', ' ', $thispage); + $thispage = preg_replace('/(\s*___HEADER___MARKER' . $this->mpdf->uniqstr . '\s*)/', ' ', $thispage); + $thispage = preg_replace('/(\s*___PAGE___START' . $this->mpdf->uniqstr . '\s*)/', ' ', $thispage); + $thispage = preg_replace('/(\s*___TABLE___BACKGROUNDS' . $this->mpdf->uniqstr . '\s*)/', ' ', $thispage); + + // mPDF 5.7.3 TRANSFORMS + while (preg_match('/(\% BTR(.*?)\% ETR)/is', $thispage, $m)) { + $thispage = preg_replace('/(\% BTR.*?\% ETR)/is', '', $thispage, 1) . "\n" . $m[2]; + } + + // Page + $this->writer->object(); + $this->writer->write('<writer->write('/Parent 1 0 R'); + + if (isset($this->mpdf->OrientationChanges[$n])) { + + $this->writer->write(sprintf('/MediaBox [0 0 %.3F %.3F]', $hPt, $wPt)); + + // If BleedBox is defined, it must be larger than the TrimBox, but smaller than the MediaBox + $bleedMargin = $this->mpdf->pageDim[$n]['bleedMargin'] * Mpdf::SCALE; + + if ($bleedMargin && ($owidthPt_TB || $owidthPt_LR)) { + $x0 = $owidthPt_TB - $bleedMargin; + $y0 = $owidthPt_LR - $bleedMargin; + $x1 = $hPt - $owidthPt_TB + $bleedMargin; + $y1 = $wPt - $owidthPt_LR + $bleedMargin; + $this->writer->write(sprintf('/BleedBox [%.3F %.3F %.3F %.3F]', $x0, $y0, $x1, $y1)); + } + + $this->writer->write(sprintf('/TrimBox [%.3F %.3F %.3F %.3F]', $owidthPt_TB, $owidthPt_LR, $hPt - $owidthPt_TB, $wPt - $owidthPt_LR)); + + if ($this->mpdf->displayDefaultOrientation) { + if ($this->mpdf->DefOrientation === 'P') { + $this->writer->write('/Rotate 270'); + } else { + $this->writer->write('/Rotate 90'); + } + } + + } else { // elseif($wPt != $defwPt || $hPt != $defhPt) { + + $this->writer->write(sprintf('/MediaBox [0 0 %.3F %.3F]', $wPt, $hPt)); + $bleedMargin = $this->mpdf->pageDim[$n]['bleedMargin'] * Mpdf::SCALE; + + if ($bleedMargin && ($owidthPt_TB || $owidthPt_LR)) { + $x0 = $owidthPt_LR - $bleedMargin; + $y0 = $owidthPt_TB - $bleedMargin; + $x1 = $wPt - $owidthPt_LR + $bleedMargin; + $y1 = $hPt - $owidthPt_TB + $bleedMargin; + $this->writer->write(sprintf('/BleedBox [%.3F %.3F %.3F %.3F]', $x0, $y0, $x1, $y1)); + } + + $this->writer->write(sprintf('/TrimBox [%.3F %.3F %.3F %.3F]', $owidthPt_LR, $owidthPt_TB, $wPt - $owidthPt_LR, $hPt - $owidthPt_TB)); + } + $this->writer->write('/Resources 2 0 R'); + + // Important to keep in RGB colorSpace when using transparency + if (!$this->mpdf->PDFA && !$this->mpdf->PDFX) { + if ($this->mpdf->restrictColorSpace === 3) { + $this->writer->write('/Group << /Type /Group /S /Transparency /CS /DeviceCMYK >> '); + } elseif ($this->mpdf->restrictColorSpace === 1) { + $this->writer->write('/Group << /Type /Group /S /Transparency /CS /DeviceGray >> '); + } else { + $this->writer->write('/Group << /Type /Group /S /Transparency /CS /DeviceRGB >> '); + } + } + + $annotsnum = 0; + $embeddedfiles = []; // mPDF 5.7.2 /EmbeddedFiles + + if (isset($this->mpdf->PageLinks[$n])) { + $annotsnum += count($this->mpdf->PageLinks[$n]); + } + + if (isset($this->mpdf->PageAnnots[$n])) { + foreach ($this->mpdf->PageAnnots[$n] as $k => $pl) { + if (!empty($pl['opt']['file'])) { + $embeddedfiles[$annotsnum + 1] = true; + } // mPDF 5.7.2 /EmbeddedFiles + if (!empty($pl['opt']['popup']) || !empty($pl['opt']['file'])) { + $annotsnum += 2; + } else { + $annotsnum++; + } + $this->mpdf->PageAnnots[$n][$k]['pageobj'] = $this->mpdf->n; + } + } + + // Active Forms + $formsnum = 0; + if (count($this->form->forms) > 0) { + foreach ($this->form->forms as $val) { + if ($val['page'] == $n) { + $formsnum++; + } + } + } + + if ($annotsnum || $formsnum) { + + $s = '/Annots [ '; + + for ($i = 0; $i < $annotsnum; $i++) { + if (!isset($embeddedfiles[$i])) { + $s .= ($annotid + $i) . ' 0 R '; + } // mPDF 5.7.2 /EmbeddedFiles + } + + $annotid += $annotsnum; + + /* -- FORMS -- */ + if (count($this->form->forms) > 0) { + $this->form->addFormIds($n, $s, $annotid); + } + /* -- END FORMS -- */ + + $s .= '] '; + $this->writer->write($s); + } + + $this->writer->write('/Contents ' . ($this->mpdf->n + 1) . ' 0 R>>'); + $this->writer->write('endobj'); + + // Page content + $this->writer->object(); + $p = $this->mpdf->compress ? gzcompress($thispage) : $thispage; + $this->writer->write('<<' . $filter . '/Length ' . strlen($p) . '>>'); + $this->writer->stream($p); + $this->writer->write('endobj'); + } + + $this->metadataWriter->writeAnnotations(); // mPDF 5.7.2 + + // Pages root + $this->mpdf->offsets[1] = strlen($this->mpdf->buffer); + $this->writer->write('1 0 obj'); + $this->writer->write('<writer->write($kids . ']'); + $this->writer->write('/Count ' . $nb); + $this->writer->write(sprintf('/MediaBox [0 0 %.3F %.3F]', $defwPt, $defhPt)); + $this->writer->write('>>'); + $this->writer->write('endobj'); + } + +} diff --git a/src/bb-vendor/mpdf/mpdf/src/Writer/ResourceWriter.php b/src/bb-vendor/mpdf/mpdf/src/Writer/ResourceWriter.php new file mode 100644 index 000000000..996b88234 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/Writer/ResourceWriter.php @@ -0,0 +1,256 @@ +mpdf = $mpdf; + $this->writer = $writer; + $this->colorWriter = $colorWriter; + $this->fontWriter = $fontWriter; + $this->imageWriter = $imageWriter; + $this->formWriter = $formWriter; + $this->optionalContentWriter = $optionalContentWriter; + $this->backgroundWriter = $backgroundWriter; + $this->bookmarkWriter = $bookmarkWriter; + $this->metadataWriter = $metadataWriter; + $this->javaScriptWriter = $javaScriptWriter; + $this->logger = $logger; + } + + public function writeResources() // _putresources + { + if ($this->mpdf->hasOC || count($this->mpdf->layers)) { + $this->optionalContentWriter->writeOptionalContentGroups(); + } + + $this->mpdf->_putextgstates(); + $this->colorWriter->writeSpotColors(); + + // @log Compiling Fonts + + $this->fontWriter->writeFonts(); + + // @log Compiling Images + + $this->imageWriter->writeImages(); + + $this->formWriter->writeFormObjects(); + + $this->mpdf->writeImportedPagesAndResolvedObjects(); + + $this->backgroundWriter->writeShaders(); + $this->backgroundWriter->writePatterns(); + + // Resource dictionary + $this->mpdf->offsets[2] = strlen($this->mpdf->buffer); + $this->writer->write('2 0 obj'); + $this->writer->write('<writer->write('/Font <<'); + foreach ($this->mpdf->fonts as $font) { + if (isset($font['type']) && $font['type'] === 'TTF' && !$font['used']) { + continue; + } + if (isset($font['type']) && $font['type'] === 'TTF' && ($font['sip'] || $font['smp'])) { + foreach ($font['n'] as $k => $fid) { + $this->writer->write('/F' . $font['subsetfontids'][$k] . ' ' . $font['n'][$k] . ' 0 R'); + } + } else { + $this->writer->write('/F' . $font['i'] . ' ' . $font['n'] . ' 0 R'); + } + } + $this->writer->write('>>'); + + if (count($this->mpdf->spotColors)) { + $this->writer->write('/ColorSpace <<'); + foreach ($this->mpdf->spotColors as $color) { + $this->writer->write('/CS' . $color['i'] . ' ' . $color['n'] . ' 0 R'); + } + $this->writer->write('>>'); + } + + if (count($this->mpdf->extgstates)) { + $this->writer->write('/ExtGState <<'); + foreach ($this->mpdf->extgstates as $k => $extgstate) { + if (isset($extgstate['trans'])) { + $this->writer->write('/' . $extgstate['trans'] . ' ' . $extgstate['n'] . ' 0 R'); + } else { + $this->writer->write('/GS' . $k . ' ' . $extgstate['n'] . ' 0 R'); + } + } + $this->writer->write('>>'); + } + + /* -- BACKGROUNDS -- */ + if (($this->mpdf->gradients !== null && (count($this->mpdf->gradients) > 0))) { // mPDF 5.7.3 + + $this->writer->write('/Shading <<'); + + foreach ($this->mpdf->gradients as $id => $grad) { + $this->writer->write('/Sh' . $id . ' ' . $grad['id'] . ' 0 R'); + } + + $this->writer->write('>>'); + + /* + // ??? Not needed !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + $this->writer->write('/Pattern <<'); + foreach ($this->mpdf->gradients as $id => $grad) { + $this->writer->write('/P'.$id.' '.$grad['pattern'].' 0 R'); + } + $this->writer->write('>>'); + */ + } + /* -- END BACKGROUNDS -- */ + + if (count($this->mpdf->images) || count($this->mpdf->formobjects) || count($this->mpdf->getImportedPages())) { + $this->writer->write('/XObject <<'); + foreach ($this->mpdf->images as $image) { + $this->writer->write('/I' . $image['i'] . ' ' . $image['n'] . ' 0 R'); + } + foreach ($this->mpdf->formobjects as $formobject) { + $this->writer->write('/FO' . $formobject['i'] . ' ' . $formobject['n'] . ' 0 R'); + } + /* -- IMPORTS -- */ + foreach ($this->mpdf->getImportedPages() as $pageData) { + $this->writer->write('/' . $pageData['id'] . ' ' . $pageData['objectNumber'] . ' 0 R'); + } + /* -- END IMPORTS -- */ + $this->writer->write('>>'); + } + + /* -- BACKGROUNDS -- */ + + if (count($this->mpdf->patterns)) { + $this->writer->write('/Pattern <<'); + foreach ($this->mpdf->patterns as $k => $patterns) { + $this->writer->write('/P' . $k . ' ' . $patterns['n'] . ' 0 R'); + } + $this->writer->write('>>'); + } + /* -- END BACKGROUNDS -- */ + + if ($this->mpdf->hasOC || count($this->mpdf->layers)) { + $this->writer->write('/Properties <<'); + if ($this->mpdf->hasOC) { + $this->writer->write('/OC1 ' . $this->mpdf->n_ocg_print . ' 0 R /OC2 ' . $this->mpdf->n_ocg_view . ' 0 R /OC3 ' . $this->mpdf->n_ocg_hidden . ' 0 R '); + } + if (count($this->mpdf->layers)) { + foreach ($this->mpdf->layers as $id => $layer) { + $this->writer->write('/ZI' . $id . ' ' . $layer['n'] . ' 0 R'); + } + } + $this->writer->write('>>'); + } + + $this->writer->write('>>'); + $this->writer->write('endobj'); // end resource dictionary + + $this->bookmarkWriter->writeBookmarks(); + + if (!empty($this->mpdf->js)) { + $this->javaScriptWriter->writeJavascript(); + } + + if ($this->mpdf->encrypted) { + $this->writer->object(); + $this->mpdf->enc_obj_id = $this->mpdf->n; + $this->writer->write('<<'); + $this->metadataWriter->writeEncryption(); + $this->writer->write('>>'); + $this->writer->write('endobj'); + } + } + + /** + * @param \Psr\Log\LoggerInterface $logger + * + * @return void + */ + public function setLogger(LoggerInterface $logger) + { + $this->logger = $logger; + } +} diff --git a/src/bb-vendor/mpdf/mpdf/src/functions-dev.php b/src/bb-vendor/mpdf/mpdf/src/functions-dev.php new file mode 100644 index 000000000..355f3e3fd --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/src/functions-dev.php @@ -0,0 +1,13 @@ + is used for editing the fonts. + +Design Issues +------------- + +Which font shapes should be made? Historical style terms like Renaissance +or Baroque letterforms cannot be applied beyond Latin/Cyrillic/Greek +scripts to any greater extent than Kufi or Nashki can be applied beyond +Arabic script; "italic" is really only meaningful for Latin letters. + +However, most modern writing systems have typographic formulations for +contrasting uniform and modulated character stroke widths, and have some +history with "oblique", faces. Since the advent of the typewriter, most +have developed a typographic style with uniform-width characters. + +Accordingly, the FreeFont family has one monospaced - FreeMono - and two +proportional faces (one with uniform stroke - FreeSans - and one with +modulated stroke - FreeSerif). + +To make text from different writing systems look good side-by-side, each +FreeFont face is meant to contain characters of similar style and weight. + +Licensing +--------- + +Free UCS scalable fonts 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 2 of the License, or +(at your option) any later version. + +The fonts are distributed in the hope that they will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + +As a special exception, if you create a document which uses this font, and +embed this font or unaltered portions of this font into the document, this +font does not by itself cause the resulting document to be covered by the +GNU General Public License. This exception does not however invalidate any +other reasons why the document might be covered by the GNU General Public +License. If you modify this font, you may extend this exception to your +version of the font, but you are not obligated to do so. If you do not +wish to do so, delete this exception statement from your version. + + +Files and their suffixes +------------------------ + +The files with .sfd (Spline Font Database) are in FontForge's native format. +Please use these if you plan to modify the font files. + +TrueType fonts for immediate consumption are the files with the .ttf +(TrueType Font) suffix. These are ready to use in Xwindows based +systems using FreeType, on Mac OS, and on older Windows systems. + +OpenType fonts (with suffix .otf) are for use in Windows Vista. +Note that although they can be installed on Linux, but many applications +in Linux still don't support them. + + +-------------------------------------------------------------------------- +Primoz Peterlin, +Steve White + +Free UCS scalable fonts: http://savannah.gnu.org/projects/freefont/ +$Id: README,v 1.6 2008/12/25 12:51:41 Stevan_White Exp $ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/Garuda-Bold.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/Garuda-Bold.ttf new file mode 100644 index 000000000..c2aa87edb Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/Garuda-Bold.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/Garuda-BoldOblique.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/Garuda-BoldOblique.ttf new file mode 100644 index 000000000..889be702a Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/Garuda-BoldOblique.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/Garuda-Oblique.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/Garuda-Oblique.ttf new file mode 100644 index 000000000..7d1219907 Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/Garuda-Oblique.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/Garuda.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/Garuda.ttf new file mode 100644 index 000000000..b9fcdfd90 Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/Garuda.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/Jomolhari-OFL.txt b/src/bb-vendor/mpdf/mpdf/ttfonts/Jomolhari-OFL.txt new file mode 100644 index 000000000..b723c35f6 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/ttfonts/Jomolhari-OFL.txt @@ -0,0 +1,98 @@ +This Font Software is Copyright (c) 2006, Christopher J Fynn +All Rights Reserved. + +"Jomolhari" is a Reserved Font Name for this Font Software. + +This Font Software is licensed under the SIL Open Font License, Version 1.0. +No modification of the license is permitted, only verbatim copy is allowed. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.0 - 22 November 2005 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of cooperative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide an open +framework in which fonts may be shared and improved in partnership with +others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and sold with any software provided that the font +names of derivative works are changed. The fonts and derivatives, +however, cannot be released under any other type of license. + +DEFINITIONS +"Font Software" refers to any and all of the following: + - font files + - data files + - source code + - build scripts + - documentation + +"Reserved Font Name" refers to the Font Software name as seen by +users and any other names as specified after the copyright statement. + +"Standard Version" refers to the collection of Font Software +components as distributed by the Copyright Holder. + +"Modified Version" refers to any derivative font software made by +adding to, deleting, or substituting -- in part or in whole -- +any of the components of the Standard Version, by changing formats +or by porting the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Standard or Modified Versions, may be sold by itself. + +2) Standard or Modified Versions of the Font Software may be bundled, +redistributed and sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s), in part or in whole, unless explicit written permission is +granted by the Copyright Holder. This restriction applies to all +references stored in the Font Software, such as the font menu name and +other font description fields, which are used to differentiate the +font from others. + +4) The name(s) of the Copyright Holder or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed using this license, and may not be distributed +under any other license. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/Jomolhari.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/Jomolhari.ttf new file mode 100644 index 000000000..ca695b61d Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/Jomolhari.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/KhmerOFL.txt b/src/bb-vendor/mpdf/mpdf/ttfonts/KhmerOFL.txt new file mode 100644 index 000000000..bfa6ae45c --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/ttfonts/KhmerOFL.txt @@ -0,0 +1,93 @@ +Copyright (c) 2010, Danh Hong (khmertype.blogspot.com), +with Reserved Font Name Khmer. +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/KhmerOS.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/KhmerOS.ttf new file mode 100644 index 000000000..7aa5bdcd5 Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/KhmerOS.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/Lateef font OFL.txt b/src/bb-vendor/mpdf/mpdf/ttfonts/Lateef font OFL.txt new file mode 100644 index 000000000..7a1b1c7e4 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/ttfonts/Lateef font OFL.txt @@ -0,0 +1,93 @@ +Copyright (c) 2004-2011, SIL International (http://www.sil.org/), +with Reserved Font Names "Scheherazade" and "SIL". + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/LateefRegOT.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/LateefRegOT.ttf new file mode 100644 index 000000000..f89d32be3 Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/LateefRegOT.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/Lohit-Kannada.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/Lohit-Kannada.ttf new file mode 100644 index 000000000..2911ce7b6 Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/Lohit-Kannada.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/LohitKannadaOFL.txt b/src/bb-vendor/mpdf/mpdf/ttfonts/LohitKannadaOFL.txt new file mode 100644 index 000000000..01b830782 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/ttfonts/LohitKannadaOFL.txt @@ -0,0 +1,94 @@ +Copyright 2011-12 Lohit Fonts Project contributors + + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/Padauk-book.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/Padauk-book.ttf new file mode 100644 index 000000000..590cdadd4 Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/Padauk-book.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/Pothana2000.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/Pothana2000.ttf new file mode 100644 index 000000000..296d7d665 Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/Pothana2000.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/Quivira.otf b/src/bb-vendor/mpdf/mpdf/ttfonts/Quivira.otf new file mode 100644 index 000000000..531edf16c Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/Quivira.otf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/Sun-ExtA.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/Sun-ExtA.ttf new file mode 100644 index 000000000..1c9c2cfa5 Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/Sun-ExtA.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/Sun-ExtB.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/Sun-ExtB.ttf new file mode 100644 index 000000000..8a53b20c5 Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/Sun-ExtB.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/SundaneseUnicode-1.0.5.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/SundaneseUnicode-1.0.5.ttf new file mode 100644 index 000000000..a86b47578 Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/SundaneseUnicode-1.0.5.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/SyrCOMEdessa.otf b/src/bb-vendor/mpdf/mpdf/ttfonts/SyrCOMEdessa.otf new file mode 100644 index 000000000..9e1fbda08 Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/SyrCOMEdessa.otf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/SyrCOMEdessa_license.txt b/src/bb-vendor/mpdf/mpdf/ttfonts/SyrCOMEdessa_license.txt new file mode 100644 index 000000000..35c74dddc --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/ttfonts/SyrCOMEdessa_license.txt @@ -0,0 +1,61 @@ +This license is derived from the Bigelow & Holmes Font License +found at http://www.xfree86.org/current/LICENSE2.html + +The following reasonable modifications have been made to the +Bigelow & Holmes Font License: + +* All references to Luxi have been replaced with Meltho + +* All references to Bigelow & Holmes Inc. and URW++ GmbH haven + been replaced with Beth Mardutho: The Syriac Institute + +* The registered trademark notice belonging to Bigelow & Holmes + Inc. has been removed + +* Contact information has been modified to show that the + contact person for these fonts is the Director of the + Institute, George Kiraz. + +------------------------------------------------------------- + +Meltho fonts and font code copyright © 2002 by Beth Mardutho: +The Syriac Institute. All Right Reserved. + +Permission is hereby granted, free of charge, to any person +obtaining a copy of these Fonts and associated documentation +files (the "Font Software"), to deal in the Font Software, +including without limitation the rights to use, copy, merge, +publish, distribute, sublicense, and/or sell copies of the +Font Software, and to permit persons to whom the Font Software +is furnished to do so, subject to the following conditions: + +The above copyright and trademark notices and this permission +notice shall be included in all copies of one or more of the +Font Software. + +The Font Software may not be modified, altered, or added to, +and in particular the designs of glyphs or characters in the +Fonts may not be modified nor may additional glyphs or +characters be added to the Fonts. This License becomes null +and void when the Fonts or Font Software have been modified. + +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER +RIGHT. IN NO EVENT SHALL BETH MARDUTHO: THE SYRIAC INSTITUTE BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY +GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR +FROM OTHER DEALINGS IN THE FONT SOFTWARE. + +Except as contained in this notice, the name of Beth Mardutho: +The Syriac Institute shall not be used in advertising or otherwise +to promote the sale, use or other dealings in this Font Software +without prior written authorization from Beth Mardutho: The +Syriac Institute. + +For further information, contact: +George Kiraz, Director of Beth Mardutho +gkiraz@bethmardutho.org diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/TaameyDavidCLM-LICENSE.txt b/src/bb-vendor/mpdf/mpdf/ttfonts/TaameyDavidCLM-LICENSE.txt new file mode 100644 index 000000000..de1ef6320 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/ttfonts/TaameyDavidCLM-LICENSE.txt @@ -0,0 +1,17 @@ +This package is distributed under the terms of GNU General Public License +version 2 (see file GNU-GPL). +--------------------------------------------------------------------- + +"Taamey David CLM" fonts are copyright (C) 2010 by Yoram Gnat +(gyoramg@users.sourceforge.net). All rights reserved. + +As a special exception, if you create a document which uses +this font, and embed this font or unaltered portions of this +font into the document, this font does not by itself cause +the resulting document to be covered by the +GNU General Public License. This exception does not however +invalidate any other reasons why the document might be covered +by the GNU General Public License. If you modify this font, +you may extend this exception to your version of the font, +but you are not obligated to do so. If you do not wish to do so, +delete this exception statement from your version. diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/TaameyDavidCLM-Medium.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/TaameyDavidCLM-Medium.ttf new file mode 100644 index 000000000..2aed6f85e Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/TaameyDavidCLM-Medium.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/TaiHeritagePro.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/TaiHeritagePro.ttf new file mode 100644 index 000000000..d4ed9538b Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/TaiHeritagePro.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/Tharlon-Regular.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/Tharlon-Regular.ttf new file mode 100644 index 000000000..4717d70cd Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/Tharlon-Regular.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/TharlonOFL.txt b/src/bb-vendor/mpdf/mpdf/ttfonts/TharlonOFL.txt new file mode 100644 index 000000000..2973d5df3 --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/ttfonts/TharlonOFL.txt @@ -0,0 +1,93 @@ +Copyright (c) 2010-2012, Sai Zin Di Di Zone (www.yunghkio.com/unicode|saiddzone@gmail.com), with Reserved Font Name 'Yunghkio'. Copyright (c) 2012, Google, Inc (http://code.google.com/p/googlefontdirectory/), with Reserved Font Name 'Arimo'. Copyright (c) 2012, Sun Tun, Ngwe Tun, Solveware Solution (http://code.google.com/p/tharlon-font|info@parabaik.info), with Reserved Font Name 'TharLon'. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/UnBatang_0613.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/UnBatang_0613.ttf new file mode 100644 index 000000000..2e93d5f86 Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/UnBatang_0613.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/Uthman.otf b/src/bb-vendor/mpdf/mpdf/ttfonts/Uthman.otf new file mode 100644 index 000000000..bb650a24e Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/Uthman.otf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/XB Riyaz.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/XB Riyaz.ttf new file mode 100644 index 000000000..80e15803d Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/XB Riyaz.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/XB RiyazBd.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/XB RiyazBd.ttf new file mode 100644 index 000000000..e6cf58f93 Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/XB RiyazBd.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/XB RiyazBdIt.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/XB RiyazBdIt.ttf new file mode 100644 index 000000000..19fba7887 Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/XB RiyazBdIt.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/XB RiyazIt.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/XB RiyazIt.ttf new file mode 100644 index 000000000..cc9cc3ab2 Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/XB RiyazIt.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/XW Zar Font Info.txt b/src/bb-vendor/mpdf/mpdf/ttfonts/XW Zar Font Info.txt new file mode 100644 index 000000000..d42e4544b --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/ttfonts/XW Zar Font Info.txt @@ -0,0 +1,92 @@ + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/ZawgyiOne.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/ZawgyiOne.ttf new file mode 100644 index 000000000..573147158 Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/ZawgyiOne.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/ayar.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/ayar.ttf new file mode 100644 index 000000000..e74c61204 Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/ayar.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/damase_v.2.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/damase_v.2.ttf new file mode 100644 index 000000000..a60240bab Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/damase_v.2.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/kaputaunicode.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/kaputaunicode.ttf new file mode 100644 index 000000000..fe0269726 Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/kaputaunicode.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/lannaalif-v1-03.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/lannaalif-v1-03.ttf new file mode 100644 index 000000000..7c20d9791 Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/lannaalif-v1-03.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/ocrb10.ttf b/src/bb-vendor/mpdf/mpdf/ttfonts/ocrb10.ttf new file mode 100644 index 000000000..34980b80c Binary files /dev/null and b/src/bb-vendor/mpdf/mpdf/ttfonts/ocrb10.ttf differ diff --git a/src/bb-vendor/mpdf/mpdf/ttfonts/ocrbinfo.txt b/src/bb-vendor/mpdf/mpdf/ttfonts/ocrbinfo.txt new file mode 100644 index 000000000..c2dd9954c --- /dev/null +++ b/src/bb-vendor/mpdf/mpdf/ttfonts/ocrbinfo.txt @@ -0,0 +1,60 @@ +Mostly-free OCR B + +This font is used in UPC bar code symbols, including the ISBN symbols on +most published books. + +A freely distributable version seems to be sorely needed. Until now, it's +been very difficult to find the font in computer-usable format except by +paying a high fee to a commercial font vendor. Even many serious commercial +publishers have so much trouble getting it right that they just go ahead and +use Helvetica instead, or even (shudder) Arial. Since the OCR B font is +required by an international standard, it seems like it ought to be free. +So here it is. The font in this package is not a "ripped", pirated, or +shadily reverse engineered version; every effort has been made to ensure +that it genuinely derives from free sources and all the creators involved +have actually intended it for free public use. + +Converted by Matthew Skala from Metafont format to Postscript and TrueType +formats, July 28, 2006, using mftrace 1.2.4 by Paul Vojta, which is +available from + http://www.xs4all.nl/~hanwen/mftrace/ +and Autotrace 0.31.1 available from + http://autotrace.sourceforge.net/ + +The Metafont files (not included - see notes below) were coded by Norbert +Schwarz in the 1980s, based on German standards documents. He has attached +a notice, notably not actually claiming any copyright - see the file +"ocrbinfo" - saying that the fonts are "given to free non commercial use", +but commenting that he is only free to grant rights to his own work on the +digitization, because he did not design the original letter forms. He +suggests that there may be other copyright claims attached to the letter +forms themselves, which Schwarz credits as being originally designed by +"Adam Frutiger" [sic], almost certainly a mistake for Adrian Frutiger. My +(Matthew Skala's) understanding of copyright law, at least in the USA and +Canada, is that in fact typefaces per se cannot be subject to copyright +claims, so the software embodiment is the only thing subject to copyright +and Schwarz's release makes it available for whatever "non commercial use" +means. + +To avoid muddying the waters further, any copyright claims by Matthew Skala +on these files are hereby released to the public domain. I'd like for these +fonts to be freely usable even in marginally commercial applications, such +as to generate UPC labels for books that will be sold for profit, but it may +not be within my power to grant that myself because I didn't write the +Metafont files although I did do considerable, and probably copyrightable, +work on the translation to Postscript and TrueType. It was *not* a purely +automated process; try using the tools I used and see how far you get +without human editing! I'd also like for these fonts (the fonts themselves +as opposed to documents made with them) not to be sold, not even indirectly +by those Web sites that advertise "free downloads" but make it difficult to +actually download fonts without paying a fee. + +NOTE: This ZIP archive is a stripped-down version containing just the +essential files for using the main OCR B font on most systems. If you want +the much larger complete package, which contains Metafont sources and several +variant fonts (reverse-video, outline, and slanted), look for a ZIP archive +called ocrb-complete.zip wherever you found this one. + +Matthew Skala +mskala@ansuz.sooke.bc.ca +http://ansuz.sooke.bc.ca/ diff --git a/src/bb-vendor/myclabs/deep-copy/.github/FUNDING.yml b/src/bb-vendor/myclabs/deep-copy/.github/FUNDING.yml new file mode 100644 index 000000000..b8da664dd --- /dev/null +++ b/src/bb-vendor/myclabs/deep-copy/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: "packagist/myclabs/deep-copy" +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/src/bb-vendor/myclabs/deep-copy/LICENSE b/src/bb-vendor/myclabs/deep-copy/LICENSE new file mode 100644 index 000000000..c3e835001 --- /dev/null +++ b/src/bb-vendor/myclabs/deep-copy/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013 My C-Sense + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/src/bb-vendor/myclabs/deep-copy/README.md b/src/bb-vendor/myclabs/deep-copy/README.md new file mode 100644 index 000000000..007ad5bb8 --- /dev/null +++ b/src/bb-vendor/myclabs/deep-copy/README.md @@ -0,0 +1,375 @@ +# DeepCopy + +DeepCopy helps you create deep copies (clones) of your objects. It is designed to handle cycles in the association graph. + +[![Build Status](https://travis-ci.org/myclabs/DeepCopy.png?branch=1.x)](https://travis-ci.org/myclabs/DeepCopy) +[![Coverage Status](https://coveralls.io/repos/myclabs/DeepCopy/badge.png?branch=1.x)](https://coveralls.io/r/myclabs/DeepCopy?branch=1.x) +[![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/myclabs/DeepCopy/badges/quality-score.png?s=2747100c19b275f93a777e3297c6c12d1b68b934)](https://scrutinizer-ci.com/g/myclabs/DeepCopy/) +[![Total Downloads](https://poser.pugx.org/myclabs/deep-copy/downloads.svg)](https://packagist.org/packages/myclabs/deep-copy) + +## Table of Contents + +1. [How](#how) +1. [Why](#why) + 1. [Using simply `clone`](#using-simply-clone) + 1. [Overridding `__clone()`](#overridding-__clone) + 1. [With `DeepCopy`](#with-deepcopy) +1. [How it works](#how-it-works) +1. [Going further](#going-further) + 1. [Matchers](#matchers) + 1. [Property name](#property-name) + 1. [Specific property](#specific-property) + 1. [Type](#type) + 1. [Filters](#filters) + 1. [`SetNullFilter`](#setnullfilter-filter) + 1. [`KeepFilter`](#keepfilter-filter) + 1. [`DoctrineCollectionFilter`](#doctrinecollectionfilter-filter) + 1. [`DoctrineEmptyCollectionFilter`](#doctrineemptycollectionfilter-filter) + 1. [`DoctrineProxyFilter`](#doctrineproxyfilter-filter) + 1. [`ReplaceFilter`](#replacefilter-type-filter) + 1. [`ShallowCopyFilter`](#shallowcopyfilter-type-filter) +1. [Edge cases](#edge-cases) +1. [Contributing](#contributing) + 1. [Tests](#tests) + + +## How? + +Install with Composer: + +```json +composer require myclabs/deep-copy +``` + +Use simply: + +```php +use DeepCopy\DeepCopy; + +$copier = new DeepCopy(); +$myCopy = $copier->copy($myObject); +``` + + +## Why? + +- How do you create copies of your objects? + +```php +$myCopy = clone $myObject; +``` + +- How do you create **deep** copies of your objects (i.e. copying also all the objects referenced in the properties)? + +You use [`__clone()`](http://www.php.net/manual/en/language.oop5.cloning.php#object.clone) and implement the behavior +yourself. + +- But how do you handle **cycles** in the association graph? + +Now you're in for a big mess :( + +![association graph](doc/graph.png) + + +### Using simply `clone` + +![Using clone](doc/clone.png) + + +### Overridding `__clone()` + +![Overridding __clone](doc/deep-clone.png) + + +### With `DeepCopy` + +![With DeepCopy](doc/deep-copy.png) + + +## How it works + +DeepCopy recursively traverses all the object's properties and clones them. To avoid cloning the same object twice it +keeps a hash map of all instances and thus preserves the object graph. + +To use it: + +```php +use function DeepCopy\deep_copy; + +$copy = deep_copy($var); +``` + +Alternatively, you can create your own `DeepCopy` instance to configure it differently for example: + +```php +use DeepCopy\DeepCopy; + +$copier = new DeepCopy(true); + +$copy = $copier->copy($var); +``` + +You may want to roll your own deep copy function: + +```php +namespace Acme; + +use DeepCopy\DeepCopy; + +function deep_copy($var) +{ + static $copier = null; + + if (null === $copier) { + $copier = new DeepCopy(true); + } + + return $copier->copy($var); +} +``` + + +## Going further + +You can add filters to customize the copy process. + +The method to add a filter is `DeepCopy\DeepCopy::addFilter($filter, $matcher)`, +with `$filter` implementing `DeepCopy\Filter\Filter` +and `$matcher` implementing `DeepCopy\Matcher\Matcher`. + +We provide some generic filters and matchers. + + +### Matchers + + - `DeepCopy\Matcher` applies on a object attribute. + - `DeepCopy\TypeMatcher` applies on any element found in graph, including array elements. + + +#### Property name + +The `PropertyNameMatcher` will match a property by its name: + +```php +use DeepCopy\Matcher\PropertyNameMatcher; + +// Will apply a filter to any property of any objects named "id" +$matcher = new PropertyNameMatcher('id'); +``` + + +#### Specific property + +The `PropertyMatcher` will match a specific property of a specific class: + +```php +use DeepCopy\Matcher\PropertyMatcher; + +// Will apply a filter to the property "id" of any objects of the class "MyClass" +$matcher = new PropertyMatcher('MyClass', 'id'); +``` + + +#### Type + +The `TypeMatcher` will match any element by its type (instance of a class or any value that could be parameter of +[gettype()](http://php.net/manual/en/function.gettype.php) function): + +```php +use DeepCopy\TypeMatcher\TypeMatcher; + +// Will apply a filter to any object that is an instance of Doctrine\Common\Collections\Collection +$matcher = new TypeMatcher('Doctrine\Common\Collections\Collection'); +``` + + +### Filters + +- `DeepCopy\Filter` applies a transformation to the object attribute matched by `DeepCopy\Matcher` +- `DeepCopy\TypeFilter` applies a transformation to any element matched by `DeepCopy\TypeMatcher` + + +#### `SetNullFilter` (filter) + +Let's say for example that you are copying a database record (or a Doctrine entity), so you want the copy not to have +any ID: + +```php +use DeepCopy\DeepCopy; +use DeepCopy\Filter\SetNullFilter; +use DeepCopy\Matcher\PropertyNameMatcher; + +$object = MyClass::load(123); +echo $object->id; // 123 + +$copier = new DeepCopy(); +$copier->addFilter(new SetNullFilter(), new PropertyNameMatcher('id')); + +$copy = $copier->copy($object); + +echo $copy->id; // null +``` + + +#### `KeepFilter` (filter) + +If you want a property to remain untouched (for example, an association to an object): + +```php +use DeepCopy\DeepCopy; +use DeepCopy\Filter\KeepFilter; +use DeepCopy\Matcher\PropertyMatcher; + +$copier = new DeepCopy(); +$copier->addFilter(new KeepFilter(), new PropertyMatcher('MyClass', 'category')); + +$copy = $copier->copy($object); +// $copy->category has not been touched +``` + + +#### `DoctrineCollectionFilter` (filter) + +If you use Doctrine and want to copy an entity, you will need to use the `DoctrineCollectionFilter`: + +```php +use DeepCopy\DeepCopy; +use DeepCopy\Filter\Doctrine\DoctrineCollectionFilter; +use DeepCopy\Matcher\PropertyTypeMatcher; + +$copier = new DeepCopy(); +$copier->addFilter(new DoctrineCollectionFilter(), new PropertyTypeMatcher('Doctrine\Common\Collections\Collection')); + +$copy = $copier->copy($object); +``` + + +#### `DoctrineEmptyCollectionFilter` (filter) + +If you use Doctrine and want to copy an entity who contains a `Collection` that you want to be reset, you can use the +`DoctrineEmptyCollectionFilter` + +```php +use DeepCopy\DeepCopy; +use DeepCopy\Filter\Doctrine\DoctrineEmptyCollectionFilter; +use DeepCopy\Matcher\PropertyMatcher; + +$copier = new DeepCopy(); +$copier->addFilter(new DoctrineEmptyCollectionFilter(), new PropertyMatcher('MyClass', 'myProperty')); + +$copy = $copier->copy($object); + +// $copy->myProperty will return an empty collection +``` + + +#### `DoctrineProxyFilter` (filter) + +If you use Doctrine and use cloning on lazy loaded entities, you might encounter errors mentioning missing fields on a +Doctrine proxy class (...\\\_\_CG\_\_\Proxy). +You can use the `DoctrineProxyFilter` to load the actual entity behind the Doctrine proxy class. +**Make sure, though, to put this as one of your very first filters in the filter chain so that the entity is loaded +before other filters are applied!** + +```php +use DeepCopy\DeepCopy; +use DeepCopy\Filter\Doctrine\DoctrineProxyFilter; +use DeepCopy\Matcher\Doctrine\DoctrineProxyMatcher; + +$copier = new DeepCopy(); +$copier->addFilter(new DoctrineProxyFilter(), new DoctrineProxyMatcher()); + +$copy = $copier->copy($object); + +// $copy should now contain a clone of all entities, including those that were not yet fully loaded. +``` + + +#### `ReplaceFilter` (type filter) + +1. If you want to replace the value of a property: + +```php +use DeepCopy\DeepCopy; +use DeepCopy\Filter\ReplaceFilter; +use DeepCopy\Matcher\PropertyMatcher; + +$copier = new DeepCopy(); +$callback = function ($currentValue) { + return $currentValue . ' (copy)' +}; +$copier->addFilter(new ReplaceFilter($callback), new PropertyMatcher('MyClass', 'title')); + +$copy = $copier->copy($object); + +// $copy->title will contain the data returned by the callback, e.g. 'The title (copy)' +``` + +2. If you want to replace whole element: + +```php +use DeepCopy\DeepCopy; +use DeepCopy\TypeFilter\ReplaceFilter; +use DeepCopy\TypeMatcher\TypeMatcher; + +$copier = new DeepCopy(); +$callback = function (MyClass $myClass) { + return get_class($myClass); +}; +$copier->addTypeFilter(new ReplaceFilter($callback), new TypeMatcher('MyClass')); + +$copy = $copier->copy([new MyClass, 'some string', new MyClass]); + +// $copy will contain ['MyClass', 'some string', 'MyClass'] +``` + + +The `$callback` parameter of the `ReplaceFilter` constructor accepts any PHP callable. + + +#### `ShallowCopyFilter` (type filter) + +Stop *DeepCopy* from recursively copying element, using standard `clone` instead: + +```php +use DeepCopy\DeepCopy; +use DeepCopy\TypeFilter\ShallowCopyFilter; +use DeepCopy\TypeMatcher\TypeMatcher; +use Mockery as m; + +$this->deepCopy = new DeepCopy(); +$this->deepCopy->addTypeFilter( + new ShallowCopyFilter, + new TypeMatcher(m\MockInterface::class) +); + +$myServiceWithMocks = new MyService(m::mock(MyDependency1::class), m::mock(MyDependency2::class)); +// All mocks will be just cloned, not deep copied +``` + + +## Edge cases + +The following structures cannot be deep-copied with PHP Reflection. As a result they are shallow cloned and filters are +not applied. There is two ways for you to handle them: + +- Implement your own `__clone()` method +- Use a filter with a type matcher + + +## Contributing + +DeepCopy is distributed under the MIT license. + + +### Tests + +Running the tests is simple: + +```php +vendor/bin/phpunit +``` + +### Support + +Get professional support via [the Tidelift Subscription](https://tidelift.com/subscription/pkg/packagist-myclabs-deep-copy?utm_source=packagist-myclabs-deep-copy&utm_medium=referral&utm_campaign=readme). diff --git a/src/bb-vendor/myclabs/deep-copy/composer.json b/src/bb-vendor/myclabs/deep-copy/composer.json new file mode 100644 index 000000000..45656c916 --- /dev/null +++ b/src/bb-vendor/myclabs/deep-copy/composer.json @@ -0,0 +1,38 @@ +{ + "name": "myclabs/deep-copy", + "type": "library", + "description": "Create deep copies (clones) of your objects", + "keywords": ["clone", "copy", "duplicate", "object", "object graph"], + "license": "MIT", + + "autoload": { + "psr-4": { + "DeepCopy\\": "src/DeepCopy/" + }, + "files": [ + "src/DeepCopy/deep_copy.php" + ] + }, + "autoload-dev": { + "psr-4": { + "DeepCopy\\": "fixtures/", + "DeepCopyTest\\": "tests/DeepCopyTest/" + } + }, + + "require": { + "php": "^7.1 || ^8.0" + }, + "require-dev": { + "doctrine/collections": "^1.0", + "doctrine/common": "^2.6", + "phpunit/phpunit": "^7.1" + }, + "replace": { + "myclabs/deep-copy": "self.version" + }, + + "config": { + "sort-packages": true + } +} diff --git a/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/DeepCopy.php b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/DeepCopy.php new file mode 100644 index 000000000..15e5c6893 --- /dev/null +++ b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/DeepCopy.php @@ -0,0 +1,298 @@ + Filter, 'matcher' => Matcher] pairs. + */ + private $filters = []; + + /** + * Type Filters to apply. + * + * @var array Array of ['filter' => Filter, 'matcher' => Matcher] pairs. + */ + private $typeFilters = []; + + /** + * @var bool + */ + private $skipUncloneable = false; + + /** + * @var bool + */ + private $useCloneMethod; + + /** + * @param bool $useCloneMethod If set to true, when an object implements the __clone() function, it will be used + * instead of the regular deep cloning. + */ + public function __construct($useCloneMethod = false) + { + $this->useCloneMethod = $useCloneMethod; + + $this->addTypeFilter(new ArrayObjectFilter($this), new TypeMatcher(ArrayObject::class)); + $this->addTypeFilter(new DateIntervalFilter(), new TypeMatcher(DateInterval::class)); + $this->addTypeFilter(new SplDoublyLinkedListFilter($this), new TypeMatcher(SplDoublyLinkedList::class)); + } + + /** + * If enabled, will not throw an exception when coming across an uncloneable property. + * + * @param $skipUncloneable + * + * @return $this + */ + public function skipUncloneable($skipUncloneable = true) + { + $this->skipUncloneable = $skipUncloneable; + + return $this; + } + + /** + * Deep copies the given object. + * + * @param mixed $object + * + * @return mixed + */ + public function copy($object) + { + $this->hashMap = []; + + return $this->recursiveCopy($object); + } + + public function addFilter(Filter $filter, Matcher $matcher) + { + $this->filters[] = [ + 'matcher' => $matcher, + 'filter' => $filter, + ]; + } + + public function prependFilter(Filter $filter, Matcher $matcher) + { + array_unshift($this->filters, [ + 'matcher' => $matcher, + 'filter' => $filter, + ]); + } + + public function addTypeFilter(TypeFilter $filter, TypeMatcher $matcher) + { + $this->typeFilters[] = [ + 'matcher' => $matcher, + 'filter' => $filter, + ]; + } + + private function recursiveCopy($var) + { + // Matches Type Filter + if ($filter = $this->getFirstMatchedTypeFilter($this->typeFilters, $var)) { + return $filter->apply($var); + } + + // Resource + if (is_resource($var)) { + return $var; + } + + // Array + if (is_array($var)) { + return $this->copyArray($var); + } + + // Scalar + if (! is_object($var)) { + return $var; + } + + // Object + return $this->copyObject($var); + } + + /** + * Copy an array + * @param array $array + * @return array + */ + private function copyArray(array $array) + { + foreach ($array as $key => $value) { + $array[$key] = $this->recursiveCopy($value); + } + + return $array; + } + + /** + * Copies an object. + * + * @param object $object + * + * @throws CloneException + * + * @return object + */ + private function copyObject($object) + { + $objectHash = spl_object_hash($object); + + if (isset($this->hashMap[$objectHash])) { + return $this->hashMap[$objectHash]; + } + + $reflectedObject = new ReflectionObject($object); + $isCloneable = $reflectedObject->isCloneable(); + + if (false === $isCloneable) { + if ($this->skipUncloneable) { + $this->hashMap[$objectHash] = $object; + + return $object; + } + + throw new CloneException( + sprintf( + 'The class "%s" is not cloneable.', + $reflectedObject->getName() + ) + ); + } + + $newObject = clone $object; + $this->hashMap[$objectHash] = $newObject; + + if ($this->useCloneMethod && $reflectedObject->hasMethod('__clone')) { + return $newObject; + } + + if ($newObject instanceof DateTimeInterface || $newObject instanceof DateTimeZone) { + return $newObject; + } + + foreach (ReflectionHelper::getProperties($reflectedObject) as $property) { + $this->copyObjectProperty($newObject, $property); + } + + return $newObject; + } + + private function copyObjectProperty($object, ReflectionProperty $property) + { + // Ignore static properties + if ($property->isStatic()) { + return; + } + + // Apply the filters + foreach ($this->filters as $item) { + /** @var Matcher $matcher */ + $matcher = $item['matcher']; + /** @var Filter $filter */ + $filter = $item['filter']; + + if ($matcher->matches($object, $property->getName())) { + $filter->apply( + $object, + $property->getName(), + function ($object) { + return $this->recursiveCopy($object); + } + ); + + // If a filter matches, we stop processing this property + return; + } + } + + $property->setAccessible(true); + + // Ignore uninitialized properties (for PHP >7.4) + if (method_exists($property, 'isInitialized') && !$property->isInitialized($object)) { + return; + } + + $propertyValue = $property->getValue($object); + + // Copy the property + $property->setValue($object, $this->recursiveCopy($propertyValue)); + } + + /** + * Returns first filter that matches variable, `null` if no such filter found. + * + * @param array $filterRecords Associative array with 2 members: 'filter' with value of type {@see TypeFilter} and + * 'matcher' with value of type {@see TypeMatcher} + * @param mixed $var + * + * @return TypeFilter|null + */ + private function getFirstMatchedTypeFilter(array $filterRecords, $var) + { + $matched = $this->first( + $filterRecords, + function (array $record) use ($var) { + /* @var TypeMatcher $matcher */ + $matcher = $record['matcher']; + + return $matcher->matches($var); + } + ); + + return isset($matched) ? $matched['filter'] : null; + } + + /** + * Returns first element that matches predicate, `null` if no such element found. + * + * @param array $elements Array of ['filter' => Filter, 'matcher' => Matcher] pairs. + * @param callable $predicate Predicate arguments are: element. + * + * @return array|null Associative array with 2 members: 'filter' with value of type {@see TypeFilter} and 'matcher' + * with value of type {@see TypeMatcher} or `null`. + */ + private function first(array $elements, callable $predicate) + { + foreach ($elements as $element) { + if (call_user_func($predicate, $element)) { + return $element; + } + } + + return null; + } +} diff --git a/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Exception/CloneException.php b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Exception/CloneException.php new file mode 100644 index 000000000..c046706a2 --- /dev/null +++ b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Exception/CloneException.php @@ -0,0 +1,9 @@ +setAccessible(true); + $oldCollection = $reflectionProperty->getValue($object); + + $newCollection = $oldCollection->map( + function ($item) use ($objectCopier) { + return $objectCopier($item); + } + ); + + $reflectionProperty->setValue($object, $newCollection); + } +} diff --git a/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Filter/Doctrine/DoctrineEmptyCollectionFilter.php b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Filter/Doctrine/DoctrineEmptyCollectionFilter.php new file mode 100644 index 000000000..7b33fd547 --- /dev/null +++ b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Filter/Doctrine/DoctrineEmptyCollectionFilter.php @@ -0,0 +1,28 @@ +setAccessible(true); + + $reflectionProperty->setValue($object, new ArrayCollection()); + } +} \ No newline at end of file diff --git a/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Filter/Doctrine/DoctrineProxyFilter.php b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Filter/Doctrine/DoctrineProxyFilter.php new file mode 100644 index 000000000..8bee8f769 --- /dev/null +++ b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Filter/Doctrine/DoctrineProxyFilter.php @@ -0,0 +1,22 @@ +__load(); + } +} diff --git a/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Filter/Filter.php b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Filter/Filter.php new file mode 100644 index 000000000..85ba18ce1 --- /dev/null +++ b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Filter/Filter.php @@ -0,0 +1,18 @@ +callback = $callable; + } + + /** + * Replaces the object property by the result of the callback called with the object property. + * + * {@inheritdoc} + */ + public function apply($object, $property, $objectCopier) + { + $reflectionProperty = ReflectionHelper::getProperty($object, $property); + $reflectionProperty->setAccessible(true); + + $value = call_user_func($this->callback, $reflectionProperty->getValue($object)); + + $reflectionProperty->setValue($object, $value); + } +} diff --git a/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Filter/SetNullFilter.php b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Filter/SetNullFilter.php new file mode 100644 index 000000000..bea86b884 --- /dev/null +++ b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Filter/SetNullFilter.php @@ -0,0 +1,24 @@ +setAccessible(true); + $reflectionProperty->setValue($object, null); + } +} diff --git a/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Matcher/Doctrine/DoctrineProxyMatcher.php b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Matcher/Doctrine/DoctrineProxyMatcher.php new file mode 100644 index 000000000..ec8856f50 --- /dev/null +++ b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Matcher/Doctrine/DoctrineProxyMatcher.php @@ -0,0 +1,22 @@ +class = $class; + $this->property = $property; + } + + /** + * Matches a specific property of a specific class. + * + * {@inheritdoc} + */ + public function matches($object, $property) + { + return ($object instanceof $this->class) && $property == $this->property; + } +} diff --git a/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Matcher/PropertyNameMatcher.php b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Matcher/PropertyNameMatcher.php new file mode 100644 index 000000000..c8ec0d2bc --- /dev/null +++ b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Matcher/PropertyNameMatcher.php @@ -0,0 +1,32 @@ +property = $property; + } + + /** + * Matches a property by its name. + * + * {@inheritdoc} + */ + public function matches($object, $property) + { + return $property == $this->property; + } +} diff --git a/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Matcher/PropertyTypeMatcher.php b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Matcher/PropertyTypeMatcher.php new file mode 100644 index 000000000..a6b0c0bc5 --- /dev/null +++ b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Matcher/PropertyTypeMatcher.php @@ -0,0 +1,46 @@ +propertyType = $propertyType; + } + + /** + * {@inheritdoc} + */ + public function matches($object, $property) + { + try { + $reflectionProperty = ReflectionHelper::getProperty($object, $property); + } catch (ReflectionException $exception) { + return false; + } + + $reflectionProperty->setAccessible(true); + + return $reflectionProperty->getValue($object) instanceof $this->propertyType; + } +} diff --git a/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Reflection/ReflectionHelper.php b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Reflection/ReflectionHelper.php new file mode 100644 index 000000000..742410cb2 --- /dev/null +++ b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/Reflection/ReflectionHelper.php @@ -0,0 +1,78 @@ +getProperties() does not return private properties from ancestor classes. + * + * @author muratyaman@gmail.com + * @see http://php.net/manual/en/reflectionclass.getproperties.php + * + * @param ReflectionClass $ref + * + * @return ReflectionProperty[] + */ + public static function getProperties(ReflectionClass $ref) + { + $props = $ref->getProperties(); + $propsArr = array(); + + foreach ($props as $prop) { + $propertyName = $prop->getName(); + $propsArr[$propertyName] = $prop; + } + + if ($parentClass = $ref->getParentClass()) { + $parentPropsArr = self::getProperties($parentClass); + foreach ($propsArr as $key => $property) { + $parentPropsArr[$key] = $property; + } + + return $parentPropsArr; + } + + return $propsArr; + } + + /** + * Retrieves property by name from object and all its ancestors. + * + * @param object|string $object + * @param string $name + * + * @throws PropertyException + * @throws ReflectionException + * + * @return ReflectionProperty + */ + public static function getProperty($object, $name) + { + $reflection = is_object($object) ? new ReflectionObject($object) : new ReflectionClass($object); + + if ($reflection->hasProperty($name)) { + return $reflection->getProperty($name); + } + + if ($parentClass = $reflection->getParentClass()) { + return self::getProperty($parentClass->getName(), $name); + } + + throw new PropertyException( + sprintf( + 'The class "%s" doesn\'t have a property with the given name: "%s".', + is_object($object) ? get_class($object) : $object, + $name + ) + ); + } +} diff --git a/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/TypeFilter/Date/DateIntervalFilter.php b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/TypeFilter/Date/DateIntervalFilter.php new file mode 100644 index 000000000..becd1cfff --- /dev/null +++ b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/TypeFilter/Date/DateIntervalFilter.php @@ -0,0 +1,33 @@ + $propertyValue) { + $copy->{$propertyName} = $propertyValue; + } + + return $copy; + } +} diff --git a/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/TypeFilter/ReplaceFilter.php b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/TypeFilter/ReplaceFilter.php new file mode 100644 index 000000000..164f8b8e2 --- /dev/null +++ b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/TypeFilter/ReplaceFilter.php @@ -0,0 +1,30 @@ +callback = $callable; + } + + /** + * {@inheritdoc} + */ + public function apply($element) + { + return call_user_func($this->callback, $element); + } +} diff --git a/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/TypeFilter/ShallowCopyFilter.php b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/TypeFilter/ShallowCopyFilter.php new file mode 100644 index 000000000..a5fbd7a2b --- /dev/null +++ b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/TypeFilter/ShallowCopyFilter.php @@ -0,0 +1,17 @@ +copier = $copier; + } + + /** + * {@inheritdoc} + */ + public function apply($arrayObject) + { + $clone = clone $arrayObject; + foreach ($arrayObject->getArrayCopy() as $k => $v) { + $clone->offsetSet($k, $this->copier->copy($v)); + } + + return $clone; + } +} + diff --git a/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/TypeFilter/Spl/SplDoublyLinkedList.php b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/TypeFilter/Spl/SplDoublyLinkedList.php new file mode 100644 index 000000000..c5644cff8 --- /dev/null +++ b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/TypeFilter/Spl/SplDoublyLinkedList.php @@ -0,0 +1,10 @@ +copier = $copier; + } + + /** + * {@inheritdoc} + */ + public function apply($element) + { + $newElement = clone $element; + + $copy = $this->createCopyClosure(); + + return $copy($newElement); + } + + private function createCopyClosure() + { + $copier = $this->copier; + + $copy = function (SplDoublyLinkedList $list) use ($copier) { + // Replace each element in the list with a deep copy of itself + for ($i = 1; $i <= $list->count(); $i++) { + $copy = $copier->recursiveCopy($list->shift()); + + $list->push($copy); + } + + return $list; + }; + + return Closure::bind($copy, null, DeepCopy::class); + } +} diff --git a/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/TypeFilter/TypeFilter.php b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/TypeFilter/TypeFilter.php new file mode 100644 index 000000000..5785a7da9 --- /dev/null +++ b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/TypeFilter/TypeFilter.php @@ -0,0 +1,13 @@ +type = $type; + } + + /** + * @param mixed $element + * + * @return boolean + */ + public function matches($element) + { + return is_object($element) ? is_a($element, $this->type) : gettype($element) === $this->type; + } +} diff --git a/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/deep_copy.php b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/deep_copy.php new file mode 100644 index 000000000..55dcc9261 --- /dev/null +++ b/src/bb-vendor/myclabs/deep-copy/src/DeepCopy/deep_copy.php @@ -0,0 +1,20 @@ +copy($value); + } +} diff --git a/src/bb-vendor/paragonie/random_compat/LICENSE b/src/bb-vendor/paragonie/random_compat/LICENSE new file mode 100644 index 000000000..45c7017df --- /dev/null +++ b/src/bb-vendor/paragonie/random_compat/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Paragon Initiative Enterprises + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/src/bb-vendor/paragonie/random_compat/build-phar.sh b/src/bb-vendor/paragonie/random_compat/build-phar.sh new file mode 100755 index 000000000..b4a5ba31c --- /dev/null +++ b/src/bb-vendor/paragonie/random_compat/build-phar.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash + +basedir=$( dirname $( readlink -f ${BASH_SOURCE[0]} ) ) + +php -dphar.readonly=0 "$basedir/other/build_phar.php" $* \ No newline at end of file diff --git a/src/bb-vendor/paragonie/random_compat/composer.json b/src/bb-vendor/paragonie/random_compat/composer.json new file mode 100644 index 000000000..1fa8de9f1 --- /dev/null +++ b/src/bb-vendor/paragonie/random_compat/composer.json @@ -0,0 +1,34 @@ +{ + "name": "paragonie/random_compat", + "description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7", + "keywords": [ + "csprng", + "random", + "polyfill", + "pseudorandom" + ], + "license": "MIT", + "type": "library", + "authors": [ + { + "name": "Paragon Initiative Enterprises", + "email": "security@paragonie.com", + "homepage": "https://paragonie.com" + } + ], + "support": { + "issues": "https://github.com/paragonie/random_compat/issues", + "email": "info@paragonie.com", + "source": "https://github.com/paragonie/random_compat" + }, + "require": { + "php": "^7" + }, + "require-dev": { + "vimeo/psalm": "^1", + "phpunit/phpunit": "4.*|5.*" + }, + "suggest": { + "ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes." + } +} diff --git a/src/bb-vendor/paragonie/random_compat/dist/random_compat.phar.pubkey b/src/bb-vendor/paragonie/random_compat/dist/random_compat.phar.pubkey new file mode 100644 index 000000000..eb50ebfcd --- /dev/null +++ b/src/bb-vendor/paragonie/random_compat/dist/random_compat.phar.pubkey @@ -0,0 +1,5 @@ +-----BEGIN PUBLIC KEY----- +MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEEd+wCqJDrx5B4OldM0dQE0ZMX+lx1ZWm +pui0SUqD4G29L3NGsz9UhJ/0HjBdbnkhIK5xviT0X5vtjacF6ajgcCArbTB+ds+p ++h7Q084NuSuIpNb6YPfoUFgC/CL9kAoc +-----END PUBLIC KEY----- diff --git a/src/bb-vendor/paragonie/random_compat/dist/random_compat.phar.pubkey.asc b/src/bb-vendor/paragonie/random_compat/dist/random_compat.phar.pubkey.asc new file mode 100644 index 000000000..6a1d7f300 --- /dev/null +++ b/src/bb-vendor/paragonie/random_compat/dist/random_compat.phar.pubkey.asc @@ -0,0 +1,11 @@ +-----BEGIN PGP SIGNATURE----- +Version: GnuPG v2.0.22 (MingW32) + +iQEcBAABAgAGBQJWtW1hAAoJEGuXocKCZATaJf0H+wbZGgskK1dcRTsuVJl9IWip +QwGw/qIKI280SD6/ckoUMxKDCJiFuPR14zmqnS36k7N5UNPnpdTJTS8T11jttSpg +1LCmgpbEIpgaTah+cELDqFCav99fS+bEiAL5lWDAHBTE/XPjGVCqeehyPYref4IW +NDBIEsvnHPHPLsn6X5jq4+Yj5oUixgxaMPiR+bcO4Sh+RzOVB6i2D0upWfRXBFXA +NNnsg9/zjvoC7ZW73y9uSH+dPJTt/Vgfeiv52/v41XliyzbUyLalf02GNPY+9goV +JHG1ulEEBJOCiUD9cE1PUIJwHA/HqyhHIvV350YoEFiHl8iSwm7SiZu5kPjaq74= +=B6+8 +-----END PGP SIGNATURE----- diff --git a/src/bb-vendor/paragonie/random_compat/lib/random.php b/src/bb-vendor/paragonie/random_compat/lib/random.php new file mode 100644 index 000000000..c7731a56f --- /dev/null +++ b/src/bb-vendor/paragonie/random_compat/lib/random.php @@ -0,0 +1,32 @@ +buildFromDirectory(dirname(__DIR__).'/lib'); +rename( + dirname(__DIR__).'/lib/index.php', + dirname(__DIR__).'/lib/random.php' +); + +/** + * If we pass an (optional) path to a private key as a second argument, we will + * sign the Phar with OpenSSL. + * + * If you leave this out, it will produce an unsigned .phar! + */ +if ($argc > 1) { + if (!@is_readable($argv[1])) { + echo 'Could not read the private key file:', $argv[1], "\n"; + exit(255); + } + $pkeyFile = file_get_contents($argv[1]); + + $private = openssl_get_privatekey($pkeyFile); + if ($private !== false) { + $pkey = ''; + openssl_pkey_export($private, $pkey); + $phar->setSignatureAlgorithm(Phar::OPENSSL, $pkey); + + /** + * Save the corresponding public key to the file + */ + if (!@is_readable($dist.'/random_compat.phar.pubkey')) { + $details = openssl_pkey_get_details($private); + file_put_contents( + $dist.'/random_compat.phar.pubkey', + $details['key'] + ); + } + } else { + echo 'An error occurred reading the private key from OpenSSL.', "\n"; + exit(255); + } +} diff --git a/src/bb-vendor/paragonie/random_compat/psalm-autoload.php b/src/bb-vendor/paragonie/random_compat/psalm-autoload.php new file mode 100644 index 000000000..d71d1b818 --- /dev/null +++ b/src/bb-vendor/paragonie/random_compat/psalm-autoload.php @@ -0,0 +1,9 @@ + + + + + + + + + + + + + + + diff --git a/src/bb-vendor/phpmailer/phpmailer/VERSION b/src/bb-vendor/phpmailer/phpmailer/VERSION new file mode 100644 index 000000000..3af67b5cb --- /dev/null +++ b/src/bb-vendor/phpmailer/phpmailer/VERSION @@ -0,0 +1 @@ +6.1.6 \ No newline at end of file diff --git a/src/bb-vendor/phpmailer/phpmailer/language/phpmailer.lang-sv.php b/src/bb-vendor/phpmailer/phpmailer/language/phpmailer.lang-sv.php new file mode 100644 index 000000000..4408e63eb --- /dev/null +++ b/src/bb-vendor/phpmailer/phpmailer/language/phpmailer.lang-sv.php @@ -0,0 +1,26 @@ + + */ + +$PHPMAILER_LANG['authenticate'] = 'SMTP fel: Kunde inte autentisera.'; +$PHPMAILER_LANG['connect_host'] = 'SMTP fel: Kunde inte ansluta till SMTP-server.'; +$PHPMAILER_LANG['data_not_accepted'] = 'SMTP fel: Data accepterades inte.'; +//$PHPMAILER_LANG['empty_message'] = 'Message body empty'; +$PHPMAILER_LANG['encoding'] = 'Okänt encode-format: '; +$PHPMAILER_LANG['execute'] = 'Kunde inte köra: '; +$PHPMAILER_LANG['file_access'] = 'Ingen åtkomst till fil: '; +$PHPMAILER_LANG['file_open'] = 'Fil fel: Kunde inte öppna fil: '; +$PHPMAILER_LANG['from_failed'] = 'Följande avsändaradress är felaktig: '; +$PHPMAILER_LANG['instantiate'] = 'Kunde inte initiera e-postfunktion.'; +$PHPMAILER_LANG['invalid_address'] = 'Felaktig adress: '; +$PHPMAILER_LANG['provide_address'] = 'Du måste ange minst en mottagares e-postadress.'; +$PHPMAILER_LANG['mailer_not_supported'] = ' mailer stöds inte.'; +$PHPMAILER_LANG['recipients_failed'] = 'SMTP fel: Följande mottagare är felaktig: '; +$PHPMAILER_LANG['signing'] = 'Signerings fel: '; +$PHPMAILER_LANG['smtp_connect_failed'] = 'SMTP Connect() misslyckades.'; +$PHPMAILER_LANG['smtp_error'] = 'SMTP server fel: '; +$PHPMAILER_LANG['variable_set'] = 'Kunde inte definiera eller återställa variabel: '; +$PHPMAILER_LANG['extension_missing'] = 'Tillägg ej tillgängligt: '; diff --git a/src/bb-vendor/phpmailer/phpmailer/src/PHPMailer.php b/src/bb-vendor/phpmailer/phpmailer/src/PHPMailer.php new file mode 100644 index 000000000..ed14d7c7a --- /dev/null +++ b/src/bb-vendor/phpmailer/phpmailer/src/PHPMailer.php @@ -0,0 +1,4834 @@ + + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + * @copyright 2012 - 2019 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ + +namespace PHPMailer\PHPMailer; + +/** + * PHPMailer - PHP email creation and transport class. + * + * @author Marcus Bointon (Synchro/coolbru) + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + */ +class PHPMailer +{ + const CHARSET_ASCII = 'us-ascii'; + const CHARSET_ISO88591 = 'iso-8859-1'; + const CHARSET_UTF8 = 'utf-8'; + + const CONTENT_TYPE_PLAINTEXT = 'text/plain'; + const CONTENT_TYPE_TEXT_CALENDAR = 'text/calendar'; + const CONTENT_TYPE_TEXT_HTML = 'text/html'; + const CONTENT_TYPE_MULTIPART_ALTERNATIVE = 'multipart/alternative'; + const CONTENT_TYPE_MULTIPART_MIXED = 'multipart/mixed'; + const CONTENT_TYPE_MULTIPART_RELATED = 'multipart/related'; + + const ENCODING_7BIT = '7bit'; + const ENCODING_8BIT = '8bit'; + const ENCODING_BASE64 = 'base64'; + const ENCODING_BINARY = 'binary'; + const ENCODING_QUOTED_PRINTABLE = 'quoted-printable'; + + const ENCRYPTION_STARTTLS = 'tls'; + const ENCRYPTION_SMTPS = 'ssl'; + + const ICAL_METHOD_REQUEST = 'REQUEST'; + const ICAL_METHOD_PUBLISH = 'PUBLISH'; + const ICAL_METHOD_REPLY = 'REPLY'; + const ICAL_METHOD_ADD = 'ADD'; + const ICAL_METHOD_CANCEL = 'CANCEL'; + const ICAL_METHOD_REFRESH = 'REFRESH'; + const ICAL_METHOD_COUNTER = 'COUNTER'; + const ICAL_METHOD_DECLINECOUNTER = 'DECLINECOUNTER'; + + /** + * Email priority. + * Options: null (default), 1 = High, 3 = Normal, 5 = low. + * When null, the header is not set at all. + * + * @var int|null + */ + public $Priority; + + /** + * The character set of the message. + * + * @var string + */ + public $CharSet = self::CHARSET_ISO88591; + + /** + * The MIME Content-type of the message. + * + * @var string + */ + public $ContentType = self::CONTENT_TYPE_PLAINTEXT; + + /** + * The message encoding. + * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable". + * + * @var string + */ + public $Encoding = self::ENCODING_8BIT; + + /** + * Holds the most recent mailer error message. + * + * @var string + */ + public $ErrorInfo = ''; + + /** + * The From email address for the message. + * + * @var string + */ + public $From = 'root@localhost'; + + /** + * The From name of the message. + * + * @var string + */ + public $FromName = 'Root User'; + + /** + * The envelope sender of the message. + * This will usually be turned into a Return-Path header by the receiver, + * and is the address that bounces will be sent to. + * If not empty, will be passed via `-f` to sendmail or as the 'MAIL FROM' value over SMTP. + * + * @var string + */ + public $Sender = ''; + + /** + * The Subject of the message. + * + * @var string + */ + public $Subject = ''; + + /** + * An HTML or plain text message body. + * If HTML then call isHTML(true). + * + * @var string + */ + public $Body = ''; + + /** + * The plain-text message body. + * This body can be read by mail clients that do not have HTML email + * capability such as mutt & Eudora. + * Clients that can read HTML will view the normal Body. + * + * @var string + */ + public $AltBody = ''; + + /** + * An iCal message part body. + * Only supported in simple alt or alt_inline message types + * To generate iCal event structures, use classes like EasyPeasyICS or iCalcreator. + * + * @see http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/ + * @see http://kigkonsult.se/iCalcreator/ + * + * @var string + */ + public $Ical = ''; + + /** + * Value-array of "method" in Contenttype header "text/calendar" + * + * @var string[] + */ + protected static $IcalMethods = [ + self::ICAL_METHOD_REQUEST, + self::ICAL_METHOD_PUBLISH, + self::ICAL_METHOD_REPLY, + self::ICAL_METHOD_ADD, + self::ICAL_METHOD_CANCEL, + self::ICAL_METHOD_REFRESH, + self::ICAL_METHOD_COUNTER, + self::ICAL_METHOD_DECLINECOUNTER, + ]; + + /** + * The complete compiled MIME message body. + * + * @var string + */ + protected $MIMEBody = ''; + + /** + * The complete compiled MIME message headers. + * + * @var string + */ + protected $MIMEHeader = ''; + + /** + * Extra headers that createHeader() doesn't fold in. + * + * @var string + */ + protected $mailHeader = ''; + + /** + * Word-wrap the message body to this number of chars. + * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance. + * + * @see static::STD_LINE_LENGTH + * + * @var int + */ + public $WordWrap = 0; + + /** + * Which method to use to send mail. + * Options: "mail", "sendmail", or "smtp". + * + * @var string + */ + public $Mailer = 'mail'; + + /** + * The path to the sendmail program. + * + * @var string + */ + public $Sendmail = '/usr/sbin/sendmail'; + + /** + * Whether mail() uses a fully sendmail-compatible MTA. + * One which supports sendmail's "-oi -f" options. + * + * @var bool + */ + public $UseSendmailOptions = true; + + /** + * The email address that a reading confirmation should be sent to, also known as read receipt. + * + * @var string + */ + public $ConfirmReadingTo = ''; + + /** + * The hostname to use in the Message-ID header and as default HELO string. + * If empty, PHPMailer attempts to find one with, in order, + * $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value + * 'localhost.localdomain'. + * + * @see PHPMailer::$Helo + * + * @var string + */ + public $Hostname = ''; + + /** + * An ID to be used in the Message-ID header. + * If empty, a unique id will be generated. + * You can set your own, but it must be in the format "", + * as defined in RFC5322 section 3.6.4 or it will be ignored. + * + * @see https://tools.ietf.org/html/rfc5322#section-3.6.4 + * + * @var string + */ + public $MessageID = ''; + + /** + * The message Date to be used in the Date header. + * If empty, the current date will be added. + * + * @var string + */ + public $MessageDate = ''; + + /** + * SMTP hosts. + * Either a single hostname or multiple semicolon-delimited hostnames. + * You can also specify a different port + * for each host by using this format: [hostname:port] + * (e.g. "smtp1.example.com:25;smtp2.example.com"). + * You can also specify encryption type, for example: + * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465"). + * Hosts will be tried in order. + * + * @var string + */ + public $Host = 'localhost'; + + /** + * The default SMTP server port. + * + * @var int + */ + public $Port = 25; + + /** + * The SMTP HELO/EHLO name used for the SMTP connection. + * Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find + * one with the same method described above for $Hostname. + * + * @see PHPMailer::$Hostname + * + * @var string + */ + public $Helo = ''; + + /** + * What kind of encryption to use on the SMTP connection. + * Options: '', static::ENCRYPTION_STARTTLS, or static::ENCRYPTION_SMTPS. + * + * @var string + */ + public $SMTPSecure = ''; + + /** + * Whether to enable TLS encryption automatically if a server supports it, + * even if `SMTPSecure` is not set to 'tls'. + * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid. + * + * @var bool + */ + public $SMTPAutoTLS = true; + + /** + * Whether to use SMTP authentication. + * Uses the Username and Password properties. + * + * @see PHPMailer::$Username + * @see PHPMailer::$Password + * + * @var bool + */ + public $SMTPAuth = false; + + /** + * Options array passed to stream_context_create when connecting via SMTP. + * + * @var array + */ + public $SMTPOptions = []; + + /** + * SMTP username. + * + * @var string + */ + public $Username = ''; + + /** + * SMTP password. + * + * @var string + */ + public $Password = ''; + + /** + * SMTP auth type. + * Options are CRAM-MD5, LOGIN, PLAIN, XOAUTH2, attempted in that order if not specified. + * + * @var string + */ + public $AuthType = ''; + + /** + * An instance of the PHPMailer OAuth class. + * + * @var OAuth + */ + protected $oauth; + + /** + * The SMTP server timeout in seconds. + * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2. + * + * @var int + */ + public $Timeout = 300; + + /** + * Comma separated list of DSN notifications + * 'NEVER' under no circumstances a DSN must be returned to the sender. + * If you use NEVER all other notifications will be ignored. + * 'SUCCESS' will notify you when your mail has arrived at its destination. + * 'FAILURE' will arrive if an error occurred during delivery. + * 'DELAY' will notify you if there is an unusual delay in delivery, but the actual + * delivery's outcome (success or failure) is not yet decided. + * + * @see https://tools.ietf.org/html/rfc3461 See section 4.1 for more information about NOTIFY + */ + public $dsn = ''; + + /** + * SMTP class debug output mode. + * Debug output level. + * Options: + * * SMTP::DEBUG_OFF: No output + * * SMTP::DEBUG_CLIENT: Client messages + * * SMTP::DEBUG_SERVER: Client and server messages + * * SMTP::DEBUG_CONNECTION: As SERVER plus connection status + * * SMTP::DEBUG_LOWLEVEL: Noisy, low-level data output, rarely needed + * + * @see SMTP::$do_debug + * + * @var int + */ + public $SMTPDebug = 0; + + /** + * How to handle debug output. + * Options: + * * `echo` Output plain-text as-is, appropriate for CLI + * * `html` Output escaped, line breaks converted to `
    `, appropriate for browser output + * * `error_log` Output to error log as configured in php.ini + * By default PHPMailer will use `echo` if run from a `cli` or `cli-server` SAPI, `html` otherwise. + * Alternatively, you can provide a callable expecting two params: a message string and the debug level: + * + * ```php + * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";}; + * ``` + * + * Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug` + * level output is used: + * + * ```php + * $mail->Debugoutput = new myPsr3Logger; + * ``` + * + * @see SMTP::$Debugoutput + * + * @var string|callable|\Psr\Log\LoggerInterface + */ + public $Debugoutput = 'echo'; + + /** + * Whether to keep SMTP connection open after each message. + * If this is set to true then to close the connection + * requires an explicit call to smtpClose(). + * + * @var bool + */ + public $SMTPKeepAlive = false; + + /** + * Whether to split multiple to addresses into multiple messages + * or send them all in one message. + * Only supported in `mail` and `sendmail` transports, not in SMTP. + * + * @var bool + */ + public $SingleTo = false; + + /** + * Storage for addresses when SingleTo is enabled. + * + * @var array + */ + protected $SingleToArray = []; + + /** + * Whether to generate VERP addresses on send. + * Only applicable when sending via SMTP. + * + * @see https://en.wikipedia.org/wiki/Variable_envelope_return_path + * @see http://www.postfix.org/VERP_README.html Postfix VERP info + * + * @var bool + */ + public $do_verp = false; + + /** + * Whether to allow sending messages with an empty body. + * + * @var bool + */ + public $AllowEmpty = false; + + /** + * DKIM selector. + * + * @var string + */ + public $DKIM_selector = ''; + + /** + * DKIM Identity. + * Usually the email address used as the source of the email. + * + * @var string + */ + public $DKIM_identity = ''; + + /** + * DKIM passphrase. + * Used if your key is encrypted. + * + * @var string + */ + public $DKIM_passphrase = ''; + + /** + * DKIM signing domain name. + * + * @example 'example.com' + * + * @var string + */ + public $DKIM_domain = ''; + + /** + * DKIM Copy header field values for diagnostic use. + * + * @var bool + */ + public $DKIM_copyHeaderFields = true; + + /** + * DKIM Extra signing headers. + * + * @example ['List-Unsubscribe', 'List-Help'] + * + * @var array + */ + public $DKIM_extraHeaders = []; + + /** + * DKIM private key file path. + * + * @var string + */ + public $DKIM_private = ''; + + /** + * DKIM private key string. + * + * If set, takes precedence over `$DKIM_private`. + * + * @var string + */ + public $DKIM_private_string = ''; + + /** + * Callback Action function name. + * + * The function that handles the result of the send email action. + * It is called out by send() for each email sent. + * + * Value can be any php callable: http://www.php.net/is_callable + * + * Parameters: + * bool $result result of the send action + * array $to email addresses of the recipients + * array $cc cc email addresses + * array $bcc bcc email addresses + * string $subject the subject + * string $body the email body + * string $from email address of sender + * string $extra extra information of possible use + * "smtp_transaction_id' => last smtp transaction id + * + * @var string + */ + public $action_function = ''; + + /** + * What to put in the X-Mailer header. + * Options: An empty string for PHPMailer default, whitespace/null for none, or a string to use. + * + * @var string|null + */ + public $XMailer = ''; + + /** + * Which validator to use by default when validating email addresses. + * May be a callable to inject your own validator, but there are several built-in validators. + * The default validator uses PHP's FILTER_VALIDATE_EMAIL filter_var option. + * + * @see PHPMailer::validateAddress() + * + * @var string|callable + */ + public static $validator = 'php'; + + /** + * An instance of the SMTP sender class. + * + * @var SMTP + */ + protected $smtp; + + /** + * The array of 'to' names and addresses. + * + * @var array + */ + protected $to = []; + + /** + * The array of 'cc' names and addresses. + * + * @var array + */ + protected $cc = []; + + /** + * The array of 'bcc' names and addresses. + * + * @var array + */ + protected $bcc = []; + + /** + * The array of reply-to names and addresses. + * + * @var array + */ + protected $ReplyTo = []; + + /** + * An array of all kinds of addresses. + * Includes all of $to, $cc, $bcc. + * + * @see PHPMailer::$to + * @see PHPMailer::$cc + * @see PHPMailer::$bcc + * + * @var array + */ + protected $all_recipients = []; + + /** + * An array of names and addresses queued for validation. + * In send(), valid and non duplicate entries are moved to $all_recipients + * and one of $to, $cc, or $bcc. + * This array is used only for addresses with IDN. + * + * @see PHPMailer::$to + * @see PHPMailer::$cc + * @see PHPMailer::$bcc + * @see PHPMailer::$all_recipients + * + * @var array + */ + protected $RecipientsQueue = []; + + /** + * An array of reply-to names and addresses queued for validation. + * In send(), valid and non duplicate entries are moved to $ReplyTo. + * This array is used only for addresses with IDN. + * + * @see PHPMailer::$ReplyTo + * + * @var array + */ + protected $ReplyToQueue = []; + + /** + * The array of attachments. + * + * @var array + */ + protected $attachment = []; + + /** + * The array of custom headers. + * + * @var array + */ + protected $CustomHeader = []; + + /** + * The most recent Message-ID (including angular brackets). + * + * @var string + */ + protected $lastMessageID = ''; + + /** + * The message's MIME type. + * + * @var string + */ + protected $message_type = ''; + + /** + * The array of MIME boundary strings. + * + * @var array + */ + protected $boundary = []; + + /** + * The array of available languages. + * + * @var array + */ + protected $language = []; + + /** + * The number of errors encountered. + * + * @var int + */ + protected $error_count = 0; + + /** + * The S/MIME certificate file path. + * + * @var string + */ + protected $sign_cert_file = ''; + + /** + * The S/MIME key file path. + * + * @var string + */ + protected $sign_key_file = ''; + + /** + * The optional S/MIME extra certificates ("CA Chain") file path. + * + * @var string + */ + protected $sign_extracerts_file = ''; + + /** + * The S/MIME password for the key. + * Used only if the key is encrypted. + * + * @var string + */ + protected $sign_key_pass = ''; + + /** + * Whether to throw exceptions for errors. + * + * @var bool + */ + protected $exceptions = false; + + /** + * Unique ID used for message ID and boundaries. + * + * @var string + */ + protected $uniqueid = ''; + + /** + * The PHPMailer Version number. + * + * @var string + */ + const VERSION = '6.1.6'; + + /** + * Error severity: message only, continue processing. + * + * @var int + */ + const STOP_MESSAGE = 0; + + /** + * Error severity: message, likely ok to continue processing. + * + * @var int + */ + const STOP_CONTINUE = 1; + + /** + * Error severity: message, plus full stop, critical error reached. + * + * @var int + */ + const STOP_CRITICAL = 2; + + /** + * The SMTP standard CRLF line break. + * If you want to change line break format, change static::$LE, not this. + */ + const CRLF = "\r\n"; + + /** + * "Folding White Space" a white space string used for line folding. + */ + const FWS = ' '; + + /** + * SMTP RFC standard line ending; Carriage Return, Line Feed. + * + * @var string + */ + protected static $LE = self::CRLF; + + /** + * The maximum line length supported by mail(). + * + * Background: mail() will sometimes corrupt messages + * with headers headers longer than 65 chars, see #818. + * + * @var int + */ + const MAIL_MAX_LINE_LENGTH = 63; + + /** + * The maximum line length allowed by RFC 2822 section 2.1.1. + * + * @var int + */ + const MAX_LINE_LENGTH = 998; + + /** + * The lower maximum line length allowed by RFC 2822 section 2.1.1. + * This length does NOT include the line break + * 76 means that lines will be 77 or 78 chars depending on whether + * the line break format is LF or CRLF; both are valid. + * + * @var int + */ + const STD_LINE_LENGTH = 76; + + /** + * Constructor. + * + * @param bool $exceptions Should we throw external exceptions? + */ + public function __construct($exceptions = null) + { + if (null !== $exceptions) { + $this->exceptions = (bool) $exceptions; + } + //Pick an appropriate debug output format automatically + $this->Debugoutput = (strpos(PHP_SAPI, 'cli') !== false ? 'echo' : 'html'); + } + + /** + * Destructor. + */ + public function __destruct() + { + //Close any open SMTP connection nicely + $this->smtpClose(); + } + + /** + * Call mail() in a safe_mode-aware fashion. + * Also, unless sendmail_path points to sendmail (or something that + * claims to be sendmail), don't pass params (not a perfect fix, + * but it will do). + * + * @param string $to To + * @param string $subject Subject + * @param string $body Message Body + * @param string $header Additional Header(s) + * @param string|null $params Params + * + * @return bool + */ + private function mailPassthru($to, $subject, $body, $header, $params) + { + //Check overloading of mail function to avoid double-encoding + if (ini_get('mbstring.func_overload') & 1) { + $subject = $this->secureHeader($subject); + } else { + $subject = $this->encodeHeader($this->secureHeader($subject)); + } + //Calling mail() with null params breaks + if (!$this->UseSendmailOptions || null === $params) { + $result = @mail($to, $subject, $body, $header); + } else { + $result = @mail($to, $subject, $body, $header, $params); + } + + return $result; + } + + /** + * Output debugging info via user-defined method. + * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug). + * + * @see PHPMailer::$Debugoutput + * @see PHPMailer::$SMTPDebug + * + * @param string $str + */ + protected function edebug($str) + { + if ($this->SMTPDebug <= 0) { + return; + } + //Is this a PSR-3 logger? + if ($this->Debugoutput instanceof \Psr\Log\LoggerInterface) { + $this->Debugoutput->debug($str); + + return; + } + //Avoid clash with built-in function names + if (is_callable($this->Debugoutput) && !in_array($this->Debugoutput, ['error_log', 'html', 'echo'])) { + call_user_func($this->Debugoutput, $str, $this->SMTPDebug); + + return; + } + switch ($this->Debugoutput) { + case 'error_log': + //Don't output, just log + error_log($str); + break; + case 'html': + //Cleans up output a bit for a better looking, HTML-safe output + echo htmlentities( + preg_replace('/[\r\n]+/', '', $str), + ENT_QUOTES, + 'UTF-8' + ), "
    \n"; + break; + case 'echo': + default: + //Normalize line breaks + $str = preg_replace('/\r\n|\r/m', "\n", $str); + echo gmdate('Y-m-d H:i:s'), + "\t", + //Trim trailing space + trim( + //Indent for readability, except for trailing break + str_replace( + "\n", + "\n \t ", + trim($str) + ) + ), + "\n"; + } + } + + /** + * Sets message type to HTML or plain. + * + * @param bool $isHtml True for HTML mode + */ + public function isHTML($isHtml = true) + { + if ($isHtml) { + $this->ContentType = static::CONTENT_TYPE_TEXT_HTML; + } else { + $this->ContentType = static::CONTENT_TYPE_PLAINTEXT; + } + } + + /** + * Send messages using SMTP. + */ + public function isSMTP() + { + $this->Mailer = 'smtp'; + } + + /** + * Send messages using PHP's mail() function. + */ + public function isMail() + { + $this->Mailer = 'mail'; + } + + /** + * Send messages using $Sendmail. + */ + public function isSendmail() + { + $ini_sendmail_path = ini_get('sendmail_path'); + + if (false === stripos($ini_sendmail_path, 'sendmail')) { + $this->Sendmail = '/usr/sbin/sendmail'; + } else { + $this->Sendmail = $ini_sendmail_path; + } + $this->Mailer = 'sendmail'; + } + + /** + * Send messages using qmail. + */ + public function isQmail() + { + $ini_sendmail_path = ini_get('sendmail_path'); + + if (false === stripos($ini_sendmail_path, 'qmail')) { + $this->Sendmail = '/var/qmail/bin/qmail-inject'; + } else { + $this->Sendmail = $ini_sendmail_path; + } + $this->Mailer = 'qmail'; + } + + /** + * Add a "To" address. + * + * @param string $address The email address to send to + * @param string $name + * + * @throws Exception + * + * @return bool true on success, false if address already used or invalid in some way + */ + public function addAddress($address, $name = '') + { + return $this->addOrEnqueueAnAddress('to', $address, $name); + } + + /** + * Add a "CC" address. + * + * @param string $address The email address to send to + * @param string $name + * + * @throws Exception + * + * @return bool true on success, false if address already used or invalid in some way + */ + public function addCC($address, $name = '') + { + return $this->addOrEnqueueAnAddress('cc', $address, $name); + } + + /** + * Add a "BCC" address. + * + * @param string $address The email address to send to + * @param string $name + * + * @throws Exception + * + * @return bool true on success, false if address already used or invalid in some way + */ + public function addBCC($address, $name = '') + { + return $this->addOrEnqueueAnAddress('bcc', $address, $name); + } + + /** + * Add a "Reply-To" address. + * + * @param string $address The email address to reply to + * @param string $name + * + * @throws Exception + * + * @return bool true on success, false if address already used or invalid in some way + */ + public function addReplyTo($address, $name = '') + { + return $this->addOrEnqueueAnAddress('Reply-To', $address, $name); + } + + /** + * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer + * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still + * be modified after calling this function), addition of such addresses is delayed until send(). + * Addresses that have been added already return false, but do not throw exceptions. + * + * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo' + * @param string $address The email address to send, resp. to reply to + * @param string $name + * + * @throws Exception + * + * @return bool true on success, false if address already used or invalid in some way + */ + protected function addOrEnqueueAnAddress($kind, $address, $name) + { + $address = trim($address); + $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim + $pos = strrpos($address, '@'); + if (false === $pos) { + // At-sign is missing. + $error_message = sprintf( + '%s (%s): %s', + $this->lang('invalid_address'), + $kind, + $address + ); + $this->setError($error_message); + $this->edebug($error_message); + if ($this->exceptions) { + throw new Exception($error_message); + } + + return false; + } + $params = [$kind, $address, $name]; + // Enqueue addresses with IDN until we know the PHPMailer::$CharSet. + if (static::idnSupported() && $this->has8bitChars(substr($address, ++$pos))) { + if ('Reply-To' !== $kind) { + if (!array_key_exists($address, $this->RecipientsQueue)) { + $this->RecipientsQueue[$address] = $params; + + return true; + } + } elseif (!array_key_exists($address, $this->ReplyToQueue)) { + $this->ReplyToQueue[$address] = $params; + + return true; + } + + return false; + } + + // Immediately add standard addresses without IDN. + return call_user_func_array([$this, 'addAnAddress'], $params); + } + + /** + * Add an address to one of the recipient arrays or to the ReplyTo array. + * Addresses that have been added already return false, but do not throw exceptions. + * + * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo' + * @param string $address The email address to send, resp. to reply to + * @param string $name + * + * @throws Exception + * + * @return bool true on success, false if address already used or invalid in some way + */ + protected function addAnAddress($kind, $address, $name = '') + { + if (!in_array($kind, ['to', 'cc', 'bcc', 'Reply-To'])) { + $error_message = sprintf( + '%s: %s', + $this->lang('Invalid recipient kind'), + $kind + ); + $this->setError($error_message); + $this->edebug($error_message); + if ($this->exceptions) { + throw new Exception($error_message); + } + + return false; + } + if (!static::validateAddress($address)) { + $error_message = sprintf( + '%s (%s): %s', + $this->lang('invalid_address'), + $kind, + $address + ); + $this->setError($error_message); + $this->edebug($error_message); + if ($this->exceptions) { + throw new Exception($error_message); + } + + return false; + } + if ('Reply-To' !== $kind) { + if (!array_key_exists(strtolower($address), $this->all_recipients)) { + $this->{$kind}[] = [$address, $name]; + $this->all_recipients[strtolower($address)] = true; + + return true; + } + } elseif (!array_key_exists(strtolower($address), $this->ReplyTo)) { + $this->ReplyTo[strtolower($address)] = [$address, $name]; + + return true; + } + + return false; + } + + /** + * Parse and validate a string containing one or more RFC822-style comma-separated email addresses + * of the form "display name

    " into an array of name/address pairs. + * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available. + * Note that quotes in the name part are removed. + * + * @see http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation + * + * @param string $addrstr The address list string + * @param bool $useimap Whether to use the IMAP extension to parse the list + * + * @return array + */ + public static function parseAddresses($addrstr, $useimap = true) + { + $addresses = []; + if ($useimap && function_exists('imap_rfc822_parse_adrlist')) { + //Use this built-in parser if it's available + $list = imap_rfc822_parse_adrlist($addrstr, ''); + foreach ($list as $address) { + if (('.SYNTAX-ERROR.' !== $address->host) && static::validateAddress( + $address->mailbox . '@' . $address->host + )) { + $addresses[] = [ + 'name' => (property_exists($address, 'personal') ? $address->personal : ''), + 'address' => $address->mailbox . '@' . $address->host, + ]; + } + } + } else { + //Use this simpler parser + $list = explode(',', $addrstr); + foreach ($list as $address) { + $address = trim($address); + //Is there a separate name part? + if (strpos($address, '<') === false) { + //No separate name, just use the whole thing + if (static::validateAddress($address)) { + $addresses[] = [ + 'name' => '', + 'address' => $address, + ]; + } + } else { + list($name, $email) = explode('<', $address); + $email = trim(str_replace('>', '', $email)); + if (static::validateAddress($email)) { + $addresses[] = [ + 'name' => trim(str_replace(['"', "'"], '', $name)), + 'address' => $email, + ]; + } + } + } + } + + return $addresses; + } + + /** + * Set the From and FromName properties. + * + * @param string $address + * @param string $name + * @param bool $auto Whether to also set the Sender address, defaults to true + * + * @throws Exception + * + * @return bool + */ + public function setFrom($address, $name = '', $auto = true) + { + $address = trim($address); + $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim + // Don't validate now addresses with IDN. Will be done in send(). + $pos = strrpos($address, '@'); + if ((false === $pos) + || ((!$this->has8bitChars(substr($address, ++$pos)) || !static::idnSupported()) + && !static::validateAddress($address)) + ) { + $error_message = sprintf( + '%s (From): %s', + $this->lang('invalid_address'), + $address + ); + $this->setError($error_message); + $this->edebug($error_message); + if ($this->exceptions) { + throw new Exception($error_message); + } + + return false; + } + $this->From = $address; + $this->FromName = $name; + if ($auto && empty($this->Sender)) { + $this->Sender = $address; + } + + return true; + } + + /** + * Return the Message-ID header of the last email. + * Technically this is the value from the last time the headers were created, + * but it's also the message ID of the last sent message except in + * pathological cases. + * + * @return string + */ + public function getLastMessageID() + { + return $this->lastMessageID; + } + + /** + * Check that a string looks like an email address. + * Validation patterns supported: + * * `auto` Pick best pattern automatically; + * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0; + * * `pcre` Use old PCRE implementation; + * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL; + * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements. + * * `noregex` Don't use a regex: super fast, really dumb. + * Alternatively you may pass in a callable to inject your own validator, for example: + * + * ```php + * PHPMailer::validateAddress('user@example.com', function($address) { + * return (strpos($address, '@') !== false); + * }); + * ``` + * + * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator. + * + * @param string $address The email address to check + * @param string|callable $patternselect Which pattern to use + * + * @return bool + */ + public static function validateAddress($address, $patternselect = null) + { + if (null === $patternselect) { + $patternselect = static::$validator; + } + if (is_callable($patternselect)) { + return $patternselect($address); + } + //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321 + if (strpos($address, "\n") !== false || strpos($address, "\r") !== false) { + return false; + } + switch ($patternselect) { + case 'pcre': //Kept for BC + case 'pcre8': + /* + * A more complex and more permissive version of the RFC5322 regex on which FILTER_VALIDATE_EMAIL + * is based. + * In addition to the addresses allowed by filter_var, also permits: + * * dotless domains: `a@b` + * * comments: `1234 @ local(blah) .machine .example` + * * quoted elements: `'"test blah"@example.org'` + * * numeric TLDs: `a@b.123` + * * unbracketed IPv4 literals: `a@192.168.0.1` + * * IPv6 literals: 'first.last@[IPv6:a1::]' + * Not all of these will necessarily work for sending! + * + * @see http://squiloople.com/2009/12/20/email-address-validation/ + * @copyright 2009-2010 Michael Rushton + * Feel free to use and redistribute this code. But please keep this copyright notice. + */ + return (bool) preg_match( + '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' . + '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' . + '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' . + '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' . + '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' . + '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' . + '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' . + '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' . + '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', + $address + ); + case 'html5': + /* + * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements. + * + * @see http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email) + */ + return (bool) preg_match( + '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' . + '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD', + $address + ); + case 'php': + default: + return filter_var($address, FILTER_VALIDATE_EMAIL) !== false; + } + } + + /** + * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the + * `intl` and `mbstring` PHP extensions. + * + * @return bool `true` if required functions for IDN support are present + */ + public static function idnSupported() + { + return function_exists('idn_to_ascii') && function_exists('mb_convert_encoding'); + } + + /** + * Converts IDN in given email address to its ASCII form, also known as punycode, if possible. + * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet. + * This function silently returns unmodified address if: + * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form) + * - Conversion to punycode is impossible (e.g. required PHP functions are not available) + * or fails for any reason (e.g. domain contains characters not allowed in an IDN). + * + * @see PHPMailer::$CharSet + * + * @param string $address The email address to convert + * + * @return string The encoded address in ASCII form + */ + public function punyencodeAddress($address) + { + // Verify we have required functions, CharSet, and at-sign. + $pos = strrpos($address, '@'); + if (!empty($this->CharSet) && + false !== $pos && + static::idnSupported() + ) { + $domain = substr($address, ++$pos); + // Verify CharSet string is a valid one, and domain properly encoded in this CharSet. + if ($this->has8bitChars($domain) && @mb_check_encoding($domain, $this->CharSet)) { + $domain = mb_convert_encoding($domain, 'UTF-8', $this->CharSet); + //Ignore IDE complaints about this line - method signature changed in PHP 5.4 + $errorcode = 0; + if (defined('INTL_IDNA_VARIANT_UTS46')) { + $punycode = idn_to_ascii($domain, $errorcode, INTL_IDNA_VARIANT_UTS46); + } elseif (defined('INTL_IDNA_VARIANT_2003')) { + $punycode = idn_to_ascii($domain, $errorcode, INTL_IDNA_VARIANT_2003); + } else { + $punycode = idn_to_ascii($domain, $errorcode); + } + if (false !== $punycode) { + return substr($address, 0, $pos) . $punycode; + } + } + } + + return $address; + } + + /** + * Create a message and send it. + * Uses the sending method specified by $Mailer. + * + * @throws Exception + * + * @return bool false on error - See the ErrorInfo property for details of the error + */ + public function send() + { + try { + if (!$this->preSend()) { + return false; + } + + return $this->postSend(); + } catch (Exception $exc) { + $this->mailHeader = ''; + $this->setError($exc->getMessage()); + if ($this->exceptions) { + throw $exc; + } + + return false; + } + } + + /** + * Prepare a message for sending. + * + * @throws Exception + * + * @return bool + */ + public function preSend() + { + if ('smtp' === $this->Mailer + || ('mail' === $this->Mailer && stripos(PHP_OS, 'WIN') === 0) + ) { + //SMTP mandates RFC-compliant line endings + //and it's also used with mail() on Windows + static::setLE(self::CRLF); + } else { + //Maintain backward compatibility with legacy Linux command line mailers + static::setLE(PHP_EOL); + } + //Check for buggy PHP versions that add a header with an incorrect line break + if ('mail' === $this->Mailer + && ((PHP_VERSION_ID >= 70000 && PHP_VERSION_ID < 70017) + || (PHP_VERSION_ID >= 70100 && PHP_VERSION_ID < 70103)) + && ini_get('mail.add_x_header') === '1' + && stripos(PHP_OS, 'WIN') === 0 + ) { + trigger_error( + 'Your version of PHP is affected by a bug that may result in corrupted messages.' . + ' To fix it, switch to sending using SMTP, disable the mail.add_x_header option in' . + ' your php.ini, switch to MacOS or Linux, or upgrade your PHP to version 7.0.17+ or 7.1.3+.', + E_USER_WARNING + ); + } + + try { + $this->error_count = 0; // Reset errors + $this->mailHeader = ''; + + // Dequeue recipient and Reply-To addresses with IDN + foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) { + $params[1] = $this->punyencodeAddress($params[1]); + call_user_func_array([$this, 'addAnAddress'], $params); + } + if (count($this->to) + count($this->cc) + count($this->bcc) < 1) { + throw new Exception($this->lang('provide_address'), self::STOP_CRITICAL); + } + + // Validate From, Sender, and ConfirmReadingTo addresses + foreach (['From', 'Sender', 'ConfirmReadingTo'] as $address_kind) { + $this->$address_kind = trim($this->$address_kind); + if (empty($this->$address_kind)) { + continue; + } + $this->$address_kind = $this->punyencodeAddress($this->$address_kind); + if (!static::validateAddress($this->$address_kind)) { + $error_message = sprintf( + '%s (%s): %s', + $this->lang('invalid_address'), + $address_kind, + $this->$address_kind + ); + $this->setError($error_message); + $this->edebug($error_message); + if ($this->exceptions) { + throw new Exception($error_message); + } + + return false; + } + } + + // Set whether the message is multipart/alternative + if ($this->alternativeExists()) { + $this->ContentType = static::CONTENT_TYPE_MULTIPART_ALTERNATIVE; + } + + $this->setMessageType(); + // Refuse to send an empty message unless we are specifically allowing it + if (!$this->AllowEmpty && empty($this->Body)) { + throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL); + } + + //Trim subject consistently + $this->Subject = trim($this->Subject); + // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding) + $this->MIMEHeader = ''; + $this->MIMEBody = $this->createBody(); + // createBody may have added some headers, so retain them + $tempheaders = $this->MIMEHeader; + $this->MIMEHeader = $this->createHeader(); + $this->MIMEHeader .= $tempheaders; + + // To capture the complete message when using mail(), create + // an extra header list which createHeader() doesn't fold in + if ('mail' === $this->Mailer) { + if (count($this->to) > 0) { + $this->mailHeader .= $this->addrAppend('To', $this->to); + } else { + $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;'); + } + $this->mailHeader .= $this->headerLine( + 'Subject', + $this->encodeHeader($this->secureHeader($this->Subject)) + ); + } + + // Sign with DKIM if enabled + if (!empty($this->DKIM_domain) + && !empty($this->DKIM_selector) + && (!empty($this->DKIM_private_string) + || (!empty($this->DKIM_private) + && static::isPermittedPath($this->DKIM_private) + && file_exists($this->DKIM_private) + ) + ) + ) { + $header_dkim = $this->DKIM_Add( + $this->MIMEHeader . $this->mailHeader, + $this->encodeHeader($this->secureHeader($this->Subject)), + $this->MIMEBody + ); + $this->MIMEHeader = static::stripTrailingWSP($this->MIMEHeader) . static::$LE . + static::normalizeBreaks($header_dkim) . static::$LE; + } + + return true; + } catch (Exception $exc) { + $this->setError($exc->getMessage()); + if ($this->exceptions) { + throw $exc; + } + + return false; + } + } + + /** + * Actually send a message via the selected mechanism. + * + * @throws Exception + * + * @return bool + */ + public function postSend() + { + try { + // Choose the mailer and send through it + switch ($this->Mailer) { + case 'sendmail': + case 'qmail': + return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody); + case 'smtp': + return $this->smtpSend($this->MIMEHeader, $this->MIMEBody); + case 'mail': + return $this->mailSend($this->MIMEHeader, $this->MIMEBody); + default: + $sendMethod = $this->Mailer . 'Send'; + if (method_exists($this, $sendMethod)) { + return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody); + } + + return $this->mailSend($this->MIMEHeader, $this->MIMEBody); + } + } catch (Exception $exc) { + $this->setError($exc->getMessage()); + $this->edebug($exc->getMessage()); + if ($this->exceptions) { + throw $exc; + } + } + + return false; + } + + /** + * Send mail using the $Sendmail program. + * + * @see PHPMailer::$Sendmail + * + * @param string $header The message headers + * @param string $body The message body + * + * @throws Exception + * + * @return bool + */ + protected function sendmailSend($header, $body) + { + $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; + + // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped. + if (!empty($this->Sender) && self::isShellSafe($this->Sender)) { + if ('qmail' === $this->Mailer) { + $sendmailFmt = '%s -f%s'; + } else { + $sendmailFmt = '%s -oi -f%s -t'; + } + } elseif ('qmail' === $this->Mailer) { + $sendmailFmt = '%s'; + } else { + $sendmailFmt = '%s -oi -t'; + } + + $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender); + + if ($this->SingleTo) { + foreach ($this->SingleToArray as $toAddr) { + $mail = @popen($sendmail, 'w'); + if (!$mail) { + throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + fwrite($mail, 'To: ' . $toAddr . "\n"); + fwrite($mail, $header); + fwrite($mail, $body); + $result = pclose($mail); + $this->doCallback( + ($result === 0), + [$toAddr], + $this->cc, + $this->bcc, + $this->Subject, + $body, + $this->From, + [] + ); + if (0 !== $result) { + throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + } + } else { + $mail = @popen($sendmail, 'w'); + if (!$mail) { + throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + fwrite($mail, $header); + fwrite($mail, $body); + $result = pclose($mail); + $this->doCallback( + ($result === 0), + $this->to, + $this->cc, + $this->bcc, + $this->Subject, + $body, + $this->From, + [] + ); + if (0 !== $result) { + throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + } + + return true; + } + + /** + * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters. + * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows. + * + * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report + * + * @param string $string The string to be validated + * + * @return bool + */ + protected static function isShellSafe($string) + { + // Future-proof + if (escapeshellcmd($string) !== $string + || !in_array(escapeshellarg($string), ["'$string'", "\"$string\""]) + ) { + return false; + } + + $length = strlen($string); + + for ($i = 0; $i < $length; ++$i) { + $c = $string[$i]; + + // All other characters have a special meaning in at least one common shell, including = and +. + // Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here. + // Note that this does permit non-Latin alphanumeric characters based on the current locale. + if (!ctype_alnum($c) && strpos('@_-.', $c) === false) { + return false; + } + } + + return true; + } + + /** + * Check whether a file path is of a permitted type. + * Used to reject URLs and phar files from functions that access local file paths, + * such as addAttachment. + * + * @param string $path A relative or absolute path to a file + * + * @return bool + */ + protected static function isPermittedPath($path) + { + return !preg_match('#^[a-z]+://#i', $path); + } + + /** + * Send mail using the PHP mail() function. + * + * @see http://www.php.net/manual/en/book.mail.php + * + * @param string $header The message headers + * @param string $body The message body + * + * @throws Exception + * + * @return bool + */ + protected function mailSend($header, $body) + { + $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; + + $toArr = []; + foreach ($this->to as $toaddr) { + $toArr[] = $this->addrFormat($toaddr); + } + $to = implode(', ', $toArr); + + $params = null; + //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver + //A space after `-f` is optional, but there is a long history of its presence + //causing problems, so we don't use one + //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html + //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html + //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html + //Example problem: https://www.drupal.org/node/1057954 + // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped. + if (!empty($this->Sender) && static::validateAddress($this->Sender) && self::isShellSafe($this->Sender)) { + $params = sprintf('-f%s', $this->Sender); + } + if (!empty($this->Sender) && static::validateAddress($this->Sender)) { + $old_from = ini_get('sendmail_from'); + ini_set('sendmail_from', $this->Sender); + } + $result = false; + if ($this->SingleTo && count($toArr) > 1) { + foreach ($toArr as $toAddr) { + $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params); + $this->doCallback($result, [$toAddr], $this->cc, $this->bcc, $this->Subject, $body, $this->From, []); + } + } else { + $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params); + $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From, []); + } + if (isset($old_from)) { + ini_set('sendmail_from', $old_from); + } + if (!$result) { + throw new Exception($this->lang('instantiate'), self::STOP_CRITICAL); + } + + return true; + } + + /** + * Get an instance to use for SMTP operations. + * Override this function to load your own SMTP implementation, + * or set one with setSMTPInstance. + * + * @return SMTP + */ + public function getSMTPInstance() + { + if (!is_object($this->smtp)) { + $this->smtp = new SMTP(); + } + + return $this->smtp; + } + + /** + * Provide an instance to use for SMTP operations. + * + * @return SMTP + */ + public function setSMTPInstance(SMTP $smtp) + { + $this->smtp = $smtp; + + return $this->smtp; + } + + /** + * Send mail via SMTP. + * Returns false if there is a bad MAIL FROM, RCPT, or DATA input. + * + * @see PHPMailer::setSMTPInstance() to use a different class. + * + * @uses \PHPMailer\PHPMailer\SMTP + * + * @param string $header The message headers + * @param string $body The message body + * + * @throws Exception + * + * @return bool + */ + protected function smtpSend($header, $body) + { + $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; + $bad_rcpt = []; + if (!$this->smtpConnect($this->SMTPOptions)) { + throw new Exception($this->lang('smtp_connect_failed'), self::STOP_CRITICAL); + } + //Sender already validated in preSend() + if ('' === $this->Sender) { + $smtp_from = $this->From; + } else { + $smtp_from = $this->Sender; + } + if (!$this->smtp->mail($smtp_from)) { + $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError())); + throw new Exception($this->ErrorInfo, self::STOP_CRITICAL); + } + + $callbacks = []; + // Attempt to send to all recipients + foreach ([$this->to, $this->cc, $this->bcc] as $togroup) { + foreach ($togroup as $to) { + if (!$this->smtp->recipient($to[0], $this->dsn)) { + $error = $this->smtp->getError(); + $bad_rcpt[] = ['to' => $to[0], 'error' => $error['detail']]; + $isSent = false; + } else { + $isSent = true; + } + + $callbacks[] = ['issent'=>$isSent, 'to'=>$to[0]]; + } + } + + // Only send the DATA command if we have viable recipients + if ((count($this->all_recipients) > count($bad_rcpt)) && !$this->smtp->data($header . $body)) { + throw new Exception($this->lang('data_not_accepted'), self::STOP_CRITICAL); + } + + $smtp_transaction_id = $this->smtp->getLastTransactionID(); + + if ($this->SMTPKeepAlive) { + $this->smtp->reset(); + } else { + $this->smtp->quit(); + $this->smtp->close(); + } + + foreach ($callbacks as $cb) { + $this->doCallback( + $cb['issent'], + [$cb['to']], + [], + [], + $this->Subject, + $body, + $this->From, + ['smtp_transaction_id' => $smtp_transaction_id] + ); + } + + //Create error message for any bad addresses + if (count($bad_rcpt) > 0) { + $errstr = ''; + foreach ($bad_rcpt as $bad) { + $errstr .= $bad['to'] . ': ' . $bad['error']; + } + throw new Exception($this->lang('recipients_failed') . $errstr, self::STOP_CONTINUE); + } + + return true; + } + + /** + * Initiate a connection to an SMTP server. + * Returns false if the operation failed. + * + * @param array $options An array of options compatible with stream_context_create() + * + * @throws Exception + * + * @uses \PHPMailer\PHPMailer\SMTP + * + * @return bool + */ + public function smtpConnect($options = null) + { + if (null === $this->smtp) { + $this->smtp = $this->getSMTPInstance(); + } + + //If no options are provided, use whatever is set in the instance + if (null === $options) { + $options = $this->SMTPOptions; + } + + // Already connected? + if ($this->smtp->connected()) { + return true; + } + + $this->smtp->setTimeout($this->Timeout); + $this->smtp->setDebugLevel($this->SMTPDebug); + $this->smtp->setDebugOutput($this->Debugoutput); + $this->smtp->setVerp($this->do_verp); + $hosts = explode(';', $this->Host); + $lastexception = null; + + foreach ($hosts as $hostentry) { + $hostinfo = []; + if (!preg_match( + '/^(?:(ssl|tls):\/\/)?(.+?)(?::(\d+))?$/', + trim($hostentry), + $hostinfo + )) { + $this->edebug($this->lang('invalid_hostentry') . ' ' . trim($hostentry)); + // Not a valid host entry + continue; + } + // $hostinfo[1]: optional ssl or tls prefix + // $hostinfo[2]: the hostname + // $hostinfo[3]: optional port number + // The host string prefix can temporarily override the current setting for SMTPSecure + // If it's not specified, the default value is used + + //Check the host name is a valid name or IP address before trying to use it + if (!static::isValidHost($hostinfo[2])) { + $this->edebug($this->lang('invalid_host') . ' ' . $hostinfo[2]); + continue; + } + $prefix = ''; + $secure = $this->SMTPSecure; + $tls = (static::ENCRYPTION_STARTTLS === $this->SMTPSecure); + if ('ssl' === $hostinfo[1] || ('' === $hostinfo[1] && static::ENCRYPTION_SMTPS === $this->SMTPSecure)) { + $prefix = 'ssl://'; + $tls = false; // Can't have SSL and TLS at the same time + $secure = static::ENCRYPTION_SMTPS; + } elseif ('tls' === $hostinfo[1]) { + $tls = true; + // tls doesn't use a prefix + $secure = static::ENCRYPTION_STARTTLS; + } + //Do we need the OpenSSL extension? + $sslext = defined('OPENSSL_ALGO_SHA256'); + if (static::ENCRYPTION_STARTTLS === $secure || static::ENCRYPTION_SMTPS === $secure) { + //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled + if (!$sslext) { + throw new Exception($this->lang('extension_missing') . 'openssl', self::STOP_CRITICAL); + } + } + $host = $hostinfo[2]; + $port = $this->Port; + if (array_key_exists(3, $hostinfo) && is_numeric($hostinfo[3]) && $hostinfo[3] > 0 && $hostinfo[3] < 65536) { + $port = (int) $hostinfo[3]; + } + if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) { + try { + if ($this->Helo) { + $hello = $this->Helo; + } else { + $hello = $this->serverHostname(); + } + $this->smtp->hello($hello); + //Automatically enable TLS encryption if: + // * it's not disabled + // * we have openssl extension + // * we are not already using SSL + // * the server offers STARTTLS + if ($this->SMTPAutoTLS && $sslext && 'ssl' !== $secure && $this->smtp->getServerExt('STARTTLS')) { + $tls = true; + } + if ($tls) { + if (!$this->smtp->startTLS()) { + throw new Exception($this->lang('connect_host')); + } + // We must resend EHLO after TLS negotiation + $this->smtp->hello($hello); + } + if ($this->SMTPAuth && !$this->smtp->authenticate( + $this->Username, + $this->Password, + $this->AuthType, + $this->oauth + )) { + throw new Exception($this->lang('authenticate')); + } + + return true; + } catch (Exception $exc) { + $lastexception = $exc; + $this->edebug($exc->getMessage()); + // We must have connected, but then failed TLS or Auth, so close connection nicely + $this->smtp->quit(); + } + } + } + // If we get here, all connection attempts have failed, so close connection hard + $this->smtp->close(); + // As we've caught all exceptions, just report whatever the last one was + if ($this->exceptions && null !== $lastexception) { + throw $lastexception; + } + + return false; + } + + /** + * Close the active SMTP session if one exists. + */ + public function smtpClose() + { + if ((null !== $this->smtp) && $this->smtp->connected()) { + $this->smtp->quit(); + $this->smtp->close(); + } + } + + /** + * Set the language for error messages. + * Returns false if it cannot load the language file. + * The default language is English. + * + * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr") + * @param string $lang_path Path to the language file directory, with trailing separator (slash) + * + * @return bool + */ + public function setLanguage($langcode = 'en', $lang_path = '') + { + // Backwards compatibility for renamed language codes + $renamed_langcodes = [ + 'br' => 'pt_br', + 'cz' => 'cs', + 'dk' => 'da', + 'no' => 'nb', + 'se' => 'sv', + 'rs' => 'sr', + 'tg' => 'tl', + 'am' => 'hy', + ]; + + if (isset($renamed_langcodes[$langcode])) { + $langcode = $renamed_langcodes[$langcode]; + } + + // Define full set of translatable strings in English + $PHPMAILER_LANG = [ + 'authenticate' => 'SMTP Error: Could not authenticate.', + 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', + 'data_not_accepted' => 'SMTP Error: data not accepted.', + 'empty_message' => 'Message body empty', + 'encoding' => 'Unknown encoding: ', + 'execute' => 'Could not execute: ', + 'file_access' => 'Could not access file: ', + 'file_open' => 'File Error: Could not open file: ', + 'from_failed' => 'The following From address failed: ', + 'instantiate' => 'Could not instantiate mail function.', + 'invalid_address' => 'Invalid address: ', + 'invalid_hostentry' => 'Invalid hostentry: ', + 'invalid_host' => 'Invalid host: ', + 'mailer_not_supported' => ' mailer is not supported.', + 'provide_address' => 'You must provide at least one recipient email address.', + 'recipients_failed' => 'SMTP Error: The following recipients failed: ', + 'signing' => 'Signing Error: ', + 'smtp_connect_failed' => 'SMTP connect() failed.', + 'smtp_error' => 'SMTP server error: ', + 'variable_set' => 'Cannot set or reset variable: ', + 'extension_missing' => 'Extension missing: ', + ]; + if (empty($lang_path)) { + // Calculate an absolute path so it can work if CWD is not here + $lang_path = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR; + } + //Validate $langcode + if (!preg_match('/^[a-z]{2}(?:_[a-zA-Z]{2})?$/', $langcode)) { + $langcode = 'en'; + } + $foundlang = true; + $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php'; + // There is no English translation file + if ('en' !== $langcode) { + // Make sure language file path is readable + if (!static::isPermittedPath($lang_file) || !file_exists($lang_file)) { + $foundlang = false; + } else { + // Overwrite language-specific strings. + // This way we'll never have missing translation keys. + $foundlang = include $lang_file; + } + } + $this->language = $PHPMAILER_LANG; + + return (bool) $foundlang; // Returns false if language not found + } + + /** + * Get the array of strings for the current language. + * + * @return array + */ + public function getTranslations() + { + return $this->language; + } + + /** + * Create recipient headers. + * + * @param string $type + * @param array $addr An array of recipients, + * where each recipient is a 2-element indexed array with element 0 containing an address + * and element 1 containing a name, like: + * [['joe@example.com', 'Joe User'], ['zoe@example.com', 'Zoe User']] + * + * @return string + */ + public function addrAppend($type, $addr) + { + $addresses = []; + foreach ($addr as $address) { + $addresses[] = $this->addrFormat($address); + } + + return $type . ': ' . implode(', ', $addresses) . static::$LE; + } + + /** + * Format an address for use in a message header. + * + * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name like + * ['joe@example.com', 'Joe User'] + * + * @return string + */ + public function addrFormat($addr) + { + if (empty($addr[1])) { // No name provided + return $this->secureHeader($addr[0]); + } + + return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . + ' <' . $this->secureHeader($addr[0]) . '>'; + } + + /** + * Word-wrap message. + * For use with mailers that do not automatically perform wrapping + * and for quoted-printable encoded messages. + * Original written by philippe. + * + * @param string $message The message to wrap + * @param int $length The line length to wrap to + * @param bool $qp_mode Whether to run in Quoted-Printable mode + * + * @return string + */ + public function wrapText($message, $length, $qp_mode = false) + { + if ($qp_mode) { + $soft_break = sprintf(' =%s', static::$LE); + } else { + $soft_break = static::$LE; + } + // If utf-8 encoding is used, we will need to make sure we don't + // split multibyte characters when we wrap + $is_utf8 = static::CHARSET_UTF8 === strtolower($this->CharSet); + $lelen = strlen(static::$LE); + $crlflen = strlen(static::$LE); + + $message = static::normalizeBreaks($message); + //Remove a trailing line break + if (substr($message, -$lelen) === static::$LE) { + $message = substr($message, 0, -$lelen); + } + + //Split message into lines + $lines = explode(static::$LE, $message); + //Message will be rebuilt in here + $message = ''; + foreach ($lines as $line) { + $words = explode(' ', $line); + $buf = ''; + $firstword = true; + foreach ($words as $word) { + if ($qp_mode && (strlen($word) > $length)) { + $space_left = $length - strlen($buf) - $crlflen; + if (!$firstword) { + if ($space_left > 20) { + $len = $space_left; + if ($is_utf8) { + $len = $this->utf8CharBoundary($word, $len); + } elseif ('=' === substr($word, $len - 1, 1)) { + --$len; + } elseif ('=' === substr($word, $len - 2, 1)) { + $len -= 2; + } + $part = substr($word, 0, $len); + $word = substr($word, $len); + $buf .= ' ' . $part; + $message .= $buf . sprintf('=%s', static::$LE); + } else { + $message .= $buf . $soft_break; + } + $buf = ''; + } + while ($word !== '') { + if ($length <= 0) { + break; + } + $len = $length; + if ($is_utf8) { + $len = $this->utf8CharBoundary($word, $len); + } elseif ('=' === substr($word, $len - 1, 1)) { + --$len; + } elseif ('=' === substr($word, $len - 2, 1)) { + $len -= 2; + } + $part = substr($word, 0, $len); + $word = (string) substr($word, $len); + + if ($word !== '') { + $message .= $part . sprintf('=%s', static::$LE); + } else { + $buf = $part; + } + } + } else { + $buf_o = $buf; + if (!$firstword) { + $buf .= ' '; + } + $buf .= $word; + + if ('' !== $buf_o && strlen($buf) > $length) { + $message .= $buf_o . $soft_break; + $buf = $word; + } + } + $firstword = false; + } + $message .= $buf . static::$LE; + } + + return $message; + } + + /** + * Find the last character boundary prior to $maxLength in a utf-8 + * quoted-printable encoded string. + * Original written by Colin Brown. + * + * @param string $encodedText utf-8 QP text + * @param int $maxLength Find the last character boundary prior to this length + * + * @return int + */ + public function utf8CharBoundary($encodedText, $maxLength) + { + $foundSplitPos = false; + $lookBack = 3; + while (!$foundSplitPos) { + $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack); + $encodedCharPos = strpos($lastChunk, '='); + if (false !== $encodedCharPos) { + // Found start of encoded character byte within $lookBack block. + // Check the encoded byte value (the 2 chars after the '=') + $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2); + $dec = hexdec($hex); + if ($dec < 128) { + // Single byte character. + // If the encoded char was found at pos 0, it will fit + // otherwise reduce maxLength to start of the encoded char + if ($encodedCharPos > 0) { + $maxLength -= $lookBack - $encodedCharPos; + } + $foundSplitPos = true; + } elseif ($dec >= 192) { + // First byte of a multi byte character + // Reduce maxLength to split at start of character + $maxLength -= $lookBack - $encodedCharPos; + $foundSplitPos = true; + } elseif ($dec < 192) { + // Middle byte of a multi byte character, look further back + $lookBack += 3; + } + } else { + // No encoded character found + $foundSplitPos = true; + } + } + + return $maxLength; + } + + /** + * Apply word wrapping to the message body. + * Wraps the message body to the number of chars set in the WordWrap property. + * You should only do this to plain-text bodies as wrapping HTML tags may break them. + * This is called automatically by createBody(), so you don't need to call it yourself. + */ + public function setWordWrap() + { + if ($this->WordWrap < 1) { + return; + } + + switch ($this->message_type) { + case 'alt': + case 'alt_inline': + case 'alt_attach': + case 'alt_inline_attach': + $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap); + break; + default: + $this->Body = $this->wrapText($this->Body, $this->WordWrap); + break; + } + } + + /** + * Assemble message headers. + * + * @return string The assembled headers + */ + public function createHeader() + { + $result = ''; + + $result .= $this->headerLine('Date', '' === $this->MessageDate ? self::rfcDate() : $this->MessageDate); + + // To be created automatically by mail() + if ($this->SingleTo) { + if ('mail' !== $this->Mailer) { + foreach ($this->to as $toaddr) { + $this->SingleToArray[] = $this->addrFormat($toaddr); + } + } + } elseif (count($this->to) > 0) { + if ('mail' !== $this->Mailer) { + $result .= $this->addrAppend('To', $this->to); + } + } elseif (count($this->cc) === 0) { + $result .= $this->headerLine('To', 'undisclosed-recipients:;'); + } + + $result .= $this->addrAppend('From', [[trim($this->From), $this->FromName]]); + + // sendmail and mail() extract Cc from the header before sending + if (count($this->cc) > 0) { + $result .= $this->addrAppend('Cc', $this->cc); + } + + // sendmail and mail() extract Bcc from the header before sending + if (( + 'sendmail' === $this->Mailer || 'qmail' === $this->Mailer || 'mail' === $this->Mailer + ) + && count($this->bcc) > 0 + ) { + $result .= $this->addrAppend('Bcc', $this->bcc); + } + + if (count($this->ReplyTo) > 0) { + $result .= $this->addrAppend('Reply-To', $this->ReplyTo); + } + + // mail() sets the subject itself + if ('mail' !== $this->Mailer) { + $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject))); + } + + // Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4 + // https://tools.ietf.org/html/rfc5322#section-3.6.4 + if ('' !== $this->MessageID && preg_match('/^<.*@.*>$/', $this->MessageID)) { + $this->lastMessageID = $this->MessageID; + } else { + $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname()); + } + $result .= $this->headerLine('Message-ID', $this->lastMessageID); + if (null !== $this->Priority) { + $result .= $this->headerLine('X-Priority', $this->Priority); + } + if ('' === $this->XMailer) { + $result .= $this->headerLine( + 'X-Mailer', + 'PHPMailer ' . self::VERSION . ' (https://github.com/PHPMailer/PHPMailer)' + ); + } else { + $myXmailer = trim($this->XMailer); + if ($myXmailer) { + $result .= $this->headerLine('X-Mailer', $myXmailer); + } + } + + if ('' !== $this->ConfirmReadingTo) { + $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>'); + } + + // Add custom headers + foreach ($this->CustomHeader as $header) { + $result .= $this->headerLine( + trim($header[0]), + $this->encodeHeader(trim($header[1])) + ); + } + if (!$this->sign_key_file) { + $result .= $this->headerLine('MIME-Version', '1.0'); + $result .= $this->getMailMIME(); + } + + return $result; + } + + /** + * Get the message MIME type headers. + * + * @return string + */ + public function getMailMIME() + { + $result = ''; + $ismultipart = true; + switch ($this->message_type) { + case 'inline': + $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';'); + $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"'); + break; + case 'attach': + case 'inline_attach': + case 'alt_attach': + case 'alt_inline_attach': + $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_MIXED . ';'); + $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"'); + break; + case 'alt': + case 'alt_inline': + $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';'); + $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"'); + break; + default: + // Catches case 'plain': and case '': + $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet); + $ismultipart = false; + break; + } + // RFC1341 part 5 says 7bit is assumed if not specified + if (static::ENCODING_7BIT !== $this->Encoding) { + // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE + if ($ismultipart) { + if (static::ENCODING_8BIT === $this->Encoding) { + $result .= $this->headerLine('Content-Transfer-Encoding', static::ENCODING_8BIT); + } + // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible + } else { + $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding); + } + } + + if ('mail' !== $this->Mailer) { +// $result .= static::$LE; + } + + return $result; + } + + /** + * Returns the whole MIME message. + * Includes complete headers and body. + * Only valid post preSend(). + * + * @see PHPMailer::preSend() + * + * @return string + */ + public function getSentMIMEMessage() + { + return static::stripTrailingWSP($this->MIMEHeader . $this->mailHeader) . + static::$LE . static::$LE . $this->MIMEBody; + } + + /** + * Create a unique ID to use for boundaries. + * + * @return string + */ + protected function generateId() + { + $len = 32; //32 bytes = 256 bits + $bytes = ''; + if (function_exists('random_bytes')) { + try { + $bytes = random_bytes($len); + } catch (\Exception $e) { + //Do nothing + } + } elseif (function_exists('openssl_random_pseudo_bytes')) { + /** @noinspection CryptographicallySecureRandomnessInspection */ + $bytes = openssl_random_pseudo_bytes($len); + } + if ($bytes === '') { + //We failed to produce a proper random string, so make do. + //Use a hash to force the length to the same as the other methods + $bytes = hash('sha256', uniqid((string) mt_rand(), true), true); + } + + //We don't care about messing up base64 format here, just want a random string + return str_replace(['=', '+', '/'], '', base64_encode(hash('sha256', $bytes, true))); + } + + /** + * Assemble the message body. + * Returns an empty string on failure. + * + * @throws Exception + * + * @return string The assembled message body + */ + public function createBody() + { + $body = ''; + //Create unique IDs and preset boundaries + $this->uniqueid = $this->generateId(); + $this->boundary[1] = 'b1_' . $this->uniqueid; + $this->boundary[2] = 'b2_' . $this->uniqueid; + $this->boundary[3] = 'b3_' . $this->uniqueid; + + if ($this->sign_key_file) { + $body .= $this->getMailMIME() . static::$LE; + } + + $this->setWordWrap(); + + $bodyEncoding = $this->Encoding; + $bodyCharSet = $this->CharSet; + //Can we do a 7-bit downgrade? + if (static::ENCODING_8BIT === $bodyEncoding && !$this->has8bitChars($this->Body)) { + $bodyEncoding = static::ENCODING_7BIT; + //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit + $bodyCharSet = static::CHARSET_ASCII; + } + //If lines are too long, and we're not already using an encoding that will shorten them, + //change to quoted-printable transfer encoding for the body part only + if (static::ENCODING_BASE64 !== $this->Encoding && static::hasLineLongerThanMax($this->Body)) { + $bodyEncoding = static::ENCODING_QUOTED_PRINTABLE; + } + + $altBodyEncoding = $this->Encoding; + $altBodyCharSet = $this->CharSet; + //Can we do a 7-bit downgrade? + if (static::ENCODING_8BIT === $altBodyEncoding && !$this->has8bitChars($this->AltBody)) { + $altBodyEncoding = static::ENCODING_7BIT; + //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit + $altBodyCharSet = static::CHARSET_ASCII; + } + //If lines are too long, and we're not already using an encoding that will shorten them, + //change to quoted-printable transfer encoding for the alt body part only + if (static::ENCODING_BASE64 !== $altBodyEncoding && static::hasLineLongerThanMax($this->AltBody)) { + $altBodyEncoding = static::ENCODING_QUOTED_PRINTABLE; + } + //Use this as a preamble in all multipart message types + $mimepre = 'This is a multi-part message in MIME format.' . static::$LE . static::$LE; + switch ($this->message_type) { + case 'inline': + $body .= $mimepre; + $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding); + $body .= $this->encodeString($this->Body, $bodyEncoding); + $body .= static::$LE; + $body .= $this->attachAll('inline', $this->boundary[1]); + break; + case 'attach': + $body .= $mimepre; + $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding); + $body .= $this->encodeString($this->Body, $bodyEncoding); + $body .= static::$LE; + $body .= $this->attachAll('attachment', $this->boundary[1]); + break; + case 'inline_attach': + $body .= $mimepre; + $body .= $this->textLine('--' . $this->boundary[1]); + $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';'); + $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";'); + $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"'); + $body .= static::$LE; + $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding); + $body .= $this->encodeString($this->Body, $bodyEncoding); + $body .= static::$LE; + $body .= $this->attachAll('inline', $this->boundary[2]); + $body .= static::$LE; + $body .= $this->attachAll('attachment', $this->boundary[1]); + break; + case 'alt': + $body .= $mimepre; + $body .= $this->getBoundary( + $this->boundary[1], + $altBodyCharSet, + static::CONTENT_TYPE_PLAINTEXT, + $altBodyEncoding + ); + $body .= $this->encodeString($this->AltBody, $altBodyEncoding); + $body .= static::$LE; + $body .= $this->getBoundary( + $this->boundary[1], + $bodyCharSet, + static::CONTENT_TYPE_TEXT_HTML, + $bodyEncoding + ); + $body .= $this->encodeString($this->Body, $bodyEncoding); + $body .= static::$LE; + if (!empty($this->Ical)) { + $method = static::ICAL_METHOD_REQUEST; + foreach (static::$IcalMethods as $imethod) { + if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) { + $method = $imethod; + break; + } + } + $body .= $this->getBoundary( + $this->boundary[1], + '', + static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method, + '' + ); + $body .= $this->encodeString($this->Ical, $this->Encoding); + $body .= static::$LE; + } + $body .= $this->endBoundary($this->boundary[1]); + break; + case 'alt_inline': + $body .= $mimepre; + $body .= $this->getBoundary( + $this->boundary[1], + $altBodyCharSet, + static::CONTENT_TYPE_PLAINTEXT, + $altBodyEncoding + ); + $body .= $this->encodeString($this->AltBody, $altBodyEncoding); + $body .= static::$LE; + $body .= $this->textLine('--' . $this->boundary[1]); + $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';'); + $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";'); + $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"'); + $body .= static::$LE; + $body .= $this->getBoundary( + $this->boundary[2], + $bodyCharSet, + static::CONTENT_TYPE_TEXT_HTML, + $bodyEncoding + ); + $body .= $this->encodeString($this->Body, $bodyEncoding); + $body .= static::$LE; + $body .= $this->attachAll('inline', $this->boundary[2]); + $body .= static::$LE; + $body .= $this->endBoundary($this->boundary[1]); + break; + case 'alt_attach': + $body .= $mimepre; + $body .= $this->textLine('--' . $this->boundary[1]); + $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';'); + $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"'); + $body .= static::$LE; + $body .= $this->getBoundary( + $this->boundary[2], + $altBodyCharSet, + static::CONTENT_TYPE_PLAINTEXT, + $altBodyEncoding + ); + $body .= $this->encodeString($this->AltBody, $altBodyEncoding); + $body .= static::$LE; + $body .= $this->getBoundary( + $this->boundary[2], + $bodyCharSet, + static::CONTENT_TYPE_TEXT_HTML, + $bodyEncoding + ); + $body .= $this->encodeString($this->Body, $bodyEncoding); + $body .= static::$LE; + if (!empty($this->Ical)) { + $method = static::ICAL_METHOD_REQUEST; + foreach (static::$IcalMethods as $imethod) { + if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) { + $method = $imethod; + break; + } + } + $body .= $this->getBoundary( + $this->boundary[2], + '', + static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method, + '' + ); + $body .= $this->encodeString($this->Ical, $this->Encoding); + } + $body .= $this->endBoundary($this->boundary[2]); + $body .= static::$LE; + $body .= $this->attachAll('attachment', $this->boundary[1]); + break; + case 'alt_inline_attach': + $body .= $mimepre; + $body .= $this->textLine('--' . $this->boundary[1]); + $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';'); + $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"'); + $body .= static::$LE; + $body .= $this->getBoundary( + $this->boundary[2], + $altBodyCharSet, + static::CONTENT_TYPE_PLAINTEXT, + $altBodyEncoding + ); + $body .= $this->encodeString($this->AltBody, $altBodyEncoding); + $body .= static::$LE; + $body .= $this->textLine('--' . $this->boundary[2]); + $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';'); + $body .= $this->textLine(' boundary="' . $this->boundary[3] . '";'); + $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"'); + $body .= static::$LE; + $body .= $this->getBoundary( + $this->boundary[3], + $bodyCharSet, + static::CONTENT_TYPE_TEXT_HTML, + $bodyEncoding + ); + $body .= $this->encodeString($this->Body, $bodyEncoding); + $body .= static::$LE; + $body .= $this->attachAll('inline', $this->boundary[3]); + $body .= static::$LE; + $body .= $this->endBoundary($this->boundary[2]); + $body .= static::$LE; + $body .= $this->attachAll('attachment', $this->boundary[1]); + break; + default: + // Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types + //Reset the `Encoding` property in case we changed it for line length reasons + $this->Encoding = $bodyEncoding; + $body .= $this->encodeString($this->Body, $this->Encoding); + break; + } + + if ($this->isError()) { + $body = ''; + if ($this->exceptions) { + throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL); + } + } elseif ($this->sign_key_file) { + try { + if (!defined('PKCS7_TEXT')) { + throw new Exception($this->lang('extension_missing') . 'openssl'); + } + + $file = tempnam(sys_get_temp_dir(), 'srcsign'); + $signed = tempnam(sys_get_temp_dir(), 'mailsign'); + file_put_contents($file, $body); + + //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197 + if (empty($this->sign_extracerts_file)) { + $sign = @openssl_pkcs7_sign( + $file, + $signed, + 'file://' . realpath($this->sign_cert_file), + ['file://' . realpath($this->sign_key_file), $this->sign_key_pass], + [] + ); + } else { + $sign = @openssl_pkcs7_sign( + $file, + $signed, + 'file://' . realpath($this->sign_cert_file), + ['file://' . realpath($this->sign_key_file), $this->sign_key_pass], + [], + PKCS7_DETACHED, + $this->sign_extracerts_file + ); + } + + @unlink($file); + if ($sign) { + $body = file_get_contents($signed); + @unlink($signed); + //The message returned by openssl contains both headers and body, so need to split them up + $parts = explode("\n\n", $body, 2); + $this->MIMEHeader .= $parts[0] . static::$LE . static::$LE; + $body = $parts[1]; + } else { + @unlink($signed); + throw new Exception($this->lang('signing') . openssl_error_string()); + } + } catch (Exception $exc) { + $body = ''; + if ($this->exceptions) { + throw $exc; + } + } + } + + return $body; + } + + /** + * Return the start of a message boundary. + * + * @param string $boundary + * @param string $charSet + * @param string $contentType + * @param string $encoding + * + * @return string + */ + protected function getBoundary($boundary, $charSet, $contentType, $encoding) + { + $result = ''; + if ('' === $charSet) { + $charSet = $this->CharSet; + } + if ('' === $contentType) { + $contentType = $this->ContentType; + } + if ('' === $encoding) { + $encoding = $this->Encoding; + } + $result .= $this->textLine('--' . $boundary); + $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet); + $result .= static::$LE; + // RFC1341 part 5 says 7bit is assumed if not specified + if (static::ENCODING_7BIT !== $encoding) { + $result .= $this->headerLine('Content-Transfer-Encoding', $encoding); + } + $result .= static::$LE; + + return $result; + } + + /** + * Return the end of a message boundary. + * + * @param string $boundary + * + * @return string + */ + protected function endBoundary($boundary) + { + return static::$LE . '--' . $boundary . '--' . static::$LE; + } + + /** + * Set the message type. + * PHPMailer only supports some preset message types, not arbitrary MIME structures. + */ + protected function setMessageType() + { + $type = []; + if ($this->alternativeExists()) { + $type[] = 'alt'; + } + if ($this->inlineImageExists()) { + $type[] = 'inline'; + } + if ($this->attachmentExists()) { + $type[] = 'attach'; + } + $this->message_type = implode('_', $type); + if ('' === $this->message_type) { + //The 'plain' message_type refers to the message having a single body element, not that it is plain-text + $this->message_type = 'plain'; + } + } + + /** + * Format a header line. + * + * @param string $name + * @param string|int $value + * + * @return string + */ + public function headerLine($name, $value) + { + return $name . ': ' . $value . static::$LE; + } + + /** + * Return a formatted mail line. + * + * @param string $value + * + * @return string + */ + public function textLine($value) + { + return $value . static::$LE; + } + + /** + * Add an attachment from a path on the filesystem. + * Never use a user-supplied path to a file! + * Returns false if the file could not be found or read. + * Explicitly *does not* support passing URLs; PHPMailer is not an HTTP client. + * If you need to do that, fetch the resource yourself and pass it in via a local file or string. + * + * @param string $path Path to the attachment + * @param string $name Overrides the attachment name + * @param string $encoding File encoding (see $Encoding) + * @param string $type File extension (MIME) type + * @param string $disposition Disposition to use + * + * @throws Exception + * + * @return bool + */ + public function addAttachment( + $path, + $name = '', + $encoding = self::ENCODING_BASE64, + $type = '', + $disposition = 'attachment' + ) { + try { + if (!static::isPermittedPath($path) || !@is_file($path) || !is_readable($path)) { + throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE); + } + + // If a MIME type is not specified, try to work it out from the file name + if ('' === $type) { + $type = static::filenameToType($path); + } + + $filename = (string) static::mb_pathinfo($path, PATHINFO_BASENAME); + if ('' === $name) { + $name = $filename; + } + + if (!$this->validateEncoding($encoding)) { + throw new Exception($this->lang('encoding') . $encoding); + } + + $this->attachment[] = [ + 0 => $path, + 1 => $filename, + 2 => $name, + 3 => $encoding, + 4 => $type, + 5 => false, // isStringAttachment + 6 => $disposition, + 7 => $name, + ]; + } catch (Exception $exc) { + $this->setError($exc->getMessage()); + $this->edebug($exc->getMessage()); + if ($this->exceptions) { + throw $exc; + } + + return false; + } + + return true; + } + + /** + * Return the array of attachments. + * + * @return array + */ + public function getAttachments() + { + return $this->attachment; + } + + /** + * Attach all file, string, and binary attachments to the message. + * Returns an empty string on failure. + * + * @param string $disposition_type + * @param string $boundary + * + * @throws Exception + * + * @return string + */ + protected function attachAll($disposition_type, $boundary) + { + // Return text of body + $mime = []; + $cidUniq = []; + $incl = []; + + // Add all attachments + foreach ($this->attachment as $attachment) { + // Check if it is a valid disposition_filter + if ($attachment[6] === $disposition_type) { + // Check for string attachment + $string = ''; + $path = ''; + $bString = $attachment[5]; + if ($bString) { + $string = $attachment[0]; + } else { + $path = $attachment[0]; + } + + $inclhash = hash('sha256', serialize($attachment)); + if (in_array($inclhash, $incl, true)) { + continue; + } + $incl[] = $inclhash; + $name = $attachment[2]; + $encoding = $attachment[3]; + $type = $attachment[4]; + $disposition = $attachment[6]; + $cid = $attachment[7]; + if ('inline' === $disposition && array_key_exists($cid, $cidUniq)) { + continue; + } + $cidUniq[$cid] = true; + + $mime[] = sprintf('--%s%s', $boundary, static::$LE); + //Only include a filename property if we have one + if (!empty($name)) { + $mime[] = sprintf( + 'Content-Type: %s; name=%s%s', + $type, + static::quotedString($this->encodeHeader($this->secureHeader($name))), + static::$LE + ); + } else { + $mime[] = sprintf( + 'Content-Type: %s%s', + $type, + static::$LE + ); + } + // RFC1341 part 5 says 7bit is assumed if not specified + if (static::ENCODING_7BIT !== $encoding) { + $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, static::$LE); + } + + //Only set Content-IDs on inline attachments + if ((string) $cid !== '' && $disposition === 'inline') { + $mime[] = 'Content-ID: <' . $this->encodeHeader($this->secureHeader($cid)) . '>' . static::$LE; + } + + // Allow for bypassing the Content-Disposition header + if (!empty($disposition)) { + $encoded_name = $this->encodeHeader($this->secureHeader($name)); + if (!empty($encoded_name)) { + $mime[] = sprintf( + 'Content-Disposition: %s; filename=%s%s', + $disposition, + static::quotedString($encoded_name), + static::$LE . static::$LE + ); + } else { + $mime[] = sprintf( + 'Content-Disposition: %s%s', + $disposition, + static::$LE . static::$LE + ); + } + } else { + $mime[] = static::$LE; + } + + // Encode as string attachment + if ($bString) { + $mime[] = $this->encodeString($string, $encoding); + } else { + $mime[] = $this->encodeFile($path, $encoding); + } + if ($this->isError()) { + return ''; + } + $mime[] = static::$LE; + } + } + + $mime[] = sprintf('--%s--%s', $boundary, static::$LE); + + return implode('', $mime); + } + + /** + * Encode a file attachment in requested format. + * Returns an empty string on failure. + * + * @param string $path The full path to the file + * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' + * + * @return string + */ + protected function encodeFile($path, $encoding = self::ENCODING_BASE64) + { + try { + if (!static::isPermittedPath($path) || !file_exists($path) || !is_readable($path)) { + throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE); + } + $file_buffer = file_get_contents($path); + if (false === $file_buffer) { + throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE); + } + $file_buffer = $this->encodeString($file_buffer, $encoding); + + return $file_buffer; + } catch (Exception $exc) { + $this->setError($exc->getMessage()); + $this->edebug($exc->getMessage()); + if ($this->exceptions) { + throw $exc; + } + + return ''; + } + } + + /** + * Encode a string in requested format. + * Returns an empty string on failure. + * + * @param string $str The text to encode + * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' + * + * @throws Exception + * + * @return string + */ + public function encodeString($str, $encoding = self::ENCODING_BASE64) + { + $encoded = ''; + switch (strtolower($encoding)) { + case static::ENCODING_BASE64: + $encoded = chunk_split( + base64_encode($str), + static::STD_LINE_LENGTH, + static::$LE + ); + break; + case static::ENCODING_7BIT: + case static::ENCODING_8BIT: + $encoded = static::normalizeBreaks($str); + // Make sure it ends with a line break + if (substr($encoded, -(strlen(static::$LE))) !== static::$LE) { + $encoded .= static::$LE; + } + break; + case static::ENCODING_BINARY: + $encoded = $str; + break; + case static::ENCODING_QUOTED_PRINTABLE: + $encoded = $this->encodeQP($str); + break; + default: + $this->setError($this->lang('encoding') . $encoding); + if ($this->exceptions) { + throw new Exception($this->lang('encoding') . $encoding); + } + break; + } + + return $encoded; + } + + /** + * Encode a header value (not including its label) optimally. + * Picks shortest of Q, B, or none. Result includes folding if needed. + * See RFC822 definitions for phrase, comment and text positions. + * + * @param string $str The header value to encode + * @param string $position What context the string will be used in + * + * @return string + */ + public function encodeHeader($str, $position = 'text') + { + $matchcount = 0; + switch (strtolower($position)) { + case 'phrase': + if (!preg_match('/[\200-\377]/', $str)) { + // Can't use addslashes as we don't know the value of magic_quotes_sybase + $encoded = addcslashes($str, "\0..\37\177\\\""); + if (($str === $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) { + return $encoded; + } + + return "\"$encoded\""; + } + $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches); + break; + /* @noinspection PhpMissingBreakStatementInspection */ + case 'comment': + $matchcount = preg_match_all('/[()"]/', $str, $matches); + //fallthrough + case 'text': + default: + $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches); + break; + } + + if ($this->has8bitChars($str)) { + $charset = $this->CharSet; + } else { + $charset = static::CHARSET_ASCII; + } + + // Q/B encoding adds 8 chars and the charset ("` =??[QB]??=`"). + $overhead = 8 + strlen($charset); + + if ('mail' === $this->Mailer) { + $maxlen = static::MAIL_MAX_LINE_LENGTH - $overhead; + } else { + $maxlen = static::MAX_LINE_LENGTH - $overhead; + } + + // Select the encoding that produces the shortest output and/or prevents corruption. + if ($matchcount > strlen($str) / 3) { + // More than 1/3 of the content needs encoding, use B-encode. + $encoding = 'B'; + } elseif ($matchcount > 0) { + // Less than 1/3 of the content needs encoding, use Q-encode. + $encoding = 'Q'; + } elseif (strlen($str) > $maxlen) { + // No encoding needed, but value exceeds max line length, use Q-encode to prevent corruption. + $encoding = 'Q'; + } else { + // No reformatting needed + $encoding = false; + } + + switch ($encoding) { + case 'B': + if ($this->hasMultiBytes($str)) { + // Use a custom function which correctly encodes and wraps long + // multibyte strings without breaking lines within a character + $encoded = $this->base64EncodeWrapMB($str, "\n"); + } else { + $encoded = base64_encode($str); + $maxlen -= $maxlen % 4; + $encoded = trim(chunk_split($encoded, $maxlen, "\n")); + } + $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded); + break; + case 'Q': + $encoded = $this->encodeQ($str, $position); + $encoded = $this->wrapText($encoded, $maxlen, true); + $encoded = str_replace('=' . static::$LE, "\n", trim($encoded)); + $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded); + break; + default: + return $str; + } + + return trim(static::normalizeBreaks($encoded)); + } + + /** + * Check if a string contains multi-byte characters. + * + * @param string $str multi-byte text to wrap encode + * + * @return bool + */ + public function hasMultiBytes($str) + { + if (function_exists('mb_strlen')) { + return strlen($str) > mb_strlen($str, $this->CharSet); + } + + // Assume no multibytes (we can't handle without mbstring functions anyway) + return false; + } + + /** + * Does a string contain any 8-bit chars (in any charset)? + * + * @param string $text + * + * @return bool + */ + public function has8bitChars($text) + { + return (bool) preg_match('/[\x80-\xFF]/', $text); + } + + /** + * Encode and wrap long multibyte strings for mail headers + * without breaking lines within a character. + * Adapted from a function by paravoid. + * + * @see http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283 + * + * @param string $str multi-byte text to wrap encode + * @param string $linebreak string to use as linefeed/end-of-line + * + * @return string + */ + public function base64EncodeWrapMB($str, $linebreak = null) + { + $start = '=?' . $this->CharSet . '?B?'; + $end = '?='; + $encoded = ''; + if (null === $linebreak) { + $linebreak = static::$LE; + } + + $mb_length = mb_strlen($str, $this->CharSet); + // Each line must have length <= 75, including $start and $end + $length = 75 - strlen($start) - strlen($end); + // Average multi-byte ratio + $ratio = $mb_length / strlen($str); + // Base64 has a 4:3 ratio + $avgLength = floor($length * $ratio * .75); + + $offset = 0; + for ($i = 0; $i < $mb_length; $i += $offset) { + $lookBack = 0; + do { + $offset = $avgLength - $lookBack; + $chunk = mb_substr($str, $i, $offset, $this->CharSet); + $chunk = base64_encode($chunk); + ++$lookBack; + } while (strlen($chunk) > $length); + $encoded .= $chunk . $linebreak; + } + + // Chomp the last linefeed + return substr($encoded, 0, -strlen($linebreak)); + } + + /** + * Encode a string in quoted-printable format. + * According to RFC2045 section 6.7. + * + * @param string $string The text to encode + * + * @return string + */ + public function encodeQP($string) + { + return static::normalizeBreaks(quoted_printable_encode($string)); + } + + /** + * Encode a string using Q encoding. + * + * @see http://tools.ietf.org/html/rfc2047#section-4.2 + * + * @param string $str the text to encode + * @param string $position Where the text is going to be used, see the RFC for what that means + * + * @return string + */ + public function encodeQ($str, $position = 'text') + { + // There should not be any EOL in the string + $pattern = ''; + $encoded = str_replace(["\r", "\n"], '', $str); + switch (strtolower($position)) { + case 'phrase': + // RFC 2047 section 5.3 + $pattern = '^A-Za-z0-9!*+\/ -'; + break; + /* + * RFC 2047 section 5.2. + * Build $pattern without including delimiters and [] + */ + /* @noinspection PhpMissingBreakStatementInspection */ + case 'comment': + $pattern = '\(\)"'; + /* Intentional fall through */ + case 'text': + default: + // RFC 2047 section 5.1 + // Replace every high ascii, control, =, ? and _ characters + $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern; + break; + } + $matches = []; + if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) { + // If the string contains an '=', make sure it's the first thing we replace + // so as to avoid double-encoding + $eqkey = array_search('=', $matches[0], true); + if (false !== $eqkey) { + unset($matches[0][$eqkey]); + array_unshift($matches[0], '='); + } + foreach (array_unique($matches[0]) as $char) { + $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded); + } + } + // Replace spaces with _ (more readable than =20) + // RFC 2047 section 4.2(2) + return str_replace(' ', '_', $encoded); + } + + /** + * Add a string or binary attachment (non-filesystem). + * This method can be used to attach ascii or binary data, + * such as a BLOB record from a database. + * + * @param string $string String attachment data + * @param string $filename Name of the attachment + * @param string $encoding File encoding (see $Encoding) + * @param string $type File extension (MIME) type + * @param string $disposition Disposition to use + * + * @throws Exception + * + * @return bool True on successfully adding an attachment + */ + public function addStringAttachment( + $string, + $filename, + $encoding = self::ENCODING_BASE64, + $type = '', + $disposition = 'attachment' + ) { + try { + // If a MIME type is not specified, try to work it out from the file name + if ('' === $type) { + $type = static::filenameToType($filename); + } + + if (!$this->validateEncoding($encoding)) { + throw new Exception($this->lang('encoding') . $encoding); + } + + // Append to $attachment array + $this->attachment[] = [ + 0 => $string, + 1 => $filename, + 2 => static::mb_pathinfo($filename, PATHINFO_BASENAME), + 3 => $encoding, + 4 => $type, + 5 => true, // isStringAttachment + 6 => $disposition, + 7 => 0, + ]; + } catch (Exception $exc) { + $this->setError($exc->getMessage()); + $this->edebug($exc->getMessage()); + if ($this->exceptions) { + throw $exc; + } + + return false; + } + + return true; + } + + /** + * Add an embedded (inline) attachment from a file. + * This can include images, sounds, and just about any other document type. + * These differ from 'regular' attachments in that they are intended to be + * displayed inline with the message, not just attached for download. + * This is used in HTML messages that embed the images + * the HTML refers to using the $cid value. + * Never use a user-supplied path to a file! + * + * @param string $path Path to the attachment + * @param string $cid Content ID of the attachment; Use this to reference + * the content when using an embedded image in HTML + * @param string $name Overrides the attachment name + * @param string $encoding File encoding (see $Encoding) + * @param string $type File MIME type + * @param string $disposition Disposition to use + * + * @throws Exception + * + * @return bool True on successfully adding an attachment + */ + public function addEmbeddedImage( + $path, + $cid, + $name = '', + $encoding = self::ENCODING_BASE64, + $type = '', + $disposition = 'inline' + ) { + try { + if (!static::isPermittedPath($path) || !@is_file($path) || !is_readable($path)) { + throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE); + } + + // If a MIME type is not specified, try to work it out from the file name + if ('' === $type) { + $type = static::filenameToType($path); + } + + if (!$this->validateEncoding($encoding)) { + throw new Exception($this->lang('encoding') . $encoding); + } + + $filename = (string) static::mb_pathinfo($path, PATHINFO_BASENAME); + if ('' === $name) { + $name = $filename; + } + + // Append to $attachment array + $this->attachment[] = [ + 0 => $path, + 1 => $filename, + 2 => $name, + 3 => $encoding, + 4 => $type, + 5 => false, // isStringAttachment + 6 => $disposition, + 7 => $cid, + ]; + } catch (Exception $exc) { + $this->setError($exc->getMessage()); + $this->edebug($exc->getMessage()); + if ($this->exceptions) { + throw $exc; + } + + return false; + } + + return true; + } + + /** + * Add an embedded stringified attachment. + * This can include images, sounds, and just about any other document type. + * If your filename doesn't contain an extension, be sure to set the $type to an appropriate MIME type. + * + * @param string $string The attachment binary data + * @param string $cid Content ID of the attachment; Use this to reference + * the content when using an embedded image in HTML + * @param string $name A filename for the attachment. If this contains an extension, + * PHPMailer will attempt to set a MIME type for the attachment. + * For example 'file.jpg' would get an 'image/jpeg' MIME type. + * @param string $encoding File encoding (see $Encoding), defaults to 'base64' + * @param string $type MIME type - will be used in preference to any automatically derived type + * @param string $disposition Disposition to use + * + * @throws Exception + * + * @return bool True on successfully adding an attachment + */ + public function addStringEmbeddedImage( + $string, + $cid, + $name = '', + $encoding = self::ENCODING_BASE64, + $type = '', + $disposition = 'inline' + ) { + try { + // If a MIME type is not specified, try to work it out from the name + if ('' === $type && !empty($name)) { + $type = static::filenameToType($name); + } + + if (!$this->validateEncoding($encoding)) { + throw new Exception($this->lang('encoding') . $encoding); + } + + // Append to $attachment array + $this->attachment[] = [ + 0 => $string, + 1 => $name, + 2 => $name, + 3 => $encoding, + 4 => $type, + 5 => true, // isStringAttachment + 6 => $disposition, + 7 => $cid, + ]; + } catch (Exception $exc) { + $this->setError($exc->getMessage()); + $this->edebug($exc->getMessage()); + if ($this->exceptions) { + throw $exc; + } + + return false; + } + + return true; + } + + /** + * Validate encodings. + * + * @param string $encoding + * + * @return bool + */ + protected function validateEncoding($encoding) + { + return in_array( + $encoding, + [ + self::ENCODING_7BIT, + self::ENCODING_QUOTED_PRINTABLE, + self::ENCODING_BASE64, + self::ENCODING_8BIT, + self::ENCODING_BINARY, + ], + true + ); + } + + /** + * Check if an embedded attachment is present with this cid. + * + * @param string $cid + * + * @return bool + */ + protected function cidExists($cid) + { + foreach ($this->attachment as $attachment) { + if ('inline' === $attachment[6] && $cid === $attachment[7]) { + return true; + } + } + + return false; + } + + /** + * Check if an inline attachment is present. + * + * @return bool + */ + public function inlineImageExists() + { + foreach ($this->attachment as $attachment) { + if ('inline' === $attachment[6]) { + return true; + } + } + + return false; + } + + /** + * Check if an attachment (non-inline) is present. + * + * @return bool + */ + public function attachmentExists() + { + foreach ($this->attachment as $attachment) { + if ('attachment' === $attachment[6]) { + return true; + } + } + + return false; + } + + /** + * Check if this message has an alternative body set. + * + * @return bool + */ + public function alternativeExists() + { + return !empty($this->AltBody); + } + + /** + * Clear queued addresses of given kind. + * + * @param string $kind 'to', 'cc', or 'bcc' + */ + public function clearQueuedAddresses($kind) + { + $this->RecipientsQueue = array_filter( + $this->RecipientsQueue, + static function ($params) use ($kind) { + return $params[0] !== $kind; + } + ); + } + + /** + * Clear all To recipients. + */ + public function clearAddresses() + { + foreach ($this->to as $to) { + unset($this->all_recipients[strtolower($to[0])]); + } + $this->to = []; + $this->clearQueuedAddresses('to'); + } + + /** + * Clear all CC recipients. + */ + public function clearCCs() + { + foreach ($this->cc as $cc) { + unset($this->all_recipients[strtolower($cc[0])]); + } + $this->cc = []; + $this->clearQueuedAddresses('cc'); + } + + /** + * Clear all BCC recipients. + */ + public function clearBCCs() + { + foreach ($this->bcc as $bcc) { + unset($this->all_recipients[strtolower($bcc[0])]); + } + $this->bcc = []; + $this->clearQueuedAddresses('bcc'); + } + + /** + * Clear all ReplyTo recipients. + */ + public function clearReplyTos() + { + $this->ReplyTo = []; + $this->ReplyToQueue = []; + } + + /** + * Clear all recipient types. + */ + public function clearAllRecipients() + { + $this->to = []; + $this->cc = []; + $this->bcc = []; + $this->all_recipients = []; + $this->RecipientsQueue = []; + } + + /** + * Clear all filesystem, string, and binary attachments. + */ + public function clearAttachments() + { + $this->attachment = []; + } + + /** + * Clear all custom headers. + */ + public function clearCustomHeaders() + { + $this->CustomHeader = []; + } + + /** + * Add an error message to the error container. + * + * @param string $msg + */ + protected function setError($msg) + { + ++$this->error_count; + if ('smtp' === $this->Mailer && null !== $this->smtp) { + $lasterror = $this->smtp->getError(); + if (!empty($lasterror['error'])) { + $msg .= $this->lang('smtp_error') . $lasterror['error']; + if (!empty($lasterror['detail'])) { + $msg .= ' Detail: ' . $lasterror['detail']; + } + if (!empty($lasterror['smtp_code'])) { + $msg .= ' SMTP code: ' . $lasterror['smtp_code']; + } + if (!empty($lasterror['smtp_code_ex'])) { + $msg .= ' Additional SMTP info: ' . $lasterror['smtp_code_ex']; + } + } + } + $this->ErrorInfo = $msg; + } + + /** + * Return an RFC 822 formatted date. + * + * @return string + */ + public static function rfcDate() + { + // Set the time zone to whatever the default is to avoid 500 errors + // Will default to UTC if it's not set properly in php.ini + date_default_timezone_set(@date_default_timezone_get()); + + return date('D, j M Y H:i:s O'); + } + + /** + * Get the server hostname. + * Returns 'localhost.localdomain' if unknown. + * + * @return string + */ + protected function serverHostname() + { + $result = ''; + if (!empty($this->Hostname)) { + $result = $this->Hostname; + } elseif (isset($_SERVER) && array_key_exists('SERVER_NAME', $_SERVER)) { + $result = $_SERVER['SERVER_NAME']; + } elseif (function_exists('gethostname') && gethostname() !== false) { + $result = gethostname(); + } elseif (php_uname('n') !== false) { + $result = php_uname('n'); + } + if (!static::isValidHost($result)) { + return 'localhost.localdomain'; + } + + return $result; + } + + /** + * Validate whether a string contains a valid value to use as a hostname or IP address. + * IPv6 addresses must include [], e.g. `[::1]`, not just `::1`. + * + * @param string $host The host name or IP address to check + * + * @return bool + */ + public static function isValidHost($host) + { + //Simple syntax limits + if (empty($host) + || !is_string($host) + || strlen($host) > 256 + || !preg_match('/^([a-zA-Z\d.-]*|\[[a-fA-F\d:]+])$/', $host) + ) { + return false; + } + //Looks like a bracketed IPv6 address + if (strlen($host) > 2 && substr($host, 0, 1) === '[' && substr($host, -1, 1) === ']') { + return filter_var(substr($host, 1, -1), FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false; + } + //If removing all the dots results in a numeric string, it must be an IPv4 address. + //Need to check this first because otherwise things like `999.0.0.0` are considered valid host names + if (is_numeric(str_replace('.', '', $host))) { + //Is it a valid IPv4 address? + return filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false; + } + if (filter_var('http://' . $host, FILTER_VALIDATE_URL) !== false) { + //Is it a syntactically valid hostname? + return true; + } + + return false; + } + + /** + * Get an error message in the current language. + * + * @param string $key + * + * @return string + */ + protected function lang($key) + { + if (count($this->language) < 1) { + $this->setLanguage(); // set the default language + } + + if (array_key_exists($key, $this->language)) { + if ('smtp_connect_failed' === $key) { + //Include a link to troubleshooting docs on SMTP connection failure + //this is by far the biggest cause of support questions + //but it's usually not PHPMailer's fault. + return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting'; + } + + return $this->language[$key]; + } + + //Return the key as a fallback + return $key; + } + + /** + * Check if an error occurred. + * + * @return bool True if an error did occur + */ + public function isError() + { + return $this->error_count > 0; + } + + /** + * Add a custom header. + * $name value can be overloaded to contain + * both header name and value (name:value). + * + * @param string $name Custom header name + * @param string|null $value Header value + * + * @throws Exception + */ + public function addCustomHeader($name, $value = null) + { + if (null === $value && strpos($name, ':') !== false) { + // Value passed in as name:value + list($name, $value) = explode(':', $name, 2); + } + $name = trim($name); + $value = trim($value); + //Ensure name is not empty, and that neither name nor value contain line breaks + if (empty($name) || strpbrk($name . $value, "\r\n") !== false) { + if ($this->exceptions) { + throw new Exception('Invalid header name or value'); + } + + return false; + } + $this->CustomHeader[] = [$name, $value]; + + return true; + } + + /** + * Returns all custom headers. + * + * @return array + */ + public function getCustomHeaders() + { + return $this->CustomHeader; + } + + /** + * Create a message body from an HTML string. + * Automatically inlines images and creates a plain-text version by converting the HTML, + * overwriting any existing values in Body and AltBody. + * Do not source $message content from user input! + * $basedir is prepended when handling relative URLs, e.g. and must not be empty + * will look for an image file in $basedir/images/a.png and convert it to inline. + * If you don't provide a $basedir, relative paths will be left untouched (and thus probably break in email) + * Converts data-uri images into embedded attachments. + * If you don't want to apply these transformations to your HTML, just set Body and AltBody directly. + * + * @param string $message HTML message string + * @param string $basedir Absolute path to a base directory to prepend to relative paths to images + * @param bool|callable $advanced Whether to use the internal HTML to text converter + * or your own custom converter @return string $message The transformed message Body + * + * @throws Exception + * + * @see PHPMailer::html2text() + */ + public function msgHTML($message, $basedir = '', $advanced = false) + { + preg_match_all('/(? 1 && '/' !== substr($basedir, -1)) { + // Ensure $basedir has a trailing / + $basedir .= '/'; + } + foreach ($images[2] as $imgindex => $url) { + // Convert data URIs into embedded images + //e.g. "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" + $match = []; + if (preg_match('#^data:(image/(?:jpe?g|gif|png));?(base64)?,(.+)#', $url, $match)) { + if (count($match) === 4 && static::ENCODING_BASE64 === $match[2]) { + $data = base64_decode($match[3]); + } elseif ('' === $match[2]) { + $data = rawurldecode($match[3]); + } else { + //Not recognised so leave it alone + continue; + } + //Hash the decoded data, not the URL, so that the same data-URI image used in multiple places + //will only be embedded once, even if it used a different encoding + $cid = substr(hash('sha256', $data), 0, 32) . '@phpmailer.0'; // RFC2392 S 2 + + if (!$this->cidExists($cid)) { + $this->addStringEmbeddedImage( + $data, + $cid, + 'embed' . $imgindex, + static::ENCODING_BASE64, + $match[1] + ); + } + $message = str_replace( + $images[0][$imgindex], + $images[1][$imgindex] . '="cid:' . $cid . '"', + $message + ); + continue; + } + if (// Only process relative URLs if a basedir is provided (i.e. no absolute local paths) + !empty($basedir) + // Ignore URLs containing parent dir traversal (..) + && (strpos($url, '..') === false) + // Do not change urls that are already inline images + && 0 !== strpos($url, 'cid:') + // Do not change absolute URLs, including anonymous protocol + && !preg_match('#^[a-z][a-z0-9+.-]*:?//#i', $url) + ) { + $filename = static::mb_pathinfo($url, PATHINFO_BASENAME); + $directory = dirname($url); + if ('.' === $directory) { + $directory = ''; + } + // RFC2392 S 2 + $cid = substr(hash('sha256', $url), 0, 32) . '@phpmailer.0'; + if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) { + $basedir .= '/'; + } + if (strlen($directory) > 1 && '/' !== substr($directory, -1)) { + $directory .= '/'; + } + if ($this->addEmbeddedImage( + $basedir . $directory . $filename, + $cid, + $filename, + static::ENCODING_BASE64, + static::_mime_types((string) static::mb_pathinfo($filename, PATHINFO_EXTENSION)) + ) + ) { + $message = preg_replace( + '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui', + $images[1][$imgindex] . '="cid:' . $cid . '"', + $message + ); + } + } + } + } + $this->isHTML(); + // Convert all message body line breaks to LE, makes quoted-printable encoding work much better + $this->Body = static::normalizeBreaks($message); + $this->AltBody = static::normalizeBreaks($this->html2text($message, $advanced)); + if (!$this->alternativeExists()) { + $this->AltBody = 'This is an HTML-only message. To view it, activate HTML in your email application.' + . static::$LE; + } + + return $this->Body; + } + + /** + * Convert an HTML string into plain text. + * This is used by msgHTML(). + * Note - older versions of this function used a bundled advanced converter + * which was removed for license reasons in #232. + * Example usage: + * + * ```php + * // Use default conversion + * $plain = $mail->html2text($html); + * // Use your own custom converter + * $plain = $mail->html2text($html, function($html) { + * $converter = new MyHtml2text($html); + * return $converter->get_text(); + * }); + * ``` + * + * @param string $html The HTML text to convert + * @param bool|callable $advanced Any boolean value to use the internal converter, + * or provide your own callable for custom conversion + * + * @return string + */ + public function html2text($html, $advanced = false) + { + if (is_callable($advanced)) { + return $advanced($html); + } + + return html_entity_decode( + trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))), + ENT_QUOTES, + $this->CharSet + ); + } + + /** + * Get the MIME type for a file extension. + * + * @param string $ext File extension + * + * @return string MIME type of file + */ + public static function _mime_types($ext = '') + { + $mimes = [ + 'xl' => 'application/excel', + 'js' => 'application/javascript', + 'hqx' => 'application/mac-binhex40', + 'cpt' => 'application/mac-compactpro', + 'bin' => 'application/macbinary', + 'doc' => 'application/msword', + 'word' => 'application/msword', + 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', + 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', + 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', + 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', + 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', + 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12', + 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12', + 'class' => 'application/octet-stream', + 'dll' => 'application/octet-stream', + 'dms' => 'application/octet-stream', + 'exe' => 'application/octet-stream', + 'lha' => 'application/octet-stream', + 'lzh' => 'application/octet-stream', + 'psd' => 'application/octet-stream', + 'sea' => 'application/octet-stream', + 'so' => 'application/octet-stream', + 'oda' => 'application/oda', + 'pdf' => 'application/pdf', + 'ai' => 'application/postscript', + 'eps' => 'application/postscript', + 'ps' => 'application/postscript', + 'smi' => 'application/smil', + 'smil' => 'application/smil', + 'mif' => 'application/vnd.mif', + 'xls' => 'application/vnd.ms-excel', + 'ppt' => 'application/vnd.ms-powerpoint', + 'wbxml' => 'application/vnd.wap.wbxml', + 'wmlc' => 'application/vnd.wap.wmlc', + 'dcr' => 'application/x-director', + 'dir' => 'application/x-director', + 'dxr' => 'application/x-director', + 'dvi' => 'application/x-dvi', + 'gtar' => 'application/x-gtar', + 'php3' => 'application/x-httpd-php', + 'php4' => 'application/x-httpd-php', + 'php' => 'application/x-httpd-php', + 'phtml' => 'application/x-httpd-php', + 'phps' => 'application/x-httpd-php-source', + 'swf' => 'application/x-shockwave-flash', + 'sit' => 'application/x-stuffit', + 'tar' => 'application/x-tar', + 'tgz' => 'application/x-tar', + 'xht' => 'application/xhtml+xml', + 'xhtml' => 'application/xhtml+xml', + 'zip' => 'application/zip', + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mp2' => 'audio/mpeg', + 'mp3' => 'audio/mpeg', + 'm4a' => 'audio/mp4', + 'mpga' => 'audio/mpeg', + 'aif' => 'audio/x-aiff', + 'aifc' => 'audio/x-aiff', + 'aiff' => 'audio/x-aiff', + 'ram' => 'audio/x-pn-realaudio', + 'rm' => 'audio/x-pn-realaudio', + 'rpm' => 'audio/x-pn-realaudio-plugin', + 'ra' => 'audio/x-realaudio', + 'wav' => 'audio/x-wav', + 'mka' => 'audio/x-matroska', + 'bmp' => 'image/bmp', + 'gif' => 'image/gif', + 'jpeg' => 'image/jpeg', + 'jpe' => 'image/jpeg', + 'jpg' => 'image/jpeg', + 'png' => 'image/png', + 'tiff' => 'image/tiff', + 'tif' => 'image/tiff', + 'webp' => 'image/webp', + 'heif' => 'image/heif', + 'heifs' => 'image/heif-sequence', + 'heic' => 'image/heic', + 'heics' => 'image/heic-sequence', + 'eml' => 'message/rfc822', + 'css' => 'text/css', + 'html' => 'text/html', + 'htm' => 'text/html', + 'shtml' => 'text/html', + 'log' => 'text/plain', + 'text' => 'text/plain', + 'txt' => 'text/plain', + 'rtx' => 'text/richtext', + 'rtf' => 'text/rtf', + 'vcf' => 'text/vcard', + 'vcard' => 'text/vcard', + 'ics' => 'text/calendar', + 'xml' => 'text/xml', + 'xsl' => 'text/xml', + 'wmv' => 'video/x-ms-wmv', + 'mpeg' => 'video/mpeg', + 'mpe' => 'video/mpeg', + 'mpg' => 'video/mpeg', + 'mp4' => 'video/mp4', + 'm4v' => 'video/mp4', + 'mov' => 'video/quicktime', + 'qt' => 'video/quicktime', + 'rv' => 'video/vnd.rn-realvideo', + 'avi' => 'video/x-msvideo', + 'movie' => 'video/x-sgi-movie', + 'webm' => 'video/webm', + 'mkv' => 'video/x-matroska', + ]; + $ext = strtolower($ext); + if (array_key_exists($ext, $mimes)) { + return $mimes[$ext]; + } + + return 'application/octet-stream'; + } + + /** + * Map a file name to a MIME type. + * Defaults to 'application/octet-stream', i.e.. arbitrary binary data. + * + * @param string $filename A file name or full path, does not need to exist as a file + * + * @return string + */ + public static function filenameToType($filename) + { + // In case the path is a URL, strip any query string before getting extension + $qpos = strpos($filename, '?'); + if (false !== $qpos) { + $filename = substr($filename, 0, $qpos); + } + $ext = static::mb_pathinfo($filename, PATHINFO_EXTENSION); + + return static::_mime_types($ext); + } + + /** + * Multi-byte-safe pathinfo replacement. + * Drop-in replacement for pathinfo(), but multibyte- and cross-platform-safe. + * + * @see http://www.php.net/manual/en/function.pathinfo.php#107461 + * + * @param string $path A filename or path, does not need to exist as a file + * @param int|string $options Either a PATHINFO_* constant, + * or a string name to return only the specified piece + * + * @return string|array + */ + public static function mb_pathinfo($path, $options = null) + { + $ret = ['dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '']; + $pathinfo = []; + if (preg_match('#^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^.\\\\/]+?)|))[\\\\/.]*$#m', $path, $pathinfo)) { + if (array_key_exists(1, $pathinfo)) { + $ret['dirname'] = $pathinfo[1]; + } + if (array_key_exists(2, $pathinfo)) { + $ret['basename'] = $pathinfo[2]; + } + if (array_key_exists(5, $pathinfo)) { + $ret['extension'] = $pathinfo[5]; + } + if (array_key_exists(3, $pathinfo)) { + $ret['filename'] = $pathinfo[3]; + } + } + switch ($options) { + case PATHINFO_DIRNAME: + case 'dirname': + return $ret['dirname']; + case PATHINFO_BASENAME: + case 'basename': + return $ret['basename']; + case PATHINFO_EXTENSION: + case 'extension': + return $ret['extension']; + case PATHINFO_FILENAME: + case 'filename': + return $ret['filename']; + default: + return $ret; + } + } + + /** + * Set or reset instance properties. + * You should avoid this function - it's more verbose, less efficient, more error-prone and + * harder to debug than setting properties directly. + * Usage Example: + * `$mail->set('SMTPSecure', static::ENCRYPTION_STARTTLS);` + * is the same as: + * `$mail->SMTPSecure = static::ENCRYPTION_STARTTLS;`. + * + * @param string $name The property name to set + * @param mixed $value The value to set the property to + * + * @return bool + */ + public function set($name, $value = '') + { + if (property_exists($this, $name)) { + $this->$name = $value; + + return true; + } + $this->setError($this->lang('variable_set') . $name); + + return false; + } + + /** + * Strip newlines to prevent header injection. + * + * @param string $str + * + * @return string + */ + public function secureHeader($str) + { + return trim(str_replace(["\r", "\n"], '', $str)); + } + + /** + * Normalize line breaks in a string. + * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format. + * Defaults to CRLF (for message bodies) and preserves consecutive breaks. + * + * @param string $text + * @param string $breaktype What kind of line break to use; defaults to static::$LE + * + * @return string + */ + public static function normalizeBreaks($text, $breaktype = null) + { + if (null === $breaktype) { + $breaktype = static::$LE; + } + // Normalise to \n + $text = str_replace([self::CRLF, "\r"], "\n", $text); + // Now convert LE as needed + if ("\n" !== $breaktype) { + $text = str_replace("\n", $breaktype, $text); + } + + return $text; + } + + /** + * Remove trailing breaks from a string. + * + * @param string $text + * + * @return string The text to remove breaks from + */ + public static function stripTrailingWSP($text) + { + return rtrim($text, " \r\n\t"); + } + + /** + * Return the current line break format string. + * + * @return string + */ + public static function getLE() + { + return static::$LE; + } + + /** + * Set the line break format string, e.g. "\r\n". + * + * @param string $le + */ + protected static function setLE($le) + { + static::$LE = $le; + } + + /** + * Set the public and private key files and password for S/MIME signing. + * + * @param string $cert_filename + * @param string $key_filename + * @param string $key_pass Password for private key + * @param string $extracerts_filename Optional path to chain certificate + */ + public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '') + { + $this->sign_cert_file = $cert_filename; + $this->sign_key_file = $key_filename; + $this->sign_key_pass = $key_pass; + $this->sign_extracerts_file = $extracerts_filename; + } + + /** + * Quoted-Printable-encode a DKIM header. + * + * @param string $txt + * + * @return string + */ + public function DKIM_QP($txt) + { + $line = ''; + $len = strlen($txt); + for ($i = 0; $i < $len; ++$i) { + $ord = ord($txt[$i]); + if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord === 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) { + $line .= $txt[$i]; + } else { + $line .= '=' . sprintf('%02X', $ord); + } + } + + return $line; + } + + /** + * Generate a DKIM signature. + * + * @param string $signHeader + * + * @throws Exception + * + * @return string The DKIM signature value + */ + public function DKIM_Sign($signHeader) + { + if (!defined('PKCS7_TEXT')) { + if ($this->exceptions) { + throw new Exception($this->lang('extension_missing') . 'openssl'); + } + + return ''; + } + $privKeyStr = !empty($this->DKIM_private_string) ? + $this->DKIM_private_string : + file_get_contents($this->DKIM_private); + if ('' !== $this->DKIM_passphrase) { + $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase); + } else { + $privKey = openssl_pkey_get_private($privKeyStr); + } + if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) { + openssl_pkey_free($privKey); + + return base64_encode($signature); + } + openssl_pkey_free($privKey); + + return ''; + } + + /** + * Generate a DKIM canonicalization header. + * Uses the 'relaxed' algorithm from RFC6376 section 3.4.2. + * Canonicalized headers should *always* use CRLF, regardless of mailer setting. + * + * @see https://tools.ietf.org/html/rfc6376#section-3.4.2 + * + * @param string $signHeader Header + * + * @return string + */ + public function DKIM_HeaderC($signHeader) + { + //Normalize breaks to CRLF (regardless of the mailer) + $signHeader = static::normalizeBreaks($signHeader, self::CRLF); + //Unfold header lines + //Note PCRE \s is too broad a definition of whitespace; RFC5322 defines it as `[ \t]` + //@see https://tools.ietf.org/html/rfc5322#section-2.2 + //That means this may break if you do something daft like put vertical tabs in your headers. + $signHeader = preg_replace('/\r\n[ \t]+/', ' ', $signHeader); + //Break headers out into an array + $lines = explode(self::CRLF, $signHeader); + foreach ($lines as $key => $line) { + //If the header is missing a :, skip it as it's invalid + //This is likely to happen because the explode() above will also split + //on the trailing LE, leaving an empty line + if (strpos($line, ':') === false) { + continue; + } + list($heading, $value) = explode(':', $line, 2); + //Lower-case header name + $heading = strtolower($heading); + //Collapse white space within the value, also convert WSP to space + $value = preg_replace('/[ \t]+/', ' ', $value); + //RFC6376 is slightly unclear here - it says to delete space at the *end* of each value + //But then says to delete space before and after the colon. + //Net result is the same as trimming both ends of the value. + //By elimination, the same applies to the field name + $lines[$key] = trim($heading, " \t") . ':' . trim($value, " \t"); + } + + return implode(self::CRLF, $lines); + } + + /** + * Generate a DKIM canonicalization body. + * Uses the 'simple' algorithm from RFC6376 section 3.4.3. + * Canonicalized bodies should *always* use CRLF, regardless of mailer setting. + * + * @see https://tools.ietf.org/html/rfc6376#section-3.4.3 + * + * @param string $body Message Body + * + * @return string + */ + public function DKIM_BodyC($body) + { + if (empty($body)) { + return self::CRLF; + } + // Normalize line endings to CRLF + $body = static::normalizeBreaks($body, self::CRLF); + + //Reduce multiple trailing line breaks to a single one + return static::stripTrailingWSP($body) . self::CRLF; + } + + /** + * Create the DKIM header and body in a new message header. + * + * @param string $headers_line Header lines + * @param string $subject Subject + * @param string $body Body + * + * @throws Exception + * + * @return string + */ + public function DKIM_Add($headers_line, $subject, $body) + { + $DKIMsignatureType = 'rsa-sha256'; // Signature & hash algorithms + $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization methods of header & body + $DKIMquery = 'dns/txt'; // Query method + $DKIMtime = time(); + //Always sign these headers without being asked + //Recommended list from https://tools.ietf.org/html/rfc6376#section-5.4.1 + $autoSignHeaders = [ + 'from', + 'to', + 'cc', + 'date', + 'subject', + 'reply-to', + 'message-id', + 'content-type', + 'mime-version', + 'x-mailer', + ]; + if (stripos($headers_line, 'Subject') === false) { + $headers_line .= 'Subject: ' . $subject . static::$LE; + } + $headerLines = explode(static::$LE, $headers_line); + $currentHeaderLabel = ''; + $currentHeaderValue = ''; + $parsedHeaders = []; + $headerLineIndex = 0; + $headerLineCount = count($headerLines); + foreach ($headerLines as $headerLine) { + $matches = []; + if (preg_match('/^([^ \t]*?)(?::[ \t]*)(.*)$/', $headerLine, $matches)) { + if ($currentHeaderLabel !== '') { + //We were previously in another header; This is the start of a new header, so save the previous one + $parsedHeaders[] = ['label' => $currentHeaderLabel, 'value' => $currentHeaderValue]; + } + $currentHeaderLabel = $matches[1]; + $currentHeaderValue = $matches[2]; + } elseif (preg_match('/^[ \t]+(.*)$/', $headerLine, $matches)) { + //This is a folded continuation of the current header, so unfold it + $currentHeaderValue .= ' ' . $matches[1]; + } + ++$headerLineIndex; + if ($headerLineIndex >= $headerLineCount) { + //This was the last line, so finish off this header + $parsedHeaders[] = ['label' => $currentHeaderLabel, 'value' => $currentHeaderValue]; + } + } + $copiedHeaders = []; + $headersToSignKeys = []; + $headersToSign = []; + foreach ($parsedHeaders as $header) { + //Is this header one that must be included in the DKIM signature? + if (in_array(strtolower($header['label']), $autoSignHeaders, true)) { + $headersToSignKeys[] = $header['label']; + $headersToSign[] = $header['label'] . ': ' . $header['value']; + if ($this->DKIM_copyHeaderFields) { + $copiedHeaders[] = $header['label'] . ':' . //Note no space after this, as per RFC + str_replace('|', '=7C', $this->DKIM_QP($header['value'])); + } + continue; + } + //Is this an extra custom header we've been asked to sign? + if (in_array($header['label'], $this->DKIM_extraHeaders, true)) { + //Find its value in custom headers + foreach ($this->CustomHeader as $customHeader) { + if ($customHeader[0] === $header['label']) { + $headersToSignKeys[] = $header['label']; + $headersToSign[] = $header['label'] . ': ' . $header['value']; + if ($this->DKIM_copyHeaderFields) { + $copiedHeaders[] = $header['label'] . ':' . //Note no space after this, as per RFC + str_replace('|', '=7C', $this->DKIM_QP($header['value'])); + } + //Skip straight to the next header + continue 2; + } + } + } + } + $copiedHeaderFields = ''; + if ($this->DKIM_copyHeaderFields && count($copiedHeaders) > 0) { + //Assemble a DKIM 'z' tag + $copiedHeaderFields = ' z='; + $first = true; + foreach ($copiedHeaders as $copiedHeader) { + if (!$first) { + $copiedHeaderFields .= static::$LE . ' |'; + } + //Fold long values + if (strlen($copiedHeader) > self::STD_LINE_LENGTH - 3) { + $copiedHeaderFields .= substr( + chunk_split($copiedHeader, self::STD_LINE_LENGTH - 3, static::$LE . self::FWS), + 0, + -strlen(static::$LE . self::FWS) + ); + } else { + $copiedHeaderFields .= $copiedHeader; + } + $first = false; + } + $copiedHeaderFields .= ';' . static::$LE; + } + $headerKeys = ' h=' . implode(':', $headersToSignKeys) . ';' . static::$LE; + $headerValues = implode(static::$LE, $headersToSign); + $body = $this->DKIM_BodyC($body); + $DKIMb64 = base64_encode(pack('H*', hash('sha256', $body))); // Base64 of packed binary SHA-256 hash of body + $ident = ''; + if ('' !== $this->DKIM_identity) { + $ident = ' i=' . $this->DKIM_identity . ';' . static::$LE; + } + //The DKIM-Signature header is included in the signature *except for* the value of the `b` tag + //which is appended after calculating the signature + //https://tools.ietf.org/html/rfc6376#section-3.5 + $dkimSignatureHeader = 'DKIM-Signature: v=1;' . + ' d=' . $this->DKIM_domain . ';' . + ' s=' . $this->DKIM_selector . ';' . static::$LE . + ' a=' . $DKIMsignatureType . ';' . + ' q=' . $DKIMquery . ';' . + ' t=' . $DKIMtime . ';' . + ' c=' . $DKIMcanonicalization . ';' . static::$LE . + $headerKeys . + $ident . + $copiedHeaderFields . + ' bh=' . $DKIMb64 . ';' . static::$LE . + ' b='; + //Canonicalize the set of headers + $canonicalizedHeaders = $this->DKIM_HeaderC( + $headerValues . static::$LE . $dkimSignatureHeader + ); + $signature = $this->DKIM_Sign($canonicalizedHeaders); + $signature = trim(chunk_split($signature, self::STD_LINE_LENGTH - 3, static::$LE . self::FWS)); + + return static::normalizeBreaks($dkimSignatureHeader . $signature); + } + + /** + * Detect if a string contains a line longer than the maximum line length + * allowed by RFC 2822 section 2.1.1. + * + * @param string $str + * + * @return bool + */ + public static function hasLineLongerThanMax($str) + { + return (bool) preg_match('/^(.{' . (self::MAX_LINE_LENGTH + strlen(static::$LE)) . ',})/m', $str); + } + + /** + * If a string contains any "special" characters, double-quote the name, + * and escape any double quotes with a backslash. + * + * @param string $str + * + * @return string + * + * @see RFC822 3.4.1 + */ + public static function quotedString($str) + { + if (preg_match('/[ ()<>@,;:"\/\[\]?=]/', $str)) { + //If the string contains any of these chars, it must be double-quoted + //and any double quotes must be escaped with a backslash + return '"' . str_replace('"', '\\"', $str) . '"'; + } + + //Return the string untouched, it doesn't need quoting + return $str; + } + + /** + * Allows for public read access to 'to' property. + * Before the send() call, queued addresses (i.e. with IDN) are not yet included. + * + * @return array + */ + public function getToAddresses() + { + return $this->to; + } + + /** + * Allows for public read access to 'cc' property. + * Before the send() call, queued addresses (i.e. with IDN) are not yet included. + * + * @return array + */ + public function getCcAddresses() + { + return $this->cc; + } + + /** + * Allows for public read access to 'bcc' property. + * Before the send() call, queued addresses (i.e. with IDN) are not yet included. + * + * @return array + */ + public function getBccAddresses() + { + return $this->bcc; + } + + /** + * Allows for public read access to 'ReplyTo' property. + * Before the send() call, queued addresses (i.e. with IDN) are not yet included. + * + * @return array + */ + public function getReplyToAddresses() + { + return $this->ReplyTo; + } + + /** + * Allows for public read access to 'all_recipients' property. + * Before the send() call, queued addresses (i.e. with IDN) are not yet included. + * + * @return array + */ + public function getAllRecipientAddresses() + { + return $this->all_recipients; + } + + /** + * Perform a callback. + * + * @param bool $isSent + * @param array $to + * @param array $cc + * @param array $bcc + * @param string $subject + * @param string $body + * @param string $from + * @param array $extra + */ + protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from, $extra) + { + if (!empty($this->action_function) && is_callable($this->action_function)) { + call_user_func($this->action_function, $isSent, $to, $cc, $bcc, $subject, $body, $from, $extra); + } + } + + /** + * Get the OAuth instance. + * + * @return OAuth + */ + public function getOAuth() + { + return $this->oauth; + } + + /** + * Set an OAuth instance. + */ + public function setOAuth(OAuth $oauth) + { + $this->oauth = $oauth; + } +} diff --git a/src/bb-vendor/phpmailer/phpmailer/src/POP3.php b/src/bb-vendor/phpmailer/phpmailer/src/POP3.php new file mode 100644 index 000000000..7d4c88f6c --- /dev/null +++ b/src/bb-vendor/phpmailer/phpmailer/src/POP3.php @@ -0,0 +1,421 @@ + + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + * @copyright 2012 - 2019 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ + +namespace PHPMailer\PHPMailer; + +/** + * PHPMailer POP-Before-SMTP Authentication Class. + * Specifically for PHPMailer to use for RFC1939 POP-before-SMTP authentication. + * 1) This class does not support APOP authentication. + * 2) Opening and closing lots of POP3 connections can be quite slow. If you need + * to send a batch of emails then just perform the authentication once at the start, + * and then loop through your mail sending script. Providing this process doesn't + * take longer than the verification period lasts on your POP3 server, you should be fine. + * 3) This is really ancient technology; you should only need to use it to talk to very old systems. + * 4) This POP3 class is deliberately lightweight and incomplete, implementing just + * enough to do authentication. + * If you want a more complete class there are other POP3 classes for PHP available. + * + * @author Richard Davey (original author) + * @author Marcus Bointon (Synchro/coolbru) + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + */ +class POP3 +{ + /** + * The POP3 PHPMailer Version number. + * + * @var string + */ + const VERSION = '6.1.6'; + + /** + * Default POP3 port number. + * + * @var int + */ + const DEFAULT_PORT = 110; + + /** + * Default timeout in seconds. + * + * @var int + */ + const DEFAULT_TIMEOUT = 30; + + /** + * Debug display level. + * Options: 0 = no, 1+ = yes. + * + * @var int + */ + public $do_debug = 0; + + /** + * POP3 mail server hostname. + * + * @var string + */ + public $host; + + /** + * POP3 port number. + * + * @var int + */ + public $port; + + /** + * POP3 Timeout Value in seconds. + * + * @var int + */ + public $tval; + + /** + * POP3 username. + * + * @var string + */ + public $username; + + /** + * POP3 password. + * + * @var string + */ + public $password; + + /** + * Resource handle for the POP3 connection socket. + * + * @var resource + */ + protected $pop_conn; + + /** + * Are we connected? + * + * @var bool + */ + protected $connected = false; + + /** + * Error container. + * + * @var array + */ + protected $errors = []; + + /** + * Line break constant. + */ + const LE = "\r\n"; + + /** + * Simple static wrapper for all-in-one POP before SMTP. + * + * @param string $host The hostname to connect to + * @param int|bool $port The port number to connect to + * @param int|bool $timeout The timeout value + * @param string $username + * @param string $password + * @param int $debug_level + * + * @return bool + */ + public static function popBeforeSmtp( + $host, + $port = false, + $timeout = false, + $username = '', + $password = '', + $debug_level = 0 + ) { + $pop = new self(); + + return $pop->authorise($host, $port, $timeout, $username, $password, $debug_level); + } + + /** + * Authenticate with a POP3 server. + * A connect, login, disconnect sequence + * appropriate for POP-before SMTP authorisation. + * + * @param string $host The hostname to connect to + * @param int|bool $port The port number to connect to + * @param int|bool $timeout The timeout value + * @param string $username + * @param string $password + * @param int $debug_level + * + * @return bool + */ + public function authorise($host, $port = false, $timeout = false, $username = '', $password = '', $debug_level = 0) + { + $this->host = $host; + // If no port value provided, use default + if (false === $port) { + $this->port = static::DEFAULT_PORT; + } else { + $this->port = (int) $port; + } + // If no timeout value provided, use default + if (false === $timeout) { + $this->tval = static::DEFAULT_TIMEOUT; + } else { + $this->tval = (int) $timeout; + } + $this->do_debug = $debug_level; + $this->username = $username; + $this->password = $password; + // Reset the error log + $this->errors = []; + // connect + $result = $this->connect($this->host, $this->port, $this->tval); + if ($result) { + $login_result = $this->login($this->username, $this->password); + if ($login_result) { + $this->disconnect(); + + return true; + } + } + // We need to disconnect regardless of whether the login succeeded + $this->disconnect(); + + return false; + } + + /** + * Connect to a POP3 server. + * + * @param string $host + * @param int|bool $port + * @param int $tval + * + * @return bool + */ + public function connect($host, $port = false, $tval = 30) + { + // Are we already connected? + if ($this->connected) { + return true; + } + + //On Windows this will raise a PHP Warning error if the hostname doesn't exist. + //Rather than suppress it with @fsockopen, capture it cleanly instead + set_error_handler([$this, 'catchWarning']); + + if (false === $port) { + $port = static::DEFAULT_PORT; + } + + // connect to the POP3 server + $errno = 0; + $errstr = ''; + $this->pop_conn = fsockopen( + $host, // POP3 Host + $port, // Port # + $errno, // Error Number + $errstr, // Error Message + $tval + ); // Timeout (seconds) + // Restore the error handler + restore_error_handler(); + + // Did we connect? + if (false === $this->pop_conn) { + // It would appear not... + $this->setError( + "Failed to connect to server $host on port $port. errno: $errno; errstr: $errstr" + ); + + return false; + } + + // Increase the stream time-out + stream_set_timeout($this->pop_conn, $tval, 0); + + // Get the POP3 server response + $pop3_response = $this->getResponse(); + // Check for the +OK + if ($this->checkResponse($pop3_response)) { + // The connection is established and the POP3 server is talking + $this->connected = true; + + return true; + } + + return false; + } + + /** + * Log in to the POP3 server. + * Does not support APOP (RFC 2828, 4949). + * + * @param string $username + * @param string $password + * + * @return bool + */ + public function login($username = '', $password = '') + { + if (!$this->connected) { + $this->setError('Not connected to POP3 server'); + } + if (empty($username)) { + $username = $this->username; + } + if (empty($password)) { + $password = $this->password; + } + + // Send the Username + $this->sendString("USER $username" . static::LE); + $pop3_response = $this->getResponse(); + if ($this->checkResponse($pop3_response)) { + // Send the Password + $this->sendString("PASS $password" . static::LE); + $pop3_response = $this->getResponse(); + if ($this->checkResponse($pop3_response)) { + return true; + } + } + + return false; + } + + /** + * Disconnect from the POP3 server. + */ + public function disconnect() + { + $this->sendString('QUIT'); + //The QUIT command may cause the daemon to exit, which will kill our connection + //So ignore errors here + try { + @fclose($this->pop_conn); + } catch (Exception $e) { + //Do nothing + } + } + + /** + * Get a response from the POP3 server. + * + * @param int $size The maximum number of bytes to retrieve + * + * @return string + */ + protected function getResponse($size = 128) + { + $response = fgets($this->pop_conn, $size); + if ($this->do_debug >= 1) { + echo 'Server -> Client: ', $response; + } + + return $response; + } + + /** + * Send raw data to the POP3 server. + * + * @param string $string + * + * @return int + */ + protected function sendString($string) + { + if ($this->pop_conn) { + if ($this->do_debug >= 2) { //Show client messages when debug >= 2 + echo 'Client -> Server: ', $string; + } + + return fwrite($this->pop_conn, $string, strlen($string)); + } + + return 0; + } + + /** + * Checks the POP3 server response. + * Looks for for +OK or -ERR. + * + * @param string $string + * + * @return bool + */ + protected function checkResponse($string) + { + if (strpos($string, '+OK') !== 0) { + $this->setError("Server reported an error: $string"); + + return false; + } + + return true; + } + + /** + * Add an error to the internal error store. + * Also display debug output if it's enabled. + * + * @param string $error + */ + protected function setError($error) + { + $this->errors[] = $error; + if ($this->do_debug >= 1) { + echo '
    ';
    +            foreach ($this->errors as $e) {
    +                print_r($e);
    +            }
    +            echo '
    '; + } + } + + /** + * Get an array of error messages, if any. + * + * @return array + */ + public function getErrors() + { + return $this->errors; + } + + /** + * POP3 connection error handler. + * + * @param int $errno + * @param string $errstr + * @param string $errfile + * @param int $errline + */ + protected function catchWarning($errno, $errstr, $errfile, $errline) + { + $this->setError( + 'Connecting to the POP3 server raised a PHP warning:' . + "errno: $errno errstr: $errstr; errfile: $errfile; errline: $errline" + ); + } +} diff --git a/src/bb-vendor/phpmailer/phpmailer/src/SMTP.php b/src/bb-vendor/phpmailer/phpmailer/src/SMTP.php new file mode 100644 index 000000000..aa5555149 --- /dev/null +++ b/src/bb-vendor/phpmailer/phpmailer/src/SMTP.php @@ -0,0 +1,1371 @@ + + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + * @copyright 2012 - 2019 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ + +namespace PHPMailer\PHPMailer; + +/** + * PHPMailer RFC821 SMTP email transport class. + * Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server. + * + * @author Chris Ryan + * @author Marcus Bointon + */ +class SMTP +{ + /** + * The PHPMailer SMTP version number. + * + * @var string + */ + const VERSION = '6.1.6'; + + /** + * SMTP line break constant. + * + * @var string + */ + const LE = "\r\n"; + + /** + * The SMTP port to use if one is not specified. + * + * @var int + */ + const DEFAULT_PORT = 25; + + /** + * The maximum line length allowed by RFC 5321 section 4.5.3.1.6, + * *excluding* a trailing CRLF break. + * + * @see https://tools.ietf.org/html/rfc5321#section-4.5.3.1.6 + * + * @var int + */ + const MAX_LINE_LENGTH = 998; + + /** + * The maximum line length allowed for replies in RFC 5321 section 4.5.3.1.5, + * *including* a trailing CRLF line break. + * + * @see https://tools.ietf.org/html/rfc5321#section-4.5.3.1.5 + * + * @var int + */ + const MAX_REPLY_LENGTH = 512; + + /** + * Debug level for no output. + * + * @var int + */ + const DEBUG_OFF = 0; + + /** + * Debug level to show client -> server messages. + * + * @var int + */ + const DEBUG_CLIENT = 1; + + /** + * Debug level to show client -> server and server -> client messages. + * + * @var int + */ + const DEBUG_SERVER = 2; + + /** + * Debug level to show connection status, client -> server and server -> client messages. + * + * @var int + */ + const DEBUG_CONNECTION = 3; + + /** + * Debug level to show all messages. + * + * @var int + */ + const DEBUG_LOWLEVEL = 4; + + /** + * Debug output level. + * Options: + * * self::DEBUG_OFF (`0`) No debug output, default + * * self::DEBUG_CLIENT (`1`) Client commands + * * self::DEBUG_SERVER (`2`) Client commands and server responses + * * self::DEBUG_CONNECTION (`3`) As DEBUG_SERVER plus connection status + * * self::DEBUG_LOWLEVEL (`4`) Low-level data output, all messages. + * + * @var int + */ + public $do_debug = self::DEBUG_OFF; + + /** + * How to handle debug output. + * Options: + * * `echo` Output plain-text as-is, appropriate for CLI + * * `html` Output escaped, line breaks converted to `
    `, appropriate for browser output + * * `error_log` Output to error log as configured in php.ini + * Alternatively, you can provide a callable expecting two params: a message string and the debug level: + * + * ```php + * $smtp->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";}; + * ``` + * + * Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug` + * level output is used: + * + * ```php + * $mail->Debugoutput = new myPsr3Logger; + * ``` + * + * @var string|callable|\Psr\Log\LoggerInterface + */ + public $Debugoutput = 'echo'; + + /** + * Whether to use VERP. + * + * @see http://en.wikipedia.org/wiki/Variable_envelope_return_path + * @see http://www.postfix.org/VERP_README.html Info on VERP + * + * @var bool + */ + public $do_verp = false; + + /** + * The timeout value for connection, in seconds. + * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2. + * This needs to be quite high to function correctly with hosts using greetdelay as an anti-spam measure. + * + * @see http://tools.ietf.org/html/rfc2821#section-4.5.3.2 + * + * @var int + */ + public $Timeout = 300; + + /** + * How long to wait for commands to complete, in seconds. + * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2. + * + * @var int + */ + public $Timelimit = 300; + + /** + * Patterns to extract an SMTP transaction id from reply to a DATA command. + * The first capture group in each regex will be used as the ID. + * MS ESMTP returns the message ID, which may not be correct for internal tracking. + * + * @var string[] + */ + protected $smtp_transaction_id_patterns = [ + 'exim' => '/[\d]{3} OK id=(.*)/', + 'sendmail' => '/[\d]{3} 2.0.0 (.*) Message/', + 'postfix' => '/[\d]{3} 2.0.0 Ok: queued as (.*)/', + 'Microsoft_ESMTP' => '/[0-9]{3} 2.[\d].0 (.*)@(?:.*) Queued mail for delivery/', + 'Amazon_SES' => '/[\d]{3} Ok (.*)/', + 'SendGrid' => '/[\d]{3} Ok: queued as (.*)/', + 'CampaignMonitor' => '/[\d]{3} 2.0.0 OK:([a-zA-Z\d]{48})/', + ]; + + /** + * The last transaction ID issued in response to a DATA command, + * if one was detected. + * + * @var string|bool|null + */ + protected $last_smtp_transaction_id; + + /** + * The socket for the server connection. + * + * @var ?resource + */ + protected $smtp_conn; + + /** + * Error information, if any, for the last SMTP command. + * + * @var array + */ + protected $error = [ + 'error' => '', + 'detail' => '', + 'smtp_code' => '', + 'smtp_code_ex' => '', + ]; + + /** + * The reply the server sent to us for HELO. + * If null, no HELO string has yet been received. + * + * @var string|null + */ + protected $helo_rply; + + /** + * The set of SMTP extensions sent in reply to EHLO command. + * Indexes of the array are extension names. + * Value at index 'HELO' or 'EHLO' (according to command that was sent) + * represents the server name. In case of HELO it is the only element of the array. + * Other values can be boolean TRUE or an array containing extension options. + * If null, no HELO/EHLO string has yet been received. + * + * @var array|null + */ + protected $server_caps; + + /** + * The most recent reply received from the server. + * + * @var string + */ + protected $last_reply = ''; + + /** + * Output debugging info via a user-selected method. + * + * @param string $str Debug string to output + * @param int $level The debug level of this message; see DEBUG_* constants + * + * @see SMTP::$Debugoutput + * @see SMTP::$do_debug + */ + protected function edebug($str, $level = 0) + { + if ($level > $this->do_debug) { + return; + } + //Is this a PSR-3 logger? + if ($this->Debugoutput instanceof \Psr\Log\LoggerInterface) { + $this->Debugoutput->debug($str); + + return; + } + //Avoid clash with built-in function names + if (is_callable($this->Debugoutput) && !in_array($this->Debugoutput, ['error_log', 'html', 'echo'])) { + call_user_func($this->Debugoutput, $str, $level); + + return; + } + switch ($this->Debugoutput) { + case 'error_log': + //Don't output, just log + error_log($str); + break; + case 'html': + //Cleans up output a bit for a better looking, HTML-safe output + echo gmdate('Y-m-d H:i:s'), ' ', htmlentities( + preg_replace('/[\r\n]+/', '', $str), + ENT_QUOTES, + 'UTF-8' + ), "
    \n"; + break; + case 'echo': + default: + //Normalize line breaks + $str = preg_replace('/\r\n|\r/m', "\n", $str); + echo gmdate('Y-m-d H:i:s'), + "\t", + //Trim trailing space + trim( + //Indent for readability, except for trailing break + str_replace( + "\n", + "\n \t ", + trim($str) + ) + ), + "\n"; + } + } + + /** + * Connect to an SMTP server. + * + * @param string $host SMTP server IP or host name + * @param int $port The port number to connect to + * @param int $timeout How long to wait for the connection to open + * @param array $options An array of options for stream_context_create() + * + * @return bool + */ + public function connect($host, $port = null, $timeout = 30, $options = []) + { + static $streamok; + //This is enabled by default since 5.0.0 but some providers disable it + //Check this once and cache the result + if (null === $streamok) { + $streamok = function_exists('stream_socket_client'); + } + // Clear errors to avoid confusion + $this->setError(''); + // Make sure we are __not__ connected + if ($this->connected()) { + // Already connected, generate error + $this->setError('Already connected to a server'); + + return false; + } + if (empty($port)) { + $port = self::DEFAULT_PORT; + } + // Connect to the SMTP server + $this->edebug( + "Connection: opening to $host:$port, timeout=$timeout, options=" . + (count($options) > 0 ? var_export($options, true) : 'array()'), + self::DEBUG_CONNECTION + ); + $errno = 0; + $errstr = ''; + if ($streamok) { + $socket_context = stream_context_create($options); + set_error_handler([$this, 'errorHandler']); + $this->smtp_conn = stream_socket_client( + $host . ':' . $port, + $errno, + $errstr, + $timeout, + STREAM_CLIENT_CONNECT, + $socket_context + ); + restore_error_handler(); + } else { + //Fall back to fsockopen which should work in more places, but is missing some features + $this->edebug( + 'Connection: stream_socket_client not available, falling back to fsockopen', + self::DEBUG_CONNECTION + ); + set_error_handler([$this, 'errorHandler']); + $this->smtp_conn = fsockopen( + $host, + $port, + $errno, + $errstr, + $timeout + ); + restore_error_handler(); + } + // Verify we connected properly + if (!is_resource($this->smtp_conn)) { + $this->setError( + 'Failed to connect to server', + '', + (string) $errno, + $errstr + ); + $this->edebug( + 'SMTP ERROR: ' . $this->error['error'] + . ": $errstr ($errno)", + self::DEBUG_CLIENT + ); + + return false; + } + $this->edebug('Connection: opened', self::DEBUG_CONNECTION); + // SMTP server can take longer to respond, give longer timeout for first read + // Windows does not have support for this timeout function + if (strpos(PHP_OS, 'WIN') !== 0) { + $max = (int) ini_get('max_execution_time'); + // Don't bother if unlimited + if (0 !== $max && $timeout > $max) { + @set_time_limit($timeout); + } + stream_set_timeout($this->smtp_conn, $timeout, 0); + } + // Get any announcement + $announce = $this->get_lines(); + $this->edebug('SERVER -> CLIENT: ' . $announce, self::DEBUG_SERVER); + + return true; + } + + /** + * Initiate a TLS (encrypted) session. + * + * @return bool + */ + public function startTLS() + { + if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) { + return false; + } + + //Allow the best TLS version(s) we can + $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT; + + //PHP 5.6.7 dropped inclusion of TLS 1.1 and 1.2 in STREAM_CRYPTO_METHOD_TLS_CLIENT + //so add them back in manually if we can + if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) { + $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT; + $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT; + } + + // Begin encrypted connection + set_error_handler([$this, 'errorHandler']); + $crypto_ok = stream_socket_enable_crypto( + $this->smtp_conn, + true, + $crypto_method + ); + restore_error_handler(); + + return (bool) $crypto_ok; + } + + /** + * Perform SMTP authentication. + * Must be run after hello(). + * + * @see hello() + * + * @param string $username The user name + * @param string $password The password + * @param string $authtype The auth type (CRAM-MD5, PLAIN, LOGIN, XOAUTH2) + * @param OAuth $OAuth An optional OAuth instance for XOAUTH2 authentication + * + * @return bool True if successfully authenticated + */ + public function authenticate( + $username, + $password, + $authtype = null, + $OAuth = null + ) { + if (!$this->server_caps) { + $this->setError('Authentication is not allowed before HELO/EHLO'); + + return false; + } + + if (array_key_exists('EHLO', $this->server_caps)) { + // SMTP extensions are available; try to find a proper authentication method + if (!array_key_exists('AUTH', $this->server_caps)) { + $this->setError('Authentication is not allowed at this stage'); + // 'at this stage' means that auth may be allowed after the stage changes + // e.g. after STARTTLS + + return false; + } + + $this->edebug('Auth method requested: ' . ($authtype ?: 'UNSPECIFIED'), self::DEBUG_LOWLEVEL); + $this->edebug( + 'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']), + self::DEBUG_LOWLEVEL + ); + + //If we have requested a specific auth type, check the server supports it before trying others + if (null !== $authtype && !in_array($authtype, $this->server_caps['AUTH'], true)) { + $this->edebug('Requested auth method not available: ' . $authtype, self::DEBUG_LOWLEVEL); + $authtype = null; + } + + if (empty($authtype)) { + //If no auth mechanism is specified, attempt to use these, in this order + //Try CRAM-MD5 first as it's more secure than the others + foreach (['CRAM-MD5', 'LOGIN', 'PLAIN', 'XOAUTH2'] as $method) { + if (in_array($method, $this->server_caps['AUTH'], true)) { + $authtype = $method; + break; + } + } + if (empty($authtype)) { + $this->setError('No supported authentication methods found'); + + return false; + } + $this->edebug('Auth method selected: ' . $authtype, self::DEBUG_LOWLEVEL); + } + + if (!in_array($authtype, $this->server_caps['AUTH'], true)) { + $this->setError("The requested authentication method \"$authtype\" is not supported by the server"); + + return false; + } + } elseif (empty($authtype)) { + $authtype = 'LOGIN'; + } + switch ($authtype) { + case 'PLAIN': + // Start authentication + if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) { + return false; + } + // Send encoded username and password + if (!$this->sendCommand( + 'User & Password', + base64_encode("\0" . $username . "\0" . $password), + 235 + ) + ) { + return false; + } + break; + case 'LOGIN': + // Start authentication + if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) { + return false; + } + if (!$this->sendCommand('Username', base64_encode($username), 334)) { + return false; + } + if (!$this->sendCommand('Password', base64_encode($password), 235)) { + return false; + } + break; + case 'CRAM-MD5': + // Start authentication + if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) { + return false; + } + // Get the challenge + $challenge = base64_decode(substr($this->last_reply, 4)); + + // Build the response + $response = $username . ' ' . $this->hmac($challenge, $password); + + // send encoded credentials + return $this->sendCommand('Username', base64_encode($response), 235); + case 'XOAUTH2': + //The OAuth instance must be set up prior to requesting auth. + if (null === $OAuth) { + return false; + } + $oauth = $OAuth->getOauth64(); + + // Start authentication + if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) { + return false; + } + break; + default: + $this->setError("Authentication method \"$authtype\" is not supported"); + + return false; + } + + return true; + } + + /** + * Calculate an MD5 HMAC hash. + * Works like hash_hmac('md5', $data, $key) + * in case that function is not available. + * + * @param string $data The data to hash + * @param string $key The key to hash with + * + * @return string + */ + protected function hmac($data, $key) + { + if (function_exists('hash_hmac')) { + return hash_hmac('md5', $data, $key); + } + + // The following borrowed from + // http://php.net/manual/en/function.mhash.php#27225 + + // RFC 2104 HMAC implementation for php. + // Creates an md5 HMAC. + // Eliminates the need to install mhash to compute a HMAC + // by Lance Rushing + + $bytelen = 64; // byte length for md5 + if (strlen($key) > $bytelen) { + $key = pack('H*', md5($key)); + } + $key = str_pad($key, $bytelen, chr(0x00)); + $ipad = str_pad('', $bytelen, chr(0x36)); + $opad = str_pad('', $bytelen, chr(0x5c)); + $k_ipad = $key ^ $ipad; + $k_opad = $key ^ $opad; + + return md5($k_opad . pack('H*', md5($k_ipad . $data))); + } + + /** + * Check connection state. + * + * @return bool True if connected + */ + public function connected() + { + if (is_resource($this->smtp_conn)) { + $sock_status = stream_get_meta_data($this->smtp_conn); + if ($sock_status['eof']) { + // The socket is valid but we are not connected + $this->edebug( + 'SMTP NOTICE: EOF caught while checking if connected', + self::DEBUG_CLIENT + ); + $this->close(); + + return false; + } + + return true; // everything looks good + } + + return false; + } + + /** + * Close the socket and clean up the state of the class. + * Don't use this function without first trying to use QUIT. + * + * @see quit() + */ + public function close() + { + $this->setError(''); + $this->server_caps = null; + $this->helo_rply = null; + if (is_resource($this->smtp_conn)) { + // close the connection and cleanup + fclose($this->smtp_conn); + $this->smtp_conn = null; //Makes for cleaner serialization + $this->edebug('Connection: closed', self::DEBUG_CONNECTION); + } + } + + /** + * Send an SMTP DATA command. + * Issues a data command and sends the msg_data to the server, + * finializing the mail transaction. $msg_data is the message + * that is to be send with the headers. Each header needs to be + * on a single line followed by a with the message headers + * and the message body being separated by an additional . + * Implements RFC 821: DATA . + * + * @param string $msg_data Message data to send + * + * @return bool + */ + public function data($msg_data) + { + //This will use the standard timelimit + if (!$this->sendCommand('DATA', 'DATA', 354)) { + return false; + } + + /* The server is ready to accept data! + * According to rfc821 we should not send more than 1000 characters on a single line (including the LE) + * so we will break the data up into lines by \r and/or \n then if needed we will break each of those into + * smaller lines to fit within the limit. + * We will also look for lines that start with a '.' and prepend an additional '.'. + * NOTE: this does not count towards line-length limit. + */ + + // Normalize line breaks before exploding + $lines = explode("\n", str_replace(["\r\n", "\r"], "\n", $msg_data)); + + /* To distinguish between a complete RFC822 message and a plain message body, we check if the first field + * of the first line (':' separated) does not contain a space then it _should_ be a header and we will + * process all lines before a blank line as headers. + */ + + $field = substr($lines[0], 0, strpos($lines[0], ':')); + $in_headers = false; + if (!empty($field) && strpos($field, ' ') === false) { + $in_headers = true; + } + + foreach ($lines as $line) { + $lines_out = []; + if ($in_headers && $line === '') { + $in_headers = false; + } + //Break this line up into several smaller lines if it's too long + //Micro-optimisation: isset($str[$len]) is faster than (strlen($str) > $len), + while (isset($line[self::MAX_LINE_LENGTH])) { + //Working backwards, try to find a space within the last MAX_LINE_LENGTH chars of the line to break on + //so as to avoid breaking in the middle of a word + $pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' '); + //Deliberately matches both false and 0 + if (!$pos) { + //No nice break found, add a hard break + $pos = self::MAX_LINE_LENGTH - 1; + $lines_out[] = substr($line, 0, $pos); + $line = substr($line, $pos); + } else { + //Break at the found point + $lines_out[] = substr($line, 0, $pos); + //Move along by the amount we dealt with + $line = substr($line, $pos + 1); + } + //If processing headers add a LWSP-char to the front of new line RFC822 section 3.1.1 + if ($in_headers) { + $line = "\t" . $line; + } + } + $lines_out[] = $line; + + //Send the lines to the server + foreach ($lines_out as $line_out) { + //RFC2821 section 4.5.2 + if (!empty($line_out) && $line_out[0] === '.') { + $line_out = '.' . $line_out; + } + $this->client_send($line_out . static::LE, 'DATA'); + } + } + + //Message data has been sent, complete the command + //Increase timelimit for end of DATA command + $savetimelimit = $this->Timelimit; + $this->Timelimit *= 2; + $result = $this->sendCommand('DATA END', '.', 250); + $this->recordLastTransactionID(); + //Restore timelimit + $this->Timelimit = $savetimelimit; + + return $result; + } + + /** + * Send an SMTP HELO or EHLO command. + * Used to identify the sending server to the receiving server. + * This makes sure that client and server are in a known state. + * Implements RFC 821: HELO + * and RFC 2821 EHLO. + * + * @param string $host The host name or IP to connect to + * + * @return bool + */ + public function hello($host = '') + { + //Try extended hello first (RFC 2821) + return $this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host); + } + + /** + * Send an SMTP HELO or EHLO command. + * Low-level implementation used by hello(). + * + * @param string $hello The HELO string + * @param string $host The hostname to say we are + * + * @return bool + * + * @see hello() + */ + protected function sendHello($hello, $host) + { + $noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250); + $this->helo_rply = $this->last_reply; + if ($noerror) { + $this->parseHelloFields($hello); + } else { + $this->server_caps = null; + } + + return $noerror; + } + + /** + * Parse a reply to HELO/EHLO command to discover server extensions. + * In case of HELO, the only parameter that can be discovered is a server name. + * + * @param string $type `HELO` or `EHLO` + */ + protected function parseHelloFields($type) + { + $this->server_caps = []; + $lines = explode("\n", $this->helo_rply); + + foreach ($lines as $n => $s) { + //First 4 chars contain response code followed by - or space + $s = trim(substr($s, 4)); + if (empty($s)) { + continue; + } + $fields = explode(' ', $s); + if (!empty($fields)) { + if (!$n) { + $name = $type; + $fields = $fields[0]; + } else { + $name = array_shift($fields); + switch ($name) { + case 'SIZE': + $fields = ($fields ? $fields[0] : 0); + break; + case 'AUTH': + if (!is_array($fields)) { + $fields = []; + } + break; + default: + $fields = true; + } + } + $this->server_caps[$name] = $fields; + } + } + } + + /** + * Send an SMTP MAIL command. + * Starts a mail transaction from the email address specified in + * $from. Returns true if successful or false otherwise. If True + * the mail transaction is started and then one or more recipient + * commands may be called followed by a data command. + * Implements RFC 821: MAIL FROM: . + * + * @param string $from Source address of this message + * + * @return bool + */ + public function mail($from) + { + $useVerp = ($this->do_verp ? ' XVERP' : ''); + + return $this->sendCommand( + 'MAIL FROM', + 'MAIL FROM:<' . $from . '>' . $useVerp, + 250 + ); + } + + /** + * Send an SMTP QUIT command. + * Closes the socket if there is no error or the $close_on_error argument is true. + * Implements from RFC 821: QUIT . + * + * @param bool $close_on_error Should the connection close if an error occurs? + * + * @return bool + */ + public function quit($close_on_error = true) + { + $noerror = $this->sendCommand('QUIT', 'QUIT', 221); + $err = $this->error; //Save any error + if ($noerror || $close_on_error) { + $this->close(); + $this->error = $err; //Restore any error from the quit command + } + + return $noerror; + } + + /** + * Send an SMTP RCPT command. + * Sets the TO argument to $toaddr. + * Returns true if the recipient was accepted false if it was rejected. + * Implements from RFC 821: RCPT TO: . + * + * @param string $address The address the message is being sent to + * @param string $dsn Comma separated list of DSN notifications. NEVER, SUCCESS, FAILURE + * or DELAY. If you specify NEVER all other notifications are ignored. + * + * @return bool + */ + public function recipient($address, $dsn = '') + { + if (empty($dsn)) { + $rcpt = 'RCPT TO:<' . $address . '>'; + } else { + $dsn = strtoupper($dsn); + $notify = []; + + if (strpos($dsn, 'NEVER') !== false) { + $notify[] = 'NEVER'; + } else { + foreach (['SUCCESS', 'FAILURE', 'DELAY'] as $value) { + if (strpos($dsn, $value) !== false) { + $notify[] = $value; + } + } + } + + $rcpt = 'RCPT TO:<' . $address . '> NOTIFY=' . implode(',', $notify); + } + + return $this->sendCommand( + 'RCPT TO', + $rcpt, + [250, 251] + ); + } + + /** + * Send an SMTP RSET command. + * Abort any transaction that is currently in progress. + * Implements RFC 821: RSET . + * + * @return bool True on success + */ + public function reset() + { + return $this->sendCommand('RSET', 'RSET', 250); + } + + /** + * Send a command to an SMTP server and check its return code. + * + * @param string $command The command name - not sent to the server + * @param string $commandstring The actual command to send + * @param int|array $expect One or more expected integer success codes + * + * @return bool True on success + */ + protected function sendCommand($command, $commandstring, $expect) + { + if (!$this->connected()) { + $this->setError("Called $command without being connected"); + + return false; + } + //Reject line breaks in all commands + if ((strpos($commandstring, "\n") !== false) || (strpos($commandstring, "\r") !== false)) { + $this->setError("Command '$command' contained line breaks"); + + return false; + } + $this->client_send($commandstring . static::LE, $command); + + $this->last_reply = $this->get_lines(); + // Fetch SMTP code and possible error code explanation + $matches = []; + if (preg_match('/^([\d]{3})[ -](?:([\d]\\.[\d]\\.[\d]{1,2}) )?/', $this->last_reply, $matches)) { + $code = (int) $matches[1]; + $code_ex = (count($matches) > 2 ? $matches[2] : null); + // Cut off error code from each response line + $detail = preg_replace( + "/{$code}[ -]" . + ($code_ex ? str_replace('.', '\\.', $code_ex) . ' ' : '') . '/m', + '', + $this->last_reply + ); + } else { + // Fall back to simple parsing if regex fails + $code = (int) substr($this->last_reply, 0, 3); + $code_ex = null; + $detail = substr($this->last_reply, 4); + } + + $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER); + + if (!in_array($code, (array) $expect, true)) { + $this->setError( + "$command command failed", + $detail, + $code, + $code_ex + ); + $this->edebug( + 'SMTP ERROR: ' . $this->error['error'] . ': ' . $this->last_reply, + self::DEBUG_CLIENT + ); + + return false; + } + + $this->setError(''); + + return true; + } + + /** + * Send an SMTP SAML command. + * Starts a mail transaction from the email address specified in $from. + * Returns true if successful or false otherwise. If True + * the mail transaction is started and then one or more recipient + * commands may be called followed by a data command. This command + * will send the message to the users terminal if they are logged + * in and send them an email. + * Implements RFC 821: SAML FROM: . + * + * @param string $from The address the message is from + * + * @return bool + */ + public function sendAndMail($from) + { + return $this->sendCommand('SAML', "SAML FROM:$from", 250); + } + + /** + * Send an SMTP VRFY command. + * + * @param string $name The name to verify + * + * @return bool + */ + public function verify($name) + { + return $this->sendCommand('VRFY', "VRFY $name", [250, 251]); + } + + /** + * Send an SMTP NOOP command. + * Used to keep keep-alives alive, doesn't actually do anything. + * + * @return bool + */ + public function noop() + { + return $this->sendCommand('NOOP', 'NOOP', 250); + } + + /** + * Send an SMTP TURN command. + * This is an optional command for SMTP that this class does not support. + * This method is here to make the RFC821 Definition complete for this class + * and _may_ be implemented in future. + * Implements from RFC 821: TURN . + * + * @return bool + */ + public function turn() + { + $this->setError('The SMTP TURN command is not implemented'); + $this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT); + + return false; + } + + /** + * Send raw data to the server. + * + * @param string $data The data to send + * @param string $command Optionally, the command this is part of, used only for controlling debug output + * + * @return int|bool The number of bytes sent to the server or false on error + */ + public function client_send($data, $command = '') + { + //If SMTP transcripts are left enabled, or debug output is posted online + //it can leak credentials, so hide credentials in all but lowest level + if (self::DEBUG_LOWLEVEL > $this->do_debug && + in_array($command, ['User & Password', 'Username', 'Password'], true)) { + $this->edebug('CLIENT -> SERVER: [credentials hidden]', self::DEBUG_CLIENT); + } else { + $this->edebug('CLIENT -> SERVER: ' . $data, self::DEBUG_CLIENT); + } + set_error_handler([$this, 'errorHandler']); + $result = fwrite($this->smtp_conn, $data); + restore_error_handler(); + + return $result; + } + + /** + * Get the latest error. + * + * @return array + */ + public function getError() + { + return $this->error; + } + + /** + * Get SMTP extensions available on the server. + * + * @return array|null + */ + public function getServerExtList() + { + return $this->server_caps; + } + + /** + * Get metadata about the SMTP server from its HELO/EHLO response. + * The method works in three ways, dependent on argument value and current state: + * 1. HELO/EHLO has not been sent - returns null and populates $this->error. + * 2. HELO has been sent - + * $name == 'HELO': returns server name + * $name == 'EHLO': returns boolean false + * $name == any other string: returns null and populates $this->error + * 3. EHLO has been sent - + * $name == 'HELO'|'EHLO': returns the server name + * $name == any other string: if extension $name exists, returns True + * or its options (e.g. AUTH mechanisms supported). Otherwise returns False. + * + * @param string $name Name of SMTP extension or 'HELO'|'EHLO' + * + * @return string|bool|null + */ + public function getServerExt($name) + { + if (!$this->server_caps) { + $this->setError('No HELO/EHLO was sent'); + + return; + } + + if (!array_key_exists($name, $this->server_caps)) { + if ('HELO' === $name) { + return $this->server_caps['EHLO']; + } + if ('EHLO' === $name || array_key_exists('EHLO', $this->server_caps)) { + return false; + } + $this->setError('HELO handshake was used; No information about server extensions available'); + + return; + } + + return $this->server_caps[$name]; + } + + /** + * Get the last reply from the server. + * + * @return string + */ + public function getLastReply() + { + return $this->last_reply; + } + + /** + * Read the SMTP server's response. + * Either before eof or socket timeout occurs on the operation. + * With SMTP we can tell if we have more lines to read if the + * 4th character is '-' symbol. If it is a space then we don't + * need to read anything else. + * + * @return string + */ + protected function get_lines() + { + // If the connection is bad, give up straight away + if (!is_resource($this->smtp_conn)) { + return ''; + } + $data = ''; + $endtime = 0; + stream_set_timeout($this->smtp_conn, $this->Timeout); + if ($this->Timelimit > 0) { + $endtime = time() + $this->Timelimit; + } + $selR = [$this->smtp_conn]; + $selW = null; + while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) { + //Must pass vars in here as params are by reference + if (!stream_select($selR, $selW, $selW, $this->Timelimit)) { + $this->edebug( + 'SMTP -> get_lines(): select timed-out in (' . $this->Timelimit . ' sec)', + self::DEBUG_LOWLEVEL + ); + break; + } + //Deliberate noise suppression - errors are handled afterwards + $str = @fgets($this->smtp_conn, self::MAX_REPLY_LENGTH); + $this->edebug('SMTP INBOUND: "' . trim($str) . '"', self::DEBUG_LOWLEVEL); + $data .= $str; + // If response is only 3 chars (not valid, but RFC5321 S4.2 says it must be handled), + // or 4th character is a space or a line break char, we are done reading, break the loop. + // String array access is a significant micro-optimisation over strlen + if (!isset($str[3]) || $str[3] === ' ' || $str[3] === "\r" || $str[3] === "\n") { + break; + } + // Timed-out? Log and break + $info = stream_get_meta_data($this->smtp_conn); + if ($info['timed_out']) { + $this->edebug( + 'SMTP -> get_lines(): stream timed-out (' . $this->Timeout . ' sec)', + self::DEBUG_LOWLEVEL + ); + break; + } + // Now check if reads took too long + if ($endtime && time() > $endtime) { + $this->edebug( + 'SMTP -> get_lines(): timelimit reached (' . + $this->Timelimit . ' sec)', + self::DEBUG_LOWLEVEL + ); + break; + } + } + + return $data; + } + + /** + * Enable or disable VERP address generation. + * + * @param bool $enabled + */ + public function setVerp($enabled = false) + { + $this->do_verp = $enabled; + } + + /** + * Get VERP address generation mode. + * + * @return bool + */ + public function getVerp() + { + return $this->do_verp; + } + + /** + * Set error messages and codes. + * + * @param string $message The error message + * @param string $detail Further detail on the error + * @param string $smtp_code An associated SMTP error code + * @param string $smtp_code_ex Extended SMTP code + */ + protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '') + { + $this->error = [ + 'error' => $message, + 'detail' => $detail, + 'smtp_code' => $smtp_code, + 'smtp_code_ex' => $smtp_code_ex, + ]; + } + + /** + * Set debug output method. + * + * @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it + */ + public function setDebugOutput($method = 'echo') + { + $this->Debugoutput = $method; + } + + /** + * Get debug output method. + * + * @return string + */ + public function getDebugOutput() + { + return $this->Debugoutput; + } + + /** + * Set debug output level. + * + * @param int $level + */ + public function setDebugLevel($level = 0) + { + $this->do_debug = $level; + } + + /** + * Get debug output level. + * + * @return int + */ + public function getDebugLevel() + { + return $this->do_debug; + } + + /** + * Set SMTP timeout. + * + * @param int $timeout The timeout duration in seconds + */ + public function setTimeout($timeout = 0) + { + $this->Timeout = $timeout; + } + + /** + * Get SMTP timeout. + * + * @return int + */ + public function getTimeout() + { + return $this->Timeout; + } + + /** + * Reports an error number and string. + * + * @param int $errno The error number returned by PHP + * @param string $errmsg The error message returned by PHP + * @param string $errfile The file the error occurred in + * @param int $errline The line number the error occurred on + */ + protected function errorHandler($errno, $errmsg, $errfile = '', $errline = 0) + { + $notice = 'Connection failed.'; + $this->setError( + $notice, + $errmsg, + (string) $errno + ); + $this->edebug( + "$notice Error #$errno: $errmsg [$errfile line $errline]", + self::DEBUG_CONNECTION + ); + } + + /** + * Extract and return the ID of the last SMTP transaction based on + * a list of patterns provided in SMTP::$smtp_transaction_id_patterns. + * Relies on the host providing the ID in response to a DATA command. + * If no reply has been received yet, it will return null. + * If no pattern was matched, it will return false. + * + * @return bool|string|null + */ + protected function recordLastTransactionID() + { + $reply = $this->getLastReply(); + + if (empty($reply)) { + $this->last_smtp_transaction_id = null; + } else { + $this->last_smtp_transaction_id = false; + foreach ($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) { + $matches = []; + if (preg_match($smtp_transaction_id_pattern, $reply, $matches)) { + $this->last_smtp_transaction_id = trim($matches[1]); + break; + } + } + } + + return $this->last_smtp_transaction_id; + } + + /** + * Get the queue/transaction ID of the last SMTP transaction + * If no reply has been received yet, it will return null. + * If no pattern was matched, it will return false. + * + * @return bool|string|null + * + * @see recordLastTransactionID() + */ + public function getLastTransactionID() + { + return $this->last_smtp_transaction_id; + } +} diff --git a/src/bb-vendor/psr/log/LICENSE b/src/bb-vendor/psr/log/LICENSE new file mode 100644 index 000000000..474c952b4 --- /dev/null +++ b/src/bb-vendor/psr/log/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2012 PHP Framework Interoperability Group + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/src/bb-vendor/psr/log/Psr/Log/AbstractLogger.php b/src/bb-vendor/psr/log/Psr/Log/AbstractLogger.php new file mode 100644 index 000000000..90e721af2 --- /dev/null +++ b/src/bb-vendor/psr/log/Psr/Log/AbstractLogger.php @@ -0,0 +1,128 @@ +log(LogLevel::EMERGENCY, $message, $context); + } + + /** + * Action must be taken immediately. + * + * Example: Entire website down, database unavailable, etc. This should + * trigger the SMS alerts and wake you up. + * + * @param string $message + * @param array $context + * + * @return void + */ + public function alert($message, array $context = array()) + { + $this->log(LogLevel::ALERT, $message, $context); + } + + /** + * Critical conditions. + * + * Example: Application component unavailable, unexpected exception. + * + * @param string $message + * @param array $context + * + * @return void + */ + public function critical($message, array $context = array()) + { + $this->log(LogLevel::CRITICAL, $message, $context); + } + + /** + * Runtime errors that do not require immediate action but should typically + * be logged and monitored. + * + * @param string $message + * @param array $context + * + * @return void + */ + public function error($message, array $context = array()) + { + $this->log(LogLevel::ERROR, $message, $context); + } + + /** + * Exceptional occurrences that are not errors. + * + * Example: Use of deprecated APIs, poor use of an API, undesirable things + * that are not necessarily wrong. + * + * @param string $message + * @param array $context + * + * @return void + */ + public function warning($message, array $context = array()) + { + $this->log(LogLevel::WARNING, $message, $context); + } + + /** + * Normal but significant events. + * + * @param string $message + * @param array $context + * + * @return void + */ + public function notice($message, array $context = array()) + { + $this->log(LogLevel::NOTICE, $message, $context); + } + + /** + * Interesting events. + * + * Example: User logs in, SQL logs. + * + * @param string $message + * @param array $context + * + * @return void + */ + public function info($message, array $context = array()) + { + $this->log(LogLevel::INFO, $message, $context); + } + + /** + * Detailed debug information. + * + * @param string $message + * @param array $context + * + * @return void + */ + public function debug($message, array $context = array()) + { + $this->log(LogLevel::DEBUG, $message, $context); + } +} diff --git a/src/bb-vendor/psr/log/Psr/Log/InvalidArgumentException.php b/src/bb-vendor/psr/log/Psr/Log/InvalidArgumentException.php new file mode 100644 index 000000000..67f852d1d --- /dev/null +++ b/src/bb-vendor/psr/log/Psr/Log/InvalidArgumentException.php @@ -0,0 +1,7 @@ +logger = $logger; + } +} diff --git a/src/bb-vendor/psr/log/Psr/Log/LoggerInterface.php b/src/bb-vendor/psr/log/Psr/Log/LoggerInterface.php new file mode 100644 index 000000000..2206cfde4 --- /dev/null +++ b/src/bb-vendor/psr/log/Psr/Log/LoggerInterface.php @@ -0,0 +1,125 @@ +log(LogLevel::EMERGENCY, $message, $context); + } + + /** + * Action must be taken immediately. + * + * Example: Entire website down, database unavailable, etc. This should + * trigger the SMS alerts and wake you up. + * + * @param string $message + * @param array $context + * + * @return void + */ + public function alert($message, array $context = array()) + { + $this->log(LogLevel::ALERT, $message, $context); + } + + /** + * Critical conditions. + * + * Example: Application component unavailable, unexpected exception. + * + * @param string $message + * @param array $context + * + * @return void + */ + public function critical($message, array $context = array()) + { + $this->log(LogLevel::CRITICAL, $message, $context); + } + + /** + * Runtime errors that do not require immediate action but should typically + * be logged and monitored. + * + * @param string $message + * @param array $context + * + * @return void + */ + public function error($message, array $context = array()) + { + $this->log(LogLevel::ERROR, $message, $context); + } + + /** + * Exceptional occurrences that are not errors. + * + * Example: Use of deprecated APIs, poor use of an API, undesirable things + * that are not necessarily wrong. + * + * @param string $message + * @param array $context + * + * @return void + */ + public function warning($message, array $context = array()) + { + $this->log(LogLevel::WARNING, $message, $context); + } + + /** + * Normal but significant events. + * + * @param string $message + * @param array $context + * + * @return void + */ + public function notice($message, array $context = array()) + { + $this->log(LogLevel::NOTICE, $message, $context); + } + + /** + * Interesting events. + * + * Example: User logs in, SQL logs. + * + * @param string $message + * @param array $context + * + * @return void + */ + public function info($message, array $context = array()) + { + $this->log(LogLevel::INFO, $message, $context); + } + + /** + * Detailed debug information. + * + * @param string $message + * @param array $context + * + * @return void + */ + public function debug($message, array $context = array()) + { + $this->log(LogLevel::DEBUG, $message, $context); + } + + /** + * Logs with an arbitrary level. + * + * @param mixed $level + * @param string $message + * @param array $context + * + * @return void + * + * @throws \Psr\Log\InvalidArgumentException + */ + abstract public function log($level, $message, array $context = array()); +} diff --git a/src/bb-vendor/psr/log/Psr/Log/NullLogger.php b/src/bb-vendor/psr/log/Psr/Log/NullLogger.php new file mode 100644 index 000000000..c8f7293b1 --- /dev/null +++ b/src/bb-vendor/psr/log/Psr/Log/NullLogger.php @@ -0,0 +1,30 @@ +logger) { }` + * blocks. + */ +class NullLogger extends AbstractLogger +{ + /** + * Logs with an arbitrary level. + * + * @param mixed $level + * @param string $message + * @param array $context + * + * @return void + * + * @throws \Psr\Log\InvalidArgumentException + */ + public function log($level, $message, array $context = array()) + { + // noop + } +} diff --git a/src/bb-vendor/psr/log/Psr/Log/Test/DummyTest.php b/src/bb-vendor/psr/log/Psr/Log/Test/DummyTest.php new file mode 100644 index 000000000..9638c1101 --- /dev/null +++ b/src/bb-vendor/psr/log/Psr/Log/Test/DummyTest.php @@ -0,0 +1,18 @@ + ". + * + * Example ->error('Foo') would yield "error Foo". + * + * @return string[] + */ + abstract public function getLogs(); + + public function testImplements() + { + $this->assertInstanceOf('Psr\Log\LoggerInterface', $this->getLogger()); + } + + /** + * @dataProvider provideLevelsAndMessages + */ + public function testLogsAtAllLevels($level, $message) + { + $logger = $this->getLogger(); + $logger->{$level}($message, array('user' => 'Bob')); + $logger->log($level, $message, array('user' => 'Bob')); + + $expected = array( + $level.' message of level '.$level.' with context: Bob', + $level.' message of level '.$level.' with context: Bob', + ); + $this->assertEquals($expected, $this->getLogs()); + } + + public function provideLevelsAndMessages() + { + return array( + LogLevel::EMERGENCY => array(LogLevel::EMERGENCY, 'message of level emergency with context: {user}'), + LogLevel::ALERT => array(LogLevel::ALERT, 'message of level alert with context: {user}'), + LogLevel::CRITICAL => array(LogLevel::CRITICAL, 'message of level critical with context: {user}'), + LogLevel::ERROR => array(LogLevel::ERROR, 'message of level error with context: {user}'), + LogLevel::WARNING => array(LogLevel::WARNING, 'message of level warning with context: {user}'), + LogLevel::NOTICE => array(LogLevel::NOTICE, 'message of level notice with context: {user}'), + LogLevel::INFO => array(LogLevel::INFO, 'message of level info with context: {user}'), + LogLevel::DEBUG => array(LogLevel::DEBUG, 'message of level debug with context: {user}'), + ); + } + + /** + * @expectedException \Psr\Log\InvalidArgumentException + */ + public function testThrowsOnInvalidLevel() + { + $logger = $this->getLogger(); + $logger->log('invalid level', 'Foo'); + } + + public function testContextReplacement() + { + $logger = $this->getLogger(); + $logger->info('{Message {nothing} {user} {foo.bar} a}', array('user' => 'Bob', 'foo.bar' => 'Bar')); + + $expected = array('info {Message {nothing} Bob Bar a}'); + $this->assertEquals($expected, $this->getLogs()); + } + + public function testObjectCastToString() + { + if (method_exists($this, 'createPartialMock')) { + $dummy = $this->createPartialMock('Psr\Log\Test\DummyTest', array('__toString')); + } else { + $dummy = $this->getMock('Psr\Log\Test\DummyTest', array('__toString')); + } + $dummy->expects($this->once()) + ->method('__toString') + ->will($this->returnValue('DUMMY')); + + $this->getLogger()->warning($dummy); + + $expected = array('warning DUMMY'); + $this->assertEquals($expected, $this->getLogs()); + } + + public function testContextCanContainAnything() + { + $closed = fopen('php://memory', 'r'); + fclose($closed); + + $context = array( + 'bool' => true, + 'null' => null, + 'string' => 'Foo', + 'int' => 0, + 'float' => 0.5, + 'nested' => array('with object' => new DummyTest), + 'object' => new \DateTime, + 'resource' => fopen('php://memory', 'r'), + 'closed' => $closed, + ); + + $this->getLogger()->warning('Crazy context data', $context); + + $expected = array('warning Crazy context data'); + $this->assertEquals($expected, $this->getLogs()); + } + + public function testContextExceptionKeyCanBeExceptionOrOtherValues() + { + $logger = $this->getLogger(); + $logger->warning('Random message', array('exception' => 'oops')); + $logger->critical('Uncaught Exception!', array('exception' => new \LogicException('Fail'))); + + $expected = array( + 'warning Random message', + 'critical Uncaught Exception!' + ); + $this->assertEquals($expected, $this->getLogs()); + } +} diff --git a/src/bb-vendor/psr/log/Psr/Log/Test/TestLogger.php b/src/bb-vendor/psr/log/Psr/Log/Test/TestLogger.php new file mode 100644 index 000000000..1be323049 --- /dev/null +++ b/src/bb-vendor/psr/log/Psr/Log/Test/TestLogger.php @@ -0,0 +1,147 @@ + $level, + 'message' => $message, + 'context' => $context, + ]; + + $this->recordsByLevel[$record['level']][] = $record; + $this->records[] = $record; + } + + public function hasRecords($level) + { + return isset($this->recordsByLevel[$level]); + } + + public function hasRecord($record, $level) + { + if (is_string($record)) { + $record = ['message' => $record]; + } + return $this->hasRecordThatPasses(function ($rec) use ($record) { + if ($rec['message'] !== $record['message']) { + return false; + } + if (isset($record['context']) && $rec['context'] !== $record['context']) { + return false; + } + return true; + }, $level); + } + + public function hasRecordThatContains($message, $level) + { + return $this->hasRecordThatPasses(function ($rec) use ($message) { + return strpos($rec['message'], $message) !== false; + }, $level); + } + + public function hasRecordThatMatches($regex, $level) + { + return $this->hasRecordThatPasses(function ($rec) use ($regex) { + return preg_match($regex, $rec['message']) > 0; + }, $level); + } + + public function hasRecordThatPasses(callable $predicate, $level) + { + if (!isset($this->recordsByLevel[$level])) { + return false; + } + foreach ($this->recordsByLevel[$level] as $i => $rec) { + if (call_user_func($predicate, $rec, $i)) { + return true; + } + } + return false; + } + + public function __call($method, $args) + { + if (preg_match('/(.*)(Debug|Info|Notice|Warning|Error|Critical|Alert|Emergency)(.*)/', $method, $matches) > 0) { + $genericMethod = $matches[1] . ('Records' !== $matches[3] ? 'Record' : '') . $matches[3]; + $level = strtolower($matches[2]); + if (method_exists($this, $genericMethod)) { + $args[] = $level; + return call_user_func_array([$this, $genericMethod], $args); + } + } + throw new \BadMethodCallException('Call to undefined method ' . get_class($this) . '::' . $method . '()'); + } + + public function reset() + { + $this->records = []; + $this->recordsByLevel = []; + } +} diff --git a/src/bb-vendor/psr/log/README.md b/src/bb-vendor/psr/log/README.md new file mode 100644 index 000000000..a9f20c437 --- /dev/null +++ b/src/bb-vendor/psr/log/README.md @@ -0,0 +1,58 @@ +PSR Log +======= + +This repository holds all interfaces/classes/traits related to +[PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md). + +Note that this is not a logger of its own. It is merely an interface that +describes a logger. See the specification for more details. + +Installation +------------ + +```bash +composer require psr/log +``` + +Usage +----- + +If you need a logger, you can use the interface like this: + +```php +logger = $logger; + } + + public function doSomething() + { + if ($this->logger) { + $this->logger->info('Doing work'); + } + + try { + $this->doSomethingElse(); + } catch (Exception $exception) { + $this->logger->error('Oh no!', array('exception' => $exception)); + } + + // do something useful + } +} +``` + +You can then pick one of the implementations of the interface to get a logger. + +If you want to implement the interface, you can require this package and +implement `Psr\Log\LoggerInterface` in your code. Please read the +[specification text](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md) +for details. diff --git a/src/bb-vendor/psr/log/composer.json b/src/bb-vendor/psr/log/composer.json new file mode 100644 index 000000000..3f6d4eea4 --- /dev/null +++ b/src/bb-vendor/psr/log/composer.json @@ -0,0 +1,26 @@ +{ + "name": "psr/log", + "description": "Common interface for logging libraries", + "keywords": ["psr", "psr-3", "log"], + "homepage": "https://github.com/php-fig/log", + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "require": { + "php": ">=5.3.0" + }, + "autoload": { + "psr-4": { + "Psr\\Log\\": "Psr/Log/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.1.x-dev" + } + } +} diff --git a/src/bb-vendor/setasign/fpdi/LICENSE.txt b/src/bb-vendor/setasign/fpdi/LICENSE.txt new file mode 100644 index 000000000..45672fab8 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 Setasign GmbH & Co. KG, https://www.setasign.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/src/bb-vendor/setasign/fpdi/README.md b/src/bb-vendor/setasign/fpdi/README.md new file mode 100644 index 000000000..022f1ee36 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/README.md @@ -0,0 +1,131 @@ +FPDI - Free PDF Document Importer +================================= + +[![Latest Stable Version](https://poser.pugx.org/setasign/fpdi/v/stable.svg)](https://packagist.org/packages/setasign/fpdi) +[![Total Downloads](https://poser.pugx.org/setasign/fpdi/downloads.svg)](https://packagist.org/packages/setasign/fpdi) +[![Latest Unstable Version](https://poser.pugx.org/setasign/fpdi/v/unstable.svg)](https://packagist.org/packages/setasign/fpdi) +[![License](https://poser.pugx.org/setasign/fpdi/license.svg)](https://packagist.org/packages/setasign/fpdi) + +:heavy_exclamation_mark: This document refers to FPDI 2. Version 1 is deprecated and development is discontinued. :heavy_exclamation_mark: + +FPDI is a collection of PHP classes facilitating developers to read pages from existing PDF +documents and use them as templates in [FPDF](http://www.fpdf.org), which was developed by Olivier Plathey. Apart +from a copy of [FPDF](http://www.fpdf.org), FPDI does not require any special PHP extensions. + +FPDI can also be used as an extension for [TCPDF](https://github.com/tecnickcom/TCPDF) or +[tFPDF](http://fpdf.org/en/script/script92.php), too. + +## Installation with [Composer](https://packagist.org/packages/setasign/fpdi) + +Because FPDI can be used with FPDF, TCPDF or tFPDF we haven't added a fixed dependency in the main +composer.json file. You need to add the dependency to the PDF generation library of your choice +yourself. + +To use FPDI with FPDF include following in your composer.json file: + +```json +{ + "require": { + "setasign/fpdf": "1.8.*", + "setasign/fpdi": "^2.0" + } +} +``` + +If you want to use TCPDF, you have to update your composer.json to: + +```json +{ + "require": { + "tecnickcom/tcpdf": "6.2.*", + "setasign/fpdi": "^2.0" + } +} +``` + +If you want to use tFPDF, you have to update your composer.json to: + +```json +{ + "require": { + "setasign/tfpdf": "1.31.*", + "setasign/fpdi": "^2.3" + } +} +``` + +## Manual Installation + +If you do not use composer, just require the autoload.php in the /src folder: + +```php +require_once('src/autoload.php'); +``` + +If you have a PSR-4 autoloader implemented, just register the src path as follows: +```php +$loader = new \Example\Psr4AutoloaderClass; +$loader->register(); +$loader->addNamespace('setasign\Fpdi', 'path/to/src/'); +``` + +## Changes to Version 1 + +Version 2 is a complete rewrite from scratch of FPDI which comes with: +- Namespaced code +- Clean and up-to-date code base and style +- PSR-4 compatible autoloading +- Performance improvements by up to 100% +- Less memory consumption +- Native support for reading PDFs from strings or stream-resources +- Support for documents with "invalid" data before their file-header +- Optimized page tree resolving +- Usage of individual exceptions +- Several test types (unit, functional and visual tests) + +We tried to keep the main methods and logical workflow the same as in version 1 but please +notice that there were incompatible changes which you should consider when updating to +version 2: +- You need to load the code using the `src/autoload.php` file instead of `classes/FPDI.php`. +- The classes and traits are namespaced now: `setasign\Fpdi` +- Page boundaries beginning with a slash, such as `/MediaBox`, are not supported anymore. Remove + the slash or use a constant of `PdfReader\PageBoundaries`. +- The parameters $x, $y, $width and $height of the `useTemplate()` or `getTemplateSize()` + method have more logical correct default values now. Passing `0` as width or height will + result in an `InvalidArgumentException` now. +- The return value of `getTemplateSize()` had changed to an array with more speaking keys + and reusability: Use `width` instead of `w` and `height` instead of `h`. +- If you want to use **FPDI with TCPDF** you need to refactor your code to use the class `Tcpdf\Fpdi` +(since 2.1; before it was `TcpdfFpdi`) instead of `FPDI`. + +## Example and Documentation + +A simple example, that imports a single page and places this onto a new created page: + +```php +AddPage(); +// set the source file +$pdf->setSourceFile("Fantastic-Speaker.pdf"); +// import page 1 +$tplId = $pdf->importPage(1); +// use the imported page and place it at point 10,10 with a width of 100 mm +$pdf->useTemplate($tplId, 10, 10, 100); + +$pdf->Output(); +``` + +A full end-user documentation and API reference is available [here](https://manuals.setasign.com/fpdi-manual/). diff --git a/src/bb-vendor/setasign/fpdi/SECURITY.md b/src/bb-vendor/setasign/fpdi/SECURITY.md new file mode 100644 index 000000000..da9c516dd --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/SECURITY.md @@ -0,0 +1,5 @@ +## Security contact information + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. diff --git a/src/bb-vendor/setasign/fpdi/composer.json b/src/bb-vendor/setasign/fpdi/composer.json new file mode 100644 index 000000000..eafee7781 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/composer.json @@ -0,0 +1,51 @@ +{ + "name": "setasign/fpdi", + "homepage": "https://www.setasign.com/fpdi", + "description": "FPDI is a collection of PHP classes facilitating developers to read pages from existing PDF documents and use them as templates in FPDF. Because it is also possible to use FPDI with TCPDF, there are no fixed dependencies defined. Please see suggestions for packages which evaluates the dependencies automatically.", + "type": "library", + "keywords": [ + "pdf", + "fpdi", + "fpdf" + ], + "license": "MIT", + "autoload": { + "psr-4": { + "setasign\\Fpdi\\": "src/" + } + }, + "require": { + "php": "^5.6 || ^7.0", + "ext-zlib": "*" + }, + "conflict": { + "setasign/tfpdf": "<1.31" + }, + "authors": [ + { + "name": "Jan Slabon", + "email": "jan.slabon@setasign.com", + "homepage": "https://www.setasign.com" + }, + { + "name": "Maximilian Kresse", + "email": "maximilian.kresse@setasign.com", + "homepage": "https://www.setasign.com" + } + ], + "suggest": { + "setasign/fpdf": "FPDI will extend this class but as it is also possible to use TCPDF or tFPDF as an alternative. There's no fixed dependency configured." + }, + "require-dev": { + "phpunit/phpunit": "~5.7", + "setasign/fpdf": "~1.8", + "tecnickcom/tcpdf": "~6.2", + "setasign/tfpdf": "1.31", + "squizlabs/php_codesniffer": "^3.5" + }, + "autoload-dev": { + "psr-4": { + "setasign\\Fpdi\\": "tests/" + } + } +} diff --git a/src/bb-vendor/setasign/fpdi/phpcs.xml b/src/bb-vendor/setasign/fpdi/phpcs.xml new file mode 100644 index 000000000..2beccd516 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/phpcs.xml @@ -0,0 +1,17 @@ + + + src + + + + + + + + + + + + \ No newline at end of file diff --git a/src/bb-vendor/setasign/fpdi/phpstan.neon b/src/bb-vendor/setasign/fpdi/phpstan.neon new file mode 100644 index 000000000..89b65cd4e --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/phpstan.neon @@ -0,0 +1,19 @@ +parameters: + level: 5 + paths: + - src + #- tests + + ignoreErrors: + - + message: "#^Return typehint of method setasign\\\\Fpdi\\\\Fpdi\\:\\:getPdfParserInstance\\(\\) has invalid type setasign\\\\FpdiPdfParser\\\\PdfParser\\\\PdfParser\\.$#" + count: 1 + path: src/Fpdi.php + - + message: "#^Return typehint of method setasign\\\\Fpdi\\\\Tcpdf\\\\Fpdi\\:\\:getPdfParserInstance\\(\\) has invalid type setasign\\\\FpdiPdfParser\\\\PdfParser\\\\PdfParser\\.$#" + count: 1 + path: src/Tcpdf/Fpdi.php + - + message: "#^Return typehint of method setasign\\\\Fpdi\\\\Tfpdf\\\\Fpdi\\:\\:getPdfParserInstance\\(\\) has invalid type setasign\\\\FpdiPdfParser\\\\PdfParser\\\\PdfParser\\.$#" + count: 1 + path: src/Tfpdf/Fpdi.php \ No newline at end of file diff --git a/src/bb-vendor/setasign/fpdi/src/FpdfTpl.php b/src/bb-vendor/setasign/fpdi/src/FpdfTpl.php new file mode 100644 index 000000000..4b93f5396 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/FpdfTpl.php @@ -0,0 +1,21 @@ +currentTemplateId !== null) { + throw new \BadMethodCallException('The page format cannot be changed when writing to a template.'); + } + + if (!\in_array($orientation, ['P', 'L'], true)) { + throw new \InvalidArgumentException(\sprintf( + 'Invalid page orientation "%s"! Only "P" and "L" are allowed!', + $orientation + )); + } + + $size = $this->_getpagesize($size); + + if ( + $orientation != $this->CurOrientation + || $size[0] != $this->CurPageSize[0] + || $size[1] != $this->CurPageSize[1] + ) { + // New size or orientation + if ($orientation === 'P') { + $this->w = $size[0]; + $this->h = $size[1]; + } else { + $this->w = $size[1]; + $this->h = $size[0]; + } + $this->wPt = $this->w * $this->k; + $this->hPt = $this->h * $this->k; + $this->PageBreakTrigger = $this->h - $this->bMargin; + $this->CurOrientation = $orientation; + $this->CurPageSize = $size; + + $this->PageInfo[$this->page]['size'] = array($this->wPt, $this->hPt); + } + } + + /** + * Draws a template onto the page or another template. + * + * Give only one of the size parameters (width, height) to calculate the other one automatically in view to the + * aspect ratio. + * + * @param mixed $tpl The template id + * @param array|float|int $x The abscissa of upper-left corner. Alternatively you could use an assoc array + * with the keys "x", "y", "width", "height", "adjustPageSize". + * @param float|int $y The ordinate of upper-left corner. + * @param float|int|null $width The width. + * @param float|int|null $height The height. + * @param bool $adjustPageSize + * @return array The size + * @see FpdfTplTrait::getTemplateSize() + */ + public function useTemplate($tpl, $x = 0, $y = 0, $width = null, $height = null, $adjustPageSize = false) + { + if (!isset($this->templates[$tpl])) { + throw new \InvalidArgumentException('Template does not exist!'); + } + + if (\is_array($x)) { + unset($x['tpl']); + \extract($x, EXTR_IF_EXISTS); + /** @noinspection NotOptimalIfConditionsInspection */ + /** @noinspection PhpConditionAlreadyCheckedInspection */ + if (\is_array($x)) { + $x = 0; + } + } + + $template = $this->templates[$tpl]; + + $originalSize = $this->getTemplateSize($tpl); + $newSize = $this->getTemplateSize($tpl, $width, $height); + if ($adjustPageSize) { + $this->setPageFormat($newSize, $newSize['orientation']); + } + + $this->_out( + // reset standard values, translate and scale + \sprintf( + 'q 0 J 1 w 0 j 0 G 0 g %.4F 0 0 %.4F %.4F %.4F cm /%s Do Q', + ($newSize['width'] / $originalSize['width']), + ($newSize['height'] / $originalSize['height']), + $x * $this->k, + ($this->h - $y - $newSize['height']) * $this->k, + $template['id'] + ) + ); + + return $newSize; + } + + /** + * Get the size of a template. + * + * Give only one of the size parameters (width, height) to calculate the other one automatically in view to the + * aspect ratio. + * + * @param mixed $tpl The template id + * @param float|int|null $width The width. + * @param float|int|null $height The height. + * @return array|bool An array with following keys: width, height, 0 (=width), 1 (=height), orientation (L or P) + */ + public function getTemplateSize($tpl, $width = null, $height = null) + { + if (!isset($this->templates[$tpl])) { + return false; + } + + if ($width === null && $height === null) { + $width = $this->templates[$tpl]['width']; + $height = $this->templates[$tpl]['height']; + } elseif ($width === null) { + $width = $height * $this->templates[$tpl]['width'] / $this->templates[$tpl]['height']; + } + + if ($height === null) { + $height = $width * $this->templates[$tpl]['height'] / $this->templates[$tpl]['width']; + } + + if ($height <= 0. || $width <= 0.) { + throw new \InvalidArgumentException('Width or height parameter needs to be larger than zero.'); + } + + return [ + 'width' => $width, + 'height' => $height, + 0 => $width, + 1 => $height, + 'orientation' => $width > $height ? 'L' : 'P' + ]; + } + + /** + * Begins a new template. + * + * @param float|int|null $width The width of the template. If null, the current page width is used. + * @param float|int|null $height The height of the template. If null, the current page height is used. + * @param bool $groupXObject Define the form XObject as a group XObject to support transparency (if used). + * @return int A template identifier. + */ + public function beginTemplate($width = null, $height = null, $groupXObject = false) + { + if ($width === null) { + $width = $this->w; + } + + if ($height === null) { + $height = $this->h; + } + + $templateId = $this->getNextTemplateId(); + + // initiate buffer with current state of FPDF + $buffer = "2 J\n" + . \sprintf('%.2F w', $this->LineWidth * $this->k) . "\n"; + + if ($this->FontFamily) { + $buffer .= \sprintf("BT /F%d %.2F Tf ET\n", $this->CurrentFont['i'], $this->FontSizePt); + } + + if ($this->DrawColor !== '0 G') { + $buffer .= $this->DrawColor . "\n"; + } + if ($this->FillColor !== '0 g') { + $buffer .= $this->FillColor . "\n"; + } + + if ($groupXObject && \version_compare('1.4', $this->PDFVersion, '>')) { + $this->PDFVersion = '1.4'; + } + + $this->templates[$templateId] = [ + 'objectNumber' => null, + 'id' => 'TPL' . $templateId, + 'buffer' => $buffer, + 'width' => $width, + 'height' => $height, + 'groupXObject' => $groupXObject, + 'state' => [ + 'x' => $this->x, + 'y' => $this->y, + 'AutoPageBreak' => $this->AutoPageBreak, + 'bMargin' => $this->bMargin, + 'tMargin' => $this->tMargin, + 'lMargin' => $this->lMargin, + 'rMargin' => $this->rMargin, + 'h' => $this->h, + 'w' => $this->w, + 'FontFamily' => $this->FontFamily, + 'FontStyle' => $this->FontStyle, + 'FontSizePt' => $this->FontSizePt, + 'FontSize' => $this->FontSize, + 'underline' => $this->underline, + 'TextColor' => $this->TextColor, + 'DrawColor' => $this->DrawColor, + 'FillColor' => $this->FillColor, + 'ColorFlag' => $this->ColorFlag + ] + ]; + + $this->SetAutoPageBreak(false); + $this->currentTemplateId = $templateId; + + $this->h = $height; + $this->w = $width; + + $this->SetXY($this->lMargin, $this->tMargin); + $this->SetRightMargin($this->w - $width + $this->rMargin); + + return $templateId; + } + + /** + * Ends a template. + * + * @return bool|int|null A template identifier. + */ + public function endTemplate() + { + if ($this->currentTemplateId === null) { + return false; + } + + $templateId = $this->currentTemplateId; + $template = $this->templates[$templateId]; + + $state = $template['state']; + $this->SetXY($state['x'], $state['y']); + $this->tMargin = $state['tMargin']; + $this->lMargin = $state['lMargin']; + $this->rMargin = $state['rMargin']; + $this->h = $state['h']; + $this->w = $state['w']; + $this->SetAutoPageBreak($state['AutoPageBreak'], $state['bMargin']); + + $this->FontFamily = $state['FontFamily']; + $this->FontStyle = $state['FontStyle']; + $this->FontSizePt = $state['FontSizePt']; + $this->FontSize = $state['FontSize']; + + $this->TextColor = $state['TextColor']; + $this->DrawColor = $state['DrawColor']; + $this->FillColor = $state['FillColor']; + $this->ColorFlag = $state['ColorFlag']; + + $this->underline = $state['underline']; + + $fontKey = $this->FontFamily . $this->FontStyle; + if ($fontKey) { + $this->CurrentFont =& $this->fonts[$fontKey]; + } else { + unset($this->CurrentFont); + } + + $this->currentTemplateId = null; + + return $templateId; + } + + /** + * Get the next template id. + * + * @return int + */ + protected function getNextTemplateId() + { + return $this->templateId++; + } + + /* overwritten FPDF methods: */ + + /** + * @inheritdoc + */ + public function AddPage($orientation = '', $size = '', $rotation = 0) + { + if ($this->currentTemplateId !== null) { + throw new \BadMethodCallException('Pages cannot be added when writing to a template.'); + } + parent::AddPage($orientation, $size, $rotation); + } + + /** + * @inheritdoc + */ + public function Link($x, $y, $w, $h, $link) + { + if ($this->currentTemplateId !== null) { + throw new \BadMethodCallException('Links cannot be set when writing to a template.'); + } + parent::Link($x, $y, $w, $h, $link); + } + + /** + * @inheritdoc + */ + public function SetLink($link, $y = 0, $page = -1) + { + if ($this->currentTemplateId !== null) { + throw new \BadMethodCallException('Links cannot be set when writing to a template.'); + } + return parent::SetLink($link, $y, $page); + } + + /** + * @inheritdoc + */ + public function SetDrawColor($r, $g = null, $b = null) + { + parent::SetDrawColor($r, $g, $b); + if ($this->page === 0 && $this->currentTemplateId !== null) { + $this->_out($this->DrawColor); + } + } + + /** + * @inheritdoc + */ + public function SetFillColor($r, $g = null, $b = null) + { + parent::SetFillColor($r, $g, $b); + if ($this->page === 0 && $this->currentTemplateId !== null) { + $this->_out($this->FillColor); + } + } + + /** + * @inheritdoc + */ + public function SetLineWidth($width) + { + parent::SetLineWidth($width); + if ($this->page === 0 && $this->currentTemplateId !== null) { + $this->_out(\sprintf('%.2F w', $width * $this->k)); + } + } + + /** + * @inheritdoc + */ + public function SetFont($family, $style = '', $size = 0) + { + parent::SetFont($family, $style, $size); + if ($this->page === 0 && $this->currentTemplateId !== null) { + $this->_out(\sprintf('BT /F%d %.2F Tf ET', $this->CurrentFont['i'], $this->FontSizePt)); + } + } + + /** + * @inheritdoc + */ + public function SetFontSize($size) + { + parent::SetFontSize($size); + if ($this->page === 0 && $this->currentTemplateId !== null) { + $this->_out(sprintf('BT /F%d %.2F Tf ET', $this->CurrentFont['i'], $this->FontSizePt)); + } + } + + /** + * @inheritdoc + */ + protected function _putimages() + { + parent::_putimages(); + + foreach ($this->templates as $key => $template) { + $this->_newobj(); + $this->templates[$key]['objectNumber'] = $this->n; + + $this->_put('<_put(\sprintf( + '/BBox[0 0 %.2F %.2F]', + $template['width'] * $this->k, + $template['height'] * $this->k + )); + $this->_put('/Resources 2 0 R'); // default resources dictionary of FPDF + + if ($this->compress) { + $buffer = \gzcompress($template['buffer']); + $this->_put('/Filter/FlateDecode'); + } else { + $buffer = $template['buffer']; + } + + $this->_put('/Length ' . \strlen($buffer)); + + if ($template['groupXObject']) { + $this->_put('/Group <>'); + } + + $this->_put('>>'); + $this->_putstream($buffer); + $this->_put('endobj'); + } + } + + /** + * @inheritdoc + */ + protected function _putxobjectdict() + { + foreach ($this->templates as $key => $template) { + $this->_put('/' . $template['id'] . ' ' . $template['objectNumber'] . ' 0 R'); + } + + parent::_putxobjectdict(); + } + + /** + * @inheritdoc + */ + public function _out($s) + { + if ($this->currentTemplateId !== null) { + $this->templates[$this->currentTemplateId]['buffer'] .= $s . "\n"; + } else { + parent::_out($s); + } + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/Fpdi.php b/src/bb-vendor/setasign/fpdi/src/Fpdi.php new file mode 100644 index 000000000..0ebce466a --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/Fpdi.php @@ -0,0 +1,153 @@ +cleanUp(); + } + + /** + * Draws an imported page or a template onto the page or another template. + * + * Give only one of the size parameters (width, height) to calculate the other one automatically in view to the + * aspect ratio. + * + * @param mixed $tpl The template id + * @param float|int|array $x The abscissa of upper-left corner. Alternatively you could use an assoc array + * with the keys "x", "y", "width", "height", "adjustPageSize". + * @param float|int $y The ordinate of upper-left corner. + * @param float|int|null $width The width. + * @param float|int|null $height The height. + * @param bool $adjustPageSize + * @return array The size + * @see Fpdi::getTemplateSize() + */ + public function useTemplate($tpl, $x = 0, $y = 0, $width = null, $height = null, $adjustPageSize = false) + { + if (isset($this->importedPages[$tpl])) { + $size = $this->useImportedPage($tpl, $x, $y, $width, $height, $adjustPageSize); + if ($this->currentTemplateId !== null) { + $this->templates[$this->currentTemplateId]['resources']['templates']['importedPages'][$tpl] = $tpl; + } + return $size; + } + + return parent::useTemplate($tpl, $x, $y, $width, $height, $adjustPageSize); + } + + /** + * Get the size of an imported page or template. + * + * Give only one of the size parameters (width, height) to calculate the other one automatically in view to the + * aspect ratio. + * + * @param mixed $tpl The template id + * @param float|int|null $width The width. + * @param float|int|null $height The height. + * @return array|bool An array with following keys: width, height, 0 (=width), 1 (=height), orientation (L or P) + */ + public function getTemplateSize($tpl, $width = null, $height = null) + { + $size = parent::getTemplateSize($tpl, $width, $height); + if ($size === false) { + return $this->getImportedPageSize($tpl, $width, $height); + } + + return $size; + } + + /** + * @inheritdoc + * @throws CrossReferenceException + * @throws PdfParserException + */ + protected function _putimages() + { + $this->currentReaderId = null; + parent::_putimages(); + + foreach ($this->importedPages as $key => $pageData) { + $this->_newobj(); + $this->importedPages[$key]['objectNumber'] = $this->n; + $this->currentReaderId = $pageData['readerId']; + $this->writePdfType($pageData['stream']); + $this->_put('endobj'); + } + + foreach (\array_keys($this->readers) as $readerId) { + $parser = $this->getPdfReader($readerId)->getParser(); + $this->currentReaderId = $readerId; + + while (($objectNumber = \array_pop($this->objectsToCopy[$readerId])) !== null) { + try { + $object = $parser->getIndirectObject($objectNumber); + } catch (CrossReferenceException $e) { + if ($e->getCode() === CrossReferenceException::OBJECT_NOT_FOUND) { + $object = PdfIndirectObject::create($objectNumber, 0, new PdfNull()); + } else { + throw $e; + } + } + + $this->writePdfType($object); + } + } + + $this->currentReaderId = null; + } + + /** + * @inheritdoc + */ + protected function _putxobjectdict() + { + foreach ($this->importedPages as $key => $pageData) { + $this->_put('/' . $pageData['id'] . ' ' . $pageData['objectNumber'] . ' 0 R'); + } + + parent::_putxobjectdict(); + } + + /** + * @inheritdoc + */ + protected function _put($s, $newLine = true) + { + if ($newLine) { + $this->buffer .= $s . "\n"; + } else { + $this->buffer .= $s; + } + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/FpdiException.php b/src/bb-vendor/setasign/fpdi/src/FpdiException.php new file mode 100644 index 000000000..228666744 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/FpdiException.php @@ -0,0 +1,18 @@ +readers) : $this->createdReaders; + foreach ($readers as $id) { + $this->readers[$id]->getParser()->getStreamReader()->cleanUp(); + unset($this->readers[$id]); + } + + $this->createdReaders = []; + } + + /** + * Set the minimal PDF version. + * + * @param string $pdfVersion + */ + protected function setMinPdfVersion($pdfVersion) + { + if (\version_compare($pdfVersion, $this->PDFVersion, '>')) { + $this->PDFVersion = $pdfVersion; + } + } + + /** @noinspection PhpUndefinedClassInspection */ + /** + * Get a new pdf parser instance. + * + * @param StreamReader $streamReader + * @return PdfParser|FpdiPdfParser + */ + protected function getPdfParserInstance(StreamReader $streamReader) + { + /** @noinspection PhpUndefinedClassInspection */ + if (\class_exists(FpdiPdfParser::class)) { + /** @noinspection PhpUndefinedClassInspection */ + return new FpdiPdfParser($streamReader); + } + + return new PdfParser($streamReader); + } + + /** + * Get an unique reader id by the $file parameter. + * + * @param string|resource|PdfReader|StreamReader $file An open file descriptor, a path to a file, a PdfReader + * instance or a StreamReader instance. + * @return string + */ + protected function getPdfReaderId($file) + { + if (\is_resource($file)) { + $id = (string) $file; + } elseif (\is_string($file)) { + $id = \realpath($file); + if ($id === false) { + $id = $file; + } + } elseif (\is_object($file)) { + $id = \spl_object_hash($file); + } else { + throw new \InvalidArgumentException( + \sprintf('Invalid type in $file parameter (%s)', \gettype($file)) + ); + } + + /** @noinspection OffsetOperationsInspection */ + if (isset($this->readers[$id])) { + return $id; + } + + if (\is_resource($file)) { + $streamReader = new StreamReader($file); + } elseif (\is_string($file)) { + $streamReader = StreamReader::createByFile($file); + $this->createdReaders[] = $id; + } else { + $streamReader = $file; + } + + $reader = new PdfReader($this->getPdfParserInstance($streamReader)); + /** @noinspection OffsetOperationsInspection */ + $this->readers[$id] = $reader; + + return $id; + } + + /** + * Get a pdf reader instance by its id. + * + * @param string $id + * @return PdfReader + */ + protected function getPdfReader($id) + { + if (isset($this->readers[$id])) { + return $this->readers[$id]; + } + + throw new \InvalidArgumentException( + \sprintf('No pdf reader with the given id (%s) exists.', $id) + ); + } + + /** + * Set the source PDF file. + * + * @param string|resource|StreamReader $file Path to the file or a stream resource or a StreamReader instance. + * @return int The page count of the PDF document. + * @throws PdfParserException + */ + public function setSourceFile($file) + { + $this->currentReaderId = $this->getPdfReaderId($file); + $this->objectsToCopy[$this->currentReaderId] = []; + + $reader = $this->getPdfReader($this->currentReaderId); + $this->setMinPdfVersion($reader->getPdfVersion()); + + return $reader->getPageCount(); + } + + /** + * Imports a page. + * + * @param int $pageNumber The page number. + * @param string $box The page boundary to import. Default set to PageBoundaries::CROP_BOX. + * @param bool $groupXObject Define the form XObject as a group XObject to support transparency (if used). + * @return string A unique string identifying the imported page. + * @throws CrossReferenceException + * @throws FilterException + * @throws PdfParserException + * @throws PdfTypeException + * @throws PdfReaderException + * @see PageBoundaries + */ + public function importPage($pageNumber, $box = PageBoundaries::CROP_BOX, $groupXObject = true) + { + if (null === $this->currentReaderId) { + throw new \BadMethodCallException('No reader initiated. Call setSourceFile() first.'); + } + + $pageId = $this->currentReaderId; + + $pageNumber = (int)$pageNumber; + $pageId .= '|' . $pageNumber . '|' . ($groupXObject ? '1' : '0'); + + // for backwards compatibility with FPDI 1 + $box = \ltrim($box, '/'); + if (!PageBoundaries::isValidName($box)) { + throw new \InvalidArgumentException( + \sprintf('Box name is invalid: "%s"', $box) + ); + } + + $pageId .= '|' . $box; + + if (isset($this->importedPages[$pageId])) { + return $pageId; + } + + $reader = $this->getPdfReader($this->currentReaderId); + $page = $reader->getPage($pageNumber); + + $bbox = $page->getBoundary($box); + if ($bbox === false) { + throw new PdfReaderException( + \sprintf("Page doesn't have a boundary box (%s).", $box), + PdfReaderException::MISSING_DATA + ); + } + + $dict = new PdfDictionary(); + $dict->value['Type'] = PdfName::create('XObject'); + $dict->value['Subtype'] = PdfName::create('Form'); + $dict->value['FormType'] = PdfNumeric::create(1); + $dict->value['BBox'] = $bbox->toPdfArray(); + + if ($groupXObject) { + $this->setMinPdfVersion('1.4'); + $dict->value['Group'] = PdfDictionary::create([ + 'Type' => PdfName::create('Group'), + 'S' => PdfName::create('Transparency') + ]); + } + + $resources = $page->getAttribute('Resources'); + if ($resources !== null) { + $dict->value['Resources'] = $resources; + } + + list($width, $height) = $page->getWidthAndHeight($box); + + $a = 1; + $b = 0; + $c = 0; + $d = 1; + $e = -$bbox->getLlx(); + $f = -$bbox->getLly(); + + $rotation = $page->getRotation(); + + if ($rotation !== 0) { + $rotation *= -1; + $angle = $rotation * M_PI / 180; + $a = \cos($angle); + $b = \sin($angle); + $c = -$b; + $d = $a; + + switch ($rotation) { + case -90: + $e = -$bbox->getLly(); + $f = $bbox->getUrx(); + break; + case -180: + $e = $bbox->getUrx(); + $f = $bbox->getUry(); + break; + case -270: + $e = $bbox->getUry(); + $f = -$bbox->getLlx(); + break; + } + } + + // we need to rotate/translate + if ($a != 1 || $b != 0 || $c != 0 || $d != 1 || $e != 0 || $f != 0) { + $dict->value['Matrix'] = PdfArray::create([ + PdfNumeric::create($a), PdfNumeric::create($b), PdfNumeric::create($c), + PdfNumeric::create($d), PdfNumeric::create($e), PdfNumeric::create($f) + ]); + } + + // try to use the existing content stream + $pageDict = $page->getPageDictionary(); + + $contentsObject = PdfType::resolve(PdfDictionary::get($pageDict, 'Contents'), $reader->getParser(), true); + $contents = PdfType::resolve($contentsObject, $reader->getParser()); + + // just copy the stream reference if it is only a single stream + if ( + ($contentsIsStream = ($contents instanceof PdfStream)) + || ($contents instanceof PdfArray && \count($contents->value) === 1) + ) { + if ($contentsIsStream) { + /** + * @var PdfIndirectObject $contentsObject + */ + $stream = $contents; + } else { + $stream = PdfType::resolve($contents->value[0], $reader->getParser()); + } + + $filter = PdfDictionary::get($stream->value, 'Filter'); + if (!$filter instanceof PdfNull) { + $dict->value['Filter'] = $filter; + } + $length = PdfType::resolve(PdfDictionary::get($stream->value, 'Length'), $reader->getParser()); + $dict->value['Length'] = $length; + $stream->value = $dict; + + // otherwise extract it from the array and re-compress the whole stream + } else { + $streamContent = $this->compress + ? \gzcompress($page->getContentStream()) + : $page->getContentStream(); + + $dict->value['Length'] = PdfNumeric::create(\strlen($streamContent)); + if ($this->compress) { + $dict->value['Filter'] = PdfName::create('FlateDecode'); + } + + $stream = PdfStream::create($dict, $streamContent); + } + + $this->importedPages[$pageId] = [ + 'objectNumber' => null, + 'readerId' => $this->currentReaderId, + 'id' => 'TPL' . $this->getNextTemplateId(), + 'width' => $width / $this->k, + 'height' => $height / $this->k, + 'stream' => $stream + ]; + + return $pageId; + } + + /** + * Draws an imported page onto the page. + * + * Give only one of the size parameters (width, height) to calculate the other one automatically in view to the + * aspect ratio. + * + * @param mixed $pageId The page id + * @param float|int|array $x The abscissa of upper-left corner. Alternatively you could use an assoc array + * with the keys "x", "y", "width", "height", "adjustPageSize". + * @param float|int $y The ordinate of upper-left corner. + * @param float|int|null $width The width. + * @param float|int|null $height The height. + * @param bool $adjustPageSize + * @return array The size. + * @see Fpdi::getTemplateSize() + */ + public function useImportedPage($pageId, $x = 0, $y = 0, $width = null, $height = null, $adjustPageSize = false) + { + if (\is_array($x)) { + /** @noinspection OffsetOperationsInspection */ + unset($x['pageId']); + \extract($x, EXTR_IF_EXISTS); + /** @noinspection NotOptimalIfConditionsInspection */ + if (\is_array($x)) { + $x = 0; + } + } + + if (!isset($this->importedPages[$pageId])) { + throw new \InvalidArgumentException('Imported page does not exist!'); + } + + $importedPage = $this->importedPages[$pageId]; + + $originalSize = $this->getTemplateSize($pageId); + $newSize = $this->getTemplateSize($pageId, $width, $height); + if ($adjustPageSize) { + $this->setPageFormat($newSize, $newSize['orientation']); + } + + $this->_out( + // reset standard values, translate and scale + \sprintf( + 'q 0 J 1 w 0 j 0 G 0 g %.4F 0 0 %.4F %.4F %.4F cm /%s Do Q', + ($newSize['width'] / $originalSize['width']), + ($newSize['height'] / $originalSize['height']), + $x * $this->k, + ($this->h - $y - $newSize['height']) * $this->k, + $importedPage['id'] + ) + ); + + return $newSize; + } + + /** + * Get the size of an imported page. + * + * Give only one of the size parameters (width, height) to calculate the other one automatically in view to the + * aspect ratio. + * + * @param mixed $tpl The template id + * @param float|int|null $width The width. + * @param float|int|null $height The height. + * @return array|bool An array with following keys: width, height, 0 (=width), 1 (=height), orientation (L or P) + */ + public function getImportedPageSize($tpl, $width = null, $height = null) + { + if (isset($this->importedPages[$tpl])) { + $importedPage = $this->importedPages[$tpl]; + + if ($width === null && $height === null) { + $width = $importedPage['width']; + $height = $importedPage['height']; + } elseif ($width === null) { + $width = $height * $importedPage['width'] / $importedPage['height']; + } + + if ($height === null) { + $height = $width * $importedPage['height'] / $importedPage['width']; + } + + if ($height <= 0. || $width <= 0.) { + throw new \InvalidArgumentException('Width or height parameter needs to be larger than zero.'); + } + + return [ + 'width' => $width, + 'height' => $height, + 0 => $width, + 1 => $height, + 'orientation' => $width > $height ? 'L' : 'P' + ]; + } + + return false; + } + + /** + * Writes a PdfType object to the resulting buffer. + * + * @param PdfType $value + * @throws PdfTypeException + */ + protected function writePdfType(PdfType $value) + { + if ($value instanceof PdfNumeric) { + if (\is_int($value->value)) { + $this->_put($value->value . ' ', false); + } else { + $this->_put(\rtrim(\rtrim(\sprintf('%.5F', $value->value), '0'), '.') . ' ', false); + } + } elseif ($value instanceof PdfName) { + $this->_put('/' . $value->value . ' ', false); + } elseif ($value instanceof PdfString) { + $this->_put('(' . $value->value . ')', false); + } elseif ($value instanceof PdfHexString) { + $this->_put('<' . $value->value . '>'); + } elseif ($value instanceof PdfBoolean) { + $this->_put($value->value ? 'true ' : 'false ', false); + } elseif ($value instanceof PdfArray) { + $this->_put('[', false); + foreach ($value->value as $entry) { + $this->writePdfType($entry); + } + $this->_put(']'); + } elseif ($value instanceof PdfDictionary) { + $this->_put('<<', false); + foreach ($value->value as $name => $entry) { + $this->_put('/' . $name . ' ', false); + $this->writePdfType($entry); + } + $this->_put('>>'); + } elseif ($value instanceof PdfToken) { + $this->_put($value->value); + } elseif ($value instanceof PdfNull) { + $this->_put('null '); + } elseif ($value instanceof PdfStream) { + /** + * @var $value PdfStream + */ + $this->writePdfType($value->value); + $this->_put('stream'); + $this->_put($value->getStream()); + $this->_put('endstream'); + } elseif ($value instanceof PdfIndirectObjectReference) { + if (!isset($this->objectMap[$this->currentReaderId])) { + $this->objectMap[$this->currentReaderId] = []; + } + + if (!isset($this->objectMap[$this->currentReaderId][$value->value])) { + $this->objectMap[$this->currentReaderId][$value->value] = ++$this->n; + $this->objectsToCopy[$this->currentReaderId][] = $value->value; + } + + $this->_put($this->objectMap[$this->currentReaderId][$value->value] . ' 0 R ', false); + } elseif ($value instanceof PdfIndirectObject) { + /** + * @var PdfIndirectObject $value + */ + $n = $this->objectMap[$this->currentReaderId][$value->objectNumber]; + $this->_newobj($n); + $this->writePdfType($value->value); + $this->_put('endobj'); + } + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfParser/CrossReference/AbstractReader.php b/src/bb-vendor/setasign/fpdi/src/PdfParser/CrossReference/AbstractReader.php new file mode 100644 index 000000000..b54237bc1 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfParser/CrossReference/AbstractReader.php @@ -0,0 +1,95 @@ +parser = $parser; + $this->readTrailer(); + } + + /** + * Get the trailer dictionary. + * + * @return PdfDictionary + */ + public function getTrailer() + { + return $this->trailer; + } + + /** + * Read the trailer dictionary. + * + * @throws CrossReferenceException + * @throws PdfTypeException + */ + protected function readTrailer() + { + try { + $trailerKeyword = $this->parser->readValue(null, PdfToken::class); + if ($trailerKeyword->value !== 'trailer') { + throw new CrossReferenceException( + \sprintf( + 'Unexpected end of cross reference. "trailer"-keyword expected, got: %s.', + $trailerKeyword->value + ), + CrossReferenceException::UNEXPECTED_END + ); + } + } catch (PdfTypeException $e) { + throw new CrossReferenceException( + 'Unexpected end of cross reference. "trailer"-keyword expected, got an invalid object type.', + CrossReferenceException::UNEXPECTED_END, + $e + ); + } + + try { + $trailer = $this->parser->readValue(null, PdfDictionary::class); + } catch (PdfTypeException $e) { + throw new CrossReferenceException( + 'Unexpected end of cross reference. Trailer not found.', + CrossReferenceException::UNEXPECTED_END, + $e + ); + } + + $this->trailer = $trailer; + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfParser/CrossReference/CrossReference.php b/src/bb-vendor/setasign/fpdi/src/PdfParser/CrossReference/CrossReference.php new file mode 100644 index 000000000..89905a563 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfParser/CrossReference/CrossReference.php @@ -0,0 +1,326 @@ +parser = $parser; + $this->fileHeaderOffset = $fileHeaderOffset; + + $offset = $this->findStartXref(); + $reader = null; + /** @noinspection TypeUnsafeComparisonInspection */ + while ($offset != false) { // By doing an unsafe comparsion we ignore faulty references to byte offset 0 + try { + $reader = $this->readXref($offset + $this->fileHeaderOffset); + } catch (CrossReferenceException $e) { + // sometimes the file header offset is part of the byte offsets, so let's retry by resetting it to zero. + if ($e->getCode() === CrossReferenceException::INVALID_DATA && $this->fileHeaderOffset !== 0) { + $this->fileHeaderOffset = 0; + $reader = $this->readXref($offset + $this->fileHeaderOffset); + } else { + throw $e; + } + } + + $trailer = $reader->getTrailer(); + $this->checkForEncryption($trailer); + $this->readers[] = $reader; + + if (isset($trailer->value['Prev'])) { + $offset = $trailer->value['Prev']->value; + } else { + $offset = false; + } + } + + // fix faulty sub-section header + if ($reader instanceof FixedReader) { + /** + * @var FixedReader $reader + */ + $reader->fixFaultySubSectionShift(); + } + + if ($reader === null) { + throw new CrossReferenceException('No cross-reference found.', CrossReferenceException::NO_XREF_FOUND); + } + } + + /** + * Get the size of the cross reference. + * + * @return integer + */ + public function getSize() + { + return $this->getTrailer()->value['Size']->value; + } + + /** + * Get the trailer dictionary. + * + * @return PdfDictionary + */ + public function getTrailer() + { + return $this->readers[0]->getTrailer(); + } + + /** + * Get the cross reference readser instances. + * + * @return ReaderInterface[] + */ + public function getReaders() + { + return $this->readers; + } + + /** + * Get the offset by an object number. + * + * @param int $objectNumber + * @return integer|bool + */ + public function getOffsetFor($objectNumber) + { + foreach ($this->getReaders() as $reader) { + $offset = $reader->getOffsetFor($objectNumber); + if ($offset !== false) { + return $offset; + } + } + + return false; + } + + /** + * Get an indirect object by its object number. + * + * @param int $objectNumber + * @return PdfIndirectObject + * @throws CrossReferenceException + */ + public function getIndirectObject($objectNumber) + { + $offset = $this->getOffsetFor($objectNumber); + if ($offset === false) { + throw new CrossReferenceException( + \sprintf('Object (id:%s) not found.', $objectNumber), + CrossReferenceException::OBJECT_NOT_FOUND + ); + } + + $parser = $this->parser; + + $parser->getTokenizer()->clearStack(); + $parser->getStreamReader()->reset($offset + $this->fileHeaderOffset); + + try { + /** @var PdfIndirectObject $object */ + $object = $parser->readValue(null, PdfIndirectObject::class); + } catch (PdfTypeException $e) { + throw new CrossReferenceException( + \sprintf('Object (id:%s) not found at location (%s).', $objectNumber, $offset), + CrossReferenceException::OBJECT_NOT_FOUND, + $e + ); + } + + if ($object->objectNumber !== $objectNumber) { + throw new CrossReferenceException( + \sprintf('Wrong object found, got %s while %s was expected.', $object->objectNumber, $objectNumber), + CrossReferenceException::OBJECT_NOT_FOUND + ); + } + + return $object; + } + + /** + * Read the cross-reference table at a given offset. + * + * Internally the method will try to evaluate the best reader for this cross-reference. + * + * @param int $offset + * @return ReaderInterface + * @throws CrossReferenceException + * @throws PdfTypeException + */ + protected function readXref($offset) + { + $this->parser->getStreamReader()->reset($offset); + $this->parser->getTokenizer()->clearStack(); + $initValue = $this->parser->readValue(); + + return $this->initReaderInstance($initValue); + } + + /** + * Get a cross-reference reader instance. + * + * @param PdfToken|PdfIndirectObject $initValue + * @return ReaderInterface|bool + * @throws CrossReferenceException + * @throws PdfTypeException + */ + protected function initReaderInstance($initValue) + { + $position = $this->parser->getStreamReader()->getPosition() + + $this->parser->getStreamReader()->getOffset() + $this->fileHeaderOffset; + + if ($initValue instanceof PdfToken && $initValue->value === 'xref') { + try { + return new FixedReader($this->parser); + } catch (CrossReferenceException $e) { + $this->parser->getStreamReader()->reset($position); + $this->parser->getTokenizer()->clearStack(); + + return new LineReader($this->parser); + } + } + + if ($initValue instanceof PdfIndirectObject) { + try { + $stream = PdfStream::ensure($initValue->value); + } catch (PdfTypeException $e) { + throw new CrossReferenceException( + 'Invalid object type at xref reference offset.', + CrossReferenceException::INVALID_DATA, + $e + ); + } + + $type = PdfDictionary::get($stream->value, 'Type'); + if ($type->value !== 'XRef') { + throw new CrossReferenceException( + 'The xref position points to an incorrect object type.', + CrossReferenceException::INVALID_DATA + ); + } + + $this->checkForEncryption($stream->value); + + throw new CrossReferenceException( + 'This PDF document probably uses a compression technique which is not supported by the ' . + 'free parser shipped with FPDI. (See https://www.setasign.com/fpdi-pdf-parser for more details)', + CrossReferenceException::COMPRESSED_XREF + ); + } + + throw new CrossReferenceException( + 'The xref position points to an incorrect object type.', + CrossReferenceException::INVALID_DATA + ); + } + + /** + * Check for encryption. + * + * @param PdfDictionary $dictionary + * @throws CrossReferenceException + */ + protected function checkForEncryption(PdfDictionary $dictionary) + { + if (isset($dictionary->value['Encrypt'])) { + throw new CrossReferenceException( + 'This PDF document is encrypted and cannot be processed with FPDI.', + CrossReferenceException::ENCRYPTED + ); + } + } + + /** + * Find the start position for the first cross-reference. + * + * @return int The byte-offset position of the first cross-reference. + * @throws CrossReferenceException + */ + protected function findStartXref() + { + $reader = $this->parser->getStreamReader(); + $reader->reset(-self::$trailerSearchLength, self::$trailerSearchLength); + + $buffer = $reader->getBuffer(false); + $pos = \strrpos($buffer, 'startxref'); + $addOffset = 9; + if ($pos === false) { + // Some corrupted documents uses startref, instead of startxref + $pos = \strrpos($buffer, 'startref'); + if ($pos === false) { + throw new CrossReferenceException( + 'Unable to find pointer to xref table', + CrossReferenceException::NO_STARTXREF_FOUND + ); + } + $addOffset = 8; + } + + $reader->setOffset($pos + $addOffset); + + try { + $value = $this->parser->readValue(null, PdfNumeric::class); + } catch (PdfTypeException $e) { + throw new CrossReferenceException( + 'Invalid data after startxref keyword.', + CrossReferenceException::INVALID_DATA, + $e + ); + } + + return $value->value; + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfParser/CrossReference/CrossReferenceException.php b/src/bb-vendor/setasign/fpdi/src/PdfParser/CrossReference/CrossReferenceException.php new file mode 100644 index 000000000..7d88d5d05 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfParser/CrossReference/CrossReferenceException.php @@ -0,0 +1,79 @@ +reader = $parser->getStreamReader(); + $this->read(); + parent::__construct($parser); + } + + /** + * Get all subsection data. + * + * @return array + */ + public function getSubSections() + { + return $this->subSections; + } + + /** + * @inheritdoc + */ + public function getOffsetFor($objectNumber) + { + foreach ($this->subSections as $offset => list($startObject, $objectCount)) { + /** + * @var int $startObject + * @var int $objectCount + */ + if ($objectNumber >= $startObject && $objectNumber < ($startObject + $objectCount)) { + $position = $offset + 20 * ($objectNumber - $startObject); + $this->reader->ensure($position, 20); + $line = $this->reader->readBytes(20); + if ($line[17] === 'f') { + return false; + } + + return (int) \substr($line, 0, 10); + } + } + + return false; + } + + /** + * Read the cross-reference. + * + * This reader will only read the subsections in this method. The offsets were resolved individually by this + * information. + * + * @throws CrossReferenceException + */ + protected function read() + { + $subSections = []; + + $startObject = $entryCount = $lastLineStart = null; + $validityChecked = false; + while (($line = $this->reader->readLine(20)) !== false) { + if (\strpos($line, 'trailer') !== false) { + $this->reader->reset($lastLineStart); + break; + } + + // jump over if line content doesn't match the expected string + if (\sscanf($line, '%d %d', $startObject, $entryCount) !== 2) { + continue; + } + + $oldPosition = $this->reader->getPosition(); + $position = $oldPosition + $this->reader->getOffset(); + + if (!$validityChecked && $entryCount > 0) { + $nextLine = $this->reader->readBytes(21); + /* Check the next line for maximum of 20 bytes and not longer + * By catching 21 bytes and trimming the length should be still 21. + */ + if (\strlen(\trim($nextLine)) !== 21) { + throw new CrossReferenceException( + 'Cross-reference entries are larger than 20 bytes.', + CrossReferenceException::ENTRIES_TOO_LARGE + ); + } + + /* Check for less than 20 bytes: cut the line to 20 bytes and trim; have to result in exactly 18 bytes. + * If it would have less bytes the substring would get the first bytes of the next line which would + * evaluate to a 20 bytes long string after trimming. + */ + if (\strlen(\trim(\substr($nextLine, 0, 20))) !== 18) { + throw new CrossReferenceException( + 'Cross-reference entries are less than 20 bytes.', + CrossReferenceException::ENTRIES_TOO_SHORT + ); + } + + $validityChecked = true; + } + + $subSections[$position] = [$startObject, $entryCount]; + + $lastLineStart = $position + $entryCount * 20; + $this->reader->reset($lastLineStart); + } + + // reset after the last correct parsed line + $this->reader->reset($lastLineStart); + + if (\count($subSections) === 0) { + throw new CrossReferenceException( + 'No entries found in cross-reference.', + CrossReferenceException::NO_ENTRIES + ); + } + + $this->subSections = $subSections; + } + + /** + * Fixes an invalid object number shift. + * + * This method can be used to repair documents with an invalid subsection header: + * + * + * xref + * 1 7 + * 0000000000 65535 f + * 0000000009 00000 n + * 0000412075 00000 n + * 0000412172 00000 n + * 0000412359 00000 n + * 0000412417 00000 n + * 0000412468 00000 n + * + * + * It shall only be called on the first table. + * + * @return bool + */ + public function fixFaultySubSectionShift() + { + $subSections = $this->getSubSections(); + if (\count($subSections) > 1) { + return false; + } + + $subSection = \current($subSections); + if ($subSection[0] != 1) { + return false; + } + + if ($this->getOffsetFor(1) === false) { + foreach ($subSections as $offset => list($startObject, $objectCount)) { + $this->subSections[$offset] = [$startObject - 1, $objectCount]; + } + return true; + } + + return false; + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfParser/CrossReference/LineReader.php b/src/bb-vendor/setasign/fpdi/src/PdfParser/CrossReference/LineReader.php new file mode 100644 index 000000000..b6f0e4211 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfParser/CrossReference/LineReader.php @@ -0,0 +1,167 @@ + 20 bytes). + */ +class LineReader extends AbstractReader implements ReaderInterface +{ + /** + * The object offsets. + * + * @var array + */ + protected $offsets; + + /** + * LineReader constructor. + * + * @param PdfParser $parser + * @throws CrossReferenceException + */ + public function __construct(PdfParser $parser) + { + $this->read($this->extract($parser->getStreamReader())); + parent::__construct($parser); + } + + /** + * @inheritdoc + */ + public function getOffsetFor($objectNumber) + { + if (isset($this->offsets[$objectNumber])) { + return $this->offsets[$objectNumber][0]; + } + + return false; + } + + /** + * Get all found offsets. + * + * @return array + */ + public function getOffsets() + { + return $this->offsets; + } + + /** + * Extracts the cross reference data from the stream reader. + * + * @param StreamReader $reader + * @return string + * @throws CrossReferenceException + */ + protected function extract(StreamReader $reader) + { + $bytesPerCycle = 100; + $reader->reset(null, $bytesPerCycle); + + $cycles = 0; + do { + // 6 = length of "trailer" - 1 + $pos = \max(($bytesPerCycle * $cycles) - 6, 0); + $trailerPos = \strpos($reader->getBuffer(false), 'trailer', $pos); + $cycles++; + } while ($trailerPos === false && $reader->increaseLength($bytesPerCycle) !== false); + + if ($trailerPos === false) { + throw new CrossReferenceException( + 'Unexpected end of cross reference. "trailer"-keyword not found.', + CrossReferenceException::NO_TRAILER_FOUND + ); + } + + $xrefContent = \substr($reader->getBuffer(false), 0, $trailerPos); + $reader->reset($reader->getPosition() + $trailerPos); + + return $xrefContent; + } + + /** + * Read the cross-reference entries. + * + * @param string $xrefContent + * @throws CrossReferenceException + */ + protected function read($xrefContent) + { + // get eol markers in the first 100 bytes + \preg_match_all("/(\r\n|\n|\r)/", \substr($xrefContent, 0, 100), $m); + + if (\count($m[0]) === 0) { + throw new CrossReferenceException( + 'No data found in cross-reference.', + CrossReferenceException::INVALID_DATA + ); + } + + // count(array_count_values()) is faster then count(array_unique()) + // @see https://github.com/symfony/symfony/pull/23731 + // can be reverted for php7.2 + $differentLineEndings = \count(\array_count_values($m[0])); + if ($differentLineEndings > 1) { + $lines = \preg_split("/(\r\n|\n|\r)/", $xrefContent, -1, PREG_SPLIT_NO_EMPTY); + } else { + $lines = \explode($m[0][0], $xrefContent); + } + + unset($differentLineEndings, $m); + if (!\is_array($lines)) { + $this->offsets = []; + return; + } + + $start = 0; + $offsets = []; + + // trim all lines and remove empty lines + $lines = \array_filter(\array_map('\trim', $lines)); + foreach ($lines as $line) { + $pieces = \explode(' ', $line); + + switch (\count($pieces)) { + case 2: + $start = (int) $pieces[0]; + break; + + case 3: + switch ($pieces[2]) { + case 'n': + $offsets[$start] = [(int) $pieces[0], (int) $pieces[1]]; + $start++; + break 2; + case 'f': + $start++; + break 2; + } + // fall through if pieces doesn't match + + default: + throw new CrossReferenceException( + \sprintf('Unexpected data in xref table (%s)', \implode(' ', $pieces)), + CrossReferenceException::INVALID_DATA + ); + } + } + + $this->offsets = $offsets; + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfParser/CrossReference/ReaderInterface.php b/src/bb-vendor/setasign/fpdi/src/PdfParser/CrossReference/ReaderInterface.php new file mode 100644 index 000000000..d2dfdd0c9 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfParser/CrossReference/ReaderInterface.php @@ -0,0 +1,34 @@ + + if ($ch === 126 && isset($data[$k + 1]) && (\ord($data[$k + 1]) & 0xFF) === 62) { + break; + } + + if ($ch === 122 /* z */ && $state === 0) { + $out .= \chr(0) . \chr(0) . \chr(0) . \chr(0); + continue; + } + + if ($ch < 33 /* ! */ || $ch > 117 /* u */) { + throw new Ascii85Exception( + 'Illegal character found while ASCII85 decode.', + Ascii85Exception::ILLEGAL_CHAR_FOUND + ); + } + + $chn[$state] = $ch - 33;/* ! */ + $state++; + + if ($state === 5) { + $state = 0; + $r = 0; + for ($j = 0; $j < 5; ++$j) { + /** @noinspection UnnecessaryCastingInspection */ + $r = (int)($r * 85 + $chn[$j]); + } + + $out .= \chr($r >> 24) + . \chr($r >> 16) + . \chr($r >> 8) + . \chr($r); + } + } + + if ($state === 1) { + throw new Ascii85Exception( + 'Illegal length while ASCII85 decode.', + Ascii85Exception::ILLEGAL_LENGTH + ); + } + + if ($state === 2) { + $r = $chn[0] * 85 * 85 * 85 * 85 + ($chn[1] + 1) * 85 * 85 * 85; + $out .= \chr($r >> 24); + } elseif ($state === 3) { + $r = $chn[0] * 85 * 85 * 85 * 85 + $chn[1] * 85 * 85 * 85 + ($chn[2] + 1) * 85 * 85; + $out .= \chr($r >> 24); + $out .= \chr($r >> 16); + } elseif ($state === 4) { + $r = $chn[0] * 85 * 85 * 85 * 85 + $chn[1] * 85 * 85 * 85 + $chn[2] * 85 * 85 + ($chn[3] + 1) * 85; + $out .= \chr($r >> 24); + $out .= \chr($r >> 16); + $out .= \chr($r >> 8); + } + + return $out; + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfParser/Filter/Ascii85Exception.php b/src/bb-vendor/setasign/fpdi/src/PdfParser/Filter/Ascii85Exception.php new file mode 100644 index 000000000..f4b675837 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfParser/Filter/Ascii85Exception.php @@ -0,0 +1,27 @@ +')); + if ((\strlen($data) % 2) === 1) { + $data .= '0'; + } + + return \pack('H*', $data); + } + + /** + * Converts a string into ASCII hexadecimal representation. + * + * @param string $data The input string + * @param boolean $leaveEOD + * @return string + */ + public function encode($data, $leaveEOD = false) + { + $t = \unpack('H*', $data); + return \current($t) + . ($leaveEOD ? '' : '>'); + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfParser/Filter/FilterException.php b/src/bb-vendor/setasign/fpdi/src/PdfParser/Filter/FilterException.php new file mode 100644 index 000000000..c55a7a82a --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfParser/Filter/FilterException.php @@ -0,0 +1,23 @@ +extensionLoaded()) { + $oData = $data; + $data = (($data !== '') ? @\gzuncompress($data) : ''); + if ($data === false) { + // let's try if the checksum is CRC32 + $fh = fopen('php://temp', 'w+b'); + fwrite($fh, "\x1f\x8b\x08\x00\x00\x00\x00\x00" . $oData); + stream_filter_append($fh, 'zlib.inflate', STREAM_FILTER_READ, ['window' => 30]); + fseek($fh, 0); + $data = @stream_get_contents($fh); + fclose($fh); + + if ($data) { + return $data; + } + + // Try this fallback + $tries = 0; + + $oDataLen = strlen($oData); + while ($tries < 6 && ($data === false || (strlen($data) < ($oDataLen - $tries - 1)))) { + $data = @(gzinflate(substr($oData, $tries))); + $tries++; + } + + // let's use this fallback only if the $data is longer than the original data + if (strlen($data) > ($oDataLen - $tries - 1)) { + return $data; + } + + if (!$data) { + throw new FlateException( + 'Error while decompressing stream.', + FlateException::DECOMPRESS_ERROR + ); + } + } + } else { + throw new FlateException( + 'To handle FlateDecode filter, enable zlib support in PHP.', + FlateException::NO_ZLIB + ); + } + + return $data; + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfParser/Filter/FlateException.php b/src/bb-vendor/setasign/fpdi/src/PdfParser/Filter/FlateException.php new file mode 100644 index 000000000..d897ac8ee --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfParser/Filter/FlateException.php @@ -0,0 +1,27 @@ +initsTable(); + + $this->data = $data; + $this->dataLength = \strlen($data); + + // Initialize pointers + $this->bytePointer = 0; + + $this->nextData = 0; + $this->nextBits = 0; + + $oldCode = 0; + + $uncompData = ''; + + while (($code = $this->getNextCode()) !== 257) { + if ($code === 256) { + $this->initsTable(); + $code = $this->getNextCode(); + + if ($code === 257) { + break; + } + + $uncompData .= $this->sTable[$code]; + $oldCode = $code; + } else { + if ($code < $this->tIdx) { + $string = $this->sTable[$code]; + $uncompData .= $string; + + $this->addStringToTable($this->sTable[$oldCode], $string[0]); + $oldCode = $code; + } else { + $string = $this->sTable[$oldCode]; + $string .= $string[0]; + $uncompData .= $string; + + $this->addStringToTable($string); + $oldCode = $code; + } + } + } + + return $uncompData; + } + + /** + * Initialize the string table. + */ + protected function initsTable() + { + $this->sTable = []; + + for ($i = 0; $i < 256; $i++) { + $this->sTable[$i] = \chr($i); + } + + $this->tIdx = 258; + $this->bitsToGet = 9; + } + + /** + * Add a new string to the string table. + * + * @param string $oldString + * @param string $newString + */ + protected function addStringToTable($oldString, $newString = '') + { + $string = $oldString . $newString; + + // Add this new String to the table + $this->sTable[$this->tIdx++] = $string; + + if ($this->tIdx === 511) { + $this->bitsToGet = 10; + } elseif ($this->tIdx === 1023) { + $this->bitsToGet = 11; + } elseif ($this->tIdx === 2047) { + $this->bitsToGet = 12; + } + } + + /** + * Returns the next 9, 10, 11 or 12 bits. + * + * @return integer + */ + protected function getNextCode() + { + if ($this->bytePointer === $this->dataLength) { + return 257; + } + + $this->nextData = ($this->nextData << 8) | (\ord($this->data[$this->bytePointer++]) & 0xff); + $this->nextBits += 8; + + if ($this->nextBits < $this->bitsToGet) { + $this->nextData = ($this->nextData << 8) | (\ord($this->data[$this->bytePointer++]) & 0xff); + $this->nextBits += 8; + } + + $code = ($this->nextData >> ($this->nextBits - $this->bitsToGet)) & $this->andTable[$this->bitsToGet - 9]; + $this->nextBits -= $this->bitsToGet; + + return $code; + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfParser/Filter/LzwException.php b/src/bb-vendor/setasign/fpdi/src/PdfParser/Filter/LzwException.php new file mode 100644 index 000000000..6ebad4f45 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfParser/Filter/LzwException.php @@ -0,0 +1,22 @@ +streamReader = $streamReader; + $this->tokenizer = new Tokenizer($streamReader); + } + + /** + * Removes cycled references. + * + * @internal + */ + public function cleanUp() + { + $this->xref = null; + } + + /** + * Get the stream reader instance. + * + * @return StreamReader + */ + public function getStreamReader() + { + return $this->streamReader; + } + + /** + * Get the tokenizer instance. + * + * @return Tokenizer + */ + public function getTokenizer() + { + return $this->tokenizer; + } + + /** + * Resolves the file header. + * + * @throws PdfParserException + * @return int + */ + protected function resolveFileHeader() + { + if ($this->fileHeader) { + return $this->fileHeaderOffset; + } + + $this->streamReader->reset(0); + $maxIterations = 1000; + while (true) { + $buffer = $this->streamReader->getBuffer(false); + $offset = \strpos($buffer, '%PDF-'); + if ($offset === false) { + if (!$this->streamReader->increaseLength(100) || (--$maxIterations === 0)) { + throw new PdfParserException( + 'Unable to find PDF file header.', + PdfParserException::FILE_HEADER_NOT_FOUND + ); + } + continue; + } + break; + } + + $this->fileHeaderOffset = $offset; + $this->streamReader->setOffset($offset); + + $this->fileHeader = \trim($this->streamReader->readLine()); + return $this->fileHeaderOffset; + } + + /** + * Get the cross reference instance. + * + * @return CrossReference + * @throws CrossReferenceException + * @throws PdfParserException + */ + public function getCrossReference() + { + if ($this->xref === null) { + $this->xref = new CrossReference($this, $this->resolveFileHeader()); + } + + return $this->xref; + } + + /** + * Get the PDF version. + * + * @return int[] An array of major and minor version. + * @throws PdfParserException + */ + public function getPdfVersion() + { + $this->resolveFileHeader(); + + if (\preg_match('/%PDF-(\d)\.(\d)/', $this->fileHeader, $result) === 0) { + throw new PdfParserException( + 'Unable to extract PDF version from file header.', + PdfParserException::PDF_VERSION_NOT_FOUND + ); + } + list(, $major, $minor) = $result; + + $catalog = $this->getCatalog(); + if (isset($catalog->value['Version'])) { + $versionParts = \explode( + '.', + PdfName::unescape(PdfType::resolve($catalog->value['Version'], $this)->value) + ); + if (count($versionParts) === 2) { + list($major, $minor) = $versionParts; + } + } + + return [(int) $major, (int) $minor]; + } + + /** + * Get the catalog dictionary. + * + * @return PdfDictionary + * @throws Type\PdfTypeException + * @throws CrossReferenceException + * @throws PdfParserException + */ + public function getCatalog() + { + $trailer = $this->getCrossReference()->getTrailer(); + + $catalog = PdfType::resolve(PdfDictionary::get($trailer, 'Root'), $this); + + return PdfDictionary::ensure($catalog); + } + + /** + * Get an indirect object by its object number. + * + * @param int $objectNumber + * @param bool $cache + * @return PdfIndirectObject + * @throws CrossReferenceException + * @throws PdfParserException + */ + public function getIndirectObject($objectNumber, $cache = false) + { + $objectNumber = (int) $objectNumber; + if (isset($this->objects[$objectNumber])) { + return $this->objects[$objectNumber]; + } + + $object = $this->getCrossReference()->getIndirectObject($objectNumber); + + if ($cache) { + $this->objects[$objectNumber] = $object; + } + + return $object; + } + + /** + * Read a PDF value. + * + * @param null|bool|string $token + * @param null|string $expectedType + * @return false|PdfArray|PdfBoolean|PdfDictionary|PdfHexString|PdfIndirectObject|PdfIndirectObjectReference|PdfName|PdfNull|PdfNumeric|PdfStream|PdfString|PdfToken + * @throws Type\PdfTypeException + */ + public function readValue($token = null, $expectedType = null) + { + if ($token === null) { + $token = $this->tokenizer->getNextToken(); + } + + if ($token === false) { + if ($expectedType !== null) { + throw new Type\PdfTypeException('Got unexpected token type.', Type\PdfTypeException::INVALID_DATA_TYPE); + } + return false; + } + + switch ($token) { + case '(': + $this->ensureExpectedType($token, $expectedType); + return PdfString::parse($this->streamReader); + + case '<': + if ($this->streamReader->getByte() === '<') { + $this->ensureExpectedType('<<', $expectedType); + $this->streamReader->addOffset(1); + return PdfDictionary::parse($this->tokenizer, $this->streamReader, $this); + } + + $this->ensureExpectedType($token, $expectedType); + return PdfHexString::parse($this->streamReader); + + case '/': + $this->ensureExpectedType($token, $expectedType); + return PdfName::parse($this->tokenizer, $this->streamReader); + + case '[': + $this->ensureExpectedType($token, $expectedType); + return PdfArray::parse($this->tokenizer, $this); + + default: + if (\is_numeric($token)) { + if (($token2 = $this->tokenizer->getNextToken()) !== false) { + if (\is_numeric($token2) && ($token3 = $this->tokenizer->getNextToken()) !== false) { + switch ($token3) { + case 'obj': + if ($expectedType !== null && $expectedType !== PdfIndirectObject::class) { + throw new Type\PdfTypeException( + 'Got unexpected token type.', + Type\PdfTypeException::INVALID_DATA_TYPE + ); + } + + return PdfIndirectObject::parse( + (int) $token, + (int) $token2, + $this, + $this->tokenizer, + $this->streamReader + ); + case 'R': + if ( + $expectedType !== null && + $expectedType !== PdfIndirectObjectReference::class + ) { + throw new Type\PdfTypeException( + 'Got unexpected token type.', + Type\PdfTypeException::INVALID_DATA_TYPE + ); + } + + return PdfIndirectObjectReference::create((int) $token, (int) $token2); + } + + $this->tokenizer->pushStack($token3); + } + + $this->tokenizer->pushStack($token2); + } + + if ($expectedType !== null && $expectedType !== PdfNumeric::class) { + throw new Type\PdfTypeException( + 'Got unexpected token type.', + Type\PdfTypeException::INVALID_DATA_TYPE + ); + } + return PdfNumeric::create($token + 0); + } + + if ($token === 'true' || $token === 'false') { + $this->ensureExpectedType($token, $expectedType); + return PdfBoolean::create($token === 'true'); + } + + if ($token === 'null') { + $this->ensureExpectedType($token, $expectedType); + return new PdfNull(); + } + + if ($expectedType !== null && $expectedType !== PdfToken::class) { + throw new Type\PdfTypeException( + 'Got unexpected token type.', + Type\PdfTypeException::INVALID_DATA_TYPE + ); + } + + $v = new PdfToken(); + $v->value = $token; + + return $v; + } + } + + /** + * Ensures that the token will evaluate to an expected object type (or not). + * + * @param string $token + * @param string|null $expectedType + * @return bool + * @throws Type\PdfTypeException + */ + private function ensureExpectedType($token, $expectedType) + { + static $mapping = [ + '(' => PdfString::class, + '<' => PdfHexString::class, + '<<' => PdfDictionary::class, + '/' => PdfName::class, + '[' => PdfArray::class, + 'true' => PdfBoolean::class, + 'false' => PdfBoolean::class, + 'null' => PdfNull::class + ]; + + if ($expectedType === null || $mapping[$token] === $expectedType) { + return true; + } + + throw new Type\PdfTypeException('Got unexpected token type.', Type\PdfTypeException::INVALID_DATA_TYPE); + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfParser/PdfParserException.php b/src/bb-vendor/setasign/fpdi/src/PdfParser/PdfParserException.php new file mode 100644 index 000000000..6d034d86d --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfParser/PdfParserException.php @@ -0,0 +1,49 @@ +stream = $stream; + $this->closeStream = $closeStream; + $this->reset(); + } + + /** + * The destructor. + */ + public function __destruct() + { + $this->cleanUp(); + } + + /** + * Closes the file handle. + */ + public function cleanUp() + { + if ($this->closeStream && is_resource($this->stream)) { + \fclose($this->stream); + } + } + + /** + * Returns the byte length of the buffer. + * + * @param bool $atOffset + * @return int + */ + public function getBufferLength($atOffset = false) + { + if ($atOffset === false) { + return $this->bufferLength; + } + + return $this->bufferLength - $this->offset; + } + + /** + * Get the current position in the stream. + * + * @return int + */ + public function getPosition() + { + return $this->position; + } + + /** + * Returns the current buffer. + * + * @param bool $atOffset + * @return string + */ + public function getBuffer($atOffset = true) + { + if ($atOffset === false) { + return $this->buffer; + } + + $string = \substr($this->buffer, $this->offset); + + return (string) $string; + } + + /** + * Gets a byte at a specific position in the buffer. + * + * If the position is invalid the method will return false. + * + * If the $position parameter is set to null the value of $this->offset will be used. + * + * @param int|null $position + * @return string|bool + */ + public function getByte($position = null) + { + $position = (int) ($position !== null ? $position : $this->offset); + if ( + $position >= $this->bufferLength + && (!$this->increaseLength() || $position >= $this->bufferLength) + ) { + return false; + } + + return $this->buffer[$position]; + } + + /** + * Returns a byte at a specific position, and set the offset to the next byte position. + * + * If the position is invalid the method will return false. + * + * If the $position parameter is set to null the value of $this->offset will be used. + * + * @param int|null $position + * @return string|bool + */ + public function readByte($position = null) + { + if ($position !== null) { + $position = (int) $position; + // check if needed bytes are available in the current buffer + if (!($position >= $this->position && $position < $this->position + $this->bufferLength)) { + $this->reset($position); + $offset = $this->offset; + } else { + $offset = $position - $this->position; + } + } else { + $offset = $this->offset; + } + + if ( + $offset >= $this->bufferLength + && ((!$this->increaseLength()) || $offset >= $this->bufferLength) + ) { + return false; + } + + $this->offset = $offset + 1; + return $this->buffer[$offset]; + } + + /** + * Read bytes from the current or a specific offset position and set the internal pointer to the next byte. + * + * If the position is invalid the method will return false. + * + * If the $position parameter is set to null the value of $this->offset will be used. + * + * @param int $length + * @param int|null $position + * @return string|false + */ + public function readBytes($length, $position = null) + { + $length = (int) $length; + if ($position !== null) { + // check if needed bytes are available in the current buffer + if (!($position >= $this->position && $position < $this->position + $this->bufferLength)) { + $this->reset($position, $length); + $offset = $this->offset; + } else { + $offset = $position - $this->position; + } + } else { + $offset = $this->offset; + } + + if ( + ($offset + $length) > $this->bufferLength + && ((!$this->increaseLength($length)) || ($offset + $length) > $this->bufferLength) + ) { + return false; + } + + $bytes = \substr($this->buffer, $offset, $length); + $this->offset = $offset + $length; + + return $bytes; + } + + /** + * Read a line from the current position. + * + * @param int $length + * @return string|bool + */ + public function readLine($length = 1024) + { + if ($this->ensureContent() === false) { + return false; + } + + $line = ''; + while ($this->ensureContent()) { + $char = $this->readByte(); + + if ($char === "\n") { + break; + } + + if ($char === "\r") { + if ($this->getByte() === "\n") { + $this->addOffset(1); + } + break; + } + + $line .= $char; + + if (\strlen($line) >= $length) { + break; + } + } + + return $line; + } + + /** + * Set the offset position in the current buffer. + * + * @param int $offset + */ + public function setOffset($offset) + { + if ($offset > $this->bufferLength || $offset < 0) { + throw new \OutOfRangeException( + \sprintf('Offset (%s) out of range (length: %s)', $offset, $this->bufferLength) + ); + } + + $this->offset = (int) $offset; + } + + /** + * Returns the current offset in the current buffer. + * + * @return int + */ + public function getOffset() + { + return $this->offset; + } + + /** + * Add an offset to the current offset. + * + * @param int $offset + */ + public function addOffset($offset) + { + $this->setOffset($this->offset + $offset); + } + + /** + * Make sure that there is at least one character beyond the current offset in the buffer. + * + * @return bool + */ + public function ensureContent() + { + while ($this->offset >= $this->bufferLength) { + if (!$this->increaseLength()) { + return false; + } + } + return true; + } + + /** + * Returns the stream. + * + * @return resource + */ + public function getStream() + { + return $this->stream; + } + + /** + * Gets the total available length. + * + * @return int + */ + public function getTotalLength() + { + if ($this->totalLength === null) { + $stat = \fstat($this->stream); + $this->totalLength = $stat['size']; + } + + return $this->totalLength; + } + + /** + * Resets the buffer to a position and re-read the buffer with the given length. + * + * If the $pos parameter is negative the start buffer position will be the $pos'th position from + * the end of the file. + * + * If the $pos parameter is negative and the absolute value is bigger then the totalLength of + * the file $pos will set to zero. + * + * @param int|null $pos Start position of the new buffer + * @param int $length Length of the new buffer. Mustn't be negative + */ + public function reset($pos = 0, $length = 200) + { + if ($pos === null) { + $pos = $this->position + $this->offset; + } elseif ($pos < 0) { + $pos = \max(0, $this->getTotalLength() + $pos); + } + + \fseek($this->stream, $pos); + + $this->position = $pos; + $this->buffer = $length > 0 ? \fread($this->stream, $length) : ''; + $this->bufferLength = \strlen($this->buffer); + $this->offset = 0; + + // If a stream wrapper is in use it is possible that + // length values > 8096 will be ignored, so use the + // increaseLength()-method to correct that behavior + if ($this->bufferLength < $length && $this->increaseLength($length - $this->bufferLength)) { + // increaseLength parameter is $minLength, so cut to have only the required bytes in the buffer + $this->buffer = \substr($this->buffer, 0, $length); + $this->bufferLength = \strlen($this->buffer); + } + } + + /** + * Ensures bytes in the buffer with a specific length and location in the file. + * + * @param int $pos + * @param int $length + * @see reset() + */ + public function ensure($pos, $length) + { + if ( + $pos >= $this->position + && $pos < ($this->position + $this->bufferLength) + && ($this->position + $this->bufferLength) >= ($pos + $length) + ) { + $this->offset = $pos - $this->position; + } else { + $this->reset($pos, $length); + } + } + + /** + * Forcefully read more data into the buffer. + * + * @param int $minLength + * @return bool Returns false if the stream reaches the end + */ + public function increaseLength($minLength = 100) + { + $length = \max($minLength, 100); + + if (\feof($this->stream) || $this->getTotalLength() === $this->position + $this->bufferLength) { + return false; + } + + $newLength = $this->bufferLength + $length; + do { + $this->buffer .= \fread($this->stream, $newLength - $this->bufferLength); + $this->bufferLength = \strlen($this->buffer); + } while (($this->bufferLength !== $newLength) && !\feof($this->stream)); + + return true; + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfParser/Tokenizer.php b/src/bb-vendor/setasign/fpdi/src/PdfParser/Tokenizer.php new file mode 100644 index 000000000..a3bcd01d9 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfParser/Tokenizer.php @@ -0,0 +1,154 @@ +streamReader = $streamReader; + } + + /** + * Get the stream reader instance. + * + * @return StreamReader + */ + public function getStreamReader() + { + return $this->streamReader; + } + + /** + * Clear the token stack. + */ + public function clearStack() + { + $this->stack = []; + } + + /** + * Push a token onto the stack. + * + * @param string $token + */ + public function pushStack($token) + { + $this->stack[] = $token; + } + + /** + * Get next token. + * + * @return bool|string + */ + public function getNextToken() + { + $token = \array_pop($this->stack); + if ($token !== null) { + return $token; + } + + if (($byte = $this->streamReader->readByte()) === false) { + return false; + } + + if (\in_array($byte, ["\x20", "\x0A", "\x0D", "\x0C", "\x09", "\x00"], true)) { + if ($this->leapWhiteSpaces() === false) { + return false; + } + $byte = $this->streamReader->readByte(); + } + + switch ($byte) { + case '/': + case '[': + case ']': + case '(': + case ')': + case '{': + case '}': + case '<': + case '>': + return $byte; + case '%': + $this->streamReader->readLine(); + return $this->getNextToken(); + } + + /* This way is faster than checking single bytes. + */ + $bufferOffset = $this->streamReader->getOffset(); + do { + $lastBuffer = $this->streamReader->getBuffer(false); + $pos = \strcspn( + $lastBuffer, + "\x00\x09\x0A\x0C\x0D\x20()<>[]{}/%", + $bufferOffset + ); + } while ( + // Break the loop if a delimiter or white space char is matched + // in the current buffer or increase the buffers length + $lastBuffer !== false && + ( + $bufferOffset + $pos === \strlen($lastBuffer) && + $this->streamReader->increaseLength() + ) + ); + + $result = \substr($lastBuffer, $bufferOffset - 1, $pos + 1); + $this->streamReader->setOffset($bufferOffset + $pos); + + return $result; + } + + /** + * Leap white spaces. + * + * @return boolean + */ + public function leapWhiteSpaces() + { + do { + if (!$this->streamReader->ensureContent()) { + return false; + } + + $buffer = $this->streamReader->getBuffer(false); + $matches = \strspn($buffer, "\x20\x0A\x0C\x0D\x09\x00", $this->streamReader->getOffset()); + if ($matches > 0) { + $this->streamReader->addOffset($matches); + } + } while ($this->streamReader->getOffset() >= $this->streamReader->getBufferLength()); + + return true; + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfArray.php b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfArray.php new file mode 100644 index 000000000..5d0bbbdad --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfArray.php @@ -0,0 +1,85 @@ +getNextToken()) !== ']') { + if ($token === false || ($value = $parser->readValue($token)) === false) { + return false; + } + + $result[] = $value; + } + + $v = new self(); + $v->value = $result; + + return $v; + } + + /** + * Helper method to create an instance. + * + * @param PdfType[] $values + * @return self + */ + public static function create(array $values = []) + { + $v = new self(); + $v->value = $values; + + return $v; + } + + /** + * Ensures that the passed array is a PdfArray instance with a (optional) specific size. + * + * @param mixed $array + * @param null|int $size + * @return self + * @throws PdfTypeException + */ + public static function ensure($array, $size = null) + { + $result = PdfType::ensureType(self::class, $array, 'Array value expected.'); + + if ($size !== null && \count($array->value) !== $size) { + throw new PdfTypeException( + \sprintf('Array with %s entries expected.', $size), + PdfTypeException::INVALID_DATA_SIZE + ); + } + + return $result; + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfBoolean.php b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfBoolean.php new file mode 100644 index 000000000..ba4233a69 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfBoolean.php @@ -0,0 +1,42 @@ +value = (bool) $value; + return $v; + } + + /** + * Ensures that the passed value is a PdfBoolean instance. + * + * @param mixed $value + * @return self + * @throws PdfTypeException + */ + public static function ensure($value) + { + return PdfType::ensureType(self::class, $value, 'Boolean value expected.'); + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfDictionary.php b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfDictionary.php new file mode 100644 index 000000000..281884245 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfDictionary.php @@ -0,0 +1,134 @@ +getNextToken(); + if ($token === '>' && $streamReader->getByte() === '>') { + $streamReader->addOffset(1); + break; + } + + $key = $parser->readValue($token); + if ($key === false) { + return false; + } + + // ensure the first value to be a Name object + if (!($key instanceof PdfName)) { + $lastToken = null; + // ignore all other entries and search for the closing brackets + while (($token = $tokenizer->getNextToken()) !== '>' && $token !== false && $lastToken !== '>') { + $lastToken = $token; + } + + if ($token === false) { + return false; + } + + break; + } + + + $value = $parser->readValue(); + if ($value === false) { + return false; + } + + if ($value instanceof PdfNull) { + continue; + } + + // catch missing value + if ($value instanceof PdfToken && $value->value === '>' && $streamReader->getByte() === '>') { + $streamReader->addOffset(1); + break; + } + + $entries[$key->value] = $value; + } + + $v = new self(); + $v->value = $entries; + + return $v; + } + + /** + * Helper method to create an instance. + * + * @param PdfType[] $entries The keys are the name entries of the dictionary. + * @return self + */ + public static function create(array $entries = []) + { + $v = new self(); + $v->value = $entries; + + return $v; + } + + /** + * Get a value by its key from a dictionary or a default value. + * + * @param mixed $dictionary + * @param string $key + * @param PdfType|null $default + * @return PdfNull|PdfType + * @throws PdfTypeException + */ + public static function get($dictionary, $key, PdfType $default = null) + { + $dictionary = self::ensure($dictionary); + + if (isset($dictionary->value[$key])) { + return $dictionary->value[$key]; + } + + return $default === null + ? new PdfNull() + : $default; + } + + /** + * Ensures that the passed value is a PdfDictionary instance. + * + * @param mixed $dictionary + * @return self + * @throws PdfTypeException + */ + public static function ensure($dictionary) + { + return PdfType::ensureType(self::class, $dictionary, 'Dictionary value expected.'); + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfHexString.php b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfHexString.php new file mode 100644 index 000000000..0084ada4d --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfHexString.php @@ -0,0 +1,77 @@ +getOffset(); + + while (true) { + $buffer = $streamReader->getBuffer(false); + $pos = \strpos($buffer, '>', $bufferOffset); + if ($pos === false) { + if (!$streamReader->increaseLength()) { + return false; + } + continue; + } + + break; + } + + $result = \substr($buffer, $bufferOffset, $pos - $bufferOffset); + $streamReader->setOffset($pos + 1); + + $v = new self(); + $v->value = $result; + + return $v; + } + + /** + * Helper method to create an instance. + * + * @param string $string The hex encoded string. + * @return self + */ + public static function create($string) + { + $v = new self(); + $v->value = $string; + + return $v; + } + + /** + * Ensures that the passed value is a PdfHexString instance. + * + * @param mixed $hexString + * @return self + * @throws PdfTypeException + */ + public static function ensure($hexString) + { + return PdfType::ensureType(self::class, $hexString, 'Hex string value expected.'); + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfIndirectObject.php b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfIndirectObject.php new file mode 100644 index 000000000..15786d00c --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfIndirectObject.php @@ -0,0 +1,103 @@ +readValue(); + if ($value === false) { + return false; + } + + $nextToken = $tokenizer->getNextToken(); + if ($nextToken === 'stream') { + $value = PdfStream::parse($value, $reader, $parser); + } elseif ($nextToken !== false) { + $tokenizer->pushStack($nextToken); + } + + $v = new self(); + $v->objectNumber = (int) $objectNumberToken; + $v->generationNumber = (int) $objectGenerationNumberToken; + $v->value = $value; + + return $v; + } + + /** + * Helper method to create an instance. + * + * @param int $objectNumber + * @param int $generationNumber + * @param PdfType $value + * @return self + */ + public static function create($objectNumber, $generationNumber, PdfType $value) + { + $v = new self(); + $v->objectNumber = (int) $objectNumber; + $v->generationNumber = (int) $generationNumber; + $v->value = $value; + + return $v; + } + + /** + * Ensures that the passed value is a PdfIndirectObject instance. + * + * @param mixed $indirectObject + * @return self + * @throws PdfTypeException + */ + public static function ensure($indirectObject) + { + return PdfType::ensureType(self::class, $indirectObject, 'Indirect object expected.'); + } + + /** + * The object number. + * + * @var int + */ + public $objectNumber; + + /** + * The generation number. + * + * @var int + */ + public $generationNumber; +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfIndirectObjectReference.php b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfIndirectObjectReference.php new file mode 100644 index 000000000..2725d0c97 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfIndirectObjectReference.php @@ -0,0 +1,52 @@ +value = (int) $objectNumber; + $v->generationNumber = (int) $generationNumber; + + return $v; + } + + /** + * Ensures that the passed value is a PdfIndirectObject instance. + * + * @param mixed $value + * @return self + * @throws PdfTypeException + */ + public static function ensure($value) + { + return PdfType::ensureType(self::class, $value, 'Indirect reference value expected.'); + } + + /** + * The generation number. + * + * @var int + */ + public $generationNumber; +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfName.php b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfName.php new file mode 100644 index 000000000..194a13fe3 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfName.php @@ -0,0 +1,82 @@ +getByte(), "\x00\x09\x0A\x0C\x0D\x20()<>[]{}/%") === 0) { + $v->value = (string) $tokenizer->getNextToken(); + return $v; + } + + $v->value = ''; + return $v; + } + + /** + * Unescapes a name string. + * + * @param string $value + * @return string + */ + public static function unescape($value) + { + if (strpos($value, '#') === false) { + return $value; + } + + return preg_replace_callback('/#([a-fA-F\d]{2})/', function ($matches) { + return chr(hexdec($matches[1])); + }, $value); + } + + /** + * Helper method to create an instance. + * + * @param string $string + * @return self + */ + public static function create($string) + { + $v = new self(); + $v->value = $string; + + return $v; + } + + /** + * Ensures that the passed value is a PdfName instance. + * + * @param mixed $name + * @return self + * @throws PdfTypeException + */ + public static function ensure($name) + { + return PdfType::ensureType(self::class, $name, 'Name value expected.'); + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfNull.php b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfNull.php new file mode 100644 index 000000000..0c4c10826 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfNull.php @@ -0,0 +1,19 @@ +value = $value + 0; + + return $v; + } + + /** + * Ensures that the passed value is a PdfNumeric instance. + * + * @param mixed $value + * @return self + * @throws PdfTypeException + */ + public static function ensure($value) + { + return PdfType::ensureType(self::class, $value, 'Numeric value expected.'); + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfStream.php b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfStream.php new file mode 100644 index 000000000..6d4c5a826 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfStream.php @@ -0,0 +1,326 @@ +value = $dictionary; + $v->reader = $reader; + $v->parser = $parser; + + $offset = $reader->getOffset(); + + // Find the first "newline" + while (($firstByte = $reader->getByte($offset)) !== false) { + if ($firstByte !== "\n" && $firstByte !== "\r") { + $offset++; + } else { + break; + } + } + + if ($firstByte === false) { + throw new PdfTypeException( + 'Unable to parse stream data. No newline after the stream keyword found.', + PdfTypeException::NO_NEWLINE_AFTER_STREAM_KEYWORD + ); + } + + $sndByte = $reader->getByte($offset + 1); + if ($firstByte === "\n" || $firstByte === "\r") { + $offset++; + } + + if ($sndByte === "\n" && $firstByte !== "\n") { + $offset++; + } + + $reader->setOffset($offset); + // let's only save the byte-offset and read the stream only when needed + $v->stream = $reader->getPosition() + $reader->getOffset(); + + return $v; + } + + /** + * Helper method to create an instance. + * + * @param PdfDictionary $dictionary + * @param string $stream + * @return self + */ + public static function create(PdfDictionary $dictionary, $stream) + { + $v = new self(); + $v->value = $dictionary; + $v->stream = (string) $stream; + + return $v; + } + + /** + * Ensures that the passed value is a PdfStream instance. + * + * @param mixed $stream + * @return self + * @throws PdfTypeException + */ + public static function ensure($stream) + { + return PdfType::ensureType(self::class, $stream, 'Stream value expected.'); + } + + /** + * The stream or its byte-offset position. + * + * @var int|string + */ + protected $stream; + + /** + * The stream reader instance. + * + * @var StreamReader|null + */ + protected $reader; + + /** + * The PDF parser instance. + * + * @var PdfParser + */ + protected $parser; + + /** + * Get the stream data. + * + * @param bool $cache Whether cache the stream data or not. + * @return bool|string + * @throws PdfTypeException + * @throws CrossReferenceException + * @throws PdfParserException + */ + public function getStream($cache = false) + { + if (\is_int($this->stream)) { + $length = PdfDictionary::get($this->value, 'Length'); + if ($this->parser !== null) { + $length = PdfType::resolve($length, $this->parser); + } + + if (!($length instanceof PdfNumeric) || $length->value === 0) { + $this->reader->reset($this->stream, 100000); + $buffer = $this->extractStream(); + } else { + $this->reader->reset($this->stream, $length->value); + $buffer = $this->reader->getBuffer(false); + if ($this->parser !== null) { + $this->reader->reset($this->stream + strlen($buffer)); + $this->parser->getTokenizer()->clearStack(); + $token = $this->parser->readValue(); + if ($token === false || !($token instanceof PdfToken) || $token->value !== 'endstream') { + $this->reader->reset($this->stream, 100000); + $buffer = $this->extractStream(); + $this->reader->reset($this->stream + strlen($buffer)); + } + } + } + + if ($cache === false) { + return $buffer; + } + + $this->stream = $buffer; + $this->reader = null; + } + + return $this->stream; + } + + /** + * Extract the stream "manually". + * + * @return string + * @throws PdfTypeException + */ + protected function extractStream() + { + while (true) { + $buffer = $this->reader->getBuffer(false); + $length = \strpos($buffer, 'endstream'); + if ($length === false) { + if (!$this->reader->increaseLength(100000)) { + throw new PdfTypeException('Cannot extract stream.'); + } + continue; + } + break; + } + + $buffer = \substr($buffer, 0, $length); + $lastByte = \substr($buffer, -1); + + /* Check for EOL marker = + * CARRIAGE RETURN (\r) and a LINE FEED (\n) or just a LINE FEED (\n}, + * and not by a CARRIAGE RETURN (\r) alone + */ + if ($lastByte === "\n") { + $buffer = \substr($buffer, 0, -1); + + $lastByte = \substr($buffer, -1); + if ($lastByte === "\r") { + $buffer = \substr($buffer, 0, -1); + } + } + + // There are streams in the wild, which have only white signs in them but need to be parsed manually due + // to a problem encountered before (e.g. Length === 0). We should set them to empty streams to avoid problems + // in further processing (e.g. applying of filters). + if (trim($buffer) === '') { + $buffer = ''; + } + + return $buffer; + } + + /** + * Get the unfiltered stream data. + * + * @return string + * @throws FilterException + * @throws PdfParserException + */ + public function getUnfilteredStream() + { + $stream = $this->getStream(); + $filters = PdfDictionary::get($this->value, 'Filter'); + if ($filters instanceof PdfNull) { + return $stream; + } + + if ($filters instanceof PdfArray) { + $filters = $filters->value; + } else { + $filters = [$filters]; + } + + $decodeParams = PdfDictionary::get($this->value, 'DecodeParms'); + if ($decodeParams instanceof PdfArray) { + $decodeParams = $decodeParams->value; + } else { + $decodeParams = [$decodeParams]; + } + + foreach ($filters as $key => $filter) { + if (!($filter instanceof PdfName)) { + continue; + } + + $decodeParam = null; + if (isset($decodeParams[$key])) { + $decodeParam = ($decodeParams[$key] instanceof PdfDictionary ? $decodeParams[$key] : null); + } + + switch ($filter->value) { + case 'FlateDecode': + case 'Fl': + case 'LZWDecode': + case 'LZW': + if (\strpos($filter->value, 'LZW') === 0) { + $filterObject = new Lzw(); + } else { + $filterObject = new Flate(); + } + + $stream = $filterObject->decode($stream); + + if ($decodeParam instanceof PdfDictionary) { + $predictor = PdfDictionary::get($decodeParam, 'Predictor', PdfNumeric::create(1)); + if ($predictor->value !== 1) { + if (!\class_exists(Predictor::class)) { + throw new PdfParserException( + 'This PDF document makes use of features which are only implemented in the ' . + 'commercial "FPDI PDF-Parser" add-on (see https://www.setasign.com/fpdi-pdf-' . + 'parser).', + PdfParserException::IMPLEMENTED_IN_FPDI_PDF_PARSER + ); + } + + $colors = PdfDictionary::get($decodeParam, 'Colors', PdfNumeric::create(1)); + $bitsPerComponent = PdfDictionary::get( + $decodeParam, + 'BitsPerComponent', + PdfNumeric::create(8) + ); + + $columns = PdfDictionary::get($decodeParam, 'Columns', PdfNumeric::create(1)); + + $filterObject = new Predictor( + $predictor->value, + $colors->value, + $bitsPerComponent->value, + $columns->value + ); + + $stream = $filterObject->decode($stream); + } + } + + break; + case 'ASCII85Decode': + case 'A85': + $filterObject = new Ascii85(); + $stream = $filterObject->decode($stream); + break; + + case 'ASCIIHexDecode': + case 'AHx': + $filterObject = new AsciiHex(); + $stream = $filterObject->decode($stream); + break; + + default: + throw new FilterException( + \sprintf('Unsupported filter "%s".', $filter->value), + FilterException::UNSUPPORTED_FILTER + ); + } + } + + return $stream; + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfString.php b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfString.php new file mode 100644 index 000000000..1636e68d6 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfString.php @@ -0,0 +1,172 @@ +getOffset(); + $openBrackets = 1; + do { + $buffer = $streamReader->getBuffer(false); + for ($length = \strlen($buffer); $openBrackets !== 0 && $pos < $length; $pos++) { + switch ($buffer[$pos]) { + case '(': + $openBrackets++; + break; + case ')': + $openBrackets--; + break; + case '\\': + $pos++; + } + } + } while ($openBrackets !== 0 && $streamReader->increaseLength()); + + $result = \substr($buffer, $startPos, $openBrackets + $pos - $startPos - 1); + $streamReader->setOffset($pos); + + $v = new self(); + $v->value = $result; + + return $v; + } + + /** + * Helper method to create an instance. + * + * @param string $value The string needs to be escaped accordingly. + * @return self + */ + public static function create($value) + { + $v = new self(); + $v->value = $value; + + return $v; + } + + /** + * Ensures that the passed value is a PdfString instance. + * + * @param mixed $string + * @return self + * @throws PdfTypeException + */ + public static function ensure($string) + { + return PdfType::ensureType(self::class, $string, 'String value expected.'); + } + + /** + * Unescapes escaped sequences in a PDF string according to the PDF specification. + * + * @param string $s + * @return string + */ + public static function unescape($s) + { + $out = ''; + /** @noinspection ForeachInvariantsInspection */ + for ($count = 0, $n = \strlen($s); $count < $n; $count++) { + if ($s[$count] !== '\\') { + $out .= $s[$count]; + } else { + // A backslash at the end of the string - ignore it + if ($count === ($n - 1)) { + break; + } + + switch ($s[++$count]) { + case ')': + case '(': + case '\\': + $out .= $s[$count]; + break; + + case 'f': + $out .= "\x0C"; + break; + + case 'b': + $out .= "\x08"; + break; + + case 't': + $out .= "\x09"; + break; + + case 'r': + $out .= "\x0D"; + break; + + case 'n': + $out .= "\x0A"; + break; + + case "\r": + if ($count !== $n - 1 && $s[$count + 1] === "\n") { + $count++; + } + break; + + case "\n": + break; + + default: + $actualChar = \ord($s[$count]); + // ascii 48 = number 0 + // ascii 57 = number 9 + if ($actualChar >= 48 && $actualChar <= 57) { + $oct = '' . $s[$count]; + + /** @noinspection NotOptimalIfConditionsInspection */ + if ( + $count + 1 < $n + && \ord($s[$count + 1]) >= 48 + && \ord($s[$count + 1]) <= 57 + ) { + $count++; + $oct .= $s[$count]; + + /** @noinspection NotOptimalIfConditionsInspection */ + if ( + $count + 1 < $n + && \ord($s[$count + 1]) >= 48 + && \ord($s[$count + 1]) <= 57 + ) { + $oct .= $s[++$count]; + } + } + + $out .= \chr(\octdec($oct)); + } else { + // If the character is not one of those defined, the backslash is ignored + $out .= $s[$count]; + } + } + } + } + return $out; + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfToken.php b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfToken.php new file mode 100644 index 000000000..012b9fd26 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfToken.php @@ -0,0 +1,43 @@ +value = $token; + + return $v; + } + + /** + * Ensures that the passed value is a PdfToken instance. + * + * @param mixed $token + * @return self + * @throws PdfTypeException + */ + public static function ensure($token) + { + return PdfType::ensureType(self::class, $token, 'Token value expected.'); + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfType.php b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfType.php new file mode 100644 index 000000000..7672dcdc1 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfType.php @@ -0,0 +1,78 @@ +value, $parser, $stopAtIndirectObject); + } + + if ($value instanceof PdfIndirectObjectReference) { + return self::resolve($parser->getIndirectObject($value->value), $parser, $stopAtIndirectObject); + } + + return $value; + } + + /** + * Ensure that a value is an instance of a specific PDF type. + * + * @param string $type + * @param PdfType $value + * @param string $errorMessage + * @return mixed + * @throws PdfTypeException + */ + protected static function ensureType($type, $value, $errorMessage) + { + if (!($value instanceof $type)) { + throw new PdfTypeException( + $errorMessage, + PdfTypeException::INVALID_DATA_TYPE + ); + } + + return $value; + } + + /** + * The value of the PDF type. + * + * @var mixed + */ + public $value; +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfTypeException.php b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfTypeException.php new file mode 100644 index 000000000..593d14740 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfParser/Type/PdfTypeException.php @@ -0,0 +1,24 @@ +value; + $ax = PdfNumeric::ensure(PdfType::resolve($array[0], $parser))->value; + $ay = PdfNumeric::ensure(PdfType::resolve($array[1], $parser))->value; + $bx = PdfNumeric::ensure(PdfType::resolve($array[2], $parser))->value; + $by = PdfNumeric::ensure(PdfType::resolve($array[3], $parser))->value; + + return new self($ax, $ay, $bx, $by); + } + + /** + * Rectangle constructor. + * + * @param float|int $ax + * @param float|int $ay + * @param float|int $bx + * @param float|int $by + */ + public function __construct($ax, $ay, $bx, $by) + { + $this->llx = \min($ax, $bx); + $this->lly = \min($ay, $by); + $this->urx = \max($ax, $bx); + $this->ury = \max($ay, $by); + } + + /** + * Get the width of the rectangle. + * + * @return float|int + */ + public function getWidth() + { + return $this->urx - $this->llx; + } + + /** + * Get the height of the rectangle. + * + * @return float|int + */ + public function getHeight() + { + return $this->ury - $this->lly; + } + + /** + * Get the lower left abscissa. + * + * @return float|int + */ + public function getLlx() + { + return $this->llx; + } + + /** + * Get the lower left ordinate. + * + * @return float|int + */ + public function getLly() + { + return $this->lly; + } + + /** + * Get the upper right abscissa. + * + * @return float|int + */ + public function getUrx() + { + return $this->urx; + } + + /** + * Get the upper right ordinate. + * + * @return float|int + */ + public function getUry() + { + return $this->ury; + } + + /** + * Get the rectangle as an array. + * + * @return array + */ + public function toArray() + { + return [ + $this->llx, + $this->lly, + $this->urx, + $this->ury + ]; + } + + /** + * Get the rectangle as a PdfArray. + * + * @return PdfArray + */ + public function toPdfArray() + { + $array = new PdfArray(); + $array->value[] = PdfNumeric::create($this->llx); + $array->value[] = PdfNumeric::create($this->lly); + $array->value[] = PdfNumeric::create($this->urx); + $array->value[] = PdfNumeric::create($this->ury); + + return $array; + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfReader/Page.php b/src/bb-vendor/setasign/fpdi/src/PdfReader/Page.php new file mode 100644 index 000000000..b207c7932 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfReader/Page.php @@ -0,0 +1,271 @@ +pageObject = $page; + $this->parser = $parser; + } + + /** + * Get the indirect object of this page. + * + * @return PdfIndirectObject + */ + public function getPageObject() + { + return $this->pageObject; + } + + /** + * Get the dictionary of this page. + * + * @return PdfDictionary + * @throws PdfParserException + * @throws PdfTypeException + * @throws CrossReferenceException + */ + public function getPageDictionary() + { + if (null === $this->pageDictionary) { + $this->pageDictionary = PdfDictionary::ensure(PdfType::resolve($this->getPageObject(), $this->parser)); + } + + return $this->pageDictionary; + } + + /** + * Get a page attribute. + * + * @param string $name + * @param bool $inherited + * @return PdfType|null + * @throws PdfParserException + * @throws PdfTypeException + * @throws CrossReferenceException + */ + public function getAttribute($name, $inherited = true) + { + $dict = $this->getPageDictionary(); + + if (isset($dict->value[$name])) { + return $dict->value[$name]; + } + + $inheritedKeys = ['Resources', 'MediaBox', 'CropBox', 'Rotate']; + if ($inherited && \in_array($name, $inheritedKeys, true)) { + if ($this->inheritedAttributes === null) { + $this->inheritedAttributes = []; + $inheritedKeys = \array_filter($inheritedKeys, function ($key) use ($dict) { + return !isset($dict->value[$key]); + }); + + if (\count($inheritedKeys) > 0) { + $parentDict = PdfType::resolve(PdfDictionary::get($dict, 'Parent'), $this->parser); + while ($parentDict instanceof PdfDictionary) { + foreach ($inheritedKeys as $index => $key) { + if (isset($parentDict->value[$key])) { + $this->inheritedAttributes[$key] = $parentDict->value[$key]; + unset($inheritedKeys[$index]); + } + } + + /** @noinspection NotOptimalIfConditionsInspection */ + if (isset($parentDict->value['Parent']) && \count($inheritedKeys) > 0) { + $parentDict = PdfType::resolve(PdfDictionary::get($parentDict, 'Parent'), $this->parser); + } else { + break; + } + } + } + } + + if (isset($this->inheritedAttributes[$name])) { + return $this->inheritedAttributes[$name]; + } + } + + return null; + } + + /** + * Get the rotation value. + * + * @return int + * @throws PdfParserException + * @throws PdfTypeException + * @throws CrossReferenceException + */ + public function getRotation() + { + $rotation = $this->getAttribute('Rotate'); + if (null === $rotation) { + return 0; + } + + $rotation = PdfNumeric::ensure(PdfType::resolve($rotation, $this->parser))->value % 360; + + if ($rotation < 0) { + $rotation += 360; + } + + return $rotation; + } + + /** + * Get a boundary of this page. + * + * @param string $box + * @param bool $fallback + * @return bool|Rectangle + * @throws PdfParserException + * @throws PdfTypeException + * @throws CrossReferenceException + * @see PageBoundaries + */ + public function getBoundary($box = PageBoundaries::CROP_BOX, $fallback = true) + { + $value = $this->getAttribute($box); + + if ($value !== null) { + return Rectangle::byPdfArray($value, $this->parser); + } + + if ($fallback === false) { + return false; + } + + switch ($box) { + case PageBoundaries::BLEED_BOX: + case PageBoundaries::TRIM_BOX: + case PageBoundaries::ART_BOX: + return $this->getBoundary(PageBoundaries::CROP_BOX, true); + case PageBoundaries::CROP_BOX: + return $this->getBoundary(PageBoundaries::MEDIA_BOX, true); + } + + return false; + } + + /** + * Get the width and height of this page. + * + * @param string $box + * @param bool $fallback + * @return array|bool + * @throws PdfParserException + * @throws PdfTypeException + * @throws CrossReferenceException + */ + public function getWidthAndHeight($box = PageBoundaries::CROP_BOX, $fallback = true) + { + $boundary = $this->getBoundary($box, $fallback); + if ($boundary === false) { + return false; + } + + $rotation = $this->getRotation(); + $interchange = ($rotation / 90) % 2; + + return [ + $interchange ? $boundary->getHeight() : $boundary->getWidth(), + $interchange ? $boundary->getWidth() : $boundary->getHeight() + ]; + } + + /** + * Get the raw content stream. + * + * @return string + * @throws PdfReaderException + * @throws PdfTypeException + * @throws FilterException + * @throws PdfParserException + */ + public function getContentStream() + { + $dict = $this->getPageDictionary(); + $contents = PdfType::resolve(PdfDictionary::get($dict, 'Contents'), $this->parser); + if ($contents instanceof PdfNull) { + return ''; + } + + if ($contents instanceof PdfArray) { + $result = []; + foreach ($contents->value as $content) { + $content = PdfType::resolve($content, $this->parser); + if (!($content instanceof PdfStream)) { + continue; + } + $result[] = $content->getUnfilteredStream(); + } + + return \implode("\n", $result); + } + + if ($contents instanceof PdfStream) { + return $contents->getUnfilteredStream(); + } + + throw new PdfReaderException( + 'Array or stream expected.', + PdfReaderException::UNEXPECTED_DATA_TYPE + ); + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfReader/PageBoundaries.php b/src/bb-vendor/setasign/fpdi/src/PdfReader/PageBoundaries.php new file mode 100644 index 000000000..9a6a1f3d1 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfReader/PageBoundaries.php @@ -0,0 +1,94 @@ +parser = $parser; + } + + /** + * PdfReader destructor. + */ + public function __destruct() + { + if ($this->parser !== null) { + $this->parser->cleanUp(); + } + } + + /** + * Get the pdf parser instance. + * + * @return PdfParser + */ + public function getParser() + { + return $this->parser; + } + + /** + * Get the PDF version. + * + * @return string + * @throws PdfParserException + */ + public function getPdfVersion() + { + return \implode('.', $this->parser->getPdfVersion()); + } + + /** + * Get the page count. + * + * @return int + * @throws PdfTypeException + * @throws CrossReferenceException + * @throws PdfParserException + */ + public function getPageCount() + { + if ($this->pageCount === null) { + $catalog = $this->parser->getCatalog(); + + $pages = PdfType::resolve(PdfDictionary::get($catalog, 'Pages'), $this->parser); + $count = PdfType::resolve(PdfDictionary::get($pages, 'Count'), $this->parser); + + $this->pageCount = PdfNumeric::ensure($count)->value; + } + + return $this->pageCount; + } + + /** + * Get a page instance. + * + * @param int $pageNumber + * @return Page + * @throws PdfTypeException + * @throws CrossReferenceException + * @throws PdfParserException + * @throws \InvalidArgumentException + */ + public function getPage($pageNumber) + { + if (!\is_numeric($pageNumber)) { + throw new \InvalidArgumentException( + 'Page number needs to be a number.' + ); + } + + if ($pageNumber < 1 || $pageNumber > $this->getPageCount()) { + throw new \InvalidArgumentException( + \sprintf( + 'Page number "%s" out of available page range (1 - %s)', + $pageNumber, + $this->getPageCount() + ) + ); + } + + $this->readPages(); + + $page = $this->pages[$pageNumber - 1]; + + if ($page instanceof PdfIndirectObjectReference) { + $readPages = function ($kids) use (&$readPages) { + $kids = PdfArray::ensure($kids); + + /** @noinspection LoopWhichDoesNotLoopInspection */ + foreach ($kids->value as $reference) { + $reference = PdfIndirectObjectReference::ensure($reference); + $object = $this->parser->getIndirectObject($reference->value); + $type = PdfDictionary::get($object->value, 'Type'); + + if ($type->value === 'Pages') { + return $readPages(PdfDictionary::get($object->value, 'Kids')); + } + + return $object; + } + + throw new PdfReaderException( + 'Kids array cannot be empty.', + PdfReaderException::KIDS_EMPTY + ); + }; + + $page = $this->parser->getIndirectObject($page->value); + $dict = PdfType::resolve($page, $this->parser); + $type = PdfDictionary::get($dict, 'Type'); + + if ($type->value === 'Pages') { + $kids = PdfType::resolve(PdfDictionary::get($dict, 'Kids'), $this->parser); + try { + $page = $this->pages[$pageNumber - 1] = $readPages($kids); + } catch (PdfReaderException $e) { + if ($e->getCode() !== PdfReaderException::KIDS_EMPTY) { + throw $e; + } + + // let's reset the pages array and read all page objects + $this->pages = []; + $this->readPages(true); + // @phpstan-ignore-next-line + $page = $this->pages[$pageNumber - 1]; + } + } else { + $this->pages[$pageNumber - 1] = $page; + } + } + + return new Page($page, $this->parser); + } + + /** + * Walk the page tree and resolve all indirect objects of all pages. + * + * @param bool $readAll + * @throws CrossReferenceException + * @throws PdfParserException + * @throws PdfTypeException + */ + protected function readPages($readAll = false) + { + if (\count($this->pages) > 0) { + return; + } + + $readPages = function ($kids, $count) use (&$readPages, $readAll) { + $kids = PdfArray::ensure($kids); + $isLeaf = ($count->value === \count($kids->value)); + + foreach ($kids->value as $reference) { + $reference = PdfIndirectObjectReference::ensure($reference); + + if (!$readAll && $isLeaf) { + $this->pages[] = $reference; + continue; + } + + $object = $this->parser->getIndirectObject($reference->value); + $type = PdfDictionary::get($object->value, 'Type'); + + if ($type->value === 'Pages') { + $readPages(PdfDictionary::get($object->value, 'Kids'), PdfDictionary::get($object->value, 'Count')); + } else { + $this->pages[] = $object; + } + } + }; + + $catalog = $this->parser->getCatalog(); + $pages = PdfType::resolve(PdfDictionary::get($catalog, 'Pages'), $this->parser); + $count = PdfType::resolve(PdfDictionary::get($pages, 'Count'), $this->parser); + $kids = PdfType::resolve(PdfDictionary::get($pages, 'Kids'), $this->parser); + $readPages($kids, $count); + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/PdfReader/PdfReaderException.php b/src/bb-vendor/setasign/fpdi/src/PdfReader/PdfReaderException.php new file mode 100644 index 000000000..99f7d125c --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/PdfReader/PdfReaderException.php @@ -0,0 +1,34 @@ +cleanUp(); + } + + /** + * Get the next template id. + * + * @return int + */ + protected function getNextTemplateId() + { + return $this->templateId++; + } + + /** + * Draws an imported page onto the page or another template. + * + * Give only one of the size parameters (width, height) to calculate the other one automatically in view to the + * aspect ratio. + * + * @param mixed $tpl The template id + * @param float|int|array $x The abscissa of upper-left corner. Alternatively you could use an assoc array + * with the keys "x", "y", "width", "height", "adjustPageSize". + * @param float|int $y The ordinate of upper-left corner. + * @param float|int|null $width The width. + * @param float|int|null $height The height. + * @param bool $adjustPageSize + * @return array The size + * @see FpdiTrait::getTemplateSize() + */ + public function useTemplate($tpl, $x = 0, $y = 0, $width = null, $height = null, $adjustPageSize = false) + { + return $this->useImportedPage($tpl, $x, $y, $width, $height, $adjustPageSize); + } + + /** + * Draws an imported page onto the page. + * + * Give only one of the size parameters (width, height) to calculate the other one automatically in view to the + * aspect ratio. + * + * @param mixed $pageId The page id + * @param float|int|array $x The abscissa of upper-left corner. Alternatively you could use an assoc array + * with the keys "x", "y", "width", "height", "adjustPageSize". + * @param float|int $y The ordinate of upper-left corner. + * @param float|int|null $width The width. + * @param float|int|null $height The height. + * @param bool $adjustPageSize + * @return array The size. + * @see Fpdi::getTemplateSize() + */ + public function useImportedPage($pageId, $x = 0, $y = 0, $width = null, $height = null, $adjustPageSize = false) + { + $size = $this->fpdiUseImportedPage($pageId, $x, $y, $width, $height, $adjustPageSize); + if ($this->inxobj) { + $importedPage = $this->importedPages[$pageId]; + $this->xobjects[$this->xobjid]['importedPages'][$importedPage['id']] = $pageId; + } + + return $size; + } + + /** + * Get the size of an imported page. + * + * Give only one of the size parameters (width, height) to calculate the other one automatically in view to the + * aspect ratio. + * + * @param mixed $tpl The template id + * @param float|int|null $width The width. + * @param float|int|null $height The height. + * @return array|bool An array with following keys: width, height, 0 (=width), 1 (=height), orientation (L or P) + */ + public function getTemplateSize($tpl, $width = null, $height = null) + { + return $this->getImportedPageSize($tpl, $width, $height); + } + + /** + * @inheritdoc + */ + protected function _getxobjectdict() + { + $out = parent::_getxobjectdict(); + + foreach ($this->importedPages as $key => $pageData) { + $out .= '/' . $pageData['id'] . ' ' . $pageData['objectNumber'] . ' 0 R '; + } + + return $out; + } + + /** + * @inheritdoc + * @throws CrossReferenceException + * @throws PdfParserException + */ + protected function _putxobjects() + { + foreach ($this->importedPages as $key => $pageData) { + $this->currentObjectNumber = $this->_newobj(); + $this->importedPages[$key]['objectNumber'] = $this->currentObjectNumber; + $this->currentReaderId = $pageData['readerId']; + $this->writePdfType($pageData['stream']); + $this->_put('endobj'); + } + + foreach (\array_keys($this->readers) as $readerId) { + $parser = $this->getPdfReader($readerId)->getParser(); + $this->currentReaderId = $readerId; + + while (($objectNumber = \array_pop($this->objectsToCopy[$readerId])) !== null) { + try { + $object = $parser->getIndirectObject($objectNumber); + } catch (CrossReferenceException $e) { + if ($e->getCode() === CrossReferenceException::OBJECT_NOT_FOUND) { + $object = PdfIndirectObject::create($objectNumber, 0, new PdfNull()); + } else { + throw $e; + } + } + + $this->writePdfType($object); + } + } + + // let's prepare resources for imported pages in templates + foreach ($this->xobjects as $xObjectId => $data) { + if (!isset($data['importedPages'])) { + continue; + } + + foreach ($data['importedPages'] as $id => $pageKey) { + $page = $this->importedPages[$pageKey]; + $this->xobjects[$xObjectId]['xobjects'][$id] = ['n' => $page['objectNumber']]; + } + } + + + parent::_putxobjects(); + $this->currentObjectNumber = null; + } + + /** + * Append content to the buffer of TCPDF. + * + * @param string $s + * @param bool $newLine + */ + protected function _put($s, $newLine = true) + { + if ($newLine) { + $this->setBuffer($s . "\n"); + } else { + $this->setBuffer($s); + } + } + + /** + * Begin a new object and return the object number. + * + * @param int|string $objid Object ID (leave empty to get a new ID). + * @return int object number + */ + protected function _newobj($objid = '') + { + $this->_out($this->_getobj($objid)); + return $this->n; + } + + /** + * Writes a PdfType object to the resulting buffer. + * + * @param PdfType $value + * @throws PdfTypeException + */ + protected function writePdfType(PdfType $value) + { + if (!$this->encrypted) { + $this->fpdiWritePdfType($value); + return; + } + + if ($value instanceof PdfString) { + $string = PdfString::unescape($value->value); + $string = $this->_encrypt_data($this->currentObjectNumber, $string); + $value->value = \TCPDF_STATIC::_escape($string); + } elseif ($value instanceof PdfHexString) { + $filter = new AsciiHex(); + $string = $filter->decode($value->value); + $string = $this->_encrypt_data($this->currentObjectNumber, $string); + $value->value = $filter->encode($string, true); + } elseif ($value instanceof PdfStream) { + $stream = $value->getStream(); + $stream = $this->_encrypt_data($this->currentObjectNumber, $stream); + $dictionary = $value->value; + $dictionary->value['Length'] = PdfNumeric::create(\strlen($stream)); + $value = PdfStream::create($dictionary, $stream); + } elseif ($value instanceof PdfIndirectObject) { + /** + * @var PdfIndirectObject $value + */ + $this->currentObjectNumber = $this->objectMap[$this->currentReaderId][$value->objectNumber]; + } + + $this->fpdiWritePdfType($value); + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/TcpdfFpdi.php b/src/bb-vendor/setasign/fpdi/src/TcpdfFpdi.php new file mode 100644 index 000000000..9e6825bd3 --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/TcpdfFpdi.php @@ -0,0 +1,23 @@ +cleanUp(); + } + + /** + * Draws an imported page or a template onto the page or another template. + * + * Give only one of the size parameters (width, height) to calculate the other one automatically in view to the + * aspect ratio. + * + * @param mixed $tpl The template id + * @param float|int|array $x The abscissa of upper-left corner. Alternatively you could use an assoc array + * with the keys "x", "y", "width", "height", "adjustPageSize". + * @param float|int $y The ordinate of upper-left corner. + * @param float|int|null $width The width. + * @param float|int|null $height The height. + * @param bool $adjustPageSize + * @return array The size + * @see Fpdi::getTemplateSize() + */ + public function useTemplate($tpl, $x = 0, $y = 0, $width = null, $height = null, $adjustPageSize = false) + { + if (isset($this->importedPages[$tpl])) { + $size = $this->useImportedPage($tpl, $x, $y, $width, $height, $adjustPageSize); + if ($this->currentTemplateId !== null) { + $this->templates[$this->currentTemplateId]['resources']['templates']['importedPages'][$tpl] = $tpl; + } + return $size; + } + + return parent::useTemplate($tpl, $x, $y, $width, $height, $adjustPageSize); + } + + /** + * Get the size of an imported page or template. + * + * Give only one of the size parameters (width, height) to calculate the other one automatically in view to the + * aspect ratio. + * + * @param mixed $tpl The template id + * @param float|int|null $width The width. + * @param float|int|null $height The height. + * @return array|bool An array with following keys: width, height, 0 (=width), 1 (=height), orientation (L or P) + */ + public function getTemplateSize($tpl, $width = null, $height = null) + { + $size = parent::getTemplateSize($tpl, $width, $height); + if ($size === false) { + return $this->getImportedPageSize($tpl, $width, $height); + } + + return $size; + } + + /** + * @inheritdoc + * @throws CrossReferenceException + * @throws PdfParserException + */ + public function _putimages() + { + $this->currentReaderId = null; + parent::_putimages(); + + foreach ($this->importedPages as $key => $pageData) { + $this->_newobj(); + $this->importedPages[$key]['objectNumber'] = $this->n; + $this->currentReaderId = $pageData['readerId']; + $this->writePdfType($pageData['stream']); + $this->_put('endobj'); + } + + foreach (\array_keys($this->readers) as $readerId) { + $parser = $this->getPdfReader($readerId)->getParser(); + $this->currentReaderId = $readerId; + + while (($objectNumber = \array_pop($this->objectsToCopy[$readerId])) !== null) { + try { + $object = $parser->getIndirectObject($objectNumber); + } catch (CrossReferenceException $e) { + if ($e->getCode() === CrossReferenceException::OBJECT_NOT_FOUND) { + $object = PdfIndirectObject::create($objectNumber, 0, new PdfNull()); + } else { + throw $e; + } + } + + $this->writePdfType($object); + } + } + + $this->currentReaderId = null; + } + + /** + * @inheritdoc + */ + protected function _putxobjectdict() + { + foreach ($this->importedPages as $key => $pageData) { + $this->_put('/' . $pageData['id'] . ' ' . $pageData['objectNumber'] . ' 0 R'); + } + + parent::_putxobjectdict(); + } + + /** + * @inheritdoc + */ + protected function _put($s, $newLine = true) + { + if ($newLine) { + $this->buffer .= $s . "\n"; + } else { + $this->buffer .= $s; + } + } +} diff --git a/src/bb-vendor/setasign/fpdi/src/autoload.php b/src/bb-vendor/setasign/fpdi/src/autoload.php new file mode 100644 index 000000000..419e8319f --- /dev/null +++ b/src/bb-vendor/setasign/fpdi/src/autoload.php @@ -0,0 +1,22 @@ +"foo", "expand" => array("customer"))) + Stripe_Charge::retrieve("foo") will continue to work + +### 1.7.12 2013-01-15 + +* Add support for setting a Stripe API version override + +### 1.7.11 2012-12-30 + +* Version bump to cleanup constants and such (github issue #26) + +### 1.7.10 2012-11-08 + +* Add support for updating charge disputes. +* Fix bug preventing retrieval of null attributes + +### 1.7.9 2012-11-08 + +* Fix usage under autoloaders such as the one generated by composer + (github issue #22) + +### 1.7.8 2012-10-30 +* Add support for creating invoices. +* Add support for new invoice lines return format +* Add support for new list objects + +### 1.7.7 2012-09-14 + +* Get all of the various version numbers in the repo in sync (no other + changes) + +### 1.7.6 2012-08-31 + +* Add update and pay methods to Invoice resource + +### 1.7.5 2012-08-23 + +* Change internal function names so that Stripe_SingletonApiRequest is + E_STRICT-clean (github issue #16) + +### 1.7.4 2012-08-21 + +* Bugfix so that Stripe objects (e.g. Customer, Charge objects) used + in API calls are transparently converted to their object IDs + +### 1.7.3 2012-08-15 + +* Add new Account resource + +### 1.7.2 2012-06-26 + +* Make clearer that you should be including lib/Stripe.php, not + test/Stripe.php (github issue #14) + +### 1.7.1 2012-05-24 + +* Add missing argument to Stripe_InvalidRequestError constructor in + Stripe_ApiResource::instanceUrl. Fixes a warning when + Stripe_ApiResource::instanceUrl is called on a resource with no ID + (github issue #12) + +### 1.7.0 2012-05-17 + +* Support Composer and Packagist (github issue #9) + +* Add new deleteDiscount method to Stripe_Customer + +* Add new Transfer resource + +* Switch from using HTTP Basic auth to Bearer auth. (Note: Stripe will + support Basic auth for the indefinite future, but recommends Bearer + auth when possible going forward) + +* Numerous test suite improvements diff --git a/src/bb-vendor/stripe/stripe-php/LICENSE b/src/bb-vendor/stripe/stripe-php/LICENSE new file mode 100644 index 000000000..ac9fd37eb --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/LICENSE @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2010-2014 Stripe + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/src/bb-vendor/stripe/stripe-php/README.md b/src/bb-vendor/stripe/stripe-php/README.md new file mode 100644 index 000000000..2f58aad42 --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/README.md @@ -0,0 +1,72 @@ +# Stripe PHP bindings + +[![Build Status](https://travis-ci.org/stripe/stripe-php.svg?branch=master)](https://travis-ci.org/stripe/stripe-php) +[![Latest Stable Version](https://poser.pugx.org/stripe/stripe-php/v/stable.svg)](https://packagist.org/packages/stripe/stripe-php) +[![Total Downloads](https://poser.pugx.org/stripe/stripe-php/downloads.svg)](https://packagist.org/packages/stripe/stripe-php) +[![License](https://poser.pugx.org/stripe/stripe-php/license.svg)](https://packagist.org/packages/stripe/stripe-php) +[![Code Coverage](https://coveralls.io/repos/stripe/stripe-php/badge.png?branch=master)](https://coveralls.io/r/stripe/stripe-php?branch=master) + +You can sign up for a Stripe account at https://stripe.com. + +## Requirements + +PHP 5.3.3 and later. + +## Composer + +You can install the bindings via [Composer](http://getcomposer.org/). Add this to your `composer.json`: + + { + "require": { + "stripe/stripe-php": "2.*" + } + } + +Then install via: + + composer.phar install + +To use the bindings, use Composer's [autoload](https://getcomposer.org/doc/00-intro.md#autoloading): + + require_once('vendor/autoload.php'); + +## Manual Installation + +If you do not wish to use Composer, you can download the [latest release](https://github.com/stripe/stripe-php/releases). Then, to use the bindings, include the `init.php` file. + + require_once('/path/to/stripe-php/init.php'); + +## Getting Started + +Simple usage looks like: + + \Stripe\Stripe::setApiKey('d8e8fca2dc0f896fd7cb4cb0031ba249'); + $myCard = array('number' => '4242424242424242', 'exp_month' => 5, 'exp_year' => 2015); + $charge = \Stripe\Charge::create(array('card' => $myCard, 'amount' => 2000, 'currency' => 'usd')); + echo $charge; + +## Documentation + +Please see https://stripe.com/docs/api for up-to-date documentation. + +## Legacy Version Support + +If you are using PHP 5.2, you can download v1.18.0 ([zip](https://github.com/stripe/stripe-php/archive/v1.18.0.zip), [tar.gz](https://github.com/stripe/stripe-php/archive/v1.18.0.tar.gz)) from our [releases page](https://github.com/stripe/stripe-php/releases). This version will continue to work with new versions of the Stripe API for all common uses. + +This legacy version may be included via `require_once("/path/to/stripe-php/lib/Stripe.php");`, and used like: + + Stripe::setApiKey('d8e8fca2dc0f896fd7cb4cb0031ba249'); + $myCard = array('number' => '4242424242424242', 'exp_month' => 5, 'exp_year' => 2015); + $charge = Stripe_Charge::create(array('card' => $myCard, 'amount' => 2000, 'currency' => 'usd')); + echo $charge; + +## Tests + +In order to run tests first install [PHPUnit](http://packagist.org/packages/phpunit/phpunit) via [Composer](http://getcomposer.org/): + + composer.phar update --dev + +To run the test suite: + + ./vendor/bin/phpunit + diff --git a/src/bb-vendor/stripe/stripe-php/VERSION b/src/bb-vendor/stripe/stripe-php/VERSION new file mode 100644 index 000000000..3e3c2f1e5 --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/VERSION @@ -0,0 +1 @@ +2.1.1 diff --git a/src/bb-vendor/stripe/stripe-php/init.php b/src/bb-vendor/stripe/stripe-php/init.php new file mode 100644 index 000000000..2f580f87d --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/init.php @@ -0,0 +1,50 @@ +_apiKey = $apiKey; + if (!$apiBase) { + $apiBase = Stripe::$apiBase; + } + $this->_apiBase = $apiBase; + } + + /** + * @param string|mixed $value A string to UTF8-encode. + * + * @return string|mixed The UTF8-encoded string, or the object passed in if + * it wasn't a string. + */ + public static function utf8($value) + { + if (is_string($value) && mb_detect_encoding($value, "UTF-8", true) != "UTF-8") { + return utf8_encode($value); + } else { + return $value; + } + } + + private static function _encodeObjects($d) + { + if ($d instanceof ApiResource) { + return self::utf8($d->id); + } elseif ($d === true) { + return 'true'; + } elseif ($d === false) { + return 'false'; + } elseif (is_array($d)) { + $res = array(); + foreach ($d as $k => $v) { + $res[$k] = self::_encodeObjects($v); + } + return $res; + } else { + return self::utf8($d); + } + } + + /** + * @param array $arr An map of param keys to values. + * @param string|null $prefix (It doesn't look like we ever use $prefix...) + * + * @return string A querystring, essentially. + */ + public static function encode($arr, $prefix = null) + { + if (!is_array($arr)) { + return $arr; + } + + $r = array(); + foreach ($arr as $k => $v) { + if (is_null($v)) { + continue; + } + + if ($prefix && $k && !is_int($k)) { + $k = $prefix."[".$k."]"; + } elseif ($prefix) { + $k = $prefix."[]"; + } + + if (is_array($v)) { + $r[] = self::encode($v, $k, true); + } else { + $r[] = urlencode($k)."=".urlencode($v); + } + } + + return implode("&", $r); + } + + /** + * @param string $method + * @param string $url + * @param array|null $params + * @param array|null $headers + * + * @return array An array whose first element is the response and second + * element is the API key used to make the request. + */ + public function request($method, $url, $params = null, $headers = null) + { + if (!$params) { + $params = array(); + } + if (!$headers) { + $headers = array(); + } + list($rbody, $rcode, $myApiKey) = + $this->_requestRaw($method, $url, $params, $headers); + $resp = $this->_interpretResponse($rbody, $rcode); + return array($resp, $myApiKey); + } + + /** + * @param string $rbody A JSON string. + * @param int $rcode + * @param array $resp + * + * @throws Error\InvalidRequest if the error is caused by the user. + * @throws Error\Authentication if the error is caused by a lack of + * permissions. + * @throws Error\Card if the error is the error code is 402 (payment + * required) + * @throws Error\Api otherwise. + */ + public function handleApiError($rbody, $rcode, $resp) + { + if (!is_array($resp) || !isset($resp['error'])) { + $msg = "Invalid response object from API: $rbody " + . "(HTTP response code was $rcode)"; + throw new Error\Api($msg, $rcode, $rbody, $resp); + } + + $error = $resp['error']; + $msg = isset($error['message']) ? $error['message'] : null; + $param = isset($error['param']) ? $error['param'] : null; + $code = isset($error['code']) ? $error['code'] : null; + + switch ($rcode) { + case 400: + if ($code == 'rate_limit') { + throw new Error\RateLimit($msg, $param, $rcode, $rbody, $resp); + } + + // intentional fall-through + case 404: + throw new Error\InvalidRequest($msg, $param, $rcode, $rbody, $resp); + case 401: + throw new Error\Authentication($msg, $rcode, $rbody, $resp); + case 402: + throw new Error\Card($msg, $param, $code, $rcode, $rbody, $resp); + default: + throw new Error\Api($msg, $rcode, $rbody, $resp); + } + } + + private function _requestRaw($method, $url, $params, $headers) + { + if (!array_key_exists($this->_apiBase, self::$_preFlight) || + !self::$_preFlight[$this->_apiBase]) { + self::$_preFlight[$this->_apiBase] = $this->checkSslCert($this->_apiBase); + } + + $myApiKey = $this->_apiKey; + if (!$myApiKey) { + $myApiKey = Stripe::$apiKey; + } + + if (!$myApiKey) { + $msg = 'No API key provided. (HINT: set your API key using ' + . '"Stripe::setApiKey()". You can generate API keys from ' + . 'the Stripe web interface. See https://stripe.com/api for ' + . 'details, or email support@stripe.com if you have any questions.'; + throw new Error\Authentication($msg); + } + + $absUrl = $this->_apiBase.$url; + $params = self::_encodeObjects($params); + $langVersion = phpversion(); + $uname = php_uname(); + $ua = array( + 'bindings_version' => Stripe::VERSION, + 'lang' => 'php', + 'lang_version' => $langVersion, + 'publisher' => 'stripe', + 'uname' => $uname, + ); + $defaultHeaders = array( + 'X-Stripe-Client-User-Agent' => json_encode($ua), + 'User-Agent' => 'Stripe/v1 PhpBindings/' . Stripe::VERSION, + 'Authorization' => 'Bearer ' . $myApiKey, + ); + if (Stripe::$apiVersion) { + $defaultHeaders['Stripe-Version'] = Stripe::$apiVersion; + } + $hasFile = false; + $hasCurlFile = class_exists('\CURLFile', false); + foreach ($params as $k => $v) { + if (is_resource($v)) { + $hasFile = true; + $params[$k] = self::_processResourceParam($v, $hasCurlFile); + } elseif ($hasCurlFile && $v instanceof \CURLFile) { + $hasFile = true; + } + } + + if ($hasFile) { + $defaultHeaders['Content-Type'] = 'multipart/form-data'; + } else { + $defaultHeaders['Content-Type'] = 'application/x-www-form-urlencoded'; + } + + $combinedHeaders = array_merge($defaultHeaders, $headers); + $rawHeaders = array(); + + foreach ($combinedHeaders as $header => $value) { + $rawHeaders[] = $header . ': ' . $value; + } + + list($rbody, $rcode) = $this->_curlRequest( + $method, + $absUrl, + $rawHeaders, + $params, + $hasFile + ); + return array($rbody, $rcode, $myApiKey); + } + + private function _processResourceParam($resource, $hasCurlFile) + { + if (get_resource_type($resource) !== 'stream') { + throw new Error\Api( + 'Attempted to upload a resource that is not a stream' + ); + } + + $metaData = stream_get_meta_data($resource); + if ($metaData['wrapper_type'] !== 'plainfile') { + throw new Error\Api( + 'Only plainfile resource streams are supported' + ); + } + + if ($hasCurlFile) { + // We don't have the filename or mimetype, but the API doesn't care + return new \CURLFile($metaData['uri']); + } else { + return '@'.$metaData['uri']; + } + } + + private function _interpretResponse($rbody, $rcode) + { + try { + $resp = json_decode($rbody, true); + } catch (Exception $e) { + $msg = "Invalid response body from API: $rbody " + . "(HTTP response code was $rcode)"; + throw new Error\Api($msg, $rcode, $rbody); + } + + if ($rcode < 200 || $rcode >= 300) { + $this->handleApiError($rbody, $rcode, $resp); + } + return $resp; + } + + private function _curlRequest($method, $absUrl, $headers, $params, $hasFile) + { + $curl = curl_init(); + $method = strtolower($method); + $opts = array(); + if ($method == 'get') { + if ($hasFile) { + throw new Error\Api( + "Issuing a GET request with a file parameter" + ); + } + $opts[CURLOPT_HTTPGET] = 1; + if (count($params) > 0) { + $encoded = self::encode($params); + $absUrl = "$absUrl?$encoded"; + } + } elseif ($method == 'post') { + $opts[CURLOPT_POST] = 1; + $opts[CURLOPT_POSTFIELDS] = $hasFile ? $params : self::encode($params); + } elseif ($method == 'delete') { + $opts[CURLOPT_CUSTOMREQUEST] = 'DELETE'; + if (count($params) > 0) { + $encoded = self::encode($params); + $absUrl = "$absUrl?$encoded"; + } + } else { + throw new Error\Api("Unrecognized method $method"); + } + + $absUrl = self::utf8($absUrl); + $opts[CURLOPT_URL] = $absUrl; + $opts[CURLOPT_RETURNTRANSFER] = true; + $opts[CURLOPT_CONNECTTIMEOUT] = 30; + $opts[CURLOPT_TIMEOUT] = 80; + $opts[CURLOPT_RETURNTRANSFER] = true; + $opts[CURLOPT_HTTPHEADER] = $headers; + if (!Stripe::$verifySslCerts) { + $opts[CURLOPT_SSL_VERIFYPEER] = false; + } + + curl_setopt_array($curl, $opts); + $rbody = curl_exec($curl); + + if (!defined('CURLE_SSL_CACERT_BADFILE')) { + define('CURLE_SSL_CACERT_BADFILE', 77); // constant not defined in PHP + } + + $errno = curl_errno($curl); + if ($errno == CURLE_SSL_CACERT || + $errno == CURLE_SSL_PEER_CERTIFICATE || + $errno == CURLE_SSL_CACERT_BADFILE + ) { + array_push( + $headers, + 'X-Stripe-Client-Info: {"ca":"using Stripe-supplied CA bundle"}' + ); + $cert = $this->caBundle(); + curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); + curl_setopt($curl, CURLOPT_CAINFO, $cert); + $rbody = curl_exec($curl); + } + + if ($rbody === false) { + $errno = curl_errno($curl); + $message = curl_error($curl); + curl_close($curl); + $this->handleCurlError($errno, $message); + } + + $rcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); + curl_close($curl); + return array($rbody, $rcode); + } + + /** + * @param number $errno + * @param string $message + * @throws ApiConnectionError + */ + public function handleCurlError($errno, $message) + { + $apiBase = $this->_apiBase; + switch ($errno) { + case CURLE_COULDNT_CONNECT: + case CURLE_COULDNT_RESOLVE_HOST: + case CURLE_OPERATION_TIMEOUTED: + $msg = "Could not connect to Stripe ($apiBase). Please check your " + . "internet connection and try again. If this problem persists, " + . "you should check Stripe's service status at " + . "https://twitter.com/stripestatus, or"; + break; + case CURLE_SSL_CACERT: + case CURLE_SSL_PEER_CERTIFICATE: + $msg = "Could not verify Stripe's SSL certificate. Please make sure " + . "that your network is not intercepting certificates. " + . "(Try going to $apiBase in your browser.) " + . "If this problem persists,"; + break; + default: + $msg = "Unexpected error communicating with Stripe. " + . "If this problem persists,"; + } + $msg .= " let us know at support@stripe.com."; + + $msg .= "\n\n(Network error [errno $errno]: $message)"; + throw new Error\ApiConnection($msg); + } + + /** + * Preflight the SSL certificate presented by the backend. This isn't 100% + * bulletproof, in that we're not actually validating the transport used to + * communicate with Stripe, merely that the first attempt to does not use a + * revoked certificate. + * + * Unfortunately the interface to OpenSSL doesn't make it easy to check the + * certificate before sending potentially sensitive data on the wire. This + * approach raises the bar for an attacker significantly. + */ + private function checkSslCert($url) + { + if (!function_exists('stream_context_get_params') || + !function_exists('stream_socket_enable_crypto')) { + error_log( + 'Warning: This version of PHP does not support checking SSL ' . + 'certificates Stripe cannot guarantee that the server has a ' . + 'certificate which is not blacklisted.' + ); + return true; + } + + $url = parse_url($url); + $port = isset($url["port"]) ? $url["port"] : 443; + $url = "ssl://{$url["host"]}:{$port}"; + + $sslContext = stream_context_create( + array('ssl' => array( + 'capture_peer_cert' => true, + 'verify_peer' => true, + 'cafile' => $this->caBundle(), + )) + ); + $result = stream_socket_client( + $url, + $errno, + $errstr, + 30, + STREAM_CLIENT_CONNECT, + $sslContext + ); + if (($errno !== 0 && $errno !== null) || $result === false) { + throw new Error\ApiConnection( + 'Could not connect to Stripe (' . $url . '). Please check your ' . + 'internet connection and try again. If this problem persists, ' . + 'you should check Stripe\'s service status at ' . + 'https://twitter.com/stripestatus. Reason was: ' . $errstr + ); + } + + $params = stream_context_get_params($result); + + $cert = $params['options']['ssl']['peer_certificate']; + + openssl_x509_export($cert, $pemCert); + + if (self::isBlackListed($pemCert)) { + throw new Error\ApiConnection( + 'Invalid server certificate. You tried to connect to a server that ' . + 'has a revoked SSL certificate, which means we cannot securely send ' . + 'data to that server. Please email support@stripe.com if you need ' . + 'help connecting to the correct API server.' + ); + } + + return true; + } + + /** + * Checks if a valid PEM encoded certificate is blacklisted + * @return boolean + */ + public static function isBlackListed($certificate) + { + $certificate = trim($certificate); + $lines = explode("\n", $certificate); + + // Kludgily remove the PEM padding + array_shift($lines); + array_pop($lines); + + $derCert = base64_decode(implode("", $lines)); + $fingerprint = sha1($derCert); + return in_array($fingerprint, self::$_blacklistedCerts); + } + + private function caBundle() + { + return dirname(__FILE__) . '/../data/ca-certificates.crt'; + } +} diff --git a/src/bb-vendor/stripe/stripe-php/lib/ApiResource.php b/src/bb-vendor/stripe/stripe-php/lib/ApiResource.php new file mode 100644 index 000000000..f80aeb85e --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/lib/ApiResource.php @@ -0,0 +1,161 @@ + true, 'Stripe-Version' => true); + + public static function baseUrl() + { + return Stripe::$apiBase; + } + + /** + * @return ApiResource The refreshed resource. + */ + public function refresh() + { + $requestor = new ApiRequestor($this->_opts->apiKey, static::baseUrl()); + $url = $this->instanceUrl(); + + list($response, $this->_opts->apiKey) = $requestor->request( + 'get', + $url, + $this->_retrieveOptions, + $this->_opts->headers + ); + $this->refreshFrom($response, $this->_opts); + return $this; + } + + /** + * @return string The name of the class, with namespacing and underscores + * stripped. + */ + public static function className() + { + $class = get_called_class(); + // Useful for namespaces: Foo\Charge + if ($postfixNamespaces = strrchr($class, '\\')) { + $class = substr($postfixNamespaces, 1); + } + // Useful for underscored 'namespaces': Foo_Charge + if ($postfixFakeNamespaces = strrchr($class, '')) { + $class = $postfixFakeNamespaces; + } + if (substr($class, 0, strlen('Stripe')) == 'Stripe') { + $class = substr($class, strlen('Stripe')); + } + $class = str_replace('_', '', $class); + $name = urlencode($class); + $name = strtolower($name); + return $name; + } + + /** + * @return string The endpoint URL for the given class. + */ + public static function classUrl() + { + $base = static::className(); + return "/v1/${base}s"; + } + + /** + * @return string The full API URL for this API resource. + */ + public function instanceUrl() + { + $id = $this['id']; + if ($id === null) { + $class = get_called_class(); + $message = "Could not determine which URL to request: " + . "$class instance has invalid ID: $id"; + throw new Error\InvalidRequest($message, null); + } + $id = ApiRequestor::utf8($id); + $base = static::classUrl(); + $extn = urlencode($id); + return "$base/$extn"; + } + + private static function _validateParams($params = null) + { + if ($params && !is_array($params)) { + $message = "You must pass an array as the first argument to Stripe API " + . "method calls. (HINT: an example call to create a charge " + . "would be: \"Stripe\\Charge::create(array('amount' => 100, " + . "'currency' => 'usd', 'card' => array('number' => " + . "4242424242424242, 'exp_month' => 5, 'exp_year' => 2015)))\")"; + throw new Error\Api($message); + } + } + + protected function _request($method, $url, $params = array(), $options = null) + { + $opts = $this->_opts->merge($options); + return static::_staticRequest($method, $url, $params, $opts); + } + + protected static function _staticRequest($method, $url, $params, $options) + { + $opts = Util\RequestOptions::parse($options); + $requestor = new ApiRequestor($opts->apiKey, static::baseUrl()); + list($response, $opts->apiKey) = $requestor->request($method, $url, $params, $opts->headers); + foreach ($opts->headers as $k => $v) { + if (!array_key_exists($k, self::$HEADERS_TO_PERSIST)) { + unset($opts->headers[$k]); + } + } + return array($response, $opts); + } + + protected static function _retrieve($id, $options = null) + { + $opts = Util\RequestOptions::parse($options); + $instance = new static($id, $opts); + $instance->refresh(); + return $instance; + } + + protected static function _all($params = null, $options = null) + { + self::_validateParams($params); + $url = static::classUrl(); + + list($response, $opts) = static::_staticRequest('get', $url, $params, $options); + return Util\Util::convertToStripeObject($response, $opts); + } + + protected static function _create($params = null, $options = null) + { + self::_validateParams($params); + $base = static::baseUrl(); + $url = static::classUrl(); + + list($response, $opts) = static::_staticRequest('post', $url, $params, $options); + return Util\Util::convertToStripeObject($response, $opts); + } + + protected function _save($options = null) + { + $params = $this->serializeParameters(); + if (count($params) > 0) { + $url = $this->instanceUrl(); + list($response, $opts) = $this->_request('post', $url, $params, $options); + $this->refreshFrom($response, $opts); + } + return $this; + } + + protected function _delete($params = null, $options = null) + { + self::_validateParams($params); + + $url = $this->instanceUrl(); + list($response, $opts) = $this->_request('delete', $url, $params, $options); + $this->refreshFrom($response, $opts); + return $this; + } +} diff --git a/src/bb-vendor/stripe/stripe-php/lib/ApplicationFeeRefund.php b/src/bb-vendor/stripe/stripe-php/lib/ApplicationFeeRefund.php new file mode 100644 index 000000000..7f4e94ff2 --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/lib/ApplicationFeeRefund.php @@ -0,0 +1,39 @@ +_save($opts); + } +} diff --git a/src/bb-vendor/stripe/stripe-php/lib/BitcoinReceiver.php b/src/bb-vendor/stripe/stripe-php/lib/BitcoinReceiver.php new file mode 100644 index 000000000..73ae59ec3 --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/lib/BitcoinReceiver.php @@ -0,0 +1,97 @@ +_delete($params, $opts); + } + + /** + * @param array|string|null $opts + * + * @return BitcoinReceiver The saved Bitcoin Receiver item. + */ + public function save($opts = null) + { + return $this->_save($opts); + } +} diff --git a/src/bb-vendor/stripe/stripe-php/lib/Card.php b/src/bb-vendor/stripe/stripe-php/lib/Card.php new file mode 100644 index 000000000..f05ff05b9 --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/lib/Card.php @@ -0,0 +1,59 @@ +_delete($params, $opts); + } + + /** + * @param array|string|null $opts + * + * @return Card The saved card. + */ + public function save($opts = null) + { + return $this->_save($opts); + } +} diff --git a/src/bb-vendor/stripe/stripe-php/lib/Charge.php b/src/bb-vendor/stripe/stripe-php/lib/Charge.php new file mode 100644 index 000000000..60d36151e --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/lib/Charge.php @@ -0,0 +1,132 @@ +_save($options); + } + + /** + * @param array|null $params + * @param array|string|null $options + * + * @return Charge The refunded charge. + */ + public function refund($params = null, $options = null) + { + $url = $this->instanceUrl() . '/refund'; + list($response, $opts) = $this->request('post', $url, $params, $options); + $this->refreshFrom($response, $opts); + return $this; + } + + /** + * @param array|null $params + * @param array|string|null $options + * + * @return Charge The captured charge. + */ + public function capture($params = null, $options = null) + { + $url = $this->instanceUrl() . '/capture'; + list($response, $opts) = $this->_request('post', $url, $params, $options); + $this->refreshFrom($response, $opts); + return $this; + } + + /** + * @param array|null $params + * @param array|string|null $options + * + * @return array The updated dispute. + */ + public function updateDispute($params = null, $options = null) + { + $url = $this->instanceUrl() . '/dispute'; + list($response, $opts) = $this->_request('post', $url, $params, $options); + $this->refreshFrom(array('dispute' => $response), $opts, true); + return $this->dispute; + } + + /** + * @param array|string|null $options + * + * @return Charge The updated charge. + */ + public function closeDispute($options = null) + { + $url = $this->instanceUrl() . '/dispute/close'; + list($response, $opts) = $this->_request('post', $url, null, $options); + $this->refreshFrom($response, $opts); + return $this; + } + + /** + * @param array|string|null $opts + * + * @return Charge The updated charge. + */ + public function markAsFraudulent($opts = null) + { + $params = array('fraud_details' => array('user_report' => 'fraudulent')); + $url = $this->instanceUrl(); + list($response, $opts) = $this->_request('post', $url, $params, $opts); + $this->refreshFrom($response, $opts); + return $this; + } + + /** + * @param array|string|null $opts + * + * @return Charge The updated charge. + */ + public function markAsSafe($opts = null) + { + $params = array('fraud_details' => array('user_report' => 'safe')); + $url = $this->instanceUrl(); + list($response, $opts) = $this->_request('post', $url, $params, $opts); + $this->refreshFrom($response, $opts); + return $this; + } +} diff --git a/src/bb-vendor/stripe/stripe-php/lib/Collection.php b/src/bb-vendor/stripe/stripe-php/lib/Collection.php new file mode 100644 index 000000000..a42771536 --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/lib/Collection.php @@ -0,0 +1,56 @@ +extractPathAndUpdateParams($params); + + list($response, $opts) = $this->_request('get', $url, $params, $opts); + return Util\Util::convertToStripeObject($response, $opts); + } + + public function create($params = null, $opts = null) + { + list($url, $params) = $this->extractPathAndUpdateParams($params); + + list($response, $opts) = $this->_request('post', $url, $params, $opts); + return Util\Util::convertToStripeObject($response, $opts); + } + + public function retrieve($id, $params = null, $opts = null) + { + list($url, $params) = $this->extractPathAndUpdateParams($params); + + $id = ApiRequestor::utf8($id); + $extn = urlencode($id); + list($response, $opts) = $this->_request( + 'get', + "$url/$extn", + $params, + $opts + ); + return Util\Util::convertToStripeObject($response, $opts); + } + + private function extractPathAndUpdateParams($params) + { + $url = parse_url($this->url); + if (!isset($url['path'])) { + throw new Error\Api("Could not parse list url into parts: $url"); + } + + if (isset($url['query'])) { + // If the URL contains a query param, parse it out into $params so they + // don't interact weirdly with each other. + $query = array(); + parse_str($url['query'], $query); + // PHP 5.2 doesn't support the ?: operator :( + $params = array_merge($params ? $params : array(), $query); + } + + return array($url['path'], $params); + } +} diff --git a/src/bb-vendor/stripe/stripe-php/lib/Error/Base.php b/src/bb-vendor/stripe/stripe-php/lib/Error/Base.php new file mode 100644 index 000000000..3bf8605d4 --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/lib/Error/Base.php @@ -0,0 +1,35 @@ +httpStatus = $httpStatus; + $this->httpBody = $httpBody; + $this->jsonBody = $jsonBody; + } + + public function getHttpStatus() + { + return $this->httpStatus; + } + + public function getHttpBody() + { + return $this->httpBody; + } + + public function getJsonBody() + { + return $this->jsonBody; + } +} diff --git a/src/bb-vendor/stripe/stripe-php/lib/Error/Card.php b/src/bb-vendor/stripe/stripe-php/lib/Error/Card.php new file mode 100644 index 000000000..9f8ca2290 --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/lib/Error/Card.php @@ -0,0 +1,19 @@ +param = $param; + $this->code = $code; + } +} diff --git a/src/bb-vendor/stripe/stripe-php/lib/Error/InvalidRequest.php b/src/bb-vendor/stripe/stripe-php/lib/Error/InvalidRequest.php new file mode 100644 index 000000000..e29a70072 --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/lib/Error/InvalidRequest.php @@ -0,0 +1,17 @@ +param = $param; + } +} diff --git a/src/bb-vendor/stripe/stripe-php/lib/Error/RateLimit.php b/src/bb-vendor/stripe/stripe-php/lib/Error/RateLimit.php new file mode 100644 index 000000000..ebb055f55 --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/lib/Error/RateLimit.php @@ -0,0 +1,16 @@ +_opts = $opts ? $opts : new Util\RequestOptions(); + $this->_values = array(); + $this->_unsavedValues = new Util\Set(); + $this->_transientValues = new Util\Set(); + + $this->_retrieveOptions = array(); + if (is_array($id)) { + foreach ($id as $key => $value) { + if ($key != 'id') { + $this->_retrieveOptions[$key] = $value; + } + } + $id = $id['id']; + } + + if ($id !== null) { + $this->id = $id; + } + } + + // Standard accessor magic methods + public function __set($k, $v) + { + if ($v === "") { + throw new InvalidArgumentException( + 'You cannot set \''.$k.'\'to an empty string. ' + .'We interpret empty strings as NULL in requests. ' + .'You may set obj->'.$k.' = NULL to delete the property' + ); + } + + if (self::$nestedUpdatableAttributes->includes($k) + && isset($this->$k) && is_array($v)) { + $this->$k->replaceWith($v); + } else { + // TODO: may want to clear from $_transientValues (Won't be user-visible). + $this->_values[$k] = $v; + } + if (!self::$permanentAttributes->includes($k)) { + $this->_unsavedValues->add($k); + } + } + + public function __isset($k) + { + return isset($this->_values[$k]); + } + public function __unset($k) + { + unset($this->_values[$k]); + $this->_transientValues->add($k); + $this->_unsavedValues->discard($k); + } + public function __get($k) + { + if (array_key_exists($k, $this->_values)) { + return $this->_values[$k]; + } else if ($this->_transientValues->includes($k)) { + $class = get_class($this); + $attrs = join(', ', array_keys($this->_values)); + $message = "Stripe Notice: Undefined property of $class instance: $k. " + . "HINT: The $k attribute was set in the past, however. " + . "It was then wiped when refreshing the object " + . "with the result returned by Stripe's API, " + . "probably as a result of a save(). The attributes currently " + . "available on this object are: $attrs"; + error_log($message); + return null; + } else { + $class = get_class($this); + error_log("Stripe Notice: Undefined property of $class instance: $k"); + return null; + } + } + + // ArrayAccess methods + public function offsetSet($k, $v) + { + $this->$k = $v; + } + + public function offsetExists($k) + { + return array_key_exists($k, $this->_values); + } + + public function offsetUnset($k) + { + unset($this->$k); + } + public function offsetGet($k) + { + return array_key_exists($k, $this->_values) ? $this->_values[$k] : null; + } + + public function keys() + { + return array_keys($this->_values); + } + + /** + * This unfortunately needs to be public to be used in Util\Util + * + * @param array $values + * @param array $opts + * + * @return Object The object constructed from the given values. + */ + public static function constructFrom($values, $opts) + { + $obj = new static(isset($values['id']) ? $values['id'] : null); + $obj->refreshFrom($values, $opts); + return $obj; + } + + /** + * Refreshes this object using the provided values. + * + * @param array $values + * @param array $opts + * @param boolean $partial Defaults to false. + */ + public function refreshFrom($values, $opts, $partial = false) + { + $this->_opts = $opts; + + // Wipe old state before setting new. This is useful for e.g. updating a + // customer, where there is no persistent card parameter. Mark those values + // which don't persist as transient + if ($partial) { + $removed = new Util\Set(); + } else { + $removed = array_diff(array_keys($this->_values), array_keys($values)); + } + + foreach ($removed as $k) { + if (self::$permanentAttributes->includes($k)) { + continue; + } + + unset($this->$k); + } + + foreach ($values as $k => $v) { + if (self::$permanentAttributes->includes($k) && isset($this[$k])) { + continue; + } + + if (self::$nestedUpdatableAttributes->includes($k) && is_array($v)) { + $this->_values[$k] = AttachedObject::constructFrom($v, $opts); + } else { + $this->_values[$k] = Util\Util::convertToStripeObject($v, $opts); + } + + $this->_transientValues->discard($k); + $this->_unsavedValues->discard($k); + } + } + + /** + * @return array A recursive mapping of attributes to values for this object, + * including the proper value for deleted attributes. + */ + public function serializeParameters() + { + $params = array(); + if ($this->_unsavedValues) { + foreach ($this->_unsavedValues->toArray() as $k) { + $v = $this->$k; + if ($v === null) { + $v = ''; + } + + $params[$k] = $v; + } + } + + // Get nested updates. + foreach (self::$nestedUpdatableAttributes->toArray() as $property) { + if (isset($this->$property) && $this->$property instanceof Object) { + $params[$property] = $this->$property->serializeParameters(); + } + } + + return $params; + } + + public function __toJSON() + { + if (defined('JSON_PRETTY_PRINT')) { + return json_encode($this->__toArray(true), JSON_PRETTY_PRINT); + } else { + return json_encode($this->__toArray(true)); + } + } + + public function __toString() + { + $class = get_class($this); + return $class . ' JSON: ' . $this->__toJSON(); + } + + public function __toArray($recursive = false) + { + if ($recursive) { + return Util\Util::convertStripeObjectToArray($this->_values); + } else { + return $this->_values; + } + } +} + +Object::init(); diff --git a/src/bb-vendor/stripe/stripe-php/lib/Refund.php b/src/bb-vendor/stripe/stripe-php/lib/Refund.php new file mode 100644 index 000000000..d0a01aa19 --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/lib/Refund.php @@ -0,0 +1,39 @@ +_save($opts); + } +} diff --git a/src/bb-vendor/stripe/stripe-php/lib/Stripe.php b/src/bb-vendor/stripe/stripe-php/lib/Stripe.php new file mode 100644 index 000000000..68e6346ea --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/lib/Stripe.php @@ -0,0 +1,74 @@ +_delete($params, $opts); + } + + /** + * @param array|string|null $opts + * + * @return Subscription The saved subscription. + */ + public function save($opts = null) + { + return $this->_save($opts); + } + + /** + * @return Subscription The updated subscription. + */ + public function deleteDiscount() + { + $url = $this->instanceUrl() . '/discount'; + list($response, $opts) = $this->_request('delete', $url); + $this->refreshFrom(array('discount' => null), $opts, true); + } +} diff --git a/src/bb-vendor/stripe/stripe-php/lib/Transfer.php b/src/bb-vendor/stripe/stripe-php/lib/Transfer.php new file mode 100644 index 000000000..1aa0eda7d --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/lib/Transfer.php @@ -0,0 +1,71 @@ +instanceUrl() . '/reversals'; + list($response, $opts) = $this->request('post', $url, $params, $options); + $this->refreshFrom($response, $opts); + return $this; + } + + /** + * @return Transfer The canceled transfer. + */ + public function cancel() + { + $url = $this->instanceUrl() . '/cancel'; + list($response, $opts) = $this->_request('post', $url); + $this->refreshFrom($response, $opts); + return $this; + } + + /** + * @param array|string|null $opts + * + * @return Transfer The saved transfer. + */ + public function save($opts = null) + { + return $this->_save($opts); + } +} diff --git a/src/bb-vendor/stripe/stripe-php/lib/TransferReversal.php b/src/bb-vendor/stripe/stripe-php/lib/TransferReversal.php new file mode 100644 index 000000000..28fb776c7 --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/lib/TransferReversal.php @@ -0,0 +1,39 @@ +_save($opts); + } +} diff --git a/src/bb-vendor/stripe/stripe-php/lib/Util/Util.php b/src/bb-vendor/stripe/stripe-php/lib/Util/Util.php new file mode 100644 index 000000000..d52798a66 --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/lib/Util/Util.php @@ -0,0 +1,102 @@ + $v) { + // FIXME: this is an encapsulation violation + if ($k[0] == '_') { + continue; + } + if ($v instanceof Object) { + $results[$k] = $v->__toArray(true); + } elseif (is_array($v)) { + $results[$k] = self::convertStripeObjectToArray($v); + } else { + $results[$k] = $v; + } + } + return $results; + } + + /** + * Converts a response from the Stripe API to the corresponding PHP object. + * + * @param array $resp The response from the Stripe API. + * @param array $opts + * @return Object|array + */ + public static function convertToStripeObject($resp, $opts) + { + $types = array( + 'account' => 'Stripe\\Account', + 'card' => 'Stripe\\Card', + 'charge' => 'Stripe\\Charge', + 'coupon' => 'Stripe\\Coupon', + 'customer' => 'Stripe\\Customer', + 'list' => 'Stripe\\Collection', + 'invoice' => 'Stripe\\Invoice', + 'invoiceitem' => 'Stripe\\InvoiceItem', + 'event' => 'Stripe\\Event', + 'file' => 'Stripe\\FileUpload', + 'token' => 'Stripe\\Token', + 'transfer' => 'Stripe\\Transfer', + 'plan' => 'Stripe\\Plan', + 'recipient' => 'Stripe\\Recipient', + 'refund' => 'Stripe\\Refund', + 'subscription' => 'Stripe\\Subscription', + 'fee_refund' => 'Stripe\\ApplicationFeeRefund', + 'bitcoin_receiver' => 'Stripe\\BitcoinReceiver', + 'bitcoin_transaction' => 'Stripe\\BitcoinTransaction', + ); + if (self::isList($resp)) { + $mapped = array(); + foreach ($resp as $i) { + array_push($mapped, self::convertToStripeObject($i, $opts)); + } + return $mapped; + } elseif (is_array($resp)) { + if (isset($resp['object']) && is_string($resp['object']) && isset($types[$resp['object']])) { + $class = $types[$resp['object']]; + } else { + $class = 'Stripe\\Object'; + } + return $class::constructFrom($resp, $opts); + } else { + return $resp; + } + } +} diff --git a/src/bb-vendor/stripe/stripe-php/tests/AccountTest.php b/src/bb-vendor/stripe/stripe-php/tests/AccountTest.php new file mode 100644 index 000000000..3de23512d --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/tests/AccountTest.php @@ -0,0 +1,26 @@ +assertSame($d->id, "cuD9Rwx8pgmRZRpVe02lsuR9cwp2Bzf7"); + $this->assertSame($d->email, "test+bindings@stripe.com"); + // @codingStandardsIgnoreStart + $this->assertSame($d->charges_enabled, false); + $this->assertSame($d->details_submitted, false); + // @codingStandardsIgnoreEnd + } + + public function testIDRetrieve() + { + self::authorizeFromEnv(); + $d = Account::retrieve('cuD9Rwx8pgmRZRpVe02lsuR9cwp2Bzf7'); + $this->assertSame($d->id, "cuD9Rwx8pgmRZRpVe02lsuR9cwp2Bzf7"); + $this->assertSame($d->email, "test+bindings@stripe.com"); + } +} diff --git a/src/bb-vendor/stripe/stripe-php/tests/ApiRequestorTest.php b/src/bb-vendor/stripe/stripe-php/tests/ApiRequestorTest.php new file mode 100644 index 000000000..b7935f946 --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/tests/ApiRequestorTest.php @@ -0,0 +1,121 @@ + 'value', + 'that' => array('your' => 'example'), + 'bar' => 1, + 'baz' => null + ); + + $enc = APIRequestor::encode($a); + $this->assertSame($enc, 'my=value&that%5Byour%5D=example&bar=1'); + + $a = array('that' => array('your' => 'example', 'foo' => null)); + $enc = APIRequestor::encode($a); + $this->assertSame($enc, 'that%5Byour%5D=example'); + + $a = array('that' => 'example', 'foo' => array('bar', 'baz')); + $enc = APIRequestor::encode($a); + $this->assertSame($enc, 'that=example&foo%5B%5D=bar&foo%5B%5D=baz'); + + $a = array( + 'my' => 'value', + 'that' => array('your' => array('cheese', 'whiz', null)), + 'bar' => 1, + 'baz' => null + ); + + $enc = APIRequestor::encode($a); + $expected = 'my=value&that%5Byour%5D%5B%5D=cheese' + . '&that%5Byour%5D%5B%5D=whiz&bar=1'; + $this->assertSame($enc, $expected); + } + + public function testUtf8() + { + // UTF-8 string + $x = "\xc3\xa9"; + $this->assertSame(ApiRequestor::utf8($x), $x); + + // Latin-1 string + $x = "\xe9"; + $this->assertSame(ApiRequestor::utf8($x), "\xc3\xa9"); + + // Not a string + $x = true; + $this->assertSame(ApiRequestor::utf8($x), $x); + } + + public function testEncodeObjects() + { + $reflector = new \ReflectionClass('Stripe\\ApiRequestor'); + $method = $reflector->getMethod('_encodeObjects'); + $method->setAccessible(true); + + $a = array('customer' => new Customer('abcd')); + $enc = $method->invoke(null, $a); + $this->assertSame($enc, array('customer' => 'abcd')); + + // Preserves UTF-8 + $v = array('customer' => "☃"); + $enc = $method->invoke(null, $v); + $this->assertSame($enc, $v); + + // Encodes latin-1 -> UTF-8 + $v = array('customer' => "\xe9"); + $enc = $method->invoke(null, $v); + $this->assertSame($enc, array('customer' => "\xc3\xa9")); + } + + public function testBlacklistedPEMCert() + { + $cert = + // {{{ Revoked certificate from api.stripe.com + '-----BEGIN CERTIFICATE----- +MIIGoDCCBYigAwIBAgIQATGh1aL1Q3mXYwp7zTQ8+zANBgkqhkiG9w0BAQUFADBm +MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSUwIwYDVQQDExxEaWdpQ2VydCBIaWdoIEFzc3VyYW5j +ZSBDQS0zMB4XDTEzMDkyNzAwMDAwMFoXDTE1MDEwODEyMDAwMFowajELMAkGA1UE +BhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBGcmFuY2lz +Y28xFTATBgNVBAoTDFN0cmlwZSwgSW5jLjEXMBUGA1UEAxMOYXBpLnN0cmlwZS5j +b20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC9a37/epvqPM/9ExSv +L4jOFyuT+h9+kSePtjRD4N2z/r9zqUt88TRe2TSPM0o7yqRAmggqck1iFQmmgkU8 +i5YjaGBVUSp9jyWZ7U+G9L9IRmxxWoYKaofpnGiGuTnpWgPPYtooXx+mhatvmiiM +tdJCU5QCN4rSvH9QnMHGrGupSw0Hb68d5nbbfk5f3IdYpjFR0+b0RHIoSrYPhiJF +r3/4h61Iu3PFea70wASLnP0olKlstQ6FONpsoYBRONvgs8/gUPQVY/VllbEceEpt +Bm5fIP5Cgd+Zya9uGqXsru1MyPIrR93u/YHDSYpC1TJ+BlSAamoC8ahtRNXLueRM +OFn5AgMBAAGjggNEMIIDQDAfBgNVHSMEGDAWgBRQ6nOJ2yn7EI+e5QEg1N55mUiD +9zAdBgNVHQ4EFgQUVhDDlYPPyDwTr1hy5uUZYYHEJyYwGQYDVR0RBBIwEIIOYXBp +LnN0cmlwZS5jb20wDgYDVR0PAQH/BAQDAgWgMB0GA1UdJQQWMBQGCCsGAQUFBwMB +BggrBgEFBQcDAjBhBgNVHR8EWjBYMCqgKKAmhiRodHRwOi8vY3JsMy5kaWdpY2Vy +dC5jb20vY2EzLWcyNC5jcmwwKqAooCaGJGh0dHA6Ly9jcmw0LmRpZ2ljZXJ0LmNv +bS9jYTMtZzI0LmNybDCCAcQGA1UdIASCAbswggG3MIIBswYJYIZIAYb9bAEBMIIB +pDA6BggrBgEFBQcCARYuaHR0cDovL3d3dy5kaWdpY2VydC5jb20vc3NsLWNwcy1y +ZXBvc2l0b3J5Lmh0bTCCAWQGCCsGAQUFBwICMIIBVh6CAVIAQQBuAHkAIAB1AHMA +ZQAgAG8AZgAgAHQAaABpAHMAIABDAGUAcgB0AGkAZgBpAGMAYQB0AGUAIABjAG8A +bgBzAHQAaQB0AHUAdABlAHMAIABhAGMAYwBlAHAAdABhAG4AYwBlACAAbwBmACAA +dABoAGUAIABEAGkAZwBpAEMAZQByAHQAIABDAFAALwBDAFAAUwAgAGEAbgBkACAA +dABoAGUAIABSAGUAbAB5AGkAbgBnACAAUABhAHIAdAB5ACAAQQBnAHIAZQBlAG0A +ZQBuAHQAIAB3AGgAaQBjAGgAIABsAGkAbQBpAHQAIABsAGkAYQBiAGkAbABpAHQA +eQAgAGEAbgBkACAAYQByAGUAIABpAG4AYwBvAHIAcABvAHIAYQB0AGUAZAAgAGgA +ZQByAGUAaQBuACAAYgB5ACAAcgBlAGYAZQByAGUAbgBjAGUALjB7BggrBgEFBQcB +AQRvMG0wJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmRpZ2ljZXJ0LmNvbTBFBggr +BgEFBQcwAoY5aHR0cDovL2NhY2VydHMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0SGln +aEFzc3VyYW5jZUNBLTMuY3J0MAwGA1UdEwEB/wQCMAAwDQYJKoZIhvcNAQEFBQAD +ggEBAKPiwJIeR52VOjhPew9cx19nmkHXDxxPzcOmSsF3gk9jogXh61yA6DevcTBY +KTNUhkTRWujOUdwZqNuvaLCLwn/TEGV9hM4lOKah8yqCQB8PhT7baMiL7mltAhEE +SBs2soRGVXHr3AczRKLW3G+IbIpUc3vilOul/PXWHutfzz7/asxXSTk/siVKROQ8 +/KWrujG6wopwEEGExhlYOYBuXObwoSCV2nqIgr92fpHGvbMIFKSICoT7RCm8EVcb +3PGuaL8B8TZVbTOPYoJHdPzeRxL8Rbg8sDogHR+jkqwwyhUCfuzVbOjWFJU1DKvr +CBoD8xKYd5r7CYf1Du+nNMmDmrE= +-----END CERTIFICATE-----'; + // }}} + $this->assertTrue(APIRequestor::isBlackListed($cert)); + } +} diff --git a/src/bb-vendor/stripe/stripe-php/tests/CardErrorTest.php b/src/bb-vendor/stripe/stripe-php/tests/CardErrorTest.php new file mode 100644 index 000000000..8e8fc186b --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/tests/CardErrorTest.php @@ -0,0 +1,39 @@ + '4000000000000002', + 'exp_month' => '3', + 'exp_year' => '2020' + ); + + $charge = array( + 'amount' => 100, + 'currency' => 'usd', + 'card' => $card + ); + + try { + Charge::create($charge); + } catch (Error\Card $e) { + $this->assertSame(402, $e->getHttpStatus()); + $actual = $e->getJsonBody(); + $this->assertSame( + array('error' => array( + 'message' => 'Your card was declined.', + 'type' => 'card_error', + 'code' => 'card_declined', + 'charge' => $actual['error']['charge'], + )), + $actual + ); + } + } +} diff --git a/src/bb-vendor/stripe/stripe-php/tests/ChargeTest.php b/src/bb-vendor/stripe/stripe-php/tests/ChargeTest.php new file mode 100644 index 000000000..f466b59b6 --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/tests/ChargeTest.php @@ -0,0 +1,202 @@ +assertSame(Charge::classUrl(), '/v1/charges'); + $charge = new Charge('abcd/efgh'); + $this->assertSame($charge->instanceUrl(), '/v1/charges/abcd%2Fefgh'); + } + + public function testCreate() + { + self::authorizeFromEnv(); + + $card = array( + 'number' => '4242424242424242', + 'exp_month' => 5, + 'exp_year' => 2015 + ); + + $c = Charge::create( + array( + 'amount' => 100, + 'currency' => 'usd', + 'card' => $card + ) + ); + $this->assertTrue($c->paid); + $this->assertFalse($c->refunded); + } + + public function testIdempotentCreate() + { + self::authorizeFromEnv(); + + $card = array( + 'number' => '4242424242424242', + 'exp_month' => 5, + 'exp_year' => 2015 + ); + + $c = Charge::create( + array( + 'amount' => 100, + 'currency' => 'usd', + 'card' => $card + ), + array( + 'idempotency_key' => self::generateRandomString(), + ) + ); + + $this->assertTrue($c->paid); + $this->assertFalse($c->refunded); + } + + public function testRetrieve() + { + self::authorizeFromEnv(); + + $card = array( + 'number' => '4242424242424242', + 'exp_month' => 5, + 'exp_year' => 2015 + ); + + $c = Charge::create( + array( + 'amount' => 100, + 'currency' => 'usd', + 'card' => $card + ) + ); + $d = Charge::retrieve($c->id); + $this->assertSame($d->id, $c->id); + } + + public function testUpdateMetadata() + { + self::authorizeFromEnv(); + + $card = array( + 'number' => '4242424242424242', + 'exp_month' => 5, + 'exp_year' => 2015 + ); + + $charge = Charge::create( + array( + 'amount' => 100, + 'currency' => 'usd', + 'card' => $card + ) + ); + + $charge->metadata['test'] = 'foo bar'; + $charge->save(); + + $updatedCharge = Charge::retrieve($charge->id); + $this->assertSame('foo bar', $updatedCharge->metadata['test']); + } + + public function testUpdateMetadataAll() + { + self::authorizeFromEnv(); + + $card = array( + 'number' => '4242424242424242', + 'exp_month' => 5, + 'exp_year' => 2015 + ); + + $charge = Charge::create( + array( + 'amount' => 100, + 'currency' => 'usd', + 'card' => $card + ) + ); + + $charge->metadata = array('test' => 'foo bar'); + $charge->save(); + + $updatedCharge = Charge::retrieve($charge->id); + $this->assertSame('foo bar', $updatedCharge->metadata['test']); + } + + public function testMarkAsFraudulent() + { + self::authorizeFromEnv(); + + $card = array( + 'number' => '4242424242424242', + 'exp_month' => 5, + 'exp_year' => 2015 + ); + + $charge = Charge::create( + array( + 'amount' => 100, + 'currency' => 'usd', + 'card' => $card + ) + ); + + $charge->refunds->create(); + $charge->markAsFraudulent(); + + $updatedCharge = Charge::retrieve($charge->id); + $this->assertSame( + 'fraudulent', + $updatedCharge['fraud_details']['user_report'] + ); + } + + public function testCreateWithBitcoinReceiverSource() + { + self::authorizeFromEnv(); + + $receiver = $this->createTestBitcoinReceiver("do+fill_now@stripe.com"); + + $charge = Charge::create( + array( + 'amount' => 100, + 'currency' => 'usd', + 'source' => $receiver->id + ) + ); + + $this->assertSame($receiver->id, $charge->source->id); + $this->assertSame("bitcoin_receiver", $charge->source->object); + $this->assertSame("succeeded", $charge->status); + $this->assertInstanceOf('Stripe\\BitcoinReceiver', $charge->source); + } + + public function markAsSafe() + { + self::authorizeFromEnv(); + + $card = array( + 'number' => '4242424242424242', + 'exp_month' => 5, + 'exp_year' => 2015 + ); + + $charge = Charge::create( + array( + 'amount' => 100, + 'currency' => 'usd', + 'card' => $card + ) + ); + + $charge->markAsSafe(); + + $updatedCharge = Charge::retrieve($charge->id); + $this->assertSame('safe', $updatedCharge['fraud_details']['user_report']); + } +} diff --git a/src/bb-vendor/stripe/stripe-php/tests/ErrorTest.php b/src/bb-vendor/stripe/stripe-php/tests/ErrorTest.php new file mode 100644 index 000000000..05ab0a6e5 --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/tests/ErrorTest.php @@ -0,0 +1,24 @@ + 'bar') + ); + $this->fail("Did not raise error"); + } catch (Error\Api $e) { + $this->assertSame("hello", $e->getMessage()); + $this->assertSame(500, $e->getHttpStatus()); + $this->assertSame("{'foo':'bar'}", $e->getHttpBody()); + $this->assertSame(array('foo' => 'bar'), $e->getJsonBody()); + } + } +} diff --git a/src/bb-vendor/stripe/stripe-php/tests/TestCase.php b/src/bb-vendor/stripe/stripe-php/tests/TestCase.php new file mode 100644 index 000000000..56421695a --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/tests/TestCase.php @@ -0,0 +1,187 @@ + 2000, + 'currency' => 'usd', + 'description' => 'Charge for test@example.com', + 'card' => array( + 'number' => '4242424242424242', + 'exp_month' => 5, + 'exp_year' => date('Y') + 3, + ), + ) + ); + } + + /** + * Create a valid test charge. + */ + protected static function createTestTransfer(array $attributes = array()) + { + self::authorizeFromEnv(); + + $recipient = self::createTestRecipient(); + + return Transfer::create( + $attributes + array( + 'amount' => 2000, + 'currency' => 'usd', + 'description' => 'Transfer to test@example.com', + 'recipient' => $recipient->id + ) + ); + } + + /** + * Create a valid test customer. + */ + protected static function createTestCustomer(array $attributes = array()) + { + self::authorizeFromEnv(); + + return Customer::create( + $attributes + array( + 'card' => array( + 'number' => '4242424242424242', + 'exp_month' => 5, + 'exp_year' => date('Y') + 3, + ), + ) + ); + } + + /** + * Create a valid test recipient + */ + protected static function createTestRecipient(array $attributes = array()) + { + self::authorizeFromEnv(); + + return Recipient::create( + $attributes + array( + 'name' => 'PHP Test', + 'type' => 'individual', + 'tax_id' => '000000000', + 'bank_account' => array( + 'country' => 'US', + 'routing_number' => '110000000', + 'account_number' => '000123456789' + ), + ) + ); + } + + /** + * Generate a random 8-character string. Useful for ensuring + * multiple test suite runs don't conflict + */ + protected static function randomString() + { + $chars = 'abcdefghijklmnopqrstuvwxyz'; + $str = ''; + for ($i = 0; $i < 10; $i++) { + $str .= $chars[rand(0, strlen($chars)-1)]; + } + + return $str; + } + + /** + * Verify that a plan with a given ID exists, or create a new one if it does + * not. + */ + protected static function retrieveOrCreatePlan($id) + { + self::authorizeFromEnv(); + + try { + $plan = Plan::retrieve($id); + } catch (Error\InvalidRequest $exception) { + $plan = Plan::create( + array( + 'id' => $id, + 'amount' => 0, + 'currency' => 'usd', + 'interval' => 'month', + 'name' => 'Gold Test Plan', + ) + ); + } + } + + /** + * Verify that a coupon with a given ID exists, or create a new one if it + * does not. + */ + protected static function retrieveOrCreateCoupon($id) + { + self::authorizeFromEnv(); + + try { + $coupon = Coupon::retrieve($id); + } catch (Error\InvalidRequest $exception) { + $coupon = Coupon::create( + array( + 'id' => $id, + 'duration' => 'forever', + 'percent_off' => 25, + ) + ); + } + } + + /** + * Genereate a semi-random string + */ + protected static function generateRandomString($length = 24) + { + $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTU'; + $charactersLength = strlen($characters); + $randomString = ''; + for ($i = 0; $i < $length; $i++) { + $randomString .= $characters[rand(0, $charactersLength - 1)]; + } + return $randomString; + } + + protected static function createTestBitcoinReceiver($email) + { + $receiver = BitcoinReceiver::create( + array( + 'amount' => 100, + 'currency' => 'usd', + 'description' => 'some details', + 'email' => $email + ) + ); + return $receiver; + } +} diff --git a/src/bb-vendor/stripe/stripe-php/tests/UtilTest.php b/src/bb-vendor/stripe/stripe-php/tests/UtilTest.php new file mode 100644 index 000000000..be2373d45 --- /dev/null +++ b/src/bb-vendor/stripe/stripe-php/tests/UtilTest.php @@ -0,0 +1,30 @@ +assertTrue(Util\Util::isList($list)); + + $notlist = array(5, 'nstaoush', array(), 'bar' => 'baz'); + $this->assertFalse(Util\Util::isList($notlist)); + } + + public function testThatPHPHasValueSemanticsForArrays() + { + $original = array('php-arrays' => 'value-semantics'); + $derived = $original; + $derived['php-arrays'] = 'reference-semantics'; + + $this->assertSame('value-semantics', $original['php-arrays']); + } + + public function testConvertStripeObjectToArrayIncludesId() + { + $customer = self::createTestCustomer(); + $this->assertTrue(array_key_exists("id", $customer->__toArray(true))); + } +} diff --git a/src/bb-vendor/symfony/event-dispatcher/.gitignore b/src/bb-vendor/symfony/event-dispatcher/.gitignore new file mode 100644 index 000000000..c49a5d8df --- /dev/null +++ b/src/bb-vendor/symfony/event-dispatcher/.gitignore @@ -0,0 +1,3 @@ +vendor/ +composer.lock +phpunit.xml diff --git a/src/bb-vendor/symfony/event-dispatcher/CHANGELOG.md b/src/bb-vendor/symfony/event-dispatcher/CHANGELOG.md new file mode 100644 index 000000000..bb42ee19c --- /dev/null +++ b/src/bb-vendor/symfony/event-dispatcher/CHANGELOG.md @@ -0,0 +1,23 @@ +CHANGELOG +========= + +2.5.0 +----- + + * added Debug\TraceableEventDispatcher (originally in HttpKernel) + * changed Debug\TraceableEventDispatcherInterface to extend EventDispatcherInterface + * added RegisterListenersPass (originally in HttpKernel) + +2.1.0 +----- + + * added TraceableEventDispatcherInterface + * added ContainerAwareEventDispatcher + * added a reference to the EventDispatcher on the Event + * added a reference to the Event name on the event + * added fluid interface to the dispatch() method which now returns the Event + object + * added GenericEvent event class + * added the possibility for subscribers to subscribe several times for the + same event + * added ImmutableEventDispatcher diff --git a/src/bb-vendor/symfony/event-dispatcher/ContainerAwareEventDispatcher.php b/src/bb-vendor/symfony/event-dispatcher/ContainerAwareEventDispatcher.php new file mode 100644 index 000000000..4dcede7e7 --- /dev/null +++ b/src/bb-vendor/symfony/event-dispatcher/ContainerAwareEventDispatcher.php @@ -0,0 +1,183 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher; + +use Symfony\Component\DependencyInjection\ContainerInterface; + +/** + * Lazily loads listeners and subscribers from the dependency injection + * container. + * + * @author Fabien Potencier + * @author Bernhard Schussek + * @author Jordan Alliot + */ +class ContainerAwareEventDispatcher extends EventDispatcher +{ + private $container; + + /** + * The service IDs of the event listeners and subscribers. + */ + private $listenerIds = array(); + + /** + * The services registered as listeners. + */ + private $listeners = array(); + + public function __construct(ContainerInterface $container) + { + $this->container = $container; + } + + /** + * Adds a service as event listener. + * + * @param string $eventName Event for which the listener is added + * @param array $callback The service ID of the listener service & the method + * name that has to be called + * @param int $priority The higher this value, the earlier an event listener + * will be triggered in the chain. + * Defaults to 0. + * + * @throws \InvalidArgumentException + */ + public function addListenerService($eventName, $callback, $priority = 0) + { + if (!\is_array($callback) || 2 !== \count($callback)) { + throw new \InvalidArgumentException('Expected an array("service", "method") argument'); + } + + $this->listenerIds[$eventName][] = array($callback[0], $callback[1], $priority); + } + + public function removeListener($eventName, $listener) + { + $this->lazyLoad($eventName); + + if (isset($this->listenerIds[$eventName])) { + foreach ($this->listenerIds[$eventName] as $i => $args) { + list($serviceId, $method) = $args; + $key = $serviceId.'.'.$method; + if (isset($this->listeners[$eventName][$key]) && $listener === array($this->listeners[$eventName][$key], $method)) { + unset($this->listeners[$eventName][$key]); + if (empty($this->listeners[$eventName])) { + unset($this->listeners[$eventName]); + } + unset($this->listenerIds[$eventName][$i]); + if (empty($this->listenerIds[$eventName])) { + unset($this->listenerIds[$eventName]); + } + } + } + } + + parent::removeListener($eventName, $listener); + } + + /** + * {@inheritdoc} + */ + public function hasListeners($eventName = null) + { + if (null === $eventName) { + return $this->listenerIds || $this->listeners || parent::hasListeners(); + } + + if (isset($this->listenerIds[$eventName])) { + return true; + } + + return parent::hasListeners($eventName); + } + + /** + * {@inheritdoc} + */ + public function getListeners($eventName = null) + { + if (null === $eventName) { + foreach ($this->listenerIds as $serviceEventName => $args) { + $this->lazyLoad($serviceEventName); + } + } else { + $this->lazyLoad($eventName); + } + + return parent::getListeners($eventName); + } + + /** + * {@inheritdoc} + */ + public function getListenerPriority($eventName, $listener) + { + $this->lazyLoad($eventName); + + return parent::getListenerPriority($eventName, $listener); + } + + /** + * Adds a service as event subscriber. + * + * @param string $serviceId The service ID of the subscriber service + * @param string $class The service's class name (which must implement EventSubscriberInterface) + */ + public function addSubscriberService($serviceId, $class) + { + foreach ($class::getSubscribedEvents() as $eventName => $params) { + if (\is_string($params)) { + $this->listenerIds[$eventName][] = array($serviceId, $params, 0); + } elseif (\is_string($params[0])) { + $this->listenerIds[$eventName][] = array($serviceId, $params[0], isset($params[1]) ? $params[1] : 0); + } else { + foreach ($params as $listener) { + $this->listenerIds[$eventName][] = array($serviceId, $listener[0], isset($listener[1]) ? $listener[1] : 0); + } + } + } + } + + public function getContainer() + { + return $this->container; + } + + /** + * Lazily loads listeners for this event from the dependency injection + * container. + * + * @param string $eventName The name of the event to dispatch. The name of + * the event is the name of the method that is + * invoked on listeners. + */ + protected function lazyLoad($eventName) + { + if (isset($this->listenerIds[$eventName])) { + foreach ($this->listenerIds[$eventName] as $args) { + list($serviceId, $method, $priority) = $args; + $listener = $this->container->get($serviceId); + + $key = $serviceId.'.'.$method; + if (!isset($this->listeners[$eventName][$key])) { + $this->addListener($eventName, array($listener, $method), $priority); + } elseif ($this->listeners[$eventName][$key] !== $listener) { + parent::removeListener($eventName, array($this->listeners[$eventName][$key], $method)); + $this->addListener($eventName, array($listener, $method), $priority); + } + + $this->listeners[$eventName][$key] = $listener; + } + } + } +} diff --git a/src/bb-vendor/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php b/src/bb-vendor/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php new file mode 100644 index 000000000..53d7c5d51 --- /dev/null +++ b/src/bb-vendor/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php @@ -0,0 +1,375 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher\Debug; + +use Psr\Log\LoggerInterface; +use Symfony\Component\EventDispatcher\Event; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\Stopwatch\Stopwatch; + +/** + * Collects some data about event listeners. + * + * This event dispatcher delegates the dispatching to another one. + * + * @author Fabien Potencier + */ +class TraceableEventDispatcher implements TraceableEventDispatcherInterface +{ + protected $logger; + protected $stopwatch; + + private $called; + private $dispatcher; + private $wrappedListeners; + + public function __construct(EventDispatcherInterface $dispatcher, Stopwatch $stopwatch, LoggerInterface $logger = null) + { + $this->dispatcher = $dispatcher; + $this->stopwatch = $stopwatch; + $this->logger = $logger; + $this->called = array(); + $this->wrappedListeners = array(); + } + + /** + * {@inheritdoc} + */ + public function addListener($eventName, $listener, $priority = 0) + { + $this->dispatcher->addListener($eventName, $listener, $priority); + } + + /** + * {@inheritdoc} + */ + public function addSubscriber(EventSubscriberInterface $subscriber) + { + $this->dispatcher->addSubscriber($subscriber); + } + + /** + * {@inheritdoc} + */ + public function removeListener($eventName, $listener) + { + if (isset($this->wrappedListeners[$eventName])) { + foreach ($this->wrappedListeners[$eventName] as $index => $wrappedListener) { + if ($wrappedListener->getWrappedListener() === $listener) { + $listener = $wrappedListener; + unset($this->wrappedListeners[$eventName][$index]); + break; + } + } + } + + return $this->dispatcher->removeListener($eventName, $listener); + } + + /** + * {@inheritdoc} + */ + public function removeSubscriber(EventSubscriberInterface $subscriber) + { + return $this->dispatcher->removeSubscriber($subscriber); + } + + /** + * {@inheritdoc} + */ + public function getListeners($eventName = null) + { + return $this->dispatcher->getListeners($eventName); + } + + /** + * {@inheritdoc} + */ + public function getListenerPriority($eventName, $listener) + { + if (!method_exists($this->dispatcher, 'getListenerPriority')) { + return 0; + } + + return $this->dispatcher->getListenerPriority($eventName, $listener); + } + + /** + * {@inheritdoc} + */ + public function hasListeners($eventName = null) + { + return $this->dispatcher->hasListeners($eventName); + } + + /** + * {@inheritdoc} + */ + public function dispatch($eventName, Event $event = null) + { + if (null === $event) { + $event = new Event(); + } + + if (null !== $this->logger && $event->isPropagationStopped()) { + $this->logger->debug(sprintf('The "%s" event is already stopped. No listeners have been called.', $eventName)); + } + + $this->preProcess($eventName); + $this->preDispatch($eventName, $event); + + $e = $this->stopwatch->start($eventName, 'section'); + + $this->dispatcher->dispatch($eventName, $event); + + if ($e->isStarted()) { + $e->stop(); + } + + $this->postDispatch($eventName, $event); + $this->postProcess($eventName); + + return $event; + } + + /** + * {@inheritdoc} + */ + public function getCalledListeners() + { + $called = array(); + foreach ($this->called as $eventName => $listeners) { + foreach ($listeners as $listener) { + $info = $this->getListenerInfo($listener->getWrappedListener(), $eventName); + $called[$eventName.'.'.$info['pretty']] = $info; + } + } + + return $called; + } + + /** + * {@inheritdoc} + */ + public function getNotCalledListeners() + { + try { + $allListeners = $this->getListeners(); + } catch (\Exception $e) { + if (null !== $this->logger) { + $this->logger->info('An exception was thrown while getting the uncalled listeners.', array('exception' => $e)); + } + + // unable to retrieve the uncalled listeners + return array(); + } + + $notCalled = array(); + foreach ($allListeners as $eventName => $listeners) { + foreach ($listeners as $listener) { + $called = false; + if (isset($this->called[$eventName])) { + foreach ($this->called[$eventName] as $l) { + if ($l->getWrappedListener() === $listener) { + $called = true; + + break; + } + } + } + + if (!$called) { + $info = $this->getListenerInfo($listener, $eventName); + $notCalled[$eventName.'.'.$info['pretty']] = $info; + } + } + } + + uasort($notCalled, array($this, 'sortListenersByPriority')); + + return $notCalled; + } + + /** + * Proxies all method calls to the original event dispatcher. + * + * @param string $method The method name + * @param array $arguments The method arguments + * + * @return mixed + */ + public function __call($method, $arguments) + { + return \call_user_func_array(array($this->dispatcher, $method), $arguments); + } + + /** + * Called before dispatching the event. + * + * @param string $eventName The event name + * @param Event $event The event + */ + protected function preDispatch($eventName, Event $event) + { + } + + /** + * Called after dispatching the event. + * + * @param string $eventName The event name + * @param Event $event The event + */ + protected function postDispatch($eventName, Event $event) + { + } + + private function preProcess($eventName) + { + foreach ($this->dispatcher->getListeners($eventName) as $listener) { + $info = $this->getListenerInfo($listener, $eventName); + $name = isset($info['class']) ? $info['class'] : $info['type']; + $wrappedListener = new WrappedListener($listener, $name, $this->stopwatch, $this); + $this->wrappedListeners[$eventName][] = $wrappedListener; + $this->dispatcher->removeListener($eventName, $listener); + $this->dispatcher->addListener($eventName, $wrappedListener, $info['priority']); + } + } + + private function postProcess($eventName) + { + unset($this->wrappedListeners[$eventName]); + $skipped = false; + foreach ($this->dispatcher->getListeners($eventName) as $listener) { + if (!$listener instanceof WrappedListener) { // #12845: a new listener was added during dispatch. + continue; + } + // Unwrap listener + $priority = $this->getListenerPriority($eventName, $listener); + $this->dispatcher->removeListener($eventName, $listener); + $this->dispatcher->addListener($eventName, $listener->getWrappedListener(), $priority); + + $info = $this->getListenerInfo($listener->getWrappedListener(), $eventName); + if ($listener->wasCalled()) { + if (null !== $this->logger) { + $this->logger->debug(sprintf('Notified event "%s" to listener "%s".', $eventName, $info['pretty'])); + } + + if (!isset($this->called[$eventName])) { + $this->called[$eventName] = new \SplObjectStorage(); + } + + $this->called[$eventName]->attach($listener); + } + + if (null !== $this->logger && $skipped) { + $this->logger->debug(sprintf('Listener "%s" was not called for event "%s".', $info['pretty'], $eventName)); + } + + if ($listener->stoppedPropagation()) { + if (null !== $this->logger) { + $this->logger->debug(sprintf('Listener "%s" stopped propagation of the event "%s".', $info['pretty'], $eventName)); + } + + $skipped = true; + } + } + } + + /** + * Returns information about the listener. + * + * @param object $listener The listener + * @param string $eventName The event name + * + * @return array Information about the listener + */ + private function getListenerInfo($listener, $eventName) + { + $info = array( + 'event' => $eventName, + 'priority' => $this->getListenerPriority($eventName, $listener), + ); + + // unwrap for correct listener info + if ($listener instanceof WrappedListener) { + $listener = $listener->getWrappedListener(); + } + + if ($listener instanceof \Closure) { + $info += array( + 'type' => 'Closure', + 'pretty' => 'closure', + ); + } elseif (\is_string($listener)) { + try { + $r = new \ReflectionFunction($listener); + $file = $r->getFileName(); + $line = $r->getStartLine(); + } catch (\ReflectionException $e) { + $file = null; + $line = null; + } + $info += array( + 'type' => 'Function', + 'function' => $listener, + 'file' => $file, + 'line' => $line, + 'pretty' => $listener, + ); + } elseif (\is_array($listener) || (\is_object($listener) && \is_callable($listener))) { + if (!\is_array($listener)) { + $listener = array($listener, '__invoke'); + } + $class = \is_object($listener[0]) ? \get_class($listener[0]) : $listener[0]; + try { + $r = new \ReflectionMethod($class, $listener[1]); + $file = $r->getFileName(); + $line = $r->getStartLine(); + } catch (\ReflectionException $e) { + $file = null; + $line = null; + } + $info += array( + 'type' => 'Method', + 'class' => $class, + 'method' => $listener[1], + 'file' => $file, + 'line' => $line, + 'pretty' => $class.'::'.$listener[1], + ); + } + + return $info; + } + + private function sortListenersByPriority($a, $b) + { + if (\is_int($a['priority']) && !\is_int($b['priority'])) { + return 1; + } + + if (!\is_int($a['priority']) && \is_int($b['priority'])) { + return -1; + } + + if ($a['priority'] === $b['priority']) { + return 0; + } + + if ($a['priority'] > $b['priority']) { + return -1; + } + + return 1; + } +} diff --git a/src/bb-vendor/symfony/event-dispatcher/Debug/TraceableEventDispatcherInterface.php b/src/bb-vendor/symfony/event-dispatcher/Debug/TraceableEventDispatcherInterface.php new file mode 100644 index 000000000..5483e8150 --- /dev/null +++ b/src/bb-vendor/symfony/event-dispatcher/Debug/TraceableEventDispatcherInterface.php @@ -0,0 +1,34 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher\Debug; + +use Symfony\Component\EventDispatcher\EventDispatcherInterface; + +/** + * @author Fabien Potencier + */ +interface TraceableEventDispatcherInterface extends EventDispatcherInterface +{ + /** + * Gets the called listeners. + * + * @return array An array of called listeners + */ + public function getCalledListeners(); + + /** + * Gets the not called listeners. + * + * @return array An array of not called listeners + */ + public function getNotCalledListeners(); +} diff --git a/src/bb-vendor/symfony/event-dispatcher/Debug/WrappedListener.php b/src/bb-vendor/symfony/event-dispatcher/Debug/WrappedListener.php new file mode 100644 index 000000000..1552af02d --- /dev/null +++ b/src/bb-vendor/symfony/event-dispatcher/Debug/WrappedListener.php @@ -0,0 +1,71 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher\Debug; + +use Symfony\Component\EventDispatcher\Event; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use Symfony\Component\Stopwatch\Stopwatch; + +/** + * @author Fabien Potencier + */ +class WrappedListener +{ + private $listener; + private $name; + private $called; + private $stoppedPropagation; + private $stopwatch; + private $dispatcher; + + public function __construct($listener, $name, Stopwatch $stopwatch, EventDispatcherInterface $dispatcher = null) + { + $this->listener = $listener; + $this->name = $name; + $this->stopwatch = $stopwatch; + $this->dispatcher = $dispatcher; + $this->called = false; + $this->stoppedPropagation = false; + } + + public function getWrappedListener() + { + return $this->listener; + } + + public function wasCalled() + { + return $this->called; + } + + public function stoppedPropagation() + { + return $this->stoppedPropagation; + } + + public function __invoke(Event $event, $eventName, EventDispatcherInterface $dispatcher) + { + $this->called = true; + + $e = $this->stopwatch->start($this->name, 'event_listener'); + + \call_user_func($this->listener, $event, $eventName, $this->dispatcher ?: $dispatcher); + + if ($e->isStarted()) { + $e->stop(); + } + + if ($event->isPropagationStopped()) { + $this->stoppedPropagation = true; + } + } +} diff --git a/src/bb-vendor/symfony/event-dispatcher/DependencyInjection/RegisterListenersPass.php b/src/bb-vendor/symfony/event-dispatcher/DependencyInjection/RegisterListenersPass.php new file mode 100644 index 000000000..5a94ae82b --- /dev/null +++ b/src/bb-vendor/symfony/event-dispatcher/DependencyInjection/RegisterListenersPass.php @@ -0,0 +1,100 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher\DependencyInjection; + +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; + +/** + * Compiler pass to register tagged services for an event dispatcher. + */ +class RegisterListenersPass implements CompilerPassInterface +{ + protected $dispatcherService; + protected $listenerTag; + protected $subscriberTag; + + /** + * @param string $dispatcherService Service name of the event dispatcher in processed container + * @param string $listenerTag Tag name used for listener + * @param string $subscriberTag Tag name used for subscribers + */ + public function __construct($dispatcherService = 'event_dispatcher', $listenerTag = 'kernel.event_listener', $subscriberTag = 'kernel.event_subscriber') + { + $this->dispatcherService = $dispatcherService; + $this->listenerTag = $listenerTag; + $this->subscriberTag = $subscriberTag; + } + + public function process(ContainerBuilder $container) + { + if (!$container->hasDefinition($this->dispatcherService) && !$container->hasAlias($this->dispatcherService)) { + return; + } + + $definition = $container->findDefinition($this->dispatcherService); + + foreach ($container->findTaggedServiceIds($this->listenerTag) as $id => $events) { + $def = $container->getDefinition($id); + if (!$def->isPublic()) { + throw new \InvalidArgumentException(sprintf('The service "%s" must be public as event listeners are lazy-loaded.', $id)); + } + + if ($def->isAbstract()) { + throw new \InvalidArgumentException(sprintf('The service "%s" must not be abstract as event listeners are lazy-loaded.', $id)); + } + + foreach ($events as $event) { + $priority = isset($event['priority']) ? $event['priority'] : 0; + + if (!isset($event['event'])) { + throw new \InvalidArgumentException(sprintf('Service "%s" must define the "event" attribute on "%s" tags.', $id, $this->listenerTag)); + } + + if (!isset($event['method'])) { + $event['method'] = 'on'.preg_replace_callback(array( + '/(?<=\b)[a-z]/i', + '/[^a-z0-9]/i', + ), function ($matches) { return strtoupper($matches[0]); }, $event['event']); + $event['method'] = preg_replace('/[^a-z0-9]/i', '', $event['method']); + } + + $definition->addMethodCall('addListenerService', array($event['event'], array($id, $event['method']), $priority)); + } + } + + foreach ($container->findTaggedServiceIds($this->subscriberTag) as $id => $attributes) { + $def = $container->getDefinition($id); + if (!$def->isPublic()) { + throw new \InvalidArgumentException(sprintf('The service "%s" must be public as event subscribers are lazy-loaded.', $id)); + } + + if ($def->isAbstract()) { + throw new \InvalidArgumentException(sprintf('The service "%s" must not be abstract as event subscribers are lazy-loaded.', $id)); + } + + // We must assume that the class value has been correctly filled, even if the service is created by a factory + $class = $container->getParameterBag()->resolveValue($def->getClass()); + $interface = 'Symfony\Component\EventDispatcher\EventSubscriberInterface'; + + if (!is_subclass_of($class, $interface)) { + if (!class_exists($class, false)) { + throw new \InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id)); + } + + throw new \InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $id, $interface)); + } + + $definition->addMethodCall('addSubscriberService', array($id, $class)); + } + } +} diff --git a/src/bb-vendor/symfony/event-dispatcher/Event.php b/src/bb-vendor/symfony/event-dispatcher/Event.php new file mode 100644 index 000000000..320919ae2 --- /dev/null +++ b/src/bb-vendor/symfony/event-dispatcher/Event.php @@ -0,0 +1,120 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher; + +/** + * Event is the base class for classes containing event data. + * + * This class contains no event data. It is used by events that do not pass + * state information to an event handler when an event is raised. + * + * You can call the method stopPropagation() to abort the execution of + * further listeners in your event listener. + * + * @author Guilherme Blanco + * @author Jonathan Wage + * @author Roman Borschel + * @author Bernhard Schussek + */ +class Event +{ + /** + * @var bool Whether no further event listeners should be triggered + */ + private $propagationStopped = false; + + /** + * @var EventDispatcherInterface Dispatcher that dispatched this event + */ + private $dispatcher; + + /** + * @var string This event's name + */ + private $name; + + /** + * Returns whether further event listeners should be triggered. + * + * @see Event::stopPropagation() + * + * @return bool Whether propagation was already stopped for this event + */ + public function isPropagationStopped() + { + return $this->propagationStopped; + } + + /** + * Stops the propagation of the event to further event listeners. + * + * If multiple event listeners are connected to the same event, no + * further event listener will be triggered once any trigger calls + * stopPropagation(). + */ + public function stopPropagation() + { + $this->propagationStopped = true; + } + + /** + * Stores the EventDispatcher that dispatches this Event. + * + * @param EventDispatcherInterface $dispatcher + * + * @deprecated since version 2.4, to be removed in 3.0. The event dispatcher is passed to the listener call. + */ + public function setDispatcher(EventDispatcherInterface $dispatcher) + { + $this->dispatcher = $dispatcher; + } + + /** + * Returns the EventDispatcher that dispatches this Event. + * + * @return EventDispatcherInterface + * + * @deprecated since version 2.4, to be removed in 3.0. The event dispatcher is passed to the listener call. + */ + public function getDispatcher() + { + @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.4 and will be removed in 3.0. The event dispatcher instance can be received in the listener call instead.', E_USER_DEPRECATED); + + return $this->dispatcher; + } + + /** + * Gets the event's name. + * + * @return string + * + * @deprecated since version 2.4, to be removed in 3.0. The event name is passed to the listener call. + */ + public function getName() + { + @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.4 and will be removed in 3.0. The event name can be received in the listener call instead.', E_USER_DEPRECATED); + + return $this->name; + } + + /** + * Sets the event's name property. + * + * @param string $name The event name + * + * @deprecated since version 2.4, to be removed in 3.0. The event name is passed to the listener call. + */ + public function setName($name) + { + $this->name = $name; + } +} diff --git a/src/bb-vendor/symfony/event-dispatcher/EventDispatcher.php b/src/bb-vendor/symfony/event-dispatcher/EventDispatcher.php new file mode 100644 index 000000000..b41b98e55 --- /dev/null +++ b/src/bb-vendor/symfony/event-dispatcher/EventDispatcher.php @@ -0,0 +1,198 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher; + +/** + * The EventDispatcherInterface is the central point of Symfony's event listener system. + * + * Listeners are registered on the manager and events are dispatched through the + * manager. + * + * @author Guilherme Blanco + * @author Jonathan Wage + * @author Roman Borschel + * @author Bernhard Schussek + * @author Fabien Potencier + * @author Jordi Boggiano + * @author Jordan Alliot + */ +class EventDispatcher implements EventDispatcherInterface +{ + private $listeners = array(); + private $sorted = array(); + + /** + * {@inheritdoc} + */ + public function dispatch($eventName, Event $event = null) + { + if (null === $event) { + $event = new Event(); + } + + $event->setDispatcher($this); + $event->setName($eventName); + + if ($listeners = $this->getListeners($eventName)) { + $this->doDispatch($listeners, $eventName, $event); + } + + return $event; + } + + /** + * {@inheritdoc} + */ + public function getListeners($eventName = null) + { + if (null !== $eventName) { + if (!isset($this->listeners[$eventName])) { + return array(); + } + + if (!isset($this->sorted[$eventName])) { + $this->sortListeners($eventName); + } + + return $this->sorted[$eventName]; + } + + foreach ($this->listeners as $eventName => $eventListeners) { + if (!isset($this->sorted[$eventName])) { + $this->sortListeners($eventName); + } + } + + return array_filter($this->sorted); + } + + /** + * Gets the listener priority for a specific event. + * + * Returns null if the event or the listener does not exist. + * + * @param string $eventName The name of the event + * @param callable $listener The listener + * + * @return int|null The event listener priority + */ + public function getListenerPriority($eventName, $listener) + { + if (!isset($this->listeners[$eventName])) { + return; + } + + foreach ($this->listeners[$eventName] as $priority => $listeners) { + if (false !== \in_array($listener, $listeners, true)) { + return $priority; + } + } + } + + /** + * {@inheritdoc} + */ + public function hasListeners($eventName = null) + { + return (bool) $this->getListeners($eventName); + } + + /** + * {@inheritdoc} + */ + public function addListener($eventName, $listener, $priority = 0) + { + $this->listeners[$eventName][$priority][] = $listener; + unset($this->sorted[$eventName]); + } + + /** + * {@inheritdoc} + */ + public function removeListener($eventName, $listener) + { + if (!isset($this->listeners[$eventName])) { + return; + } + + foreach ($this->listeners[$eventName] as $priority => $listeners) { + if (false !== ($key = array_search($listener, $listeners, true))) { + unset($this->listeners[$eventName][$priority][$key], $this->sorted[$eventName]); + } + } + } + + /** + * {@inheritdoc} + */ + public function addSubscriber(EventSubscriberInterface $subscriber) + { + foreach ($subscriber->getSubscribedEvents() as $eventName => $params) { + if (\is_string($params)) { + $this->addListener($eventName, array($subscriber, $params)); + } elseif (\is_string($params[0])) { + $this->addListener($eventName, array($subscriber, $params[0]), isset($params[1]) ? $params[1] : 0); + } else { + foreach ($params as $listener) { + $this->addListener($eventName, array($subscriber, $listener[0]), isset($listener[1]) ? $listener[1] : 0); + } + } + } + } + + /** + * {@inheritdoc} + */ + public function removeSubscriber(EventSubscriberInterface $subscriber) + { + foreach ($subscriber->getSubscribedEvents() as $eventName => $params) { + if (\is_array($params) && \is_array($params[0])) { + foreach ($params as $listener) { + $this->removeListener($eventName, array($subscriber, $listener[0])); + } + } else { + $this->removeListener($eventName, array($subscriber, \is_string($params) ? $params : $params[0])); + } + } + } + + /** + * Triggers the listeners of an event. + * + * This method can be overridden to add functionality that is executed + * for each listener. + * + * @param callable[] $listeners The event listeners + * @param string $eventName The name of the event to dispatch + * @param Event $event The event object to pass to the event handlers/listeners + */ + protected function doDispatch($listeners, $eventName, Event $event) + { + foreach ($listeners as $listener) { + if ($event->isPropagationStopped()) { + break; + } + \call_user_func($listener, $event, $eventName, $this); + } + } + + /** + * Sorts the internal list of listeners for the given event by priority. + * + * @param string $eventName The name of the event + */ + private function sortListeners($eventName) + { + krsort($this->listeners[$eventName]); + $this->sorted[$eventName] = \call_user_func_array('array_merge', $this->listeners[$eventName]); + } +} diff --git a/src/bb-vendor/symfony/event-dispatcher/EventDispatcherInterface.php b/src/bb-vendor/symfony/event-dispatcher/EventDispatcherInterface.php new file mode 100644 index 000000000..60160a90e --- /dev/null +++ b/src/bb-vendor/symfony/event-dispatcher/EventDispatcherInterface.php @@ -0,0 +1,81 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher; + +/** + * The EventDispatcherInterface is the central point of Symfony's event listener system. + * Listeners are registered on the manager and events are dispatched through the + * manager. + * + * @author Bernhard Schussek + */ +interface EventDispatcherInterface +{ + /** + * Dispatches an event to all registered listeners. + * + * @param string $eventName The name of the event to dispatch. The name of + * the event is the name of the method that is + * invoked on listeners. + * @param Event $event The event to pass to the event handlers/listeners + * If not supplied, an empty Event instance is created + * + * @return Event + */ + public function dispatch($eventName, Event $event = null); + + /** + * Adds an event listener that listens on the specified events. + * + * @param string $eventName The event to listen on + * @param callable $listener The listener + * @param int $priority The higher this value, the earlier an event + * listener will be triggered in the chain (defaults to 0) + */ + public function addListener($eventName, $listener, $priority = 0); + + /** + * Adds an event subscriber. + * + * The subscriber is asked for all the events he is + * interested in and added as a listener for these events. + */ + public function addSubscriber(EventSubscriberInterface $subscriber); + + /** + * Removes an event listener from the specified events. + * + * @param string $eventName The event to remove a listener from + * @param callable $listener The listener to remove + */ + public function removeListener($eventName, $listener); + + public function removeSubscriber(EventSubscriberInterface $subscriber); + + /** + * Gets the listeners of a specific event or all listeners sorted by descending priority. + * + * @param string $eventName The name of the event + * + * @return array The event listeners for the specified event, or all event listeners by event name + */ + public function getListeners($eventName = null); + + /** + * Checks whether an event has any registered listeners. + * + * @param string $eventName The name of the event + * + * @return bool true if the specified event has any listeners, false otherwise + */ + public function hasListeners($eventName = null); +} diff --git a/src/bb-vendor/symfony/event-dispatcher/EventSubscriberInterface.php b/src/bb-vendor/symfony/event-dispatcher/EventSubscriberInterface.php new file mode 100644 index 000000000..8af778919 --- /dev/null +++ b/src/bb-vendor/symfony/event-dispatcher/EventSubscriberInterface.php @@ -0,0 +1,46 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher; + +/** + * An EventSubscriber knows himself what events he is interested in. + * If an EventSubscriber is added to an EventDispatcherInterface, the manager invokes + * {@link getSubscribedEvents} and registers the subscriber as a listener for all + * returned events. + * + * @author Guilherme Blanco + * @author Jonathan Wage + * @author Roman Borschel + * @author Bernhard Schussek + */ +interface EventSubscriberInterface +{ + /** + * Returns an array of event names this subscriber wants to listen to. + * + * The array keys are event names and the value can be: + * + * * The method name to call (priority defaults to 0) + * * An array composed of the method name to call and the priority + * * An array of arrays composed of the method names to call and respective + * priorities, or 0 if unset + * + * For instance: + * + * * array('eventName' => 'methodName') + * * array('eventName' => array('methodName', $priority)) + * * array('eventName' => array(array('methodName1', $priority), array('methodName2'))) + * + * @return array The event names to listen to + */ + public static function getSubscribedEvents(); +} diff --git a/src/bb-vendor/symfony/event-dispatcher/GenericEvent.php b/src/bb-vendor/symfony/event-dispatcher/GenericEvent.php new file mode 100644 index 000000000..f0be7e18f --- /dev/null +++ b/src/bb-vendor/symfony/event-dispatcher/GenericEvent.php @@ -0,0 +1,175 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher; + +/** + * Event encapsulation class. + * + * Encapsulates events thus decoupling the observer from the subject they encapsulate. + * + * @author Drak + */ +class GenericEvent extends Event implements \ArrayAccess, \IteratorAggregate +{ + protected $subject; + protected $arguments; + + /** + * Encapsulate an event with $subject and $args. + * + * @param mixed $subject The subject of the event, usually an object or a callable + * @param array $arguments Arguments to store in the event + */ + public function __construct($subject = null, array $arguments = array()) + { + $this->subject = $subject; + $this->arguments = $arguments; + } + + /** + * Getter for subject property. + * + * @return mixed The observer subject + */ + public function getSubject() + { + return $this->subject; + } + + /** + * Get argument by key. + * + * @param string $key Key + * + * @return mixed Contents of array key + * + * @throws \InvalidArgumentException if key is not found + */ + public function getArgument($key) + { + if ($this->hasArgument($key)) { + return $this->arguments[$key]; + } + + throw new \InvalidArgumentException(sprintf('Argument "%s" not found.', $key)); + } + + /** + * Add argument to event. + * + * @param string $key Argument name + * @param mixed $value Value + * + * @return $this + */ + public function setArgument($key, $value) + { + $this->arguments[$key] = $value; + + return $this; + } + + /** + * Getter for all arguments. + * + * @return array + */ + public function getArguments() + { + return $this->arguments; + } + + /** + * Set args property. + * + * @param array $args Arguments + * + * @return $this + */ + public function setArguments(array $args = array()) + { + $this->arguments = $args; + + return $this; + } + + /** + * Has argument. + * + * @param string $key Key of arguments array + * + * @return bool + */ + public function hasArgument($key) + { + return array_key_exists($key, $this->arguments); + } + + /** + * ArrayAccess for argument getter. + * + * @param string $key Array key + * + * @return mixed + * + * @throws \InvalidArgumentException if key does not exist in $this->args + */ + public function offsetGet($key) + { + return $this->getArgument($key); + } + + /** + * ArrayAccess for argument setter. + * + * @param string $key Array key to set + * @param mixed $value Value + */ + public function offsetSet($key, $value) + { + $this->setArgument($key, $value); + } + + /** + * ArrayAccess for unset argument. + * + * @param string $key Array key + */ + public function offsetUnset($key) + { + if ($this->hasArgument($key)) { + unset($this->arguments[$key]); + } + } + + /** + * ArrayAccess has argument. + * + * @param string $key Array key + * + * @return bool + */ + public function offsetExists($key) + { + return $this->hasArgument($key); + } + + /** + * IteratorAggregate for iterating over the object like an array. + * + * @return \ArrayIterator + */ + public function getIterator() + { + return new \ArrayIterator($this->arguments); + } +} diff --git a/src/bb-vendor/symfony/event-dispatcher/ImmutableEventDispatcher.php b/src/bb-vendor/symfony/event-dispatcher/ImmutableEventDispatcher.php new file mode 100644 index 000000000..b3cf56c50 --- /dev/null +++ b/src/bb-vendor/symfony/event-dispatcher/ImmutableEventDispatcher.php @@ -0,0 +1,91 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher; + +/** + * A read-only proxy for an event dispatcher. + * + * @author Bernhard Schussek + */ +class ImmutableEventDispatcher implements EventDispatcherInterface +{ + private $dispatcher; + + public function __construct(EventDispatcherInterface $dispatcher) + { + $this->dispatcher = $dispatcher; + } + + /** + * {@inheritdoc} + */ + public function dispatch($eventName, Event $event = null) + { + return $this->dispatcher->dispatch($eventName, $event); + } + + /** + * {@inheritdoc} + */ + public function addListener($eventName, $listener, $priority = 0) + { + throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.'); + } + + /** + * {@inheritdoc} + */ + public function addSubscriber(EventSubscriberInterface $subscriber) + { + throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.'); + } + + /** + * {@inheritdoc} + */ + public function removeListener($eventName, $listener) + { + throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.'); + } + + /** + * {@inheritdoc} + */ + public function removeSubscriber(EventSubscriberInterface $subscriber) + { + throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.'); + } + + /** + * {@inheritdoc} + */ + public function getListeners($eventName = null) + { + return $this->dispatcher->getListeners($eventName); + } + + /** + * {@inheritdoc} + */ + public function getListenerPriority($eventName, $listener) + { + return $this->dispatcher->getListenerPriority($eventName, $listener); + } + + /** + * {@inheritdoc} + */ + public function hasListeners($eventName = null) + { + return $this->dispatcher->hasListeners($eventName); + } +} diff --git a/src/bb-vendor/symfony/event-dispatcher/LICENSE b/src/bb-vendor/symfony/event-dispatcher/LICENSE new file mode 100644 index 000000000..21d7fb9e2 --- /dev/null +++ b/src/bb-vendor/symfony/event-dispatcher/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2004-2018 Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/src/bb-vendor/symfony/event-dispatcher/README.md b/src/bb-vendor/symfony/event-dispatcher/README.md new file mode 100644 index 000000000..185c3fecf --- /dev/null +++ b/src/bb-vendor/symfony/event-dispatcher/README.md @@ -0,0 +1,15 @@ +EventDispatcher Component +========================= + +The EventDispatcher component provides tools that allow your application +components to communicate with each other by dispatching events and listening to +them. + +Resources +--------- + + * [Documentation](https://symfony.com/doc/current/components/event_dispatcher/index.html) + * [Contributing](https://symfony.com/doc/current/contributing/index.html) + * [Report issues](https://github.com/symfony/symfony/issues) and + [send Pull Requests](https://github.com/symfony/symfony/pulls) + in the [main Symfony repository](https://github.com/symfony/symfony) diff --git a/src/bb-vendor/symfony/event-dispatcher/Tests/AbstractEventDispatcherTest.php b/src/bb-vendor/symfony/event-dispatcher/Tests/AbstractEventDispatcherTest.php new file mode 100644 index 000000000..48de63213 --- /dev/null +++ b/src/bb-vendor/symfony/event-dispatcher/Tests/AbstractEventDispatcherTest.php @@ -0,0 +1,398 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher\Tests; + +use PHPUnit\Framework\TestCase; +use Symfony\Component\EventDispatcher\Event; +use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; + +abstract class AbstractEventDispatcherTest extends TestCase +{ + /* Some pseudo events */ + const preFoo = 'pre.foo'; + const postFoo = 'post.foo'; + const preBar = 'pre.bar'; + const postBar = 'post.bar'; + + /** + * @var EventDispatcher + */ + private $dispatcher; + + private $listener; + + protected function setUp() + { + $this->dispatcher = $this->createEventDispatcher(); + $this->listener = new TestEventListener(); + } + + protected function tearDown() + { + $this->dispatcher = null; + $this->listener = null; + } + + abstract protected function createEventDispatcher(); + + public function testInitialState() + { + $this->assertEquals(array(), $this->dispatcher->getListeners()); + $this->assertFalse($this->dispatcher->hasListeners(self::preFoo)); + $this->assertFalse($this->dispatcher->hasListeners(self::postFoo)); + } + + public function testAddListener() + { + $this->dispatcher->addListener('pre.foo', array($this->listener, 'preFoo')); + $this->dispatcher->addListener('post.foo', array($this->listener, 'postFoo')); + $this->assertTrue($this->dispatcher->hasListeners()); + $this->assertTrue($this->dispatcher->hasListeners(self::preFoo)); + $this->assertTrue($this->dispatcher->hasListeners(self::postFoo)); + $this->assertCount(1, $this->dispatcher->getListeners(self::preFoo)); + $this->assertCount(1, $this->dispatcher->getListeners(self::postFoo)); + $this->assertCount(2, $this->dispatcher->getListeners()); + } + + public function testGetListenersSortsByPriority() + { + $listener1 = new TestEventListener(); + $listener2 = new TestEventListener(); + $listener3 = new TestEventListener(); + $listener1->name = '1'; + $listener2->name = '2'; + $listener3->name = '3'; + + $this->dispatcher->addListener('pre.foo', array($listener1, 'preFoo'), -10); + $this->dispatcher->addListener('pre.foo', array($listener2, 'preFoo'), 10); + $this->dispatcher->addListener('pre.foo', array($listener3, 'preFoo')); + + $expected = array( + array($listener2, 'preFoo'), + array($listener3, 'preFoo'), + array($listener1, 'preFoo'), + ); + + $this->assertSame($expected, $this->dispatcher->getListeners('pre.foo')); + } + + public function testGetAllListenersSortsByPriority() + { + $listener1 = new TestEventListener(); + $listener2 = new TestEventListener(); + $listener3 = new TestEventListener(); + $listener4 = new TestEventListener(); + $listener5 = new TestEventListener(); + $listener6 = new TestEventListener(); + + $this->dispatcher->addListener('pre.foo', $listener1, -10); + $this->dispatcher->addListener('pre.foo', $listener2); + $this->dispatcher->addListener('pre.foo', $listener3, 10); + $this->dispatcher->addListener('post.foo', $listener4, -10); + $this->dispatcher->addListener('post.foo', $listener5); + $this->dispatcher->addListener('post.foo', $listener6, 10); + + $expected = array( + 'pre.foo' => array($listener3, $listener2, $listener1), + 'post.foo' => array($listener6, $listener5, $listener4), + ); + + $this->assertSame($expected, $this->dispatcher->getListeners()); + } + + public function testGetListenerPriority() + { + $listener1 = new TestEventListener(); + $listener2 = new TestEventListener(); + + $this->dispatcher->addListener('pre.foo', $listener1, -10); + $this->dispatcher->addListener('pre.foo', $listener2); + + $this->assertSame(-10, $this->dispatcher->getListenerPriority('pre.foo', $listener1)); + $this->assertSame(0, $this->dispatcher->getListenerPriority('pre.foo', $listener2)); + $this->assertNull($this->dispatcher->getListenerPriority('pre.bar', $listener2)); + $this->assertNull($this->dispatcher->getListenerPriority('pre.foo', function () {})); + } + + public function testDispatch() + { + $this->dispatcher->addListener('pre.foo', array($this->listener, 'preFoo')); + $this->dispatcher->addListener('post.foo', array($this->listener, 'postFoo')); + $this->dispatcher->dispatch(self::preFoo); + $this->assertTrue($this->listener->preFooInvoked); + $this->assertFalse($this->listener->postFooInvoked); + $this->assertInstanceOf('Symfony\Component\EventDispatcher\Event', $this->dispatcher->dispatch('noevent')); + $this->assertInstanceOf('Symfony\Component\EventDispatcher\Event', $this->dispatcher->dispatch(self::preFoo)); + $event = new Event(); + $return = $this->dispatcher->dispatch(self::preFoo, $event); + $this->assertSame($event, $return); + } + + /** + * @group legacy + */ + public function testLegacyDispatch() + { + $event = new Event(); + $this->dispatcher->dispatch(self::preFoo, $event); + $this->assertEquals('pre.foo', $event->getName()); + } + + public function testDispatchForClosure() + { + $invoked = 0; + $listener = function () use (&$invoked) { + ++$invoked; + }; + $this->dispatcher->addListener('pre.foo', $listener); + $this->dispatcher->addListener('post.foo', $listener); + $this->dispatcher->dispatch(self::preFoo); + $this->assertEquals(1, $invoked); + } + + public function testStopEventPropagation() + { + $otherListener = new TestEventListener(); + + // postFoo() stops the propagation, so only one listener should + // be executed + // Manually set priority to enforce $this->listener to be called first + $this->dispatcher->addListener('post.foo', array($this->listener, 'postFoo'), 10); + $this->dispatcher->addListener('post.foo', array($otherListener, 'postFoo')); + $this->dispatcher->dispatch(self::postFoo); + $this->assertTrue($this->listener->postFooInvoked); + $this->assertFalse($otherListener->postFooInvoked); + } + + public function testDispatchByPriority() + { + $invoked = array(); + $listener1 = function () use (&$invoked) { + $invoked[] = '1'; + }; + $listener2 = function () use (&$invoked) { + $invoked[] = '2'; + }; + $listener3 = function () use (&$invoked) { + $invoked[] = '3'; + }; + $this->dispatcher->addListener('pre.foo', $listener1, -10); + $this->dispatcher->addListener('pre.foo', $listener2); + $this->dispatcher->addListener('pre.foo', $listener3, 10); + $this->dispatcher->dispatch(self::preFoo); + $this->assertEquals(array('3', '2', '1'), $invoked); + } + + public function testRemoveListener() + { + $this->dispatcher->addListener('pre.bar', $this->listener); + $this->assertTrue($this->dispatcher->hasListeners(self::preBar)); + $this->dispatcher->removeListener('pre.bar', $this->listener); + $this->assertFalse($this->dispatcher->hasListeners(self::preBar)); + $this->dispatcher->removeListener('notExists', $this->listener); + } + + public function testAddSubscriber() + { + $eventSubscriber = new TestEventSubscriber(); + $this->dispatcher->addSubscriber($eventSubscriber); + $this->assertTrue($this->dispatcher->hasListeners(self::preFoo)); + $this->assertTrue($this->dispatcher->hasListeners(self::postFoo)); + } + + public function testAddSubscriberWithPriorities() + { + $eventSubscriber = new TestEventSubscriber(); + $this->dispatcher->addSubscriber($eventSubscriber); + + $eventSubscriber = new TestEventSubscriberWithPriorities(); + $this->dispatcher->addSubscriber($eventSubscriber); + + $listeners = $this->dispatcher->getListeners('pre.foo'); + $this->assertTrue($this->dispatcher->hasListeners(self::preFoo)); + $this->assertCount(2, $listeners); + $this->assertInstanceOf('Symfony\Component\EventDispatcher\Tests\TestEventSubscriberWithPriorities', $listeners[0][0]); + } + + public function testAddSubscriberWithMultipleListeners() + { + $eventSubscriber = new TestEventSubscriberWithMultipleListeners(); + $this->dispatcher->addSubscriber($eventSubscriber); + + $listeners = $this->dispatcher->getListeners('pre.foo'); + $this->assertTrue($this->dispatcher->hasListeners(self::preFoo)); + $this->assertCount(2, $listeners); + $this->assertEquals('preFoo2', $listeners[0][1]); + } + + public function testRemoveSubscriber() + { + $eventSubscriber = new TestEventSubscriber(); + $this->dispatcher->addSubscriber($eventSubscriber); + $this->assertTrue($this->dispatcher->hasListeners(self::preFoo)); + $this->assertTrue($this->dispatcher->hasListeners(self::postFoo)); + $this->dispatcher->removeSubscriber($eventSubscriber); + $this->assertFalse($this->dispatcher->hasListeners(self::preFoo)); + $this->assertFalse($this->dispatcher->hasListeners(self::postFoo)); + } + + public function testRemoveSubscriberWithPriorities() + { + $eventSubscriber = new TestEventSubscriberWithPriorities(); + $this->dispatcher->addSubscriber($eventSubscriber); + $this->assertTrue($this->dispatcher->hasListeners(self::preFoo)); + $this->dispatcher->removeSubscriber($eventSubscriber); + $this->assertFalse($this->dispatcher->hasListeners(self::preFoo)); + } + + public function testRemoveSubscriberWithMultipleListeners() + { + $eventSubscriber = new TestEventSubscriberWithMultipleListeners(); + $this->dispatcher->addSubscriber($eventSubscriber); + $this->assertTrue($this->dispatcher->hasListeners(self::preFoo)); + $this->assertCount(2, $this->dispatcher->getListeners(self::preFoo)); + $this->dispatcher->removeSubscriber($eventSubscriber); + $this->assertFalse($this->dispatcher->hasListeners(self::preFoo)); + } + + /** + * @group legacy + */ + public function testLegacyEventReceivesTheDispatcherInstance() + { + $dispatcher = null; + $this->dispatcher->addListener('test', function ($event) use (&$dispatcher) { + $dispatcher = $event->getDispatcher(); + }); + $this->dispatcher->dispatch('test'); + $this->assertSame($this->dispatcher, $dispatcher); + } + + public function testEventReceivesTheDispatcherInstanceAsArgument() + { + $listener = new TestWithDispatcher(); + $this->dispatcher->addListener('test', array($listener, 'foo')); + $this->assertNull($listener->name); + $this->assertNull($listener->dispatcher); + $this->dispatcher->dispatch('test'); + $this->assertEquals('test', $listener->name); + $this->assertSame($this->dispatcher, $listener->dispatcher); + } + + /** + * @see https://bugs.php.net/bug.php?id=62976 + * + * This bug affects: + * - The PHP 5.3 branch for versions < 5.3.18 + * - The PHP 5.4 branch for versions < 5.4.8 + * - The PHP 5.5 branch is not affected + */ + public function testWorkaroundForPhpBug62976() + { + $dispatcher = $this->createEventDispatcher(); + $dispatcher->addListener('bug.62976', new CallableClass()); + $dispatcher->removeListener('bug.62976', function () {}); + $this->assertTrue($dispatcher->hasListeners('bug.62976')); + } + + public function testHasListenersWhenAddedCallbackListenerIsRemoved() + { + $listener = function () {}; + $this->dispatcher->addListener('foo', $listener); + $this->dispatcher->removeListener('foo', $listener); + $this->assertFalse($this->dispatcher->hasListeners()); + } + + public function testGetListenersWhenAddedCallbackListenerIsRemoved() + { + $listener = function () {}; + $this->dispatcher->addListener('foo', $listener); + $this->dispatcher->removeListener('foo', $listener); + $this->assertSame(array(), $this->dispatcher->getListeners()); + } + + public function testHasListenersWithoutEventsReturnsFalseAfterHasListenersWithEventHasBeenCalled() + { + $this->assertFalse($this->dispatcher->hasListeners('foo')); + $this->assertFalse($this->dispatcher->hasListeners()); + } +} + +class CallableClass +{ + public function __invoke() + { + } +} + +class TestEventListener +{ + public $preFooInvoked = false; + public $postFooInvoked = false; + + /* Listener methods */ + + public function preFoo(Event $e) + { + $this->preFooInvoked = true; + } + + public function postFoo(Event $e) + { + $this->postFooInvoked = true; + + $e->stopPropagation(); + } +} + +class TestWithDispatcher +{ + public $name; + public $dispatcher; + + public function foo(Event $e, $name, $dispatcher) + { + $this->name = $name; + $this->dispatcher = $dispatcher; + } +} + +class TestEventSubscriber implements EventSubscriberInterface +{ + public static function getSubscribedEvents() + { + return array('pre.foo' => 'preFoo', 'post.foo' => 'postFoo'); + } +} + +class TestEventSubscriberWithPriorities implements EventSubscriberInterface +{ + public static function getSubscribedEvents() + { + return array( + 'pre.foo' => array('preFoo', 10), + 'post.foo' => array('postFoo'), + ); + } +} + +class TestEventSubscriberWithMultipleListeners implements EventSubscriberInterface +{ + public static function getSubscribedEvents() + { + return array('pre.foo' => array( + array('preFoo1'), + array('preFoo2', 10), + )); + } +} diff --git a/src/bb-vendor/symfony/event-dispatcher/Tests/ContainerAwareEventDispatcherTest.php b/src/bb-vendor/symfony/event-dispatcher/Tests/ContainerAwareEventDispatcherTest.php new file mode 100644 index 000000000..224a292c4 --- /dev/null +++ b/src/bb-vendor/symfony/event-dispatcher/Tests/ContainerAwareEventDispatcherTest.php @@ -0,0 +1,277 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher\Tests; + +use Symfony\Component\DependencyInjection\Container; +use Symfony\Component\DependencyInjection\Scope; +use Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher; +use Symfony\Component\EventDispatcher\Event; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; + +class ContainerAwareEventDispatcherTest extends AbstractEventDispatcherTest +{ + protected function createEventDispatcher() + { + $container = new Container(); + + return new ContainerAwareEventDispatcher($container); + } + + public function testAddAListenerService() + { + $event = new Event(); + + $service = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\Service')->getMock(); + + $service + ->expects($this->once()) + ->method('onEvent') + ->with($event) + ; + + $container = new Container(); + $container->set('service.listener', $service); + + $dispatcher = new ContainerAwareEventDispatcher($container); + $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent')); + + $dispatcher->dispatch('onEvent', $event); + } + + public function testAddASubscriberService() + { + $event = new Event(); + + $service = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\SubscriberService')->getMock(); + + $service + ->expects($this->once()) + ->method('onEvent') + ->with($event) + ; + + $service + ->expects($this->once()) + ->method('onEventWithPriority') + ->with($event) + ; + + $service + ->expects($this->once()) + ->method('onEventNested') + ->with($event) + ; + + $container = new Container(); + $container->set('service.subscriber', $service); + + $dispatcher = new ContainerAwareEventDispatcher($container); + $dispatcher->addSubscriberService('service.subscriber', 'Symfony\Component\EventDispatcher\Tests\SubscriberService'); + + $dispatcher->dispatch('onEvent', $event); + $dispatcher->dispatch('onEventWithPriority', $event); + $dispatcher->dispatch('onEventNested', $event); + } + + public function testPreventDuplicateListenerService() + { + $event = new Event(); + + $service = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\Service')->getMock(); + + $service + ->expects($this->once()) + ->method('onEvent') + ->with($event) + ; + + $container = new Container(); + $container->set('service.listener', $service); + + $dispatcher = new ContainerAwareEventDispatcher($container); + $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'), 5); + $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'), 10); + + $dispatcher->dispatch('onEvent', $event); + } + + /** + * @expectedException \InvalidArgumentException + * @group legacy + */ + public function testTriggerAListenerServiceOutOfScope() + { + $service = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\Service')->getMock(); + + $scope = new Scope('scope'); + $container = new Container(); + $container->addScope($scope); + $container->enterScope('scope'); + + $container->set('service.listener', $service, 'scope'); + + $dispatcher = new ContainerAwareEventDispatcher($container); + $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent')); + + $container->leaveScope('scope'); + $dispatcher->dispatch('onEvent'); + } + + /** + * @group legacy + */ + public function testReEnteringAScope() + { + $event = new Event(); + + $service1 = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\Service')->getMock(); + + $service1 + ->expects($this->exactly(2)) + ->method('onEvent') + ->with($event) + ; + + $scope = new Scope('scope'); + $container = new Container(); + $container->addScope($scope); + $container->enterScope('scope'); + + $container->set('service.listener', $service1, 'scope'); + + $dispatcher = new ContainerAwareEventDispatcher($container); + $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent')); + $dispatcher->dispatch('onEvent', $event); + + $service2 = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\Service')->getMock(); + + $service2 + ->expects($this->once()) + ->method('onEvent') + ->with($event) + ; + + $container->enterScope('scope'); + $container->set('service.listener', $service2, 'scope'); + + $dispatcher->dispatch('onEvent', $event); + + $container->leaveScope('scope'); + + $dispatcher->dispatch('onEvent'); + } + + public function testHasListenersOnLazyLoad() + { + $event = new Event(); + + $service = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\Service')->getMock(); + + $container = new Container(); + $container->set('service.listener', $service); + + $dispatcher = new ContainerAwareEventDispatcher($container); + $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent')); + + $event->setDispatcher($dispatcher); + $event->setName('onEvent'); + + $service + ->expects($this->once()) + ->method('onEvent') + ->with($event) + ; + + $this->assertTrue($dispatcher->hasListeners()); + + if ($dispatcher->hasListeners('onEvent')) { + $dispatcher->dispatch('onEvent'); + } + } + + public function testGetListenersOnLazyLoad() + { + $service = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\Service')->getMock(); + + $container = new Container(); + $container->set('service.listener', $service); + + $dispatcher = new ContainerAwareEventDispatcher($container); + $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent')); + + $listeners = $dispatcher->getListeners(); + + $this->assertArrayHasKey('onEvent', $listeners); + + $this->assertCount(1, $dispatcher->getListeners('onEvent')); + } + + public function testRemoveAfterDispatch() + { + $service = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\Service')->getMock(); + + $container = new Container(); + $container->set('service.listener', $service); + + $dispatcher = new ContainerAwareEventDispatcher($container); + $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent')); + + $dispatcher->dispatch('onEvent', new Event()); + $dispatcher->removeListener('onEvent', array($container->get('service.listener'), 'onEvent')); + $this->assertFalse($dispatcher->hasListeners('onEvent')); + } + + public function testRemoveBeforeDispatch() + { + $service = $this->getMockBuilder('Symfony\Component\EventDispatcher\Tests\Service')->getMock(); + + $container = new Container(); + $container->set('service.listener', $service); + + $dispatcher = new ContainerAwareEventDispatcher($container); + $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent')); + + $dispatcher->removeListener('onEvent', array($container->get('service.listener'), 'onEvent')); + $this->assertFalse($dispatcher->hasListeners('onEvent')); + } +} + +class Service +{ + public function onEvent(Event $e) + { + } +} + +class SubscriberService implements EventSubscriberInterface +{ + public static function getSubscribedEvents() + { + return array( + 'onEvent' => 'onEvent', + 'onEventWithPriority' => array('onEventWithPriority', 10), + 'onEventNested' => array(array('onEventNested')), + ); + } + + public function onEvent(Event $e) + { + } + + public function onEventWithPriority(Event $e) + { + } + + public function onEventNested(Event $e) + { + } +} diff --git a/src/bb-vendor/symfony/event-dispatcher/Tests/Debug/TraceableEventDispatcherTest.php b/src/bb-vendor/symfony/event-dispatcher/Tests/Debug/TraceableEventDispatcherTest.php new file mode 100644 index 000000000..ffdda383f --- /dev/null +++ b/src/bb-vendor/symfony/event-dispatcher/Tests/Debug/TraceableEventDispatcherTest.php @@ -0,0 +1,254 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher\Tests\Debug; + +use PHPUnit\Framework\TestCase; +use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher; +use Symfony\Component\EventDispatcher\Debug\WrappedListener; +use Symfony\Component\EventDispatcher\Event; +use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\Stopwatch\Stopwatch; + +class TraceableEventDispatcherTest extends TestCase +{ + public function testAddRemoveListener() + { + $dispatcher = new EventDispatcher(); + $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch()); + + $tdispatcher->addListener('foo', $listener = function () {}); + $listeners = $dispatcher->getListeners('foo'); + $this->assertCount(1, $listeners); + $this->assertSame($listener, $listeners[0]); + + $tdispatcher->removeListener('foo', $listener); + $this->assertCount(0, $dispatcher->getListeners('foo')); + } + + public function testGetListeners() + { + $dispatcher = new EventDispatcher(); + $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch()); + + $tdispatcher->addListener('foo', $listener = function () {}); + $this->assertSame($dispatcher->getListeners('foo'), $tdispatcher->getListeners('foo')); + } + + public function testHasListeners() + { + $dispatcher = new EventDispatcher(); + $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch()); + + $this->assertFalse($dispatcher->hasListeners('foo')); + $this->assertFalse($tdispatcher->hasListeners('foo')); + + $tdispatcher->addListener('foo', $listener = function () {}); + $this->assertTrue($dispatcher->hasListeners('foo')); + $this->assertTrue($tdispatcher->hasListeners('foo')); + } + + public function testGetListenerPriority() + { + $dispatcher = new EventDispatcher(); + $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch()); + + $tdispatcher->addListener('foo', function () {}, 123); + + $listeners = $dispatcher->getListeners('foo'); + $this->assertSame(123, $tdispatcher->getListenerPriority('foo', $listeners[0])); + + // Verify that priority is preserved when listener is removed and re-added + // in preProcess() and postProcess(). + $tdispatcher->dispatch('foo', new Event()); + $listeners = $dispatcher->getListeners('foo'); + $this->assertSame(123, $tdispatcher->getListenerPriority('foo', $listeners[0])); + } + + public function testGetListenerPriorityReturnsZeroWhenWrappedMethodDoesNotExist() + { + $dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock(); + $traceableEventDispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch()); + $traceableEventDispatcher->addListener('foo', function () {}, 123); + $listeners = $traceableEventDispatcher->getListeners('foo'); + + $this->assertSame(0, $traceableEventDispatcher->getListenerPriority('foo', $listeners[0])); + } + + public function testAddRemoveSubscriber() + { + $dispatcher = new EventDispatcher(); + $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch()); + + $subscriber = new EventSubscriber(); + + $tdispatcher->addSubscriber($subscriber); + $listeners = $dispatcher->getListeners('foo'); + $this->assertCount(1, $listeners); + $this->assertSame(array($subscriber, 'call'), $listeners[0]); + + $tdispatcher->removeSubscriber($subscriber); + $this->assertCount(0, $dispatcher->getListeners('foo')); + } + + /** + * @dataProvider isWrappedDataProvider + * + * @param bool $isWrapped + */ + public function testGetCalledListeners($isWrapped) + { + $dispatcher = new EventDispatcher(); + $stopWatch = new Stopwatch(); + $tdispatcher = new TraceableEventDispatcher($dispatcher, $stopWatch); + + $listener = function () {}; + if ($isWrapped) { + $listener = new WrappedListener($listener, 'foo', $stopWatch, $dispatcher); + } + + $tdispatcher->addListener('foo', $listener, 5); + + $this->assertEquals(array(), $tdispatcher->getCalledListeners()); + $this->assertEquals(array('foo.closure' => array('event' => 'foo', 'type' => 'Closure', 'pretty' => 'closure', 'priority' => 5)), $tdispatcher->getNotCalledListeners()); + + $tdispatcher->dispatch('foo'); + + $this->assertEquals(array('foo.closure' => array('event' => 'foo', 'type' => 'Closure', 'pretty' => 'closure', 'priority' => 5)), $tdispatcher->getCalledListeners()); + $this->assertEquals(array(), $tdispatcher->getNotCalledListeners()); + } + + public function isWrappedDataProvider() + { + return array( + array(false), + array(true), + ); + } + + public function testGetCalledListenersNested() + { + $tdispatcher = null; + $dispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); + $dispatcher->addListener('foo', function (Event $event, $eventName, $dispatcher) use (&$tdispatcher) { + $tdispatcher = $dispatcher; + $dispatcher->dispatch('bar'); + }); + $dispatcher->addListener('bar', function (Event $event) {}); + $dispatcher->dispatch('foo'); + $this->assertSame($dispatcher, $tdispatcher); + $this->assertCount(2, $dispatcher->getCalledListeners()); + } + + public function testLogger() + { + $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock(); + + $dispatcher = new EventDispatcher(); + $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch(), $logger); + $tdispatcher->addListener('foo', $listener1 = function () {}); + $tdispatcher->addListener('foo', $listener2 = function () {}); + + $logger->expects($this->at(0))->method('debug')->with('Notified event "foo" to listener "closure".'); + $logger->expects($this->at(1))->method('debug')->with('Notified event "foo" to listener "closure".'); + + $tdispatcher->dispatch('foo'); + } + + public function testLoggerWithStoppedEvent() + { + $logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock(); + + $dispatcher = new EventDispatcher(); + $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch(), $logger); + $tdispatcher->addListener('foo', $listener1 = function (Event $event) { $event->stopPropagation(); }); + $tdispatcher->addListener('foo', $listener2 = function () {}); + + $logger->expects($this->at(0))->method('debug')->with('Notified event "foo" to listener "closure".'); + $logger->expects($this->at(1))->method('debug')->with('Listener "closure" stopped propagation of the event "foo".'); + $logger->expects($this->at(2))->method('debug')->with('Listener "closure" was not called for event "foo".'); + + $tdispatcher->dispatch('foo'); + } + + public function testDispatchCallListeners() + { + $called = array(); + + $dispatcher = new EventDispatcher(); + $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch()); + $tdispatcher->addListener('foo', function () use (&$called) { $called[] = 'foo1'; }, 10); + $tdispatcher->addListener('foo', function () use (&$called) { $called[] = 'foo2'; }, 20); + + $tdispatcher->dispatch('foo'); + + $this->assertSame(array('foo2', 'foo1'), $called); + } + + public function testDispatchNested() + { + $dispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); + $loop = 1; + $dispatchedEvents = 0; + $dispatcher->addListener('foo', $listener1 = function () use ($dispatcher, &$loop) { + ++$loop; + if (2 == $loop) { + $dispatcher->dispatch('foo'); + } + }); + $dispatcher->addListener('foo', function () use (&$dispatchedEvents) { + ++$dispatchedEvents; + }); + + $dispatcher->dispatch('foo'); + + $this->assertSame(2, $dispatchedEvents); + } + + public function testDispatchReusedEventNested() + { + $nestedCall = false; + $dispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); + $dispatcher->addListener('foo', function (Event $e) use ($dispatcher) { + $dispatcher->dispatch('bar', $e); + }); + $dispatcher->addListener('bar', function (Event $e) use (&$nestedCall) { + $nestedCall = true; + }); + + $this->assertFalse($nestedCall); + $dispatcher->dispatch('foo'); + $this->assertTrue($nestedCall); + } + + public function testListenerCanRemoveItselfWhenExecuted() + { + $eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); + $listener1 = function ($event, $eventName, EventDispatcherInterface $dispatcher) use (&$listener1) { + $dispatcher->removeListener('foo', $listener1); + }; + $eventDispatcher->addListener('foo', $listener1); + $eventDispatcher->addListener('foo', function () {}); + $eventDispatcher->dispatch('foo'); + + $this->assertCount(1, $eventDispatcher->getListeners('foo'), 'expected listener1 to be removed'); + } +} + +class EventSubscriber implements EventSubscriberInterface +{ + public static function getSubscribedEvents() + { + return array('foo' => 'call'); + } +} diff --git a/src/bb-vendor/symfony/event-dispatcher/Tests/DependencyInjection/RegisterListenersPassTest.php b/src/bb-vendor/symfony/event-dispatcher/Tests/DependencyInjection/RegisterListenersPassTest.php new file mode 100644 index 000000000..7490d0d25 --- /dev/null +++ b/src/bb-vendor/symfony/event-dispatcher/Tests/DependencyInjection/RegisterListenersPassTest.php @@ -0,0 +1,154 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher\Tests\DependencyInjection; + +use PHPUnit\Framework\TestCase; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass; + +class RegisterListenersPassTest extends TestCase +{ + /** + * Tests that event subscribers not implementing EventSubscriberInterface + * trigger an exception. + * + * @expectedException \InvalidArgumentException + */ + public function testEventSubscriberWithoutInterface() + { + $builder = new ContainerBuilder(); + $builder->register('event_dispatcher'); + $builder->register('my_event_subscriber', 'stdClass') + ->addTag('kernel.event_subscriber'); + + $registerListenersPass = new RegisterListenersPass(); + $registerListenersPass->process($builder); + } + + public function testValidEventSubscriber() + { + $services = array( + 'my_event_subscriber' => array(0 => array()), + ); + + $builder = new ContainerBuilder(); + $eventDispatcherDefinition = $builder->register('event_dispatcher'); + $builder->register('my_event_subscriber', 'Symfony\Component\EventDispatcher\Tests\DependencyInjection\SubscriberService') + ->addTag('kernel.event_subscriber'); + + $registerListenersPass = new RegisterListenersPass(); + $registerListenersPass->process($builder); + + $this->assertEquals(array(array('addSubscriberService', array('my_event_subscriber', 'Symfony\Component\EventDispatcher\Tests\DependencyInjection\SubscriberService'))), $eventDispatcherDefinition->getMethodCalls()); + } + + /** + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage The service "foo" must be public as event listeners are lazy-loaded. + */ + public function testPrivateEventListener() + { + $container = new ContainerBuilder(); + $container->register('foo', 'stdClass')->setPublic(false)->addTag('kernel.event_listener', array()); + $container->register('event_dispatcher', 'stdClass'); + + $registerListenersPass = new RegisterListenersPass(); + $registerListenersPass->process($container); + } + + /** + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage The service "foo" must be public as event subscribers are lazy-loaded. + */ + public function testPrivateEventSubscriber() + { + $container = new ContainerBuilder(); + $container->register('foo', 'stdClass')->setPublic(false)->addTag('kernel.event_subscriber', array()); + $container->register('event_dispatcher', 'stdClass'); + + $registerListenersPass = new RegisterListenersPass(); + $registerListenersPass->process($container); + } + + /** + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage The service "foo" must not be abstract as event listeners are lazy-loaded. + */ + public function testAbstractEventListener() + { + $container = new ContainerBuilder(); + $container->register('foo', 'stdClass')->setAbstract(true)->addTag('kernel.event_listener', array()); + $container->register('event_dispatcher', 'stdClass'); + + $registerListenersPass = new RegisterListenersPass(); + $registerListenersPass->process($container); + } + + /** + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage The service "foo" must not be abstract as event subscribers are lazy-loaded. + */ + public function testAbstractEventSubscriber() + { + $container = new ContainerBuilder(); + $container->register('foo', 'stdClass')->setAbstract(true)->addTag('kernel.event_subscriber', array()); + $container->register('event_dispatcher', 'stdClass'); + + $registerListenersPass = new RegisterListenersPass(); + $registerListenersPass->process($container); + } + + public function testEventSubscriberResolvableClassName() + { + $container = new ContainerBuilder(); + + $container->setParameter('subscriber.class', 'Symfony\Component\EventDispatcher\Tests\DependencyInjection\SubscriberService'); + $container->register('foo', '%subscriber.class%')->addTag('kernel.event_subscriber', array()); + $container->register('event_dispatcher', 'stdClass'); + + $registerListenersPass = new RegisterListenersPass(); + $registerListenersPass->process($container); + + $definition = $container->getDefinition('event_dispatcher'); + $expected_calls = array( + array( + 'addSubscriberService', + array( + 'foo', + 'Symfony\Component\EventDispatcher\Tests\DependencyInjection\SubscriberService', + ), + ), + ); + $this->assertSame($expected_calls, $definition->getMethodCalls()); + } + + /** + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage You have requested a non-existent parameter "subscriber.class" + */ + public function testEventSubscriberUnresolvableClassName() + { + $container = new ContainerBuilder(); + $container->register('foo', '%subscriber.class%')->addTag('kernel.event_subscriber', array()); + $container->register('event_dispatcher', 'stdClass'); + + $registerListenersPass = new RegisterListenersPass(); + $registerListenersPass->process($container); + } +} + +class SubscriberService implements \Symfony\Component\EventDispatcher\EventSubscriberInterface +{ + public static function getSubscribedEvents() + { + } +} diff --git a/src/bb-vendor/symfony/event-dispatcher/Tests/EventDispatcherTest.php b/src/bb-vendor/symfony/event-dispatcher/Tests/EventDispatcherTest.php new file mode 100644 index 000000000..5faa5c8be --- /dev/null +++ b/src/bb-vendor/symfony/event-dispatcher/Tests/EventDispatcherTest.php @@ -0,0 +1,22 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher\Tests; + +use Symfony\Component\EventDispatcher\EventDispatcher; + +class EventDispatcherTest extends AbstractEventDispatcherTest +{ + protected function createEventDispatcher() + { + return new EventDispatcher(); + } +} diff --git a/src/bb-vendor/symfony/event-dispatcher/Tests/EventTest.php b/src/bb-vendor/symfony/event-dispatcher/Tests/EventTest.php new file mode 100644 index 000000000..bdc14abbf --- /dev/null +++ b/src/bb-vendor/symfony/event-dispatcher/Tests/EventTest.php @@ -0,0 +1,97 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher\Tests; + +use PHPUnit\Framework\TestCase; +use Symfony\Component\EventDispatcher\Event; +use Symfony\Component\EventDispatcher\EventDispatcher; + +/** + * Test class for Event. + */ +class EventTest extends TestCase +{ + /** + * @var \Symfony\Component\EventDispatcher\Event + */ + protected $event; + + /** + * @var \Symfony\Component\EventDispatcher\EventDispatcher + */ + protected $dispatcher; + + /** + * Sets up the fixture, for example, opens a network connection. + * This method is called before a test is executed. + */ + protected function setUp() + { + $this->event = new Event(); + $this->dispatcher = new EventDispatcher(); + } + + /** + * Tears down the fixture, for example, closes a network connection. + * This method is called after a test is executed. + */ + protected function tearDown() + { + $this->event = null; + $this->dispatcher = null; + } + + public function testIsPropagationStopped() + { + $this->assertFalse($this->event->isPropagationStopped()); + } + + public function testStopPropagationAndIsPropagationStopped() + { + $this->event->stopPropagation(); + $this->assertTrue($this->event->isPropagationStopped()); + } + + /** + * @group legacy + */ + public function testLegacySetDispatcher() + { + $this->event->setDispatcher($this->dispatcher); + $this->assertSame($this->dispatcher, $this->event->getDispatcher()); + } + + /** + * @group legacy + */ + public function testLegacyGetDispatcher() + { + $this->assertNull($this->event->getDispatcher()); + } + + /** + * @group legacy + */ + public function testLegacyGetName() + { + $this->assertNull($this->event->getName()); + } + + /** + * @group legacy + */ + public function testLegacySetName() + { + $this->event->setName('foo'); + $this->assertEquals('foo', $this->event->getName()); + } +} diff --git a/src/bb-vendor/symfony/event-dispatcher/Tests/GenericEventTest.php b/src/bb-vendor/symfony/event-dispatcher/Tests/GenericEventTest.php new file mode 100644 index 000000000..b63f69df1 --- /dev/null +++ b/src/bb-vendor/symfony/event-dispatcher/Tests/GenericEventTest.php @@ -0,0 +1,136 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher\Tests; + +use PHPUnit\Framework\TestCase; +use Symfony\Component\EventDispatcher\GenericEvent; + +/** + * Test class for Event. + */ +class GenericEventTest extends TestCase +{ + /** + * @var GenericEvent + */ + private $event; + + private $subject; + + /** + * Prepares the environment before running a test. + */ + protected function setUp() + { + $this->subject = new \stdClass(); + $this->event = new GenericEvent($this->subject, array('name' => 'Event')); + } + + /** + * Cleans up the environment after running a test. + */ + protected function tearDown() + { + $this->subject = null; + $this->event = null; + } + + public function testConstruct() + { + $this->assertEquals($this->event, new GenericEvent($this->subject, array('name' => 'Event'))); + } + + /** + * Tests Event->getArgs(). + */ + public function testGetArguments() + { + // test getting all + $this->assertSame(array('name' => 'Event'), $this->event->getArguments()); + } + + public function testSetArguments() + { + $result = $this->event->setArguments(array('foo' => 'bar')); + $this->assertAttributeSame(array('foo' => 'bar'), 'arguments', $this->event); + $this->assertSame($this->event, $result); + } + + public function testSetArgument() + { + $result = $this->event->setArgument('foo2', 'bar2'); + $this->assertAttributeSame(array('name' => 'Event', 'foo2' => 'bar2'), 'arguments', $this->event); + $this->assertEquals($this->event, $result); + } + + public function testGetArgument() + { + // test getting key + $this->assertEquals('Event', $this->event->getArgument('name')); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testGetArgException() + { + $this->event->getArgument('nameNotExist'); + } + + public function testOffsetGet() + { + // test getting key + $this->assertEquals('Event', $this->event['name']); + + // test getting invalid arg + $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('InvalidArgumentException'); + $this->assertFalse($this->event['nameNotExist']); + } + + public function testOffsetSet() + { + $this->event['foo2'] = 'bar2'; + $this->assertAttributeSame(array('name' => 'Event', 'foo2' => 'bar2'), 'arguments', $this->event); + } + + public function testOffsetUnset() + { + unset($this->event['name']); + $this->assertAttributeSame(array(), 'arguments', $this->event); + } + + public function testOffsetIsset() + { + $this->assertArrayHasKey('name', $this->event); + $this->assertArrayNotHasKey('nameNotExist', $this->event); + } + + public function testHasArgument() + { + $this->assertTrue($this->event->hasArgument('name')); + $this->assertFalse($this->event->hasArgument('nameNotExist')); + } + + public function testGetSubject() + { + $this->assertSame($this->subject, $this->event->getSubject()); + } + + public function testHasIterator() + { + $data = array(); + foreach ($this->event as $key => $value) { + $data[$key] = $value; + } + $this->assertEquals(array('name' => 'Event'), $data); + } +} diff --git a/src/bb-vendor/symfony/event-dispatcher/Tests/ImmutableEventDispatcherTest.php b/src/bb-vendor/symfony/event-dispatcher/Tests/ImmutableEventDispatcherTest.php new file mode 100644 index 000000000..04f2861e3 --- /dev/null +++ b/src/bb-vendor/symfony/event-dispatcher/Tests/ImmutableEventDispatcherTest.php @@ -0,0 +1,106 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\EventDispatcher\Tests; + +use PHPUnit\Framework\TestCase; +use Symfony\Component\EventDispatcher\Event; +use Symfony\Component\EventDispatcher\ImmutableEventDispatcher; + +/** + * @author Bernhard Schussek + */ +class ImmutableEventDispatcherTest extends TestCase +{ + /** + * @var \PHPUnit_Framework_MockObject_MockObject + */ + private $innerDispatcher; + + /** + * @var ImmutableEventDispatcher + */ + private $dispatcher; + + protected function setUp() + { + $this->innerDispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock(); + $this->dispatcher = new ImmutableEventDispatcher($this->innerDispatcher); + } + + public function testDispatchDelegates() + { + $event = new Event(); + + $this->innerDispatcher->expects($this->once()) + ->method('dispatch') + ->with('event', $event) + ->will($this->returnValue('result')); + + $this->assertSame('result', $this->dispatcher->dispatch('event', $event)); + } + + public function testGetListenersDelegates() + { + $this->innerDispatcher->expects($this->once()) + ->method('getListeners') + ->with('event') + ->will($this->returnValue('result')); + + $this->assertSame('result', $this->dispatcher->getListeners('event')); + } + + public function testHasListenersDelegates() + { + $this->innerDispatcher->expects($this->once()) + ->method('hasListeners') + ->with('event') + ->will($this->returnValue('result')); + + $this->assertSame('result', $this->dispatcher->hasListeners('event')); + } + + /** + * @expectedException \BadMethodCallException + */ + public function testAddListenerDisallowed() + { + $this->dispatcher->addListener('event', function () { return 'foo'; }); + } + + /** + * @expectedException \BadMethodCallException + */ + public function testAddSubscriberDisallowed() + { + $subscriber = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventSubscriberInterface')->getMock(); + + $this->dispatcher->addSubscriber($subscriber); + } + + /** + * @expectedException \BadMethodCallException + */ + public function testRemoveListenerDisallowed() + { + $this->dispatcher->removeListener('event', function () { return 'foo'; }); + } + + /** + * @expectedException \BadMethodCallException + */ + public function testRemoveSubscriberDisallowed() + { + $subscriber = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventSubscriberInterface')->getMock(); + + $this->dispatcher->removeSubscriber($subscriber); + } +} diff --git a/src/bb-vendor/symfony/event-dispatcher/composer.json b/src/bb-vendor/symfony/event-dispatcher/composer.json new file mode 100644 index 000000000..14fc24ba2 --- /dev/null +++ b/src/bb-vendor/symfony/event-dispatcher/composer.json @@ -0,0 +1,44 @@ +{ + "name": "symfony/event-dispatcher", + "type": "library", + "description": "Symfony EventDispatcher Component", + "keywords": [], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=5.3.9" + }, + "require-dev": { + "symfony/dependency-injection": "~2.6|~3.0.0", + "symfony/expression-language": "~2.6|~3.0.0", + "symfony/config": "^2.0.5|~3.0.0", + "symfony/stopwatch": "~2.3|~3.0.0", + "psr/log": "~1.0" + }, + "suggest": { + "symfony/dependency-injection": "", + "symfony/http-kernel": "" + }, + "autoload": { + "psr-4": { "Symfony\\Component\\EventDispatcher\\": "" }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "minimum-stability": "dev", + "extra": { + "branch-alias": { + "dev-master": "2.8-dev" + } + } +} diff --git a/src/bb-vendor/symfony/event-dispatcher/phpunit.xml.dist b/src/bb-vendor/symfony/event-dispatcher/phpunit.xml.dist new file mode 100644 index 000000000..f2eb1692c --- /dev/null +++ b/src/bb-vendor/symfony/event-dispatcher/phpunit.xml.dist @@ -0,0 +1,31 @@ + + + + + + + + + + ./Tests/ + + + + + + ./ + + ./Resources + ./Tests + ./vendor + + + + diff --git a/src/bb-vendor/twig/twig/CHANGELOG b/src/bb-vendor/twig/twig/CHANGELOG new file mode 100644 index 000000000..04cf45396 --- /dev/null +++ b/src/bb-vendor/twig/twig/CHANGELOG @@ -0,0 +1,1462 @@ +# 2.13.0 (2020-07-05) + + * Fix options not taken into account when using "Michelf\MarkdownExtra" + * Fix "Twig\Extra\Intl\IntlExtension::getCountryName()" to accept "null" as a first argument + * Drop support for PHP 7.0 + * Throw exception in case non-Traversable data is passed to "filter" + * Fix context optimization on PHP 7.4 + * Fix PHP 8 compatibility + * Fix ambiguous syntax parsing + +# 2.12.5 (2020-02-11) + + * Add a check to ensure that iconv() is defined + +# 2.12.4 (2020-02-11) + + * Avoid exceptions when an intl resource is not found + * Fix implementation of case-insensitivity for method names + +# 2.12.3 (2019-12-28) + + * fixed Symfony 5.0 support for the HTML extra extension + * fixed number formatter in Intl extra extension when using a formatter prototype + +# 2.12.2 (2019-11-11) + + * added supported for exponential numbers + +# 2.12.1 (2019-10-17) + + * added the String extension in the "extra" repositories: "u" filter + +# 2.12.0 (2019-10-05) + + * added the spaceship operator ("<=>"), useful when using an arrow function in the "sort" filter + * added support for an "arrow" function on the "sort" filter + * added the CssInliner extension in the "extra" repositories: "inline_css" + filter + * added the Inky extension in the "extra" repositories: "inky_to_html" filter + * added Intl extension in the "extra" repositories: "country_name", + "currency_name", "currency_symbol", "language_name", "locale_name", + "timezone_name", "format_currency", "format_number", + "format_*_number", "format_datetime", "format_date", and "format_time" + filters, and the "country_timezones" function + * added the Markdown extension in the "extra" repositories: "markdown_to_html", + and "html_to_markdown" filters + * added the HtmlExtension extension in the "extra" repositories: "date_uri" + filter, and "html_classes" function + * optimized "block('foo') ?? 'bar'" + * fixed the empty test on Traversable instances + * fixed array_key_exists() on objects + * fixed cache when opcache is installed but disabled + * fixed using macros in arrow functions + * fixed split filter on edge case + +# 2.11.3 (2019-06-18) + + * display partial output (PHP buffer) when an error occurs in debug mode + * fixed the filter filter (allow the result to be used several times) + * fixed macro auto-import when a template contains only macros + +# 2.11.2 (2019-06-05) + + * fixed macro auto-import + +# 2.11.1 (2019-06-04) + + * added support for "Twig\Markup" instances in the "in" test (again) + * allowed string operators as variables names in assignments + * fixed support for macros defined in parent templates + +# 2.11.0 (2019-05-31) + + * added the possibility to register classes/interfaces as being safe for the escaper ("EscaperExtension::addSafeClass()") + * deprecated CoreExtension::setEscaper() and CoreExtension::getEscapers() in favor of the same methods on EscaperExtension + * macros are now auto-imported in the template they are defined (under the ``_self`` variable) + * added support for macros on "is defined" tests + * fixed macros "import" when using the same name in the parent and child templates + * fixed recursive macros + * macros imported "globally" in a template are now available in macros without re-importing them + * fixed the "filter" filter when the argument is \Traversable but does not implement \Iterator (\SimpleXmlElement for instance) + * fixed a PHP fatal error when calling a macro imported in a block in a nested block + * fixed a PHP fatal error when calling a macro imported in the template in another macro + * fixed wrong error message on "import" and "from" + +# 2.10.0 (2019-05-14) + + * deprecated "if" conditions on "for" tags + * added "filter", "map", and "reduce" filters (and support for arrow functions) + * fixed partial output leak when a PHP fatal error occurs + * optimized context access on PHP 7.4 + +# 2.9.0 (2019-04-28) + + * deprecated returning "false" to remove a Node from NodeVisitorInterface::leaveNode() + * allowed Twig\NodeVisitor\NodeVisitorInterface::leaveNode() to return "null" instead of "false" (same meaning) + * deprecated the "filter" tag (use the "apply" tag instead) + * added the "apply" tag as a replacement for the "filter" tag + * allowed Twig\Loader\FilesystemLoader::findTemplate() to return "null" instead of "false" (same meaning) + * added support for "Twig\Markup" instances in the "in" test + * fixed "import" when macros are stored in a template string + * fixed Lexer when using custom options containing the # char + * added template line number to twig_get_attribute() + +# 2.8.1 (2019-04-16) + + * fixed EscaperNodeVisitor + * deprecated passing a 3rd, 4th, and 5th arguments to the Sandbox exception classes + * deprecated Node::setTemplateName() in favor of Node::setSourceContext() + +# 2.8.0 (2019-04-16) + + * added Traversable support for the length filter + * fixed some wrong location in error messages + * made exception creation faster + * made escaping on ternary expressions (?: and ??) more fine-grained + * added the possibility to give a nice name to string templates (template_from_string function) + * fixed the "with" behavior to always include the globals (for consistency with the "include" and "embed" tags) + * fixed "include" with "ignore missing" when an error loading occurs in the included template + * added support for a new whitespace trimming option ({%~ ~%}, {{~ ~}}, {#~ ~#}) + * added the "column" filter + +# 2.7.4 (2019-03-23) + + * fixed variadic support + * fixed CheckToStringNode implementation (broken when a function/filter is variadic) + +# 2.7.3 (2019-03-21) + + * fixed the spaceless filter so that it behaves like the spaceless tag + * fixed BC break on Environment::resolveTemplate() + * allowed Traversable objects to be used in the "with" tag + * allowed Traversable objects to be used in the "with" tag + * allowed Traversable objects to be used in the "with" argument of the "include" and "embed" tags + +# 2.7.2 (2019-03-12) + + * added TemplateWrapper::getTemplateName() + +# 2.7.1 (2019-03-12) + + * fixed class aliases + +# 2.7.0 (2019-03-12) + + * fixed sandbox security issue (under some circumstances, calling the + __toString() method on an object was possible even if not allowed by the + security policy) + * fixed batch filter clobbers array keys when fill parameter is used + * added preserveKeys support for the batch filter + * fixed "embed" support when used from "template_from_string" + * deprecated passing a Twig\Template to Twig\Environment::load()/Twig\Environment::resolveTemplate() + * added the possibility to pass a TemplateWrapper to Twig\Environment::load() + * marked Twig\Environment::getTemplateClass() as internal (implementation detail) + * improved the performance of the sandbox + * deprecated the spaceless tag + * added a spaceless filter + * added max value to the "random" function + * deprecated Twig\Extension\InitRuntimeInterface + * deprecated Twig\Loader\ExistsLoaderInterface + * deprecated PSR-0 classes in favor of namespaced ones + * made namespace classes the default classes (PSR-0 ones are aliases now) + * added Twig\Loader\ChainLoader::getLoaders() + * removed duplicated directory separator in FilesystemLoader + * deprecated the "base_template_class" option on Twig\Environment + * deprecated the Twig\Environment::getBaseTemplateClass() and + Twig\Environment::setBaseTemplateClass() methods + * changed internal code to use the namespaced classes as much as possible + * deprecated Twig_Parser::isReservedMacroName() + +# 2.6.2 (2019-01-14) + + * fixed regression (key exists check for non ArrayObject objects) + +# 2.6.1 (2019-01-14) + + * fixed ArrayObject access with a null value + * fixed embedded templates starting with a BOM + * fixed using a Twig_TemplateWrapper instance as an argument to extends + * fixed error location when calling an undefined block + * deprecated passing a string as a source on Twig_Error + * switched generated code to use the PHP short array notation + * fixed float representation in compiled templates + * added a second argument to the join filter (last separator configuration) + +# 2.6.0 (2018-12-16) + + * made sure twig_include returns a string + * fixed multi-byte UFT-8 in escape('html_attr') + * added the "deprecated" tag + * added support for dynamically named tests + * fixed GlobalsInterface extended class + * fixed filesystem loader throwing an exception instead of returning false + +# 2.5.0 (2018-07-13) + + * deprecated using the spaceless tag at the root level of a child template (noop anyway) + * deprecated the possibility to define a block in a non-capturing block in a child template + * added the Symfony ctype polyfill as a dependency + * fixed reporting the proper location for errors compiled in templates + * fixed the error handling for the optimized extension-based function calls + * ensured that syntax errors are triggered with the right line + * "js" filter now produces valid JSON + +# 2.4.8 (2018-04-02) + + * fixed a regression when using the "default" filter or the "defined" test on non-existing arrays + +# 2.4.7 (2018-03-20) + + * optimized runtime performance + * optimized parser performance by inlining the constant values + * fixed block names unicity + * fixed counting children of SimpleXMLElement objects + * added missing else clause to avoid infinite loops + * fixed .. (range operator) in sandbox policy + +# 2.4.6 (2018-03-03) + + * fixed a regression in the way the profiler is registered in templates + +# 2.4.5 (2018-03-02) + + * optimized the performance of calling an extension method at runtime + * optimized the performance of the dot operator for array and method calls + * added an exception when using "===" instead of "same as" + * fixed possible array to string conversion concealing actual error + * made variable names deterministic in compiled templates + * fixed length filter when passing an instance of IteratorAggregate + * fixed Environment::resolveTemplate to accept instances of TemplateWrapper + +# 2.4.4 (2017-09-27) + + * added Twig_Profiler_Profile::reset() + * fixed use TokenParser to return an empty Node + * added RuntimeExtensionInterface + * added circular reference detection when loading templates + * added support for runtime loaders in IntegrationTestCase + * fixed deprecation when using Twig_Profiler_Dumper_Html + * removed @final from Twig_Profiler_Dumper_Text + +# 2.4.3 (2017-06-07) + + * fixed namespaces introduction + +# 2.4.2 (2017-06-05) + + * fixed namespaces introduction + +# 2.4.1 (2017-06-05) + + * fixed namespaces introduction + +# 2.4.0 (2017-06-05) + + * added support for PHPUnit 6 when testing extensions + * fixed PHP 7.2 compatibility + * fixed template name generation in Twig_Environment::createTemplate() + * removed final tag on Twig_TokenParser_Include + * dropped HHVM support + * added namespaced aliases for all (non-deprecated) classes and interfaces + * marked Twig_Filter, Twig_Function, Twig_Test, Twig_Node_Module and Twig_Profiler_Profile as final via the @final annotation + +# 2.3.2 (2017-04-20) + + * fixed edge case in the method cache for Twig attributes + +# 2.3.1 (2017-04-18) + + * fixed the empty() test + +# 2.3.0 (2017-03-22) + + * fixed a race condition handling when writing cache files + * "length" filter now returns string length when applied to an object that does + not implement \Countable but provides __toString() + * "empty" test will now consider the return value of the __toString() method for + objects implement __toString() but not \Countable + * fixed JS escaping for unicode characters with higher code points + * added error message when calling `parent()` in a block that doesn't exist in the parent template + +# 2.2.0 (2017-02-26) + + * added a PSR-11 compatible runtime loader + * added `side` argument to `trim` to allow left or right trimming only. + +# 2.1.0 (2017-01-11) + + * fixed twig_get_attribute() + * added Twig_NodeCaptureInterface for nodes that capture all output + +# 2.0.0 (2017-01-05) + + * removed the C extension + * moved Twig_Environment::getAttribute() to twig_get_attribute() + * removed Twig_Environment::getLexer(), Twig_Environment::getParser(), Twig_Environment::getCompiler() + * removed Twig_Compiler::getFilename() + * added hasser support in Twig_Template::getAttribute() + * sped up the json_encode filter + * removed reserved macro names; all names can be used as macro + * removed Twig_Template::getEnvironment() + * changed _self variable to return the current template name + * made the loader a required argument of Twig_Environment constructor + * removed Twig_Environment::clearTemplateCache() + * removed Twig_Autoloader (use Composer instead) + * removed `true` as an equivalent to `html` for the auto-escaping strategy + * removed pre-1.8 autoescape tag syntax + * dropped support for PHP 5.x + * removed the ability to register a global variable after the runtime or the extensions have been initialized + * improved the performance of the filesystem loader + * removed features that were deprecated in 1.x + +# 1.43.1 (2020-XX-XX) + + * n/a + +# 1.43.0 (2020-07-05) + + * Throw exception in case non-Traversable data is passed to "filter" + * Fix context optimization on PHP 7.4 + * Fix PHP 8 compatibility + * Drop PHP 5.5 5.6, and 7.0 support + * Fix ambiguous syntax parsing + +# 1.42.5 (2020-02-11) + + * Fix implementation of case-insensitivity for method names + +# 1.42.4 (2019-11-11) + + * optimized "block('foo') ?? 'bar" + * added supported for exponential numbers + +# 1.42.3 (2019-08-24) + + * fixed the "split" filter when the delimiter is "0" + * fixed the "empty" test on Traversable instances + * fixed cache when opcache is installed but disabled + * fixed PHP 7.4 compatibility + * bumped the minimal PHP version to 5.5 + +# 1.42.2 (2019-06-18) + + * Display partial output (PHP buffer) when an error occurs in debug mode + +# 1.42.1 (2019-06-04) + + * added support for "Twig\Markup" instances in the "in" test (again) + * allowed string operators as variables names in assignments + +# 1.42.0 (2019-05-31) + + * fixed the "filter" filter when the argument is \Traversable but does not implement \Iterator (\SimpleXmlElement for instance) + * fixed a PHP fatal error when calling a macro imported in a block in a nested block + * fixed a PHP fatal error when calling a macro imported in the template in another macro + * fixed wrong error message on "import" and "from" + +# 1.41.0 (2019-05-14) + + * fixed support for PHP 7.4 + * added "filter", "map", and "reduce" filters (and support for arrow functions) + * fixed partial output leak when a PHP fatal error occurs + * optimized context access on PHP 7.4 + +# 1.40.1 (2019-04-29) + +# fixed regression in NodeTraverser + +# 1.40.0 (2019-04-28) + + * allowed Twig\NodeVisitor\NodeVisitorInterface::leaveNode() to return "null" instead of "false" (same meaning) + * added the "apply" tag as a replacement for the "filter" tag + * allowed Twig\Loader\FilesystemLoader::findTemplate() to return "null" instead of "false" (same meaning) + * added support for "Twig\Markup" instances in the "in" test + * fixed Lexer when using custom options containing the # char + * fixed "import" when macros are stored in a template string + +# 1.39.1 (2019-04-16) + + * fixed EscaperNodeVisitor + +# 1.39.0 (2019-04-16) + + * added Traversable support for the length filter + * fixed some wrong location in error messages + * made exception creation faster + * made escaping on ternary expressions (?: and ??) more fine-grained + * added the possibility to give a nice name to string templates (template_from_string function) + * fixed the "with" behavior to always include the globals (for consistency with the "include" and "embed" tags) + * fixed "include" with "ignore missing" when an error loading occurs in the included template + * added support for a new whitespace trimming option ({%~ ~%}, {{~ ~}}, {#~ ~#}) + +# 1.38.4 (2019-03-23) + + * fixed CheckToStringNode implementation (broken when a function/filter is variadic) + +# 1.38.3 (2019-03-21) + + * fixed the spaceless filter so that it behaves like the spaceless tag + * fixed BC break on Environment::resolveTemplate() + * fixed the bundled Autoloader to also load namespaced classes + * allowed Traversable objects to be used in the "with" tag + * allowed Traversable objects to be used in the "with" argument of the "include" and "embed" tags + +# 1.38.2 (2019-03-12) + + * added TemplateWrapper::getTemplateName() + +# 1.38.1 (2019-03-12) + + * fixed class aliases + +# 1.38.0 (2019-03-12) + + * fixed sandbox security issue (under some circumstances, calling the + __toString() method on an object was possible even if not allowed by the + security policy) + * fixed batch filter clobbers array keys when fill parameter is used + * added preserveKeys support for the batch filter + * fixed "embed" support when used from "template_from_string" + * added the possibility to pass a TemplateWrapper to Twig\Environment::load() + * improved the performance of the sandbox + * added a spaceless filter + * added max value to the "random" function + * made namespace classes the default classes (PSR-0 ones are aliases now) + * removed duplicated directory separator in FilesystemLoader + * added Twig\Loader\ChainLoader::getLoaders() + * changed internal code to use the namespaced classes as much as possible + +# 1.37.1 (2019-01-14) + + * fixed regression (key exists check for non ArrayObject objects) + * fixed logic in TemplateWrapper + +# 1.37.0 (2019-01-14) + + * fixed ArrayObject access with a null value + * fixed embedded templates starting with a BOM + * fixed using a Twig_TemplateWrapper instance as an argument to extends + * switched generated code to use the PHP short array notation + * dropped PHP 5.3 support + * fixed float representation in compiled templates + * added a second argument to the join filter (last separator configuration) + +# 1.36.0 (2018-12-16) + + * made sure twig_include returns a string + * fixed multi-byte UFT-8 in escape('html_attr') + * added the "deprecated" tag + * added support for dynamically named tests + * fixed GlobalsInterface extended class + * fixed filesystem loader throwing an exception instead of returning false + +# 1.35.4 (2018-07-13) + + * ensured that syntax errors are triggered with the right line + * added the Symfony ctype polyfill as a dependency + * "js" filter now produces valid JSON + +# 1.35.3 (2018-03-20) + + * fixed block names unicity + * fixed counting children of SimpleXMLElement objects + * added missing else clause to avoid infinite loops + * fixed .. (range operator) in sandbox policy + +# 1.35.2 (2018-03-03) + + * fixed a regression in the way the profiler is registered in templates + +# 1.35.1 (2018-03-02) + + * added an exception when using "===" instead of "same as" + * fixed possible array to string conversion concealing actual error + * made variable names deterministic in compiled templates + * fixed length filter when passing an instance of IteratorAggregate + * fixed Environment::resolveTemplate to accept instances of TemplateWrapper + +# 1.35.0 (2017-09-27) + + * added Twig_Profiler_Profile::reset() + * fixed use TokenParser to return an empty Node + * added RuntimeExtensionInterface + * added circular reference detection when loading templates + +# 1.34.4 (2017-07-04) + + * added support for runtime loaders in IntegrationTestCase + * fixed deprecation when using Twig_Profiler_Dumper_Html + +# 1.34.3 (2017-06-07) + + * fixed namespaces introduction + +# 1.34.2 (2017-06-05) + + * fixed namespaces introduction + +# 1.34.1 (2017-06-05) + + * fixed namespaces introduction + +# 1.34.0 (2017-06-05) + + * added support for PHPUnit 6 when testing extensions + * fixed PHP 7.2 compatibility + * fixed template name generation in Twig_Environment::createTemplate() + * removed final tag on Twig_TokenParser_Include + * added namespaced aliases for all (non-deprecated) classes and interfaces + * dropped HHVM support + * dropped PHP 5.2 support + +# 1.33.2 (2017-04-20) + + * fixed edge case in the method cache for Twig attributes + +# 1.33.1 (2017-04-18) + + * fixed the empty() test + +# 1.33.0 (2017-03-22) + + * fixed a race condition handling when writing cache files + * "length" filter now returns string length when applied to an object that does + not implement \Countable but provides __toString() + * "empty" test will now consider the return value of the __toString() method for + objects implement __toString() but not \Countable + * fixed JS escaping for unicode characters with higher code points + +# 1.32.0 (2017-02-26) + + * fixed deprecation notice in Twig_Util_DeprecationCollector + * added a PSR-11 compatible runtime loader + * added `side` argument to `trim` to allow left or right trimming only. + +# 1.31.0 (2017-01-11) + + * added Twig_NodeCaptureInterface for nodes that capture all output + * fixed marking the environment as initialized too early + * fixed C89 compat for the C extension + * turned fatal error into exception when a previously generated cache is corrupted + * fixed offline cache warm-ups for embedded templates + +# 1.30.0 (2016-12-23) + + * added Twig_FactoryRuntimeLoader + * deprecated function/test/filter/tag overriding + * deprecated the "disable_c_ext" attribute on Twig_Node_Expression_GetAttr + +# 1.29.0 (2016-12-13) + + * fixed sandbox being left enabled if an exception is thrown while rendering + * marked some classes as being final (via @final) + * made Twig_Error report real source path when possible + * added support for {{ _self }} to provide an upgrade path from 1.x to 2.0 (replaces {{ _self.templateName }}) + * deprecated silent display of undefined blocks + * deprecated support for mbstring.func_overload != 0 + +# 1.28.2 (2016-11-23) + + * fixed precedence between getFoo() and isFoo() in Twig_Template::getAttribute() + * improved a deprecation message + +# 1.28.1 (2016-11-18) + + * fixed block() function when used with a template argument + +# 1.28.0 (2016-11-17) + + * added support for the PHP 7 null coalescing operator for the ?? Twig implementation + * exposed a way to access template data and methods in a portable way + * changed context access to use the PHP 7 null coalescing operator when available + * added the "with" tag + * added support for a custom template on the block() function + * added "is defined" support for block() and constant() + * optimized the way attributes are fetched + +# 1.27.0 (2016-10-25) + + * deprecated Twig_Parser::getEnvironment() + * deprecated Twig_Parser::addHandler() and Twig_Parser::addNodeVisitor() + * deprecated Twig_Compiler::addIndentation() + * fixed regression when registering two extensions having the same class name + * deprecated Twig_LoaderInterface::getSource() (implement Twig_SourceContextLoaderInterface instead) + * fixed the filesystem loader with relative paths + * deprecated Twig_Node::getLine() in favor of Twig_Node::getTemplateLine() + * deprecated Twig_Template::getSource() in favor of Twig_Template::getSourceContext() + * deprecated Twig_Node::getFilename() in favor of Twig_Node::getTemplateName() + * deprecated the "filename" escaping strategy (use "name" instead) + * added Twig_Source to hold information about the original template + * deprecated Twig_Error::getTemplateFile() and Twig_Error::setTemplateFile() in favor of Twig_Error::getTemplateName() and Twig_Error::setTemplateName() + * deprecated Parser::getFilename() + * fixed template paths when a template name contains a protocol like vfs:// + * improved debugging with Twig_Sandbox_SecurityError exceptions for disallowed methods and properties + +# 1.26.1 (2016-10-05) + + * removed template source code from generated template classes when debug is disabled + * fixed default implementation of Twig_Template::getDebugInfo() for better BC + * fixed regression on static calls for functions/filters/tests + +# 1.26.0 (2016-10-02) + + * added template cache invalidation based on more environment options + * added a missing deprecation notice + * fixed template paths when a template is stored in a PHAR file + * allowed filters/functions/tests implementation to use a different class than the extension they belong to + * deprecated Twig_ExtensionInterface::getName() + +# 1.25.0 (2016-09-21) + + * changed the way we store template source in template classes + * removed usage of realpath in cache keys + * fixed Twig cache sharing when used with different versions of PHP + * removed embed parent workaround for simple use cases + * deprecated the ability to store non Node instances in Node::$nodes + * deprecated Twig_Environment::getLexer(), Twig_Environment::getParser(), Twig_Environment::getCompiler() + * deprecated Twig_Compiler::getFilename() + +# 1.24.2 (2016-09-01) + + * fixed static callables + * fixed a potential PHP warning when loading the cache + * fixed a case where the autoescaping does not work as expected + +# 1.24.1 (2016-05-30) + + * fixed reserved keywords (forbids true, false, null and none keywords for variables names) + * fixed support for PHP7 (Throwable support) + * marked the following methods as being internals on Twig_Environment: + getFunctions(), getFilters(), getTests(), getFunction(), getFilter(), getTest(), + getTokenParsers(), getTags(), getNodeVisitors(), getUnaryOperators(), getBinaryOperators(), + getFunctions(), getFilters(), getGlobals(), initGlobals(), initExtensions(), and initExtension() + +# 1.24.0 (2016-01-25) + + * adding support for the ?? operator + * fixed the defined test when used on a constant, a map, or a sequence + * undeprecated _self (should only be used to get the template name, not the template instance) + * fixed parsing on PHP7 + +# 1.23.3 (2016-01-11) + + * fixed typo + +# 1.23.2 (2015-01-11) + + * added versions in deprecated messages + * made file cache tolerant for trailing (back)slashes on directory configuration + * deprecated unused Twig_Node_Expression_ExtensionReference class + +# 1.23.1 (2015-11-05) + + * fixed some exception messages which triggered PHP warnings + * fixed BC on Twig_Test_NodeTestCase + +# 1.23.0 (2015-10-29) + + * deprecated the possibility to override an extension by registering another one with the same name + * deprecated Twig_ExtensionInterface::getGlobals() (added Twig_Extension_GlobalsInterface for BC) + * deprecated Twig_ExtensionInterface::initRuntime() (added Twig_Extension_InitRuntimeInterface for BC) + * deprecated Twig_Environment::computeAlternatives() + +# 1.22.3 (2015-10-13) + + * fixed regression when using null as a cache strategy + * improved performance when checking template freshness + * fixed warnings when loaded templates do not exist + * fixed template class name generation to prevent possible collisions + * fixed logic for custom escapers to call them even on integers and null values + * changed template cache names to take into account the Twig C extension + +# 1.22.2 (2015-09-22) + + * fixed a race condition in template loading + +# 1.22.1 (2015-09-15) + + * fixed regression in template_from_string + +# 1.22.0 (2015-09-13) + + * made Twig_Test_IntegrationTestCase more flexible + * added an option to force PHP bytecode invalidation when writing a compiled template into the cache + * fixed the profiler duration for the root node + * changed template cache names to take into account enabled extensions + * deprecated Twig_Environment::clearCacheFiles(), Twig_Environment::getCacheFilename(), + Twig_Environment::writeCacheFile(), and Twig_Environment::getTemplateClassPrefix() + * added a way to override the filesystem template cache system + * added a way to get the original template source from Twig_Template + +# 1.21.2 (2015-09-09) + + * fixed variable names for the deprecation triggering code + * fixed escaping strategy detection based on filename + * added Traversable support for replace, merge, and sort + * deprecated support for character by character replacement for the "replace" filter + +# 1.21.1 (2015-08-26) + + * fixed regression when using the deprecated Twig_Test_* classes + +# 1.21.0 (2015-08-24) + + * added deprecation notices for deprecated features + * added a deprecation "framework" for filters/functions/tests and test fixtures + +# 1.20.0 (2015-08-12) + + * forbid access to the Twig environment from templates and internal parts of Twig_Template + * fixed limited RCEs when in sandbox mode + * deprecated Twig_Template::getEnvironment() + * deprecated the _self variable for usage outside of the from and import tags + * added Twig_BaseNodeVisitor to ease the compatibility of node visitors + between 1.x and 2.x + +# 1.19.0 (2015-07-31) + + * fixed wrong error message when including an undefined template in a child template + * added support for variadic filters, functions, and tests + * added support for extra positional arguments in macros + * added ignore_missing flag to the source function + * fixed batch filter with zero items + * deprecated Twig_Environment::clearTemplateCache() + * fixed sandbox disabling when using the include function + +# 1.18.2 (2015-06-06) + + * fixed template/line guessing in exceptions for nested templates + * optimized the number of inodes and the size of realpath cache when using the cache + +# 1.18.1 (2015-04-19) + + * fixed memory leaks in the C extension + * deprecated Twig_Loader_String + * fixed the slice filter when used with a SimpleXMLElement object + * fixed filesystem loader when trying to load non-files (like directories) + +# 1.18.0 (2015-01-25) + + * fixed some error messages where the line was wrong (unknown variables or argument names) + * added a new way to customize the main Module node (via empty nodes) + * added Twig_Environment::createTemplate() to create a template from a string + * added a profiler + * fixed filesystem loader cache when different file paths are used for the same template + +# 1.17.0 (2015-01-14) + + * added a 'filename' autoescaping strategy, which dynamically chooses the + autoescaping strategy for a template based on template file extension. + +# 1.16.3 (2014-12-25) + + * fixed regression for dynamic parent templates + * fixed cache management with statcache + * fixed a regression in the slice filter + +# 1.16.2 (2014-10-17) + + * fixed timezone on dates as strings + * fixed 2-words test names when a custom node class is not used + * fixed macros when using an argument named like a PHP super global (like GET or POST) + * fixed date_modify when working with DateTimeImmutable + * optimized for loops + * fixed multi-byte characters handling in the split filter + * fixed a regression in the in operator + * fixed a regression in the slice filter + +# 1.16.1 (2014-10-10) + + * improved error reporting in a sandboxed template + * fixed missing error file/line information under certain circumstances + * fixed wrong error line number in some error messages + * fixed the in operator to use strict comparisons + * sped up the slice filter + * fixed for mb function overload mb_substr acting different + * fixed the attribute() function when passing a variable for the arguments + +# 1.16.0 (2014-07-05) + + * changed url_encode to always encode according to RFC 3986 + * fixed inheritance in a 'use'-hierarchy + * removed the __toString policy check when the sandbox is disabled + * fixed recursively calling blocks in templates with inheritance + +# 1.15.1 (2014-02-13) + + * fixed the conversion of the special '0000-00-00 00:00' date + * added an error message when trying to import an undefined block from a trait + * fixed a C extension crash when accessing defined but uninitialized property. + +# 1.15.0 (2013-12-06) + + * made ignoreStrictCheck in Template::getAttribute() works with __call() methods throwing BadMethodCallException + * added min and max functions + * added the round filter + * fixed a bug that prevented the optimizers to be enabled/disabled selectively + * fixed first and last filters for UTF-8 strings + * added a source function to include the content of a template without rendering it + * fixed the C extension sandbox behavior when get or set is prepend to method name + +# 1.14.2 (2013-10-30) + + * fixed error filename/line when an error occurs in an included file + * allowed operators that contain whitespaces to have more than one whitespace + * allowed tests to be made of 1 or 2 words (like "same as" or "divisible by") + +# 1.14.1 (2013-10-15) + + * made it possible to use named operators as variables + * fixed the possibility to have a variable named 'matches' + * added support for PHP 5.5 DateTimeInterface + +# 1.14.0 (2013-10-03) + + * fixed usage of the html_attr escaping strategy to avoid double-escaping with the html strategy + * added new operators: ends with, starts with, and matches + * fixed some compatibility issues with HHVM + * added a way to add custom escaping strategies + * fixed the C extension compilation on Windows + * fixed the batch filter when using a fill argument with an exact match of elements to batch + * fixed the filesystem loader cache when a template name exists in several namespaces + * fixed template_from_string when the template includes or extends other ones + * fixed a crash of the C extension on an edge case + +# 1.13.2 (2013-08-03) + + * fixed the error line number for an error occurs in and embedded template + * fixed crashes of the C extension on some edge cases + +# 1.13.1 (2013-06-06) + + * added the possibility to ignore the filesystem constructor argument in Twig_Loader_Filesystem + * fixed Twig_Loader_Chain::exists() for a loader which implements Twig_ExistsLoaderInterface + * adjusted backtrace call to reduce memory usage when an error occurs + * added support for object instances as the second argument of the constant test + * fixed the include function when used in an assignment + +# 1.13.0 (2013-05-10) + + * fixed getting a numeric-like item on a variable ('09' for instance) + * fixed getting a boolean or float key on an array, so it is consistent with PHP's array access: + `{{ array[false] }}` behaves the same as `echo $array[false];` (equals `$array[0]`) + * made the escape filter 20% faster for happy path (escaping string for html with UTF-8) + * changed ☃ to § in tests + * enforced usage of named arguments after positional ones + +# 1.12.3 (2013-04-08) + + * fixed a security issue in the filesystem loader where it was possible to include a template one + level above the configured path + * fixed fatal error that should be an exception when adding a filter/function/test too late + * added a batch filter + * added support for encoding an array as query string in the url_encode filter + +# 1.12.2 (2013-02-09) + + * fixed the timezone used by the date filter and function when the given date contains a timezone (like 2010-01-28T15:00:00+02:00) + * fixed globals when getGlobals is called early on + * added the first and last filter + +# 1.12.1 (2013-01-15) + + * added support for object instances as the second argument of the constant function + * relaxed globals management to avoid a BC break + * added support for {{ some_string[:2] }} + +# 1.12.0 (2013-01-08) + + * added verbatim as an alias for the raw tag to avoid confusion with the raw filter + * fixed registration of tests and functions as anonymous functions + * fixed globals management + +# 1.12.0-RC1 (2012-12-29) + + * added an include function (does the same as the include tag but in a more flexible way) + * added the ability to use any PHP callable to define filters, functions, and tests + * added a syntax error when using a loop variable that is not defined + * added the ability to set default values for macro arguments + * added support for named arguments for filters, tests, and functions + * moved filters/functions/tests syntax errors to the parser + * added support for extended ternary operator syntaxes + +# 1.11.1 (2012-11-11) + + * fixed debug info line numbering (was off by 2) + * fixed escaping when calling a macro inside another one (regression introduced in 1.9.1) + * optimized variable access on PHP 5.4 + * fixed a crash of the C extension when an exception was thrown from a macro called without being imported (using _self.XXX) + +# 1.11.0 (2012-11-07) + + * fixed macro compilation when a variable name is a PHP reserved keyword + * changed the date filter behavior to always apply the default timezone, except if false is passed as the timezone + * fixed bitwise operator precedences + * added the template_from_string function + * fixed default timezone usage for the date function + * optimized the way Twig exceptions are managed (to make them faster) + * added Twig_ExistsLoaderInterface (implementing this interface in your loader make the chain loader much faster) + +# 1.10.3 (2012-10-19) + + * fixed wrong template location in some error messages + * reverted a BC break introduced in 1.10.2 + * added a split filter + +# 1.10.2 (2012-10-15) + + * fixed macro calls on PHP 5.4 + +# 1.10.1 (2012-10-15) + + * made a speed optimization to macro calls when imported via the "import" tag + * fixed C extension compilation on Windows + * fixed a segfault in the C extension when using DateTime objects + +# 1.10.0 (2012-09-28) + + * extracted functional tests framework to make it reusable for third-party extensions + * added namespaced templates support in Twig_Loader_Filesystem + * added Twig_Loader_Filesystem::prependPath() + * fixed an error when a token parser pass a closure as a test to the subparse() method + +# 1.9.2 (2012-08-25) + + * fixed the in operator for objects that contain circular references + * fixed the C extension when accessing a public property of an object implementing the \ArrayAccess interface + +# 1.9.1 (2012-07-22) + + * optimized macro calls when auto-escaping is on + * fixed wrong parent class for Twig_Function_Node + * made Twig_Loader_Chain more explicit about problems + +# 1.9.0 (2012-07-13) + + * made the parsing independent of the template loaders + * fixed exception trace when an error occurs when rendering a child template + * added escaping strategies for CSS, URL, and HTML attributes + * fixed nested embed tag calls + * added the date_modify filter + +# 1.8.3 (2012-06-17) + + * fixed paths in the filesystem loader when passing a path that ends with a slash or a backslash + * fixed escaping when a project defines a function named html or js + * fixed chmod mode to apply the umask correctly + +# 1.8.2 (2012-05-30) + + * added the abs filter + * fixed a regression when using a number in template attributes + * fixed compiler when mbstring.func_overload is set to 2 + * fixed DateTimeZone support in date filter + +# 1.8.1 (2012-05-17) + + * fixed a regression when dealing with SimpleXMLElement instances in templates + * fixed "is_safe" value for the "dump" function when "html_errors" is not defined in php.ini + * switched to use mbstring whenever possible instead of iconv (you might need to update your encoding as mbstring and iconv encoding names sometimes differ) + +# 1.8.0 (2012-05-08) + + * enforced interface when adding tests, filters, functions, and node visitors from extensions + * fixed a side-effect of the date filter where the timezone might be changed + * simplified usage of the autoescape tag; the only (optional) argument is now the escaping strategy or false (with a BC layer) + * added a way to dynamically change the auto-escaping strategy according to the template "filename" + * changed the autoescape option to also accept a supported escaping strategy (for BC, true is equivalent to html) + * added an embed tag + +# 1.7.0 (2012-04-24) + + * fixed a PHP warning when using CIFS + * fixed template line number in some exceptions + * added an iterable test + * added an error when defining two blocks with the same name in a template + * added the preserves_safety option for filters + * fixed a PHP notice when trying to access a key on a non-object/array variable + * enhanced error reporting when the template file is an instance of SplFileInfo + * added Twig_Environment::mergeGlobals() + * added compilation checks to avoid misuses of the sandbox tag + * fixed filesystem loader freshness logic for high traffic websites + * fixed random function when charset is null + +# 1.6.5 (2012-04-11) + + * fixed a regression when a template only extends another one without defining any blocks + +# 1.6.4 (2012-04-02) + + * fixed PHP notice in Twig_Error::guessTemplateLine() introduced in 1.6.3 + * fixed performance when compiling large files + * optimized parent template creation when the template does not use dynamic inheritance + +# 1.6.3 (2012-03-22) + + * fixed usage of Z_ADDREF_P for PHP 5.2 in the C extension + * fixed compilation of numeric values used in templates when using a locale where the decimal separator is not a dot + * made the strategy used to guess the real template file name and line number in exception messages much faster and more accurate + +# 1.6.2 (2012-03-18) + + * fixed sandbox mode when used with inheritance + * added preserveKeys support for the slice filter + * fixed the date filter when a DateTime instance is passed with a specific timezone + * added a trim filter + +# 1.6.1 (2012-02-29) + + * fixed Twig C extension + * removed the creation of Twig_Markup instances when not needed + * added a way to set the default global timezone for dates + * fixed the slice filter on strings when the length is not specified + * fixed the creation of the cache directory in case of a race condition + +# 1.6.0 (2012-02-04) + + * fixed raw blocks when used with the whitespace trim option + * made a speed optimization to macro calls when imported via the "from" tag + * fixed globals, parsers, visitors, filters, tests, and functions management in Twig_Environment when a new one or new extension is added + * fixed the attribute function when passing arguments + * added slice notation support for the [] operator (syntactic sugar for the slice operator) + * added a slice filter + * added string support for the reverse filter + * fixed the empty test and the length filter for Twig_Markup instances + * added a date function to ease date comparison + * fixed unary operators precedence + * added recursive parsing support in the parser + * added string and integer handling for the random function + +# 1.5.1 (2012-01-05) + + * fixed a regression when parsing strings + +# 1.5.0 (2012-01-04) + + * added Traversable objects support for the join filter + +# 1.5.0-RC2 (2011-12-30) + + * added a way to set the default global date interval format + * fixed the date filter for DateInterval instances (setTimezone() does not exist for them) + * refactored Twig_Template::display() to ease its extension + * added a number_format filter + +# 1.5.0-RC1 (2011-12-26) + + * removed the need to quote hash keys + * allowed hash keys to be any expression + * added a do tag + * added a flush tag + * added support for dynamically named filters and functions + * added a dump function to help debugging templates + * added a nl2br filter + * added a random function + * added a way to change the default format for the date filter + * fixed the lexer when an operator ending with a letter ends a line + * added string interpolation support + * enhanced exceptions for unknown filters, functions, tests, and tags + +# 1.4.0 (2011-12-07) + + * fixed lexer when using big numbers (> PHP_INT_MAX) + * added missing preserveKeys argument to the reverse filter + * fixed macros containing filter tag calls + +# 1.4.0-RC2 (2011-11-27) + + * removed usage of Reflection in Twig_Template::getAttribute() + * added a C extension that can optionally replace Twig_Template::getAttribute() + * added negative timestamp support to the date filter + +# 1.4.0-RC1 (2011-11-20) + + * optimized variable access when using PHP 5.4 + * changed the precedence of the .. operator to be more consistent with languages that implements such a feature like Ruby + * added an Exception to Twig_Loader_Array::isFresh() method when the template does not exist to be consistent with other loaders + * added Twig_Function_Node to allow more complex functions to have their own Node class + * added Twig_Filter_Node to allow more complex filters to have their own Node class + * added Twig_Test_Node to allow more complex tests to have their own Node class + * added a better error message when a template is empty but contain a BOM + * fixed "in" operator for empty strings + * fixed the "defined" test and the "default" filter (now works with more than one call (foo.bar.foo) and for both values of the strict_variables option) + * changed the way extensions are loaded (addFilter/addFunction/addGlobal/addTest/addNodeVisitor/addTokenParser/addExtension can now be called in any order) + * added Twig_Environment::display() + * made the escape filter smarter when the encoding is not supported by PHP + * added a convert_encoding filter + * moved all node manipulations outside the compile() Node method + * made several speed optimizations + +# 1.3.0 (2011-10-08) + +no changes + +# 1.3.0-RC1 (2011-10-04) + + * added an optimization for the parent() function + * added cache reloading when auto_reload is true and an extension has been modified + * added the possibility to force the escaping of a string already marked as safe (instance of Twig_Markup) + * allowed empty templates to be used as traits + * added traits support for the "parent" function + +# 1.2.0 (2011-09-13) + +no changes + +# 1.2.0-RC1 (2011-09-10) + + * enhanced the exception when a tag remains unclosed + * added support for empty Countable objects for the "empty" test + * fixed algorithm that determines if a template using inheritance is valid (no output between block definitions) + * added better support for encoding problems when escaping a string (available as of PHP 5.4) + * added a way to ignore a missing template when using the "include" tag ({% include "foo" ignore missing %}) + * added support for an array of templates to the "include" and "extends" tags ({% include ['foo', 'bar'] %}) + * added support for bitwise operators in expressions + * added the "attribute" function to allow getting dynamic attributes on variables + * added Twig_Loader_Chain + * added Twig_Loader_Array::setTemplate() + * added an optimization for the set tag when used to capture a large chunk of static text + * changed name regex to match PHP one "[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*" (works for blocks, tags, functions, filters, and macros) + * removed the possibility to use the "extends" tag from a block + * added "if" modifier support to "for" loops + +# 1.1.2 (2011-07-30) + + * fixed json_encode filter on PHP 5.2 + * fixed regression introduced in 1.1.1 ({{ block(foo|lower) }}) + * fixed inheritance when using conditional parents + * fixed compilation of templates when the body of a child template is not empty + * fixed output when a macro throws an exception + * fixed a parsing problem when a large chunk of text is enclosed in a comment tag + * added PHPDoc for all Token parsers and Core extension functions + +# 1.1.1 (2011-07-17) + + * added a performance optimization in the Optimizer (also helps to lower the number of nested level calls) + * made some performance improvement for some edge cases + +# 1.1.0 (2011-06-28) + + * fixed json_encode filter + +# 1.1.0-RC3 (2011-06-24) + + * fixed method case-sensitivity when using the sandbox mode + * added timezone support for the date filter + * fixed possible security problems with NUL bytes + +# 1.1.0-RC2 (2011-06-16) + + * added an exception when the template passed to "use" is not a string + * made 'a.b is defined' not throw an exception if a is not defined (in strict mode) + * added {% line \d+ %} directive + +# 1.1.0-RC1 (2011-05-28) + +Flush your cache after upgrading. + + * fixed date filter when using a timestamp + * fixed the defined test for some cases + * fixed a parsing problem when a large chunk of text is enclosed in a raw tag + * added support for horizontal reuse of template blocks (see docs for more information) + * added whitespace control modifier to all tags (see docs for more information) + * added null as an alias for none (the null test is also an alias for the none test now) + * made TRUE, FALSE, NONE equivalent to their lowercase counterparts + * wrapped all compilation and runtime exceptions with Twig_Error_Runtime and added logic to guess the template name and line + * moved display() method to Twig_Template (generated templates should now use doDisplay() instead) + +# 1.0.0 (2011-03-27) + + * fixed output when using mbstring + * fixed duplicate call of methods when using the sandbox + * made the charset configurable for the escape filter + +# 1.0.0-RC2 (2011-02-21) + + * changed the way {% set %} works when capturing (the content is now marked as safe) + * added support for macro name in the endmacro tag + * make Twig_Error compatible with PHP 5.3.0 > + * fixed an infinite loop on some Windows configurations + * fixed the "length" filter for numbers + * fixed Template::getAttribute() as properties in PHP are case sensitive + * removed coupling between Twig_Node and Twig_Template + * fixed the ternary operator precedence rule + +# 1.0.0-RC1 (2011-01-09) + +Backward incompatibilities: + + * the "items" filter, which has been deprecated for quite a long time now, has been removed + * the "range" filter has been converted to a function: 0|range(10) -> range(0, 10) + * the "constant" filter has been converted to a function: {{ some_date|date('DATE_W3C'|constant) }} -> {{ some_date|date(constant('DATE_W3C')) }} + * the "cycle" filter has been converted to a function: {{ ['odd', 'even']|cycle(i) }} -> {{ cycle(['odd', 'even'], i) }} + * the "for" tag does not support "joined by" anymore + * the "autoescape" first argument is now "true"/"false" (instead of "on"/"off") + * the "parent" tag has been replaced by a "parent" function ({{ parent() }} instead of {% parent %}) + * the "display" tag has been replaced by a "block" function ({{ block('title') }} instead of {% display title %}) + * removed the grammar and simple token parser (moved to the Twig Extensions repository) + +Changes: + + * added "needs_context" option for filters and functions (the context is then passed as a first argument) + * added global variables support + * made macros return their value instead of echoing directly (fixes calling a macro in sandbox mode) + * added the "from" tag to import macros as functions + * added support for functions (a function is just syntactic sugar for a getAttribute() call) + * made macros callable when sandbox mode is enabled + * added an exception when a macro uses a reserved name + * the "default" filter now uses the "empty" test instead of just checking for null + * added the "empty" test + +# 0.9.10 (2010-12-16) + +Backward incompatibilities: + + * The Escaper extension is enabled by default, which means that all displayed + variables are now automatically escaped. You can revert to the previous + behavior by removing the extension via $env->removeExtension('escaper') + or just set the 'autoescape' option to 'false'. + * removed the "without loop" attribute for the "for" tag (not needed anymore + as the Optimizer take care of that for most cases) + * arrays and hashes have now a different syntax + * arrays keep the same syntax with square brackets: [1, 2] + * hashes now use curly braces (["a": "b"] should now be written as {"a": "b"}) + * support for "arrays with keys" and "hashes without keys" is not supported anymore ([1, "foo": "bar"] or {"foo": "bar", 1}) + * the i18n extension is now part of the Twig Extensions repository + +Changes: + + * added the merge filter + * removed 'is_escaper' option for filters (a left over from the previous version) -- you must use 'is_safe' now instead + * fixed usage of operators as method names (like is, in, and not) + * changed the order of execution for node visitors + * fixed default() filter behavior when used with strict_variables set to on + * fixed filesystem loader compatibility with PHAR files + * enhanced error messages when an unexpected token is parsed in an expression + * fixed filename not being added to syntax error messages + * added the autoescape option to enable/disable autoescaping + * removed the newline after a comment (mimics PHP behavior) + * added a syntax error exception when parent block is used on a template that does not extend another one + * made the Escaper extension enabled by default + * fixed sandbox extension when used with auto output escaping + * fixed escaper when wrapping a Twig_Node_Print (the original class must be preserved) + * added an Optimizer extension (enabled by default; optimizes "for" loops and "raw" filters) + * added priority to node visitors + +# 0.9.9 (2010-11-28) + +Backward incompatibilities: + * the self special variable has been renamed to _self + * the odd and even filters are now tests: + {{ foo|odd }} must now be written {{ foo is odd }} + * the "safe" filter has been renamed to "raw" + * in Node classes, + sub-nodes are now accessed via getNode() (instead of property access) + attributes via getAttribute() (instead of array access) + * the urlencode filter had been renamed to url_encode + * the include tag now merges the passed variables with the current context by default + (the old behavior is still possible by adding the "only" keyword) + * moved Exceptions to Twig_Error_* (Twig_SyntaxError/Twig_RuntimeError are now Twig_Error_Syntax/Twig_Error_Runtime) + * removed support for {{ 1 < i < 3 }} (use {{ i > 1 and i < 3 }} instead) + * the "in" filter has been removed ({{ a|in(b) }} should now be written {{ a in b }}) + +Changes: + * added file and line to Twig_Error_Runtime exceptions thrown from Twig_Template + * changed trans tag to accept any variable for the plural count + * fixed sandbox mode (__toString() method check was not enforced if called implicitly from complex statements) + * added the ** (power) operator + * changed the algorithm used for parsing expressions + * added the spaceless tag + * removed trim_blocks option + * added support for is*() methods for attributes (foo.bar now looks for foo->getBar() or foo->isBar()) + * changed all exceptions to extend Twig_Error + * fixed unary expressions ({{ not(1 or 0) }}) + * fixed child templates (with an extend tag) that uses one or more imports + * added support for {{ 1 not in [2, 3] }} (more readable than the current {{ not (1 in [2, 3]) }}) + * escaping has been rewritten + * the implementation of template inheritance has been rewritten + (blocks can now be called individually and still work with inheritance) + * fixed error handling for if tag when a syntax error occurs within a subparse process + * added a way to implement custom logic for resolving token parsers given a tag name + * fixed js escaper to be stricter (now uses a whilelist-based js escaper) + * added the following filers: "constant", "trans", "replace", "json_encode" + * added a "constant" test + * fixed objects with __toString() not being autoescaped + * fixed subscript expressions when calling __call() (methods now keep the case) + * added "test" feature (accessible via the "is" operator) + * removed the debug tag (should be done in an extension) + * fixed trans tag when no vars are used in plural form + * fixed race condition when writing template cache + * added the special _charset variable to reference the current charset + * added the special _context variable to reference the current context + * renamed self to _self (to avoid conflict) + * fixed Twig_Template::getAttribute() for protected properties + +# 0.9.8 (2010-06-28) + +Backward incompatibilities: + * the trans tag plural count is now attached to the plural tag: + old: `{% trans count %}...{% plural %}...{% endtrans %}` + new: `{% trans %}...{% plural count %}...{% endtrans %}` + + * added a way to translate strings coming from a variable ({% trans var %}) + * fixed trans tag when used with the Escaper extension + * fixed default cache umask + * removed Twig_Template instances from the debug tag output + * fixed objects with __isset() defined + * fixed set tag when used with a capture + * fixed type hinting for Twig_Environment::addFilter() method + +# 0.9.7 (2010-06-12) + +Backward incompatibilities: + * changed 'as' to '=' for the set tag ({% set title as "Title" %} must now be {% set title = "Title" %}) + * removed the sandboxed attribute of the include tag (use the new sandbox tag instead) + * refactored the Node system (if you have custom nodes, you will have to update them to use the new API) + + * added self as a special variable that refers to the current template (useful for importing macros from the current template) + * added Twig_Template instance support to the include tag + * added support for dynamic and conditional inheritance ({% extends some_var %} and {% extends standalone ? "minimum" : "base" %}) + * added a grammar sub-framework to ease the creation of custom tags + * fixed the for tag for large arrays (some loop variables are now only available for arrays and objects that implement the Countable interface) + * removed the Twig_Resource::resolveMissingFilter() method + * fixed the filter tag which did not apply filtering to included files + * added a bunch of unit tests + * added a bunch of phpdoc + * added a sandbox tag in the sandbox extension + * changed the date filter to support any date format supported by DateTime + * added strict_variable setting to throw an exception when an invalid variable is used in a template (disabled by default) + * added the lexer, parser, and compiler as arguments to the Twig_Environment constructor + * changed the cache option to only accepts an explicit path to a cache directory or false + * added a way to add token parsers, filters, and visitors without creating an extension + * added three interfaces: Twig_NodeInterface, Twig_TokenParserInterface, and Twig_FilterInterface + * changed the generated code to match the new coding standards + * fixed sandbox mode (__toString() method check was not enforced if called implicitly from a simple statement like {{ article }}) + * added an exception when a child template has a non-empty body (as it is always ignored when rendering) + +# 0.9.6 (2010-05-12) + + * fixed variables defined outside a loop and for which the value changes in a for loop + * fixed the test suite for PHP 5.2 and older versions of PHPUnit + * added support for __call() in expression resolution + * fixed node visiting for macros (macros are now visited by visitors as any other node) + * fixed nested block definitions with a parent call (rarely useful but nonetheless supported now) + * added the cycle filter + * fixed the Lexer when mbstring.func_overload is used with an mbstring.internal_encoding different from ASCII + * added a long-syntax for the set tag ({% set foo %}...{% endset %}) + * unit tests are now powered by PHPUnit + * added support for gettext via the `i18n` extension + * fixed twig_capitalize_string_filter() and fixed twig_length_filter() when used with UTF-8 values + * added a more useful exception if an if tag is not closed properly + * added support for escaping strategy in the autoescape tag + * fixed lexer when a template has a big chunk of text between/in a block + +# 0.9.5 (2010-01-20) + +As for any new release, don't forget to remove all cached templates after +upgrading. + +If you have defined custom filters, you MUST upgrade them for this release. To +upgrade, replace "array" with "new Twig_Filter_Function", and replace the +environment constant by the "needs_environment" option: + + // before + 'even' => array('twig_is_even_filter', false), + 'escape' => array('twig_escape_filter', true), + + // after + 'even' => new Twig_Filter_Function('twig_is_even_filter'), + 'escape' => new Twig_Filter_Function('twig_escape_filter', array('needs_environment' => true)), + +If you have created NodeTransformer classes, you will need to upgrade them to +the new interface (please note that the interface is not yet considered +stable). + + * fixed list nodes that did not extend the Twig_NodeListInterface + * added the "without loop" option to the for tag (it disables the generation of the loop variable) + * refactored node transformers to node visitors + * fixed automatic-escaping for blocks + * added a way to specify variables to pass to an included template + * changed the automatic-escaping rules to be more sensible and more configurable in custom filters (the documentation lists all the rules) + * improved the filter system to allow object methods to be used as filters + * changed the Array and String loaders to actually make use of the cache mechanism + * included the default filter function definitions in the extension class files directly (Core, Escaper) + * added the // operator (like the floor() PHP function) + * added the .. operator (as a syntactic sugar for the range filter when the step is 1) + * added the in operator (as a syntactic sugar for the in filter) + * added the following filters in the Core extension: in, range + * added support for arrays (same behavior as in PHP, a mix between lists and dictionaries, arrays and hashes) + * enhanced some error messages to provide better feedback in case of parsing errors + +# 0.9.4 (2009-12-02) + +If you have custom loaders, you MUST upgrade them for this release: The +Twig_Loader base class has been removed, and the Twig_LoaderInterface has also +been changed (see the source code for more information or the documentation). + + * added support for DateTime instances for the date filter + * fixed loop.last when the array only has one item + * made it possible to insert newlines in tag and variable blocks + * fixed a bug when a literal '\n' were present in a template text + * fixed bug when the filename of a template contains */ + * refactored loaders + +# 0.9.3 (2009-11-11) + +This release is NOT backward compatible with the previous releases. + + The loaders do not take the cache and autoReload arguments anymore. Instead, + the Twig_Environment class has two new options: cache and auto_reload. + Upgrading your code means changing this kind of code: + + $loader = new Twig_Loader_Filesystem('/path/to/templates', '/path/to/compilation_cache', true); + $twig = new Twig_Environment($loader); + + to something like this: + + $loader = new Twig_Loader_Filesystem('/path/to/templates'); + $twig = new Twig_Environment($loader, array( + 'cache' => '/path/to/compilation_cache', + 'auto_reload' => true, + )); + + * deprecated the "items" filter as it is not needed anymore + * made cache and auto_reload options of Twig_Environment instead of arguments of Twig_Loader + * optimized template loading speed + * removed output when an error occurs in a template and render() is used + * made major speed improvements for loops (up to 300% on even the smallest loops) + * added properties as part of the sandbox mode + * added public properties support (obj.item can now be the item property on the obj object) + * extended set tag to support expression as value ({% set foo as 'foo' ~ 'bar' %} ) + * fixed bug when \ was used in HTML + +# 0.9.2 (2009-10-29) + + * made some speed optimizations + * changed the cache extension to .php + * added a js escaping strategy + * added support for short block tag + * changed the filter tag to allow chained filters + * made lexer more flexible as you can now change the default delimiters + * added set tag + * changed default directory permission when cache dir does not exist (more secure) + * added macro support + * changed filters first optional argument to be a Twig_Environment instance instead of a Twig_Template instance + * made Twig_Autoloader::autoload() a static method + * avoid writing template file if an error occurs + * added $ escaping when outputting raw strings + * enhanced some error messages to ease debugging + * fixed empty cache files when the template contains an error + +# 0.9.1 (2009-10-14) + + * fixed a bug in PHP 5.2.6 + * fixed numbers with one than one decimal + * added support for method calls with arguments ({{ foo.bar('a', 43) }}) + * made small speed optimizations + * made minor tweaks to allow better extensibility and flexibility + +# 0.9.0 (2009-10-12) + + * Initial release diff --git a/src/bb-vendor/twig/twig/doc/filters/html_to_markdown.rst b/src/bb-vendor/twig/twig/doc/filters/html_to_markdown.rst new file mode 100644 index 000000000..4cb55459e --- /dev/null +++ b/src/bb-vendor/twig/twig/doc/filters/html_to_markdown.rst @@ -0,0 +1,66 @@ +``html_to_markdown`` +==================== + +.. versionadded:: 2.12 + The ``html_to_markdown`` filter was added in Twig 2.12. + +The ``html_to_markdown`` filter converts a block of HTML to Markdown: + +.. code-block:: twig + + {% apply html_to_markdown %} + +

    Hello!

    + + {% endapply %} + +You can also add some options by passing them as an argument to the filter: + +.. code-block:: twig + + {% apply html_to_markdown({hard_break: false}) %} + +

    Hello!

    + + {% endapply %} + +.. note:: + + The options are the ones provided by the ``league/html-to-markdown`` package. + +You can also use the filter on an included file: + +.. code-block:: twig + + {{ include('some_template.html.twig')|html_to_markdown }} + +.. note:: + + The ``html_to_markdown`` filter is part of the ``MarkdownExtension`` which + is not installed by default. Install it first: + + .. code-block:: bash + + $ composer req twig/markdown-extra + + Then, use the ``twig/extra-bundle`` on Symfony projects or add the extension + explicitly on the Twig environment:: + + use Twig\Extra\Markdown\MarkdownExtension; + + $twig = new \Twig\Environment(...); + $twig->addExtension(new MarkdownExtension()); + + If you are not using Symfony, you must also register the extension runtime:: + + use Twig\Extra\Markdown\DefaultMarkdown; + use Twig\Extra\Markdown\MarkdownRuntime; + use Twig\RuntimeLoader\RuntimeLoaderInterface; + + $twig->addRuntimeLoader(new class implements RuntimeLoaderInterface { + public function load($class) { + if (MarkdownRuntime::class === $class) { + return new MarkdownRuntime(new DefaultMarkdown()); + } + } + }); diff --git a/src/bb-vendor/twig/twig/doc/tags/macro.rst b/src/bb-vendor/twig/twig/doc/tags/macro.rst new file mode 100644 index 000000000..691a3c5aa --- /dev/null +++ b/src/bb-vendor/twig/twig/doc/tags/macro.rst @@ -0,0 +1,180 @@ +``macro`` +========= + +Macros are comparable with functions in regular programming languages. They +are useful to reuse template fragments to not repeat yourself. + +Macros are defined in regular templates. + +Imagine having a generic helper template that define how to render HTML forms +via macros (called ``forms.html``): + +.. code-block:: twig + + {% macro input(name, value, type = "text", size = 20) %} + + {% endmacro %} + + {% macro textarea(name, value, rows = 10, cols = 40) %} + + {% endmacro %} + +Each macro argument can have a default value (here ``text`` is the default value +for ``type`` if not provided in the call). + +Macros differ from native PHP functions in a few ways: + +* Arguments of a macro are always optional. + +* If extra positional arguments are passed to a macro, they end up in the + special ``varargs`` variable as a list of values. + +But as with PHP functions, macros don't have access to the current template +variables. + +.. tip:: + + You can pass the whole context as an argument by using the special + ``_context`` variable. + +Importing Macros +---------------- + +There are two ways to import macros. You can import the complete template +containing the macros into a local variable (via the ``import`` tag) or only +import specific macros from the template (via the ``from`` tag). + +To import all macros from a template into a local variable, use the ``import`` +tag: + +.. code-block:: twig + + {% import "forms.html" as forms %} + +The above ``import`` call imports the ``forms.html`` file (which can contain +only macros, or a template and some macros), and import the macros as items of +the ``forms`` local variable. + +The macros can then be called at will in the *current* template: + +.. code-block:: twig + +

    {{ forms.input('username') }}

    +

    {{ forms.input('password', null, 'password') }}

    + +Alternatively you can import names from the template into the current namespace +via the ``from`` tag: + +.. code-block:: twig + + {% from 'forms.html' import input as input_field, textarea %} + +

    {{ input_field('password', '', 'password') }}

    +

    {{ textarea('comment') }}

    + +.. tip:: + + When macro usages and definitions are in the same template, you don't need to + import the macros as they are automatically available under the special + ``_self`` variable: + + .. code-block:: twig + +

    {{ _self.input('password', '', 'password') }}

    + + {% macro input(name, value, type = "text", size = 20) %} + + {% endmacro %} + + Auto-import is only available as of Twig 2.11. For older versions, import + macros using the special ``_self`` variable for the template name: + + .. code-block:: twig + + {% import _self as forms %} + +

    {{ forms.input('username') }}

    + +.. note:: + + Before Twig 2.11, when you want to use a macro in another macro from the + same file, you need to import it locally: + + .. code-block:: twig + + {% macro input(name, value, type, size) %} + + {% endmacro %} + + {% macro wrapped_input(name, value, type, size) %} + {% import _self as forms %} + +
    + {{ forms.input(name, value, type, size) }} +
    + {% endmacro %} + +Macros Scoping +-------------- + +.. versionadded:: 2.11 + + The scoping rules described in this paragraph are implemented as of Twig + 2.11. + +The scoping rules are the same whether you imported macros via ``import`` or +``from``. + +Imported macros are always **local** to the current template. It means that +macros are available in all blocks and other macros defined in the current +template, but they are not available in included templates or child templates; +you need to explicitly re-import macros in each template. + +When calling ``import`` or ``from`` from a ``block`` tag, the imported macros +are only defined in the current block and they override macros defined at the +template level with the same names. + +When calling ``import`` or ``from`` from a ``macro`` tag, the imported macros +are only defined in the current macro and they override macros defined at the +template level with the same names. + +.. note:: + + Before Twig 2.11, it was possible to use macros imported in a block in a + "sub-block". When upgrading to 2.11, you need to either move the import in + the global scope or reimport the macros explicitly in the "sub-blocks". + +Checking if a Macro is defined +------------------------------ + +.. versionadded:: 2.11 + + Support for the ``defined`` test on macros was added in Twig 2.11. + +You can check if a macro is defined via the ``defined`` test: + +.. code-block:: twig + + {% import "macros.twig" as macros %} + + {% from "macros.twig" import hello %} + + {% if macros.hello is defined -%} + OK + {% endif %} + + {% if hello is defined -%} + OK + {% endif %} + +Named Macro End-Tags +-------------------- + +Twig allows you to put the name of the macro after the end tag for better +readability (the name after the ``endmacro`` word must match the macro name): + +.. code-block:: twig + + {% macro input() %} + ... + {% endmacro input %} diff --git a/src/bb-vendor/twig/twig/src/Environment.php b/src/bb-vendor/twig/twig/src/Environment.php new file mode 100644 index 000000000..fab6c7898 --- /dev/null +++ b/src/bb-vendor/twig/twig/src/Environment.php @@ -0,0 +1,995 @@ + + */ +class Environment +{ + const VERSION = '2.13.0'; + const VERSION_ID = 21300; + const MAJOR_VERSION = 2; + const MINOR_VERSION = 13; + const RELEASE_VERSION = 0; + const EXTRA_VERSION = ''; + + private $charset; + private $loader; + private $debug; + private $autoReload; + private $cache; + private $lexer; + private $parser; + private $compiler; + private $baseTemplateClass; + private $globals = []; + private $resolvedGlobals; + private $loadedTemplates; + private $strictVariables; + private $templateClassPrefix = '__TwigTemplate_'; + private $originalCache; + private $extensionSet; + private $runtimeLoaders = []; + private $runtimes = []; + private $optionsHash; + + /** + * Constructor. + * + * Available options: + * + * * debug: When set to true, it automatically set "auto_reload" to true as + * well (default to false). + * + * * charset: The charset used by the templates (default to UTF-8). + * + * * base_template_class: The base template class to use for generated + * templates (default to \Twig\Template). + * + * * cache: An absolute path where to store the compiled templates, + * a \Twig\Cache\CacheInterface implementation, + * or false to disable compilation cache (default). + * + * * auto_reload: Whether to reload the template if the original source changed. + * If you don't provide the auto_reload option, it will be + * determined automatically based on the debug value. + * + * * strict_variables: Whether to ignore invalid variables in templates + * (default to false). + * + * * autoescape: Whether to enable auto-escaping (default to html): + * * false: disable auto-escaping + * * html, js: set the autoescaping to one of the supported strategies + * * name: set the autoescaping strategy based on the template name extension + * * PHP callback: a PHP callback that returns an escaping strategy based on the template "name" + * + * * optimizations: A flag that indicates which optimizations to apply + * (default to -1 which means that all optimizations are enabled; + * set it to 0 to disable). + */ + public function __construct(LoaderInterface $loader, $options = []) + { + $this->setLoader($loader); + + $options = array_merge([ + 'debug' => false, + 'charset' => 'UTF-8', + 'base_template_class' => Template::class, + 'strict_variables' => false, + 'autoescape' => 'html', + 'cache' => false, + 'auto_reload' => null, + 'optimizations' => -1, + ], $options); + + $this->debug = (bool) $options['debug']; + $this->setCharset($options['charset']); + $this->baseTemplateClass = '\\'.ltrim($options['base_template_class'], '\\'); + if ('\\'.Template::class !== $this->baseTemplateClass && '\Twig_Template' !== $this->baseTemplateClass) { + @trigger_error('The "base_template_class" option on '.__CLASS__.' is deprecated since Twig 2.7.0.', E_USER_DEPRECATED); + } + $this->autoReload = null === $options['auto_reload'] ? $this->debug : (bool) $options['auto_reload']; + $this->strictVariables = (bool) $options['strict_variables']; + $this->setCache($options['cache']); + $this->extensionSet = new ExtensionSet(); + + $this->addExtension(new CoreExtension()); + $this->addExtension(new EscaperExtension($options['autoescape'])); + $this->addExtension(new OptimizerExtension($options['optimizations'])); + } + + /** + * Gets the base template class for compiled templates. + * + * @return string The base template class name + */ + public function getBaseTemplateClass() + { + if (1 > \func_num_args() || \func_get_arg(0)) { + @trigger_error('The '.__METHOD__.' is deprecated since Twig 2.7.0.', E_USER_DEPRECATED); + } + + return $this->baseTemplateClass; + } + + /** + * Sets the base template class for compiled templates. + * + * @param string $class The base template class name + */ + public function setBaseTemplateClass($class) + { + @trigger_error('The '.__METHOD__.' is deprecated since Twig 2.7.0.', E_USER_DEPRECATED); + + $this->baseTemplateClass = $class; + $this->updateOptionsHash(); + } + + /** + * Enables debugging mode. + */ + public function enableDebug() + { + $this->debug = true; + $this->updateOptionsHash(); + } + + /** + * Disables debugging mode. + */ + public function disableDebug() + { + $this->debug = false; + $this->updateOptionsHash(); + } + + /** + * Checks if debug mode is enabled. + * + * @return bool true if debug mode is enabled, false otherwise + */ + public function isDebug() + { + return $this->debug; + } + + /** + * Enables the auto_reload option. + */ + public function enableAutoReload() + { + $this->autoReload = true; + } + + /** + * Disables the auto_reload option. + */ + public function disableAutoReload() + { + $this->autoReload = false; + } + + /** + * Checks if the auto_reload option is enabled. + * + * @return bool true if auto_reload is enabled, false otherwise + */ + public function isAutoReload() + { + return $this->autoReload; + } + + /** + * Enables the strict_variables option. + */ + public function enableStrictVariables() + { + $this->strictVariables = true; + $this->updateOptionsHash(); + } + + /** + * Disables the strict_variables option. + */ + public function disableStrictVariables() + { + $this->strictVariables = false; + $this->updateOptionsHash(); + } + + /** + * Checks if the strict_variables option is enabled. + * + * @return bool true if strict_variables is enabled, false otherwise + */ + public function isStrictVariables() + { + return $this->strictVariables; + } + + /** + * Gets the current cache implementation. + * + * @param bool $original Whether to return the original cache option or the real cache instance + * + * @return CacheInterface|string|false A Twig\Cache\CacheInterface implementation, + * an absolute path to the compiled templates, + * or false to disable cache + */ + public function getCache($original = true) + { + return $original ? $this->originalCache : $this->cache; + } + + /** + * Sets the current cache implementation. + * + * @param CacheInterface|string|false $cache A Twig\Cache\CacheInterface implementation, + * an absolute path to the compiled templates, + * or false to disable cache + */ + public function setCache($cache) + { + if (\is_string($cache)) { + $this->originalCache = $cache; + $this->cache = new FilesystemCache($cache); + } elseif (false === $cache) { + $this->originalCache = $cache; + $this->cache = new NullCache(); + } elseif ($cache instanceof CacheInterface) { + $this->originalCache = $this->cache = $cache; + } else { + throw new \LogicException(sprintf('Cache can only be a string, false, or a \Twig\Cache\CacheInterface implementation.')); + } + } + + /** + * Gets the template class associated with the given string. + * + * The generated template class is based on the following parameters: + * + * * The cache key for the given template; + * * The currently enabled extensions; + * * Whether the Twig C extension is available or not; + * * PHP version; + * * Twig version; + * * Options with what environment was created. + * + * @param string $name The name for which to calculate the template class name + * @param int|null $index The index if it is an embedded template + * + * @return string The template class name + * + * @internal + */ + public function getTemplateClass($name, $index = null) + { + $key = $this->getLoader()->getCacheKey($name).$this->optionsHash; + + return $this->templateClassPrefix.hash('sha256', $key).(null === $index ? '' : '___'.$index); + } + + /** + * Renders a template. + * + * @param string|TemplateWrapper $name The template name + * @param array $context An array of parameters to pass to the template + * + * @return string The rendered template + * + * @throws LoaderError When the template cannot be found + * @throws SyntaxError When an error occurred during compilation + * @throws RuntimeError When an error occurred during rendering + */ + public function render($name, array $context = []) + { + return $this->load($name)->render($context); + } + + /** + * Displays a template. + * + * @param string|TemplateWrapper $name The template name + * @param array $context An array of parameters to pass to the template + * + * @throws LoaderError When the template cannot be found + * @throws SyntaxError When an error occurred during compilation + * @throws RuntimeError When an error occurred during rendering + */ + public function display($name, array $context = []) + { + $this->load($name)->display($context); + } + + /** + * Loads a template. + * + * @param string|TemplateWrapper $name The template name + * + * @throws LoaderError When the template cannot be found + * @throws RuntimeError When a previously generated cache is corrupted + * @throws SyntaxError When an error occurred during compilation + * + * @return TemplateWrapper + */ + public function load($name) + { + if ($name instanceof TemplateWrapper) { + return $name; + } + + if ($name instanceof Template) { + @trigger_error('Passing a \Twig\Template instance to '.__METHOD__.' is deprecated since Twig 2.7.0, use \Twig\TemplateWrapper instead.', E_USER_DEPRECATED); + + return new TemplateWrapper($this, $name); + } + + return new TemplateWrapper($this, $this->loadTemplate($name)); + } + + /** + * Loads a template internal representation. + * + * This method is for internal use only and should never be called + * directly. + * + * @param string $name The template name + * @param int $index The index if it is an embedded template + * + * @return Template A template instance representing the given template name + * + * @throws LoaderError When the template cannot be found + * @throws RuntimeError When a previously generated cache is corrupted + * @throws SyntaxError When an error occurred during compilation + * + * @internal + */ + public function loadTemplate($name, $index = null) + { + return $this->loadClass($this->getTemplateClass($name), $name, $index); + } + + /** + * @internal + */ + public function loadClass($cls, $name, $index = null) + { + $mainCls = $cls; + if (null !== $index) { + $cls .= '___'.$index; + } + + if (isset($this->loadedTemplates[$cls])) { + return $this->loadedTemplates[$cls]; + } + + if (!class_exists($cls, false)) { + $key = $this->cache->generateKey($name, $mainCls); + + if (!$this->isAutoReload() || $this->isTemplateFresh($name, $this->cache->getTimestamp($key))) { + $this->cache->load($key); + } + + $source = null; + if (!class_exists($cls, false)) { + $source = $this->getLoader()->getSourceContext($name); + $content = $this->compileSource($source); + $this->cache->write($key, $content); + $this->cache->load($key); + + if (!class_exists($mainCls, false)) { + /* Last line of defense if either $this->bcWriteCacheFile was used, + * $this->cache is implemented as a no-op or we have a race condition + * where the cache was cleared between the above calls to write to and load from + * the cache. + */ + eval('?>'.$content); + } + + if (!class_exists($cls, false)) { + throw new RuntimeError(sprintf('Failed to load Twig template "%s", index "%s": cache might be corrupted.', $name, $index), -1, $source); + } + } + } + + // to be removed in 3.0 + $this->extensionSet->initRuntime($this); + + return $this->loadedTemplates[$cls] = new $cls($this); + } + + /** + * Creates a template from source. + * + * This method should not be used as a generic way to load templates. + * + * @param string $template The template source + * @param string $name An optional name of the template to be used in error messages + * + * @return TemplateWrapper A template instance representing the given template name + * + * @throws LoaderError When the template cannot be found + * @throws SyntaxError When an error occurred during compilation + */ + public function createTemplate($template, string $name = null) + { + $hash = hash('sha256', $template, false); + if (null !== $name) { + $name = sprintf('%s (string template %s)', $name, $hash); + } else { + $name = sprintf('__string_template__%s', $hash); + } + + $loader = new ChainLoader([ + new ArrayLoader([$name => $template]), + $current = $this->getLoader(), + ]); + + $this->setLoader($loader); + try { + return new TemplateWrapper($this, $this->loadTemplate($name)); + } finally { + $this->setLoader($current); + } + } + + /** + * Returns true if the template is still fresh. + * + * Besides checking the loader for freshness information, + * this method also checks if the enabled extensions have + * not changed. + * + * @param string $name The template name + * @param int $time The last modification time of the cached template + * + * @return bool true if the template is fresh, false otherwise + */ + public function isTemplateFresh($name, $time) + { + return $this->extensionSet->getLastModified() <= $time && $this->getLoader()->isFresh($name, $time); + } + + /** + * Tries to load a template consecutively from an array. + * + * Similar to load() but it also accepts instances of \Twig\Template and + * \Twig\TemplateWrapper, and an array of templates where each is tried to be loaded. + * + * @param string|TemplateWrapper|array $names A template or an array of templates to try consecutively + * + * @return TemplateWrapper|Template + * + * @throws LoaderError When none of the templates can be found + * @throws SyntaxError When an error occurred during compilation + */ + public function resolveTemplate($names) + { + if (!\is_array($names)) { + $names = [$names]; + } + + foreach ($names as $name) { + if ($name instanceof Template) { + return $name; + } + if ($name instanceof TemplateWrapper) { + return $name; + } + + try { + return $this->loadTemplate($name); + } catch (LoaderError $e) { + if (1 === \count($names)) { + throw $e; + } + } + } + + throw new LoaderError(sprintf('Unable to find one of the following templates: "%s".', implode('", "', $names))); + } + + public function setLexer(Lexer $lexer) + { + $this->lexer = $lexer; + } + + /** + * Tokenizes a source code. + * + * @return TokenStream + * + * @throws SyntaxError When the code is syntactically wrong + */ + public function tokenize(Source $source) + { + if (null === $this->lexer) { + $this->lexer = new Lexer($this); + } + + return $this->lexer->tokenize($source); + } + + public function setParser(Parser $parser) + { + $this->parser = $parser; + } + + /** + * Converts a token stream to a node tree. + * + * @return ModuleNode + * + * @throws SyntaxError When the token stream is syntactically or semantically wrong + */ + public function parse(TokenStream $stream) + { + if (null === $this->parser) { + $this->parser = new Parser($this); + } + + return $this->parser->parse($stream); + } + + public function setCompiler(Compiler $compiler) + { + $this->compiler = $compiler; + } + + /** + * Compiles a node and returns the PHP code. + * + * @return string The compiled PHP source code + */ + public function compile(Node $node) + { + if (null === $this->compiler) { + $this->compiler = new Compiler($this); + } + + return $this->compiler->compile($node)->getSource(); + } + + /** + * Compiles a template source code. + * + * @return string The compiled PHP source code + * + * @throws SyntaxError When there was an error during tokenizing, parsing or compiling + */ + public function compileSource(Source $source) + { + try { + return $this->compile($this->parse($this->tokenize($source))); + } catch (Error $e) { + $e->setSourceContext($source); + throw $e; + } catch (\Exception $e) { + throw new SyntaxError(sprintf('An exception has been thrown during the compilation of a template ("%s").', $e->getMessage()), -1, $source, $e); + } + } + + public function setLoader(LoaderInterface $loader) + { + $this->loader = $loader; + } + + /** + * Gets the Loader instance. + * + * @return LoaderInterface + */ + public function getLoader() + { + return $this->loader; + } + + /** + * Sets the default template charset. + * + * @param string $charset The default charset + */ + public function setCharset($charset) + { + if ('UTF8' === $charset = strtoupper($charset)) { + // iconv on Windows requires "UTF-8" instead of "UTF8" + $charset = 'UTF-8'; + } + + $this->charset = $charset; + } + + /** + * Gets the default template charset. + * + * @return string The default charset + */ + public function getCharset() + { + return $this->charset; + } + + /** + * Returns true if the given extension is registered. + * + * @param string $class The extension class name + * + * @return bool Whether the extension is registered or not + */ + public function hasExtension($class) + { + return $this->extensionSet->hasExtension($class); + } + + /** + * Adds a runtime loader. + */ + public function addRuntimeLoader(RuntimeLoaderInterface $loader) + { + $this->runtimeLoaders[] = $loader; + } + + /** + * Gets an extension by class name. + * + * @param string $class The extension class name + * + * @return ExtensionInterface + */ + public function getExtension($class) + { + return $this->extensionSet->getExtension($class); + } + + /** + * Returns the runtime implementation of a Twig element (filter/function/test). + * + * @param string $class A runtime class name + * + * @return object The runtime implementation + * + * @throws RuntimeError When the template cannot be found + */ + public function getRuntime($class) + { + if (isset($this->runtimes[$class])) { + return $this->runtimes[$class]; + } + + foreach ($this->runtimeLoaders as $loader) { + if (null !== $runtime = $loader->load($class)) { + return $this->runtimes[$class] = $runtime; + } + } + + throw new RuntimeError(sprintf('Unable to load the "%s" runtime.', $class)); + } + + public function addExtension(ExtensionInterface $extension) + { + $this->extensionSet->addExtension($extension); + $this->updateOptionsHash(); + } + + /** + * Registers an array of extensions. + * + * @param array $extensions An array of extensions + */ + public function setExtensions(array $extensions) + { + $this->extensionSet->setExtensions($extensions); + $this->updateOptionsHash(); + } + + /** + * Returns all registered extensions. + * + * @return ExtensionInterface[] An array of extensions (keys are for internal usage only and should not be relied on) + */ + public function getExtensions() + { + return $this->extensionSet->getExtensions(); + } + + public function addTokenParser(TokenParserInterface $parser) + { + $this->extensionSet->addTokenParser($parser); + } + + /** + * Gets the registered Token Parsers. + * + * @return TokenParserInterface[] + * + * @internal + */ + public function getTokenParsers() + { + return $this->extensionSet->getTokenParsers(); + } + + /** + * Gets registered tags. + * + * @return TokenParserInterface[] + * + * @internal + */ + public function getTags() + { + $tags = []; + foreach ($this->getTokenParsers() as $parser) { + $tags[$parser->getTag()] = $parser; + } + + return $tags; + } + + public function addNodeVisitor(NodeVisitorInterface $visitor) + { + $this->extensionSet->addNodeVisitor($visitor); + } + + /** + * Gets the registered Node Visitors. + * + * @return NodeVisitorInterface[] + * + * @internal + */ + public function getNodeVisitors() + { + return $this->extensionSet->getNodeVisitors(); + } + + public function addFilter(TwigFilter $filter) + { + $this->extensionSet->addFilter($filter); + } + + /** + * Get a filter by name. + * + * Subclasses may override this method and load filters differently; + * so no list of filters is available. + * + * @param string $name The filter name + * + * @return TwigFilter|false + * + * @internal + */ + public function getFilter($name) + { + return $this->extensionSet->getFilter($name); + } + + public function registerUndefinedFilterCallback(callable $callable) + { + $this->extensionSet->registerUndefinedFilterCallback($callable); + } + + /** + * Gets the registered Filters. + * + * Be warned that this method cannot return filters defined with registerUndefinedFilterCallback. + * + * @return TwigFilter[] + * + * @see registerUndefinedFilterCallback + * + * @internal + */ + public function getFilters() + { + return $this->extensionSet->getFilters(); + } + + public function addTest(TwigTest $test) + { + $this->extensionSet->addTest($test); + } + + /** + * Gets the registered Tests. + * + * @return TwigTest[] + * + * @internal + */ + public function getTests() + { + return $this->extensionSet->getTests(); + } + + /** + * Gets a test by name. + * + * @param string $name The test name + * + * @return TwigTest|false + * + * @internal + */ + public function getTest($name) + { + return $this->extensionSet->getTest($name); + } + + public function addFunction(TwigFunction $function) + { + $this->extensionSet->addFunction($function); + } + + /** + * Get a function by name. + * + * Subclasses may override this method and load functions differently; + * so no list of functions is available. + * + * @param string $name function name + * + * @return TwigFunction|false + * + * @internal + */ + public function getFunction($name) + { + return $this->extensionSet->getFunction($name); + } + + public function registerUndefinedFunctionCallback(callable $callable) + { + $this->extensionSet->registerUndefinedFunctionCallback($callable); + } + + /** + * Gets registered functions. + * + * Be warned that this method cannot return functions defined with registerUndefinedFunctionCallback. + * + * @return TwigFunction[] + * + * @see registerUndefinedFunctionCallback + * + * @internal + */ + public function getFunctions() + { + return $this->extensionSet->getFunctions(); + } + + /** + * Registers a Global. + * + * New globals can be added before compiling or rendering a template; + * but after, you can only update existing globals. + * + * @param string $name The global name + * @param mixed $value The global value + */ + public function addGlobal($name, $value) + { + if ($this->extensionSet->isInitialized() && !\array_key_exists($name, $this->getGlobals())) { + throw new \LogicException(sprintf('Unable to add global "%s" as the runtime or the extensions have already been initialized.', $name)); + } + + if (null !== $this->resolvedGlobals) { + $this->resolvedGlobals[$name] = $value; + } else { + $this->globals[$name] = $value; + } + } + + /** + * Gets the registered Globals. + * + * @return array An array of globals + * + * @internal + */ + public function getGlobals() + { + if ($this->extensionSet->isInitialized()) { + if (null === $this->resolvedGlobals) { + $this->resolvedGlobals = array_merge($this->extensionSet->getGlobals(), $this->globals); + } + + return $this->resolvedGlobals; + } + + return array_merge($this->extensionSet->getGlobals(), $this->globals); + } + + /** + * Merges a context with the defined globals. + * + * @param array $context An array representing the context + * + * @return array The context merged with the globals + */ + public function mergeGlobals(array $context) + { + // we don't use array_merge as the context being generally + // bigger than globals, this code is faster. + foreach ($this->getGlobals() as $key => $value) { + if (!\array_key_exists($key, $context)) { + $context[$key] = $value; + } + } + + return $context; + } + + /** + * Gets the registered unary Operators. + * + * @return array An array of unary operators + * + * @internal + */ + public function getUnaryOperators() + { + return $this->extensionSet->getUnaryOperators(); + } + + /** + * Gets the registered binary Operators. + * + * @return array An array of binary operators + * + * @internal + */ + public function getBinaryOperators() + { + return $this->extensionSet->getBinaryOperators(); + } + + private function updateOptionsHash() + { + $this->optionsHash = implode(':', [ + $this->extensionSet->getSignature(), + PHP_MAJOR_VERSION, + PHP_MINOR_VERSION, + self::VERSION, + (int) $this->debug, + $this->baseTemplateClass, + (int) $this->strictVariables, + ]); + } +} + +class_alias('Twig\Environment', 'Twig_Environment'); diff --git a/src/bb-vendor/twig/twig/src/ExpressionParser.php b/src/bb-vendor/twig/twig/src/ExpressionParser.php new file mode 100644 index 000000000..e6a2073c5 --- /dev/null +++ b/src/bb-vendor/twig/twig/src/ExpressionParser.php @@ -0,0 +1,814 @@ + + * + * @internal + */ +class ExpressionParser +{ + const OPERATOR_LEFT = 1; + const OPERATOR_RIGHT = 2; + + private $parser; + private $env; + private $unaryOperators; + private $binaryOperators; + + public function __construct(Parser $parser, Environment $env) + { + $this->parser = $parser; + $this->env = $env; + $this->unaryOperators = $env->getUnaryOperators(); + $this->binaryOperators = $env->getBinaryOperators(); + } + + public function parseExpression($precedence = 0, $allowArrow = false) + { + if ($allowArrow && $arrow = $this->parseArrow()) { + return $arrow; + } + + $expr = $this->getPrimary(); + $token = $this->parser->getCurrentToken(); + while ($this->isBinary($token) && $this->binaryOperators[$token->getValue()]['precedence'] >= $precedence) { + $op = $this->binaryOperators[$token->getValue()]; + $this->parser->getStream()->next(); + + if ('is not' === $token->getValue()) { + $expr = $this->parseNotTestExpression($expr); + } elseif ('is' === $token->getValue()) { + $expr = $this->parseTestExpression($expr); + } elseif (isset($op['callable'])) { + $expr = $op['callable']($this->parser, $expr); + } else { + $expr1 = $this->parseExpression(self::OPERATOR_LEFT === $op['associativity'] ? $op['precedence'] + 1 : $op['precedence']); + $class = $op['class']; + $expr = new $class($expr, $expr1, $token->getLine()); + } + + $token = $this->parser->getCurrentToken(); + } + + if (0 === $precedence) { + return $this->parseConditionalExpression($expr); + } + + return $expr; + } + + /** + * @return ArrowFunctionExpression|null + */ + private function parseArrow() + { + $stream = $this->parser->getStream(); + + // short array syntax (one argument, no parentheses)? + if ($stream->look(1)->test(/* Token::ARROW_TYPE */ 12)) { + $line = $stream->getCurrent()->getLine(); + $token = $stream->expect(/* Token::NAME_TYPE */ 5); + $names = [new AssignNameExpression($token->getValue(), $token->getLine())]; + $stream->expect(/* Token::ARROW_TYPE */ 12); + + return new ArrowFunctionExpression($this->parseExpression(0), new Node($names), $line); + } + + // first, determine if we are parsing an arrow function by finding => (long form) + $i = 0; + if (!$stream->look($i)->test(/* Token::PUNCTUATION_TYPE */ 9, '(')) { + return null; + } + ++$i; + while (true) { + // variable name + ++$i; + if (!$stream->look($i)->test(/* Token::PUNCTUATION_TYPE */ 9, ',')) { + break; + } + ++$i; + } + if (!$stream->look($i)->test(/* Token::PUNCTUATION_TYPE */ 9, ')')) { + return null; + } + ++$i; + if (!$stream->look($i)->test(/* Token::ARROW_TYPE */ 12)) { + return null; + } + + // yes, let's parse it properly + $token = $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, '('); + $line = $token->getLine(); + + $names = []; + while (true) { + $token = $stream->expect(/* Token::NAME_TYPE */ 5); + $names[] = new AssignNameExpression($token->getValue(), $token->getLine()); + + if (!$stream->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ',')) { + break; + } + } + $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ')'); + $stream->expect(/* Token::ARROW_TYPE */ 12); + + return new ArrowFunctionExpression($this->parseExpression(0), new Node($names), $line); + } + + private function getPrimary(): AbstractExpression + { + $token = $this->parser->getCurrentToken(); + + if ($this->isUnary($token)) { + $operator = $this->unaryOperators[$token->getValue()]; + $this->parser->getStream()->next(); + $expr = $this->parseExpression($operator['precedence']); + $class = $operator['class']; + + return $this->parsePostfixExpression(new $class($expr, $token->getLine())); + } elseif ($token->test(/* Token::PUNCTUATION_TYPE */ 9, '(')) { + $this->parser->getStream()->next(); + $expr = $this->parseExpression(); + $this->parser->getStream()->expect(/* Token::PUNCTUATION_TYPE */ 9, ')', 'An opened parenthesis is not properly closed'); + + return $this->parsePostfixExpression($expr); + } + + return $this->parsePrimaryExpression(); + } + + private function parseConditionalExpression($expr): AbstractExpression + { + while ($this->parser->getStream()->nextIf(/* Token::PUNCTUATION_TYPE */ 9, '?')) { + if (!$this->parser->getStream()->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ':')) { + $expr2 = $this->parseExpression(); + if ($this->parser->getStream()->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ':')) { + $expr3 = $this->parseExpression(); + } else { + $expr3 = new ConstantExpression('', $this->parser->getCurrentToken()->getLine()); + } + } else { + $expr2 = $expr; + $expr3 = $this->parseExpression(); + } + + $expr = new ConditionalExpression($expr, $expr2, $expr3, $this->parser->getCurrentToken()->getLine()); + } + + return $expr; + } + + private function isUnary(Token $token): bool + { + return $token->test(/* Token::OPERATOR_TYPE */ 8) && isset($this->unaryOperators[$token->getValue()]); + } + + private function isBinary(Token $token): bool + { + return $token->test(/* Token::OPERATOR_TYPE */ 8) && isset($this->binaryOperators[$token->getValue()]); + } + + public function parsePrimaryExpression() + { + $token = $this->parser->getCurrentToken(); + switch ($token->getType()) { + case /* Token::NAME_TYPE */ 5: + $this->parser->getStream()->next(); + switch ($token->getValue()) { + case 'true': + case 'TRUE': + $node = new ConstantExpression(true, $token->getLine()); + break; + + case 'false': + case 'FALSE': + $node = new ConstantExpression(false, $token->getLine()); + break; + + case 'none': + case 'NONE': + case 'null': + case 'NULL': + $node = new ConstantExpression(null, $token->getLine()); + break; + + default: + if ('(' === $this->parser->getCurrentToken()->getValue()) { + $node = $this->getFunctionNode($token->getValue(), $token->getLine()); + } else { + $node = new NameExpression($token->getValue(), $token->getLine()); + } + } + break; + + case /* Token::NUMBER_TYPE */ 6: + $this->parser->getStream()->next(); + $node = new ConstantExpression($token->getValue(), $token->getLine()); + break; + + case /* Token::STRING_TYPE */ 7: + case /* Token::INTERPOLATION_START_TYPE */ 10: + $node = $this->parseStringExpression(); + break; + + case /* Token::OPERATOR_TYPE */ 8: + if (preg_match(Lexer::REGEX_NAME, $token->getValue(), $matches) && $matches[0] == $token->getValue()) { + // in this context, string operators are variable names + $this->parser->getStream()->next(); + $node = new NameExpression($token->getValue(), $token->getLine()); + break; + } elseif (isset($this->unaryOperators[$token->getValue()])) { + $class = $this->unaryOperators[$token->getValue()]['class']; + + $ref = new \ReflectionClass($class); + if (!(\in_array($ref->getName(), [NegUnary::class, PosUnary::class, 'Twig_Node_Expression_Unary_Neg', 'Twig_Node_Expression_Unary_Pos']) + || $ref->isSubclassOf(NegUnary::class) || $ref->isSubclassOf(PosUnary::class) + || $ref->isSubclassOf('Twig_Node_Expression_Unary_Neg') || $ref->isSubclassOf('Twig_Node_Expression_Unary_Pos')) + ) { + throw new SyntaxError(sprintf('Unexpected unary operator "%s".', $token->getValue()), $token->getLine(), $this->parser->getStream()->getSourceContext()); + } + + $this->parser->getStream()->next(); + $expr = $this->parsePrimaryExpression(); + + $node = new $class($expr, $token->getLine()); + break; + } + + // no break + default: + if ($token->test(/* Token::PUNCTUATION_TYPE */ 9, '[')) { + $node = $this->parseArrayExpression(); + } elseif ($token->test(/* Token::PUNCTUATION_TYPE */ 9, '{')) { + $node = $this->parseHashExpression(); + } elseif ($token->test(/* Token::OPERATOR_TYPE */ 8, '=') && ('==' === $this->parser->getStream()->look(-1)->getValue() || '!=' === $this->parser->getStream()->look(-1)->getValue())) { + throw new SyntaxError(sprintf('Unexpected operator of value "%s". Did you try to use "===" or "!==" for strict comparison? Use "is same as(value)" instead.', $token->getValue()), $token->getLine(), $this->parser->getStream()->getSourceContext()); + } else { + throw new SyntaxError(sprintf('Unexpected token "%s" of value "%s".', Token::typeToEnglish($token->getType()), $token->getValue()), $token->getLine(), $this->parser->getStream()->getSourceContext()); + } + } + + return $this->parsePostfixExpression($node); + } + + public function parseStringExpression() + { + $stream = $this->parser->getStream(); + + $nodes = []; + // a string cannot be followed by another string in a single expression + $nextCanBeString = true; + while (true) { + if ($nextCanBeString && $token = $stream->nextIf(/* Token::STRING_TYPE */ 7)) { + $nodes[] = new ConstantExpression($token->getValue(), $token->getLine()); + $nextCanBeString = false; + } elseif ($stream->nextIf(/* Token::INTERPOLATION_START_TYPE */ 10)) { + $nodes[] = $this->parseExpression(); + $stream->expect(/* Token::INTERPOLATION_END_TYPE */ 11); + $nextCanBeString = true; + } else { + break; + } + } + + $expr = array_shift($nodes); + foreach ($nodes as $node) { + $expr = new ConcatBinary($expr, $node, $node->getTemplateLine()); + } + + return $expr; + } + + public function parseArrayExpression() + { + $stream = $this->parser->getStream(); + $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, '[', 'An array element was expected'); + + $node = new ArrayExpression([], $stream->getCurrent()->getLine()); + $first = true; + while (!$stream->test(/* Token::PUNCTUATION_TYPE */ 9, ']')) { + if (!$first) { + $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ',', 'An array element must be followed by a comma'); + + // trailing ,? + if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, ']')) { + break; + } + } + $first = false; + + $node->addElement($this->parseExpression()); + } + $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ']', 'An opened array is not properly closed'); + + return $node; + } + + public function parseHashExpression() + { + $stream = $this->parser->getStream(); + $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, '{', 'A hash element was expected'); + + $node = new ArrayExpression([], $stream->getCurrent()->getLine()); + $first = true; + while (!$stream->test(/* Token::PUNCTUATION_TYPE */ 9, '}')) { + if (!$first) { + $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ',', 'A hash value must be followed by a comma'); + + // trailing ,? + if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, '}')) { + break; + } + } + $first = false; + + // a hash key can be: + // + // * a number -- 12 + // * a string -- 'a' + // * a name, which is equivalent to a string -- a + // * an expression, which must be enclosed in parentheses -- (1 + 2) + if (($token = $stream->nextIf(/* Token::STRING_TYPE */ 7)) || ($token = $stream->nextIf(/* Token::NAME_TYPE */ 5)) || $token = $stream->nextIf(/* Token::NUMBER_TYPE */ 6)) { + $key = new ConstantExpression($token->getValue(), $token->getLine()); + } elseif ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, '(')) { + $key = $this->parseExpression(); + } else { + $current = $stream->getCurrent(); + + throw new SyntaxError(sprintf('A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "%s" of value "%s".', Token::typeToEnglish($current->getType()), $current->getValue()), $current->getLine(), $stream->getSourceContext()); + } + + $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ':', 'A hash key must be followed by a colon (:)'); + $value = $this->parseExpression(); + + $node->addElement($value, $key); + } + $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, '}', 'An opened hash is not properly closed'); + + return $node; + } + + public function parsePostfixExpression($node) + { + while (true) { + $token = $this->parser->getCurrentToken(); + if (/* Token::PUNCTUATION_TYPE */ 9 == $token->getType()) { + if ('.' == $token->getValue() || '[' == $token->getValue()) { + $node = $this->parseSubscriptExpression($node); + } elseif ('|' == $token->getValue()) { + $node = $this->parseFilterExpression($node); + } else { + break; + } + } else { + break; + } + } + + return $node; + } + + public function getFunctionNode($name, $line) + { + switch ($name) { + case 'parent': + $this->parseArguments(); + if (!\count($this->parser->getBlockStack())) { + throw new SyntaxError('Calling "parent" outside a block is forbidden.', $line, $this->parser->getStream()->getSourceContext()); + } + + if (!$this->parser->getParent() && !$this->parser->hasTraits()) { + throw new SyntaxError('Calling "parent" on a template that does not extend nor "use" another template is forbidden.', $line, $this->parser->getStream()->getSourceContext()); + } + + return new ParentExpression($this->parser->peekBlockStack(), $line); + case 'block': + $args = $this->parseArguments(); + if (\count($args) < 1) { + throw new SyntaxError('The "block" function takes one argument (the block name).', $line, $this->parser->getStream()->getSourceContext()); + } + + return new BlockReferenceExpression($args->getNode(0), \count($args) > 1 ? $args->getNode(1) : null, $line); + case 'attribute': + $args = $this->parseArguments(); + if (\count($args) < 2) { + throw new SyntaxError('The "attribute" function takes at least two arguments (the variable and the attributes).', $line, $this->parser->getStream()->getSourceContext()); + } + + return new GetAttrExpression($args->getNode(0), $args->getNode(1), \count($args) > 2 ? $args->getNode(2) : null, Template::ANY_CALL, $line); + default: + if (null !== $alias = $this->parser->getImportedSymbol('function', $name)) { + $arguments = new ArrayExpression([], $line); + foreach ($this->parseArguments() as $n) { + $arguments->addElement($n); + } + + $node = new MethodCallExpression($alias['node'], $alias['name'], $arguments, $line); + $node->setAttribute('safe', true); + + return $node; + } + + $args = $this->parseArguments(true); + $class = $this->getFunctionNodeClass($name, $line); + + return new $class($name, $args, $line); + } + } + + public function parseSubscriptExpression($node) + { + $stream = $this->parser->getStream(); + $token = $stream->next(); + $lineno = $token->getLine(); + $arguments = new ArrayExpression([], $lineno); + $type = Template::ANY_CALL; + if ('.' == $token->getValue()) { + $token = $stream->next(); + if ( + /* Token::NAME_TYPE */ 5 == $token->getType() + || + /* Token::NUMBER_TYPE */ 6 == $token->getType() + || + (/* Token::OPERATOR_TYPE */ 8 == $token->getType() && preg_match(Lexer::REGEX_NAME, $token->getValue())) + ) { + $arg = new ConstantExpression($token->getValue(), $lineno); + + if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, '(')) { + $type = Template::METHOD_CALL; + foreach ($this->parseArguments() as $n) { + $arguments->addElement($n); + } + } + } else { + throw new SyntaxError('Expected name or number.', $lineno, $stream->getSourceContext()); + } + + if ($node instanceof NameExpression && null !== $this->parser->getImportedSymbol('template', $node->getAttribute('name'))) { + if (!$arg instanceof ConstantExpression) { + throw new SyntaxError(sprintf('Dynamic macro names are not supported (called on "%s").', $node->getAttribute('name')), $token->getLine(), $stream->getSourceContext()); + } + + $name = $arg->getAttribute('value'); + + $node = new MethodCallExpression($node, 'macro_'.$name, $arguments, $lineno); + $node->setAttribute('safe', true); + + return $node; + } + } else { + $type = Template::ARRAY_CALL; + + // slice? + $slice = false; + if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, ':')) { + $slice = true; + $arg = new ConstantExpression(0, $token->getLine()); + } else { + $arg = $this->parseExpression(); + } + + if ($stream->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ':')) { + $slice = true; + } + + if ($slice) { + if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, ']')) { + $length = new ConstantExpression(null, $token->getLine()); + } else { + $length = $this->parseExpression(); + } + + $class = $this->getFilterNodeClass('slice', $token->getLine()); + $arguments = new Node([$arg, $length]); + $filter = new $class($node, new ConstantExpression('slice', $token->getLine()), $arguments, $token->getLine()); + + $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ']'); + + return $filter; + } + + $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ']'); + } + + return new GetAttrExpression($node, $arg, $arguments, $type, $lineno); + } + + public function parseFilterExpression($node) + { + $this->parser->getStream()->next(); + + return $this->parseFilterExpressionRaw($node); + } + + public function parseFilterExpressionRaw($node, $tag = null) + { + while (true) { + $token = $this->parser->getStream()->expect(/* Token::NAME_TYPE */ 5); + + $name = new ConstantExpression($token->getValue(), $token->getLine()); + if (!$this->parser->getStream()->test(/* Token::PUNCTUATION_TYPE */ 9, '(')) { + $arguments = new Node(); + } else { + $arguments = $this->parseArguments(true, false, true); + } + + $class = $this->getFilterNodeClass($name->getAttribute('value'), $token->getLine()); + + $node = new $class($node, $name, $arguments, $token->getLine(), $tag); + + if (!$this->parser->getStream()->test(/* Token::PUNCTUATION_TYPE */ 9, '|')) { + break; + } + + $this->parser->getStream()->next(); + } + + return $node; + } + + /** + * Parses arguments. + * + * @param bool $namedArguments Whether to allow named arguments or not + * @param bool $definition Whether we are parsing arguments for a function definition + * + * @return Node + * + * @throws SyntaxError + */ + public function parseArguments($namedArguments = false, $definition = false, $allowArrow = false) + { + $args = []; + $stream = $this->parser->getStream(); + + $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, '(', 'A list of arguments must begin with an opening parenthesis'); + while (!$stream->test(/* Token::PUNCTUATION_TYPE */ 9, ')')) { + if (!empty($args)) { + $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ',', 'Arguments must be separated by a comma'); + } + + if ($definition) { + $token = $stream->expect(/* Token::NAME_TYPE */ 5, null, 'An argument must be a name'); + $value = new NameExpression($token->getValue(), $this->parser->getCurrentToken()->getLine()); + } else { + $value = $this->parseExpression(0, $allowArrow); + } + + $name = null; + if ($namedArguments && $token = $stream->nextIf(/* Token::OPERATOR_TYPE */ 8, '=')) { + if (!$value instanceof NameExpression) { + throw new SyntaxError(sprintf('A parameter name must be a string, "%s" given.', \get_class($value)), $token->getLine(), $stream->getSourceContext()); + } + $name = $value->getAttribute('name'); + + if ($definition) { + $value = $this->parsePrimaryExpression(); + + if (!$this->checkConstantExpression($value)) { + throw new SyntaxError(sprintf('A default value for an argument must be a constant (a boolean, a string, a number, or an array).'), $token->getLine(), $stream->getSourceContext()); + } + } else { + $value = $this->parseExpression(0, $allowArrow); + } + } + + if ($definition) { + if (null === $name) { + $name = $value->getAttribute('name'); + $value = new ConstantExpression(null, $this->parser->getCurrentToken()->getLine()); + } + $args[$name] = $value; + } else { + if (null === $name) { + $args[] = $value; + } else { + $args[$name] = $value; + } + } + } + $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ')', 'A list of arguments must be closed by a parenthesis'); + + return new Node($args); + } + + public function parseAssignmentExpression() + { + $stream = $this->parser->getStream(); + $targets = []; + while (true) { + $token = $this->parser->getCurrentToken(); + if ($stream->test(/* Token::OPERATOR_TYPE */ 8) && preg_match(Lexer::REGEX_NAME, $token->getValue())) { + // in this context, string operators are variable names + $this->parser->getStream()->next(); + } else { + $stream->expect(/* Token::NAME_TYPE */ 5, null, 'Only variables can be assigned to'); + } + $value = $token->getValue(); + if (\in_array(strtr($value, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), ['true', 'false', 'none', 'null'])) { + throw new SyntaxError(sprintf('You cannot assign a value to "%s".', $value), $token->getLine(), $stream->getSourceContext()); + } + $targets[] = new AssignNameExpression($value, $token->getLine()); + + if (!$stream->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ',')) { + break; + } + } + + return new Node($targets); + } + + public function parseMultitargetExpression() + { + $targets = []; + while (true) { + $targets[] = $this->parseExpression(); + if (!$this->parser->getStream()->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ',')) { + break; + } + } + + return new Node($targets); + } + + private function parseNotTestExpression(Node $node): NotUnary + { + return new NotUnary($this->parseTestExpression($node), $this->parser->getCurrentToken()->getLine()); + } + + private function parseTestExpression(Node $node): TestExpression + { + $stream = $this->parser->getStream(); + list($name, $test) = $this->getTest($node->getTemplateLine()); + + $class = $this->getTestNodeClass($test); + $arguments = null; + if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, '(')) { + $arguments = $this->parseArguments(true); + } + + if ('defined' === $name && $node instanceof NameExpression && null !== $alias = $this->parser->getImportedSymbol('function', $node->getAttribute('name'))) { + $node = new MethodCallExpression($alias['node'], $alias['name'], new ArrayExpression([], $node->getTemplateLine()), $node->getTemplateLine()); + $node->setAttribute('safe', true); + } + + return new $class($node, $name, $arguments, $this->parser->getCurrentToken()->getLine()); + } + + private function getTest(int $line): array + { + $stream = $this->parser->getStream(); + $name = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue(); + + if ($test = $this->env->getTest($name)) { + return [$name, $test]; + } + + if ($stream->test(/* Token::NAME_TYPE */ 5)) { + // try 2-words tests + $name = $name.' '.$this->parser->getCurrentToken()->getValue(); + + if ($test = $this->env->getTest($name)) { + $stream->next(); + + return [$name, $test]; + } + } + + $e = new SyntaxError(sprintf('Unknown "%s" test.', $name), $line, $stream->getSourceContext()); + $e->addSuggestions($name, array_keys($this->env->getTests())); + + throw $e; + } + + private function getTestNodeClass(TwigTest $test): string + { + if ($test->isDeprecated()) { + $stream = $this->parser->getStream(); + $message = sprintf('Twig Test "%s" is deprecated', $test->getName()); + + if (!\is_bool($test->getDeprecatedVersion())) { + $message .= sprintf(' since version %s', $test->getDeprecatedVersion()); + } + if ($test->getAlternative()) { + $message .= sprintf('. Use "%s" instead', $test->getAlternative()); + } + $src = $stream->getSourceContext(); + $message .= sprintf(' in %s at line %d.', $src->getPath() ?: $src->getName(), $stream->getCurrent()->getLine()); + + @trigger_error($message, E_USER_DEPRECATED); + } + + return $test->getNodeClass(); + } + + private function getFunctionNodeClass(string $name, int $line): string + { + if (false === $function = $this->env->getFunction($name)) { + $e = new SyntaxError(sprintf('Unknown "%s" function.', $name), $line, $this->parser->getStream()->getSourceContext()); + $e->addSuggestions($name, array_keys($this->env->getFunctions())); + + throw $e; + } + + if ($function->isDeprecated()) { + $message = sprintf('Twig Function "%s" is deprecated', $function->getName()); + if (!\is_bool($function->getDeprecatedVersion())) { + $message .= sprintf(' since version %s', $function->getDeprecatedVersion()); + } + if ($function->getAlternative()) { + $message .= sprintf('. Use "%s" instead', $function->getAlternative()); + } + $src = $this->parser->getStream()->getSourceContext(); + $message .= sprintf(' in %s at line %d.', $src->getPath() ?: $src->getName(), $line); + + @trigger_error($message, E_USER_DEPRECATED); + } + + return $function->getNodeClass(); + } + + private function getFilterNodeClass(string $name, int $line): string + { + if (false === $filter = $this->env->getFilter($name)) { + $e = new SyntaxError(sprintf('Unknown "%s" filter.', $name), $line, $this->parser->getStream()->getSourceContext()); + $e->addSuggestions($name, array_keys($this->env->getFilters())); + + throw $e; + } + + if ($filter->isDeprecated()) { + $message = sprintf('Twig Filter "%s" is deprecated', $filter->getName()); + if (!\is_bool($filter->getDeprecatedVersion())) { + $message .= sprintf(' since version %s', $filter->getDeprecatedVersion()); + } + if ($filter->getAlternative()) { + $message .= sprintf('. Use "%s" instead', $filter->getAlternative()); + } + $src = $this->parser->getStream()->getSourceContext(); + $message .= sprintf(' in %s at line %d.', $src->getPath() ?: $src->getName(), $line); + + @trigger_error($message, E_USER_DEPRECATED); + } + + return $filter->getNodeClass(); + } + + // checks that the node only contains "constant" elements + private function checkConstantExpression(Node $node): bool + { + if (!($node instanceof ConstantExpression || $node instanceof ArrayExpression + || $node instanceof NegUnary || $node instanceof PosUnary + )) { + return false; + } + + foreach ($node as $n) { + if (!$this->checkConstantExpression($n)) { + return false; + } + } + + return true; + } +} + +class_alias('Twig\ExpressionParser', 'Twig_ExpressionParser'); diff --git a/src/bb-vendor/twig/twig/src/Extension/CoreExtension.php b/src/bb-vendor/twig/twig/src/Extension/CoreExtension.php new file mode 100644 index 000000000..d3e490293 --- /dev/null +++ b/src/bb-vendor/twig/twig/src/Extension/CoreExtension.php @@ -0,0 +1,1570 @@ +escapers[$strategy] = $callable; + } + + /** + * Gets all defined escapers. + * + * @return callable[] An array of escapers + * + * @deprecated since Twig 2.11, to be removed in 3.0; use the same method on EscaperExtension instead + */ + public function getEscapers(/* $triggerDeprecation = true */) + { + if (0 === \func_num_args() || func_get_arg(0)) { + @trigger_error(sprintf('The "%s" method is deprecated since Twig 2.11; use "%s::getEscapers" instead.', __METHOD__, EscaperExtension::class), E_USER_DEPRECATED); + } + + return $this->escapers; + } + + /** + * Sets the default format to be used by the date filter. + * + * @param string $format The default date format string + * @param string $dateIntervalFormat The default date interval format string + */ + public function setDateFormat($format = null, $dateIntervalFormat = null) + { + if (null !== $format) { + $this->dateFormats[0] = $format; + } + + if (null !== $dateIntervalFormat) { + $this->dateFormats[1] = $dateIntervalFormat; + } + } + + /** + * Gets the default format to be used by the date filter. + * + * @return array The default date format string and the default date interval format string + */ + public function getDateFormat() + { + return $this->dateFormats; + } + + /** + * Sets the default timezone to be used by the date filter. + * + * @param \DateTimeZone|string $timezone The default timezone string or a \DateTimeZone object + */ + public function setTimezone($timezone) + { + $this->timezone = $timezone instanceof \DateTimeZone ? $timezone : new \DateTimeZone($timezone); + } + + /** + * Gets the default timezone to be used by the date filter. + * + * @return \DateTimeZone The default timezone currently in use + */ + public function getTimezone() + { + if (null === $this->timezone) { + $this->timezone = new \DateTimeZone(date_default_timezone_get()); + } + + return $this->timezone; + } + + /** + * Sets the default format to be used by the number_format filter. + * + * @param int $decimal the number of decimal places to use + * @param string $decimalPoint the character(s) to use for the decimal point + * @param string $thousandSep the character(s) to use for the thousands separator + */ + public function setNumberFormat($decimal, $decimalPoint, $thousandSep) + { + $this->numberFormat = [$decimal, $decimalPoint, $thousandSep]; + } + + /** + * Get the default format used by the number_format filter. + * + * @return array The arguments for number_format() + */ + public function getNumberFormat() + { + return $this->numberFormat; + } + + public function getTokenParsers() + { + return [ + new ApplyTokenParser(), + new ForTokenParser(), + new IfTokenParser(), + new ExtendsTokenParser(), + new IncludeTokenParser(), + new BlockTokenParser(), + new UseTokenParser(), + new FilterTokenParser(), + new MacroTokenParser(), + new ImportTokenParser(), + new FromTokenParser(), + new SetTokenParser(), + new SpacelessTokenParser(), + new FlushTokenParser(), + new DoTokenParser(), + new EmbedTokenParser(), + new WithTokenParser(), + new DeprecatedTokenParser(), + ]; + } + + public function getFilters() + { + return [ + // formatting filters + new TwigFilter('date', 'twig_date_format_filter', ['needs_environment' => true]), + new TwigFilter('date_modify', 'twig_date_modify_filter', ['needs_environment' => true]), + new TwigFilter('format', 'sprintf'), + new TwigFilter('replace', 'twig_replace_filter'), + new TwigFilter('number_format', 'twig_number_format_filter', ['needs_environment' => true]), + new TwigFilter('abs', 'abs'), + new TwigFilter('round', 'twig_round'), + + // encoding + new TwigFilter('url_encode', 'twig_urlencode_filter'), + new TwigFilter('json_encode', 'json_encode'), + new TwigFilter('convert_encoding', 'twig_convert_encoding'), + + // string filters + new TwigFilter('title', 'twig_title_string_filter', ['needs_environment' => true]), + new TwigFilter('capitalize', 'twig_capitalize_string_filter', ['needs_environment' => true]), + new TwigFilter('upper', 'twig_upper_filter', ['needs_environment' => true]), + new TwigFilter('lower', 'twig_lower_filter', ['needs_environment' => true]), + new TwigFilter('striptags', 'strip_tags'), + new TwigFilter('trim', 'twig_trim_filter'), + new TwigFilter('nl2br', 'nl2br', ['pre_escape' => 'html', 'is_safe' => ['html']]), + new TwigFilter('spaceless', 'twig_spaceless', ['is_safe' => ['html']]), + + // array helpers + new TwigFilter('join', 'twig_join_filter'), + new TwigFilter('split', 'twig_split_filter', ['needs_environment' => true]), + new TwigFilter('sort', 'twig_sort_filter'), + new TwigFilter('merge', 'twig_array_merge'), + new TwigFilter('batch', 'twig_array_batch'), + new TwigFilter('column', 'twig_array_column'), + new TwigFilter('filter', 'twig_array_filter'), + new TwigFilter('map', 'twig_array_map'), + new TwigFilter('reduce', 'twig_array_reduce'), + + // string/array filters + new TwigFilter('reverse', 'twig_reverse_filter', ['needs_environment' => true]), + new TwigFilter('length', 'twig_length_filter', ['needs_environment' => true]), + new TwigFilter('slice', 'twig_slice', ['needs_environment' => true]), + new TwigFilter('first', 'twig_first', ['needs_environment' => true]), + new TwigFilter('last', 'twig_last', ['needs_environment' => true]), + + // iteration and runtime + new TwigFilter('default', '_twig_default_filter', ['node_class' => DefaultFilter::class]), + new TwigFilter('keys', 'twig_get_array_keys_filter'), + ]; + } + + public function getFunctions() + { + return [ + new TwigFunction('max', 'max'), + new TwigFunction('min', 'min'), + new TwigFunction('range', 'range'), + new TwigFunction('constant', 'twig_constant'), + new TwigFunction('cycle', 'twig_cycle'), + new TwigFunction('random', 'twig_random', ['needs_environment' => true]), + new TwigFunction('date', 'twig_date_converter', ['needs_environment' => true]), + new TwigFunction('include', 'twig_include', ['needs_environment' => true, 'needs_context' => true, 'is_safe' => ['all']]), + new TwigFunction('source', 'twig_source', ['needs_environment' => true, 'is_safe' => ['all']]), + ]; + } + + public function getTests() + { + return [ + new TwigTest('even', null, ['node_class' => EvenTest::class]), + new TwigTest('odd', null, ['node_class' => OddTest::class]), + new TwigTest('defined', null, ['node_class' => DefinedTest::class]), + new TwigTest('same as', null, ['node_class' => SameasTest::class]), + new TwigTest('none', null, ['node_class' => NullTest::class]), + new TwigTest('null', null, ['node_class' => NullTest::class]), + new TwigTest('divisible by', null, ['node_class' => DivisiblebyTest::class]), + new TwigTest('constant', null, ['node_class' => ConstantTest::class]), + new TwigTest('empty', 'twig_test_empty'), + new TwigTest('iterable', 'twig_test_iterable'), + ]; + } + + public function getNodeVisitors() + { + return [new MacroAutoImportNodeVisitor()]; + } + + public function getOperators() + { + return [ + [ + 'not' => ['precedence' => 50, 'class' => NotUnary::class], + '-' => ['precedence' => 500, 'class' => NegUnary::class], + '+' => ['precedence' => 500, 'class' => PosUnary::class], + ], + [ + 'or' => ['precedence' => 10, 'class' => OrBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], + 'and' => ['precedence' => 15, 'class' => AndBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], + 'b-or' => ['precedence' => 16, 'class' => BitwiseOrBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], + 'b-xor' => ['precedence' => 17, 'class' => BitwiseXorBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], + 'b-and' => ['precedence' => 18, 'class' => BitwiseAndBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], + '==' => ['precedence' => 20, 'class' => EqualBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], + '!=' => ['precedence' => 20, 'class' => NotEqualBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], + '<=>' => ['precedence' => 20, 'class' => SpaceshipBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], + '<' => ['precedence' => 20, 'class' => LessBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], + '>' => ['precedence' => 20, 'class' => GreaterBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], + '>=' => ['precedence' => 20, 'class' => GreaterEqualBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], + '<=' => ['precedence' => 20, 'class' => LessEqualBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], + 'not in' => ['precedence' => 20, 'class' => NotInBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], + 'in' => ['precedence' => 20, 'class' => InBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], + 'matches' => ['precedence' => 20, 'class' => MatchesBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], + 'starts with' => ['precedence' => 20, 'class' => StartsWithBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], + 'ends with' => ['precedence' => 20, 'class' => EndsWithBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], + '..' => ['precedence' => 25, 'class' => RangeBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], + '+' => ['precedence' => 30, 'class' => AddBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], + '-' => ['precedence' => 30, 'class' => SubBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], + '~' => ['precedence' => 40, 'class' => ConcatBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], + '*' => ['precedence' => 60, 'class' => MulBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], + '/' => ['precedence' => 60, 'class' => DivBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], + '//' => ['precedence' => 60, 'class' => FloorDivBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], + '%' => ['precedence' => 60, 'class' => ModBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], + 'is' => ['precedence' => 100, 'associativity' => ExpressionParser::OPERATOR_LEFT], + 'is not' => ['precedence' => 100, 'associativity' => ExpressionParser::OPERATOR_LEFT], + '**' => ['precedence' => 200, 'class' => PowerBinary::class, 'associativity' => ExpressionParser::OPERATOR_RIGHT], + '??' => ['precedence' => 300, 'class' => NullCoalesceExpression::class, 'associativity' => ExpressionParser::OPERATOR_RIGHT], + ], + ]; + } +} + +class_alias('Twig\Extension\CoreExtension', 'Twig_Extension_Core'); +} + +namespace { + use Twig\Environment; + use Twig\Error\LoaderError; + use Twig\Error\RuntimeError; + use Twig\Extension\CoreExtension; + use Twig\Extension\SandboxExtension; + use Twig\Markup; + use Twig\Source; + use Twig\Template; + + /** + * Cycles over a value. + * + * @param \ArrayAccess|array $values + * @param int $position The cycle position + * + * @return string The next value in the cycle + */ +function twig_cycle($values, $position) +{ + if (!\is_array($values) && !$values instanceof \ArrayAccess) { + return $values; + } + + return $values[$position % \count($values)]; +} + +/** + * Returns a random value depending on the supplied parameter type: + * - a random item from a \Traversable or array + * - a random character from a string + * - a random integer between 0 and the integer parameter. + * + * @param \Traversable|array|int|float|string $values The values to pick a random item from + * @param int|null $max Maximum value used when $values is an int + * + * @throws RuntimeError when $values is an empty array (does not apply to an empty string which is returned as is) + * + * @return mixed A random value from the given sequence + */ +function twig_random(Environment $env, $values = null, $max = null) +{ + if (null === $values) { + return null === $max ? mt_rand() : mt_rand(0, $max); + } + + if (\is_int($values) || \is_float($values)) { + if (null === $max) { + if ($values < 0) { + $max = 0; + $min = $values; + } else { + $max = $values; + $min = 0; + } + } else { + $min = $values; + $max = $max; + } + + return mt_rand($min, $max); + } + + if (\is_string($values)) { + if ('' === $values) { + return ''; + } + + $charset = $env->getCharset(); + + if ('UTF-8' !== $charset) { + $values = twig_convert_encoding($values, 'UTF-8', $charset); + } + + // unicode version of str_split() + // split at all positions, but not after the start and not before the end + $values = preg_split('/(? $value) { + $values[$i] = twig_convert_encoding($value, $charset, 'UTF-8'); + } + } + } + + if (!twig_test_iterable($values)) { + return $values; + } + + $values = twig_to_array($values); + + if (0 === \count($values)) { + throw new RuntimeError('The random function cannot pick from an empty array.'); + } + + return $values[array_rand($values, 1)]; +} + +/** + * Converts a date to the given format. + * + * {{ post.published_at|date("m/d/Y") }} + * + * @param \DateTimeInterface|\DateInterval|string $date A date + * @param string|null $format The target format, null to use the default + * @param \DateTimeZone|string|false|null $timezone The target timezone, null to use the default, false to leave unchanged + * + * @return string The formatted date + */ +function twig_date_format_filter(Environment $env, $date, $format = null, $timezone = null) +{ + if (null === $format) { + $formats = $env->getExtension(CoreExtension::class)->getDateFormat(); + $format = $date instanceof \DateInterval ? $formats[1] : $formats[0]; + } + + if ($date instanceof \DateInterval) { + return $date->format($format); + } + + return twig_date_converter($env, $date, $timezone)->format($format); +} + +/** + * Returns a new date object modified. + * + * {{ post.published_at|date_modify("-1day")|date("m/d/Y") }} + * + * @param \DateTimeInterface|string $date A date + * @param string $modifier A modifier string + * + * @return \DateTimeInterface + */ +function twig_date_modify_filter(Environment $env, $date, $modifier) +{ + $date = twig_date_converter($env, $date, false); + + return $date->modify($modifier); +} + +/** + * Converts an input to a \DateTime instance. + * + * {% if date(user.created_at) < date('+2days') %} + * {# do something #} + * {% endif %} + * + * @param \DateTimeInterface|string|null $date A date or null to use the current time + * @param \DateTimeZone|string|false|null $timezone The target timezone, null to use the default, false to leave unchanged + * + * @return \DateTimeInterface + */ +function twig_date_converter(Environment $env, $date = null, $timezone = null) +{ + // determine the timezone + if (false !== $timezone) { + if (null === $timezone) { + $timezone = $env->getExtension(CoreExtension::class)->getTimezone(); + } elseif (!$timezone instanceof \DateTimeZone) { + $timezone = new \DateTimeZone($timezone); + } + } + + // immutable dates + if ($date instanceof \DateTimeImmutable) { + return false !== $timezone ? $date->setTimezone($timezone) : $date; + } + + if ($date instanceof \DateTimeInterface) { + $date = clone $date; + if (false !== $timezone) { + $date->setTimezone($timezone); + } + + return $date; + } + + if (null === $date || 'now' === $date) { + return new \DateTime($date, false !== $timezone ? $timezone : $env->getExtension(CoreExtension::class)->getTimezone()); + } + + $asString = (string) $date; + if (ctype_digit($asString) || (!empty($asString) && '-' === $asString[0] && ctype_digit(substr($asString, 1)))) { + $date = new \DateTime('@'.$date); + } else { + $date = new \DateTime($date, $env->getExtension(CoreExtension::class)->getTimezone()); + } + + if (false !== $timezone) { + $date->setTimezone($timezone); + } + + return $date; +} + +/** + * Replaces strings within a string. + * + * @param string $str String to replace in + * @param array|\Traversable $from Replace values + * + * @return string + */ +function twig_replace_filter($str, $from) +{ + if (!twig_test_iterable($from)) { + throw new RuntimeError(sprintf('The "replace" filter expects an array or "Traversable" as replace values, got "%s".', \is_object($from) ? \get_class($from) : \gettype($from))); + } + + return strtr($str, twig_to_array($from)); +} + +/** + * Rounds a number. + * + * @param int|float $value The value to round + * @param int|float $precision The rounding precision + * @param string $method The method to use for rounding + * + * @return int|float The rounded number + */ +function twig_round($value, $precision = 0, $method = 'common') +{ + if ('common' === $method) { + return round($value, $precision); + } + + if ('ceil' !== $method && 'floor' !== $method) { + throw new RuntimeError('The round filter only supports the "common", "ceil", and "floor" methods.'); + } + + return $method($value * pow(10, $precision)) / pow(10, $precision); +} + +/** + * Number format filter. + * + * All of the formatting options can be left null, in that case the defaults will + * be used. Supplying any of the parameters will override the defaults set in the + * environment object. + * + * @param mixed $number A float/int/string of the number to format + * @param int $decimal the number of decimal points to display + * @param string $decimalPoint the character(s) to use for the decimal point + * @param string $thousandSep the character(s) to use for the thousands separator + * + * @return string The formatted number + */ +function twig_number_format_filter(Environment $env, $number, $decimal = null, $decimalPoint = null, $thousandSep = null) +{ + $defaults = $env->getExtension(CoreExtension::class)->getNumberFormat(); + if (null === $decimal) { + $decimal = $defaults[0]; + } + + if (null === $decimalPoint) { + $decimalPoint = $defaults[1]; + } + + if (null === $thousandSep) { + $thousandSep = $defaults[2]; + } + + return number_format((float) $number, $decimal, $decimalPoint, $thousandSep); +} + +/** + * URL encodes (RFC 3986) a string as a path segment or an array as a query string. + * + * @param string|array $url A URL or an array of query parameters + * + * @return string The URL encoded value + */ +function twig_urlencode_filter($url) +{ + if (\is_array($url)) { + return http_build_query($url, '', '&', PHP_QUERY_RFC3986); + } + + return rawurlencode($url); +} + +/** + * Merges an array with another one. + * + * {% set items = { 'apple': 'fruit', 'orange': 'fruit' } %} + * + * {% set items = items|merge({ 'peugeot': 'car' }) %} + * + * {# items now contains { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'car' } #} + * + * @param array|\Traversable $arr1 An array + * @param array|\Traversable $arr2 An array + * + * @return array The merged array + */ +function twig_array_merge($arr1, $arr2) +{ + if (!twig_test_iterable($arr1)) { + throw new RuntimeError(sprintf('The merge filter only works with arrays or "Traversable", got "%s" as first argument.', \gettype($arr1))); + } + + if (!twig_test_iterable($arr2)) { + throw new RuntimeError(sprintf('The merge filter only works with arrays or "Traversable", got "%s" as second argument.', \gettype($arr2))); + } + + return array_merge(twig_to_array($arr1), twig_to_array($arr2)); +} + +/** + * Slices a variable. + * + * @param mixed $item A variable + * @param int $start Start of the slice + * @param int $length Size of the slice + * @param bool $preserveKeys Whether to preserve key or not (when the input is an array) + * + * @return mixed The sliced variable + */ +function twig_slice(Environment $env, $item, $start, $length = null, $preserveKeys = false) +{ + if ($item instanceof \Traversable) { + while ($item instanceof \IteratorAggregate) { + $item = $item->getIterator(); + } + + if ($start >= 0 && $length >= 0 && $item instanceof \Iterator) { + try { + return iterator_to_array(new \LimitIterator($item, $start, null === $length ? -1 : $length), $preserveKeys); + } catch (\OutOfBoundsException $e) { + return []; + } + } + + $item = iterator_to_array($item, $preserveKeys); + } + + if (\is_array($item)) { + return \array_slice($item, $start, $length, $preserveKeys); + } + + $item = (string) $item; + + return (string) mb_substr($item, $start, $length, $env->getCharset()); +} + +/** + * Returns the first element of the item. + * + * @param mixed $item A variable + * + * @return mixed The first element of the item + */ +function twig_first(Environment $env, $item) +{ + $elements = twig_slice($env, $item, 0, 1, false); + + return \is_string($elements) ? $elements : current($elements); +} + +/** + * Returns the last element of the item. + * + * @param mixed $item A variable + * + * @return mixed The last element of the item + */ +function twig_last(Environment $env, $item) +{ + $elements = twig_slice($env, $item, -1, 1, false); + + return \is_string($elements) ? $elements : current($elements); +} + +/** + * Joins the values to a string. + * + * The separators between elements are empty strings per default, you can define them with the optional parameters. + * + * {{ [1, 2, 3]|join(', ', ' and ') }} + * {# returns 1, 2 and 3 #} + * + * {{ [1, 2, 3]|join('|') }} + * {# returns 1|2|3 #} + * + * {{ [1, 2, 3]|join }} + * {# returns 123 #} + * + * @param array $value An array + * @param string $glue The separator + * @param string|null $and The separator for the last pair + * + * @return string The concatenated string + */ +function twig_join_filter($value, $glue = '', $and = null) +{ + if (!twig_test_iterable($value)) { + $value = (array) $value; + } + + $value = twig_to_array($value, false); + + if (0 === \count($value)) { + return ''; + } + + if (null === $and || $and === $glue) { + return implode($glue, $value); + } + + if (1 === \count($value)) { + return $value[0]; + } + + return implode($glue, \array_slice($value, 0, -1)).$and.$value[\count($value) - 1]; +} + +/** + * Splits the string into an array. + * + * {{ "one,two,three"|split(',') }} + * {# returns [one, two, three] #} + * + * {{ "one,two,three,four,five"|split(',', 3) }} + * {# returns [one, two, "three,four,five"] #} + * + * {{ "123"|split('') }} + * {# returns [1, 2, 3] #} + * + * {{ "aabbcc"|split('', 2) }} + * {# returns [aa, bb, cc] #} + * + * @param string $value A string + * @param string $delimiter The delimiter + * @param int $limit The limit + * + * @return array The split string as an array + */ +function twig_split_filter(Environment $env, $value, $delimiter, $limit = null) +{ + if (\strlen($delimiter) > 0) { + return null === $limit ? explode($delimiter, $value) : explode($delimiter, $value, $limit); + } + + if ($limit <= 1) { + return preg_split('/(?getCharset()); + if ($length < $limit) { + return [$value]; + } + + $r = []; + for ($i = 0; $i < $length; $i += $limit) { + $r[] = mb_substr($value, $i, $limit, $env->getCharset()); + } + + return $r; +} + +// The '_default' filter is used internally to avoid using the ternary operator +// which costs a lot for big contexts (before PHP 5.4). So, on average, +// a function call is cheaper. +/** + * @internal + */ +function _twig_default_filter($value, $default = '') +{ + if (twig_test_empty($value)) { + return $default; + } + + return $value; +} + +/** + * Returns the keys for the given array. + * + * It is useful when you want to iterate over the keys of an array: + * + * {% for key in array|keys %} + * {# ... #} + * {% endfor %} + * + * @param array $array An array + * + * @return array The keys + */ +function twig_get_array_keys_filter($array) +{ + if ($array instanceof \Traversable) { + while ($array instanceof \IteratorAggregate) { + $array = $array->getIterator(); + } + + if ($array instanceof \Iterator) { + $keys = []; + $array->rewind(); + while ($array->valid()) { + $keys[] = $array->key(); + $array->next(); + } + + return $keys; + } + + $keys = []; + foreach ($array as $key => $item) { + $keys[] = $key; + } + + return $keys; + } + + if (!\is_array($array)) { + return []; + } + + return array_keys($array); +} + +/** + * Reverses a variable. + * + * @param array|\Traversable|string $item An array, a \Traversable instance, or a string + * @param bool $preserveKeys Whether to preserve key or not + * + * @return mixed The reversed input + */ +function twig_reverse_filter(Environment $env, $item, $preserveKeys = false) +{ + if ($item instanceof \Traversable) { + return array_reverse(iterator_to_array($item), $preserveKeys); + } + + if (\is_array($item)) { + return array_reverse($item, $preserveKeys); + } + + $string = (string) $item; + + $charset = $env->getCharset(); + + if ('UTF-8' !== $charset) { + $item = twig_convert_encoding($string, 'UTF-8', $charset); + } + + preg_match_all('/./us', $item, $matches); + + $string = implode('', array_reverse($matches[0])); + + if ('UTF-8' !== $charset) { + $string = twig_convert_encoding($string, $charset, 'UTF-8'); + } + + return $string; +} + +/** + * Sorts an array. + * + * @param array|\Traversable $array + * + * @return array + */ +function twig_sort_filter($array, $arrow = null) +{ + if ($array instanceof \Traversable) { + $array = iterator_to_array($array); + } elseif (!\is_array($array)) { + throw new RuntimeError(sprintf('The sort filter only works with arrays or "Traversable", got "%s".', \gettype($array))); + } + + if (null !== $arrow) { + uasort($array, $arrow); + } else { + asort($array); + } + + return $array; +} + +/** + * @internal + */ +function twig_in_filter($value, $compare) +{ + if ($value instanceof Markup) { + $value = (string) $value; + } + if ($compare instanceof Markup) { + $compare = (string) $compare; + } + + if (\is_array($compare)) { + return \in_array($value, $compare, \is_object($value) || \is_resource($value)); + } elseif (\is_string($compare) && (\is_string($value) || \is_int($value) || \is_float($value))) { + return '' === $value || false !== strpos($compare, (string) $value); + } elseif ($compare instanceof \Traversable) { + if (\is_object($value) || \is_resource($value)) { + foreach ($compare as $item) { + if ($item === $value) { + return true; + } + } + } else { + foreach ($compare as $item) { + if ($item == $value) { + return true; + } + } + } + + return false; + } + + return false; +} + +/** + * Returns a trimmed string. + * + * @return string + * + * @throws RuntimeError When an invalid trimming side is used (not a string or not 'left', 'right', or 'both') + */ +function twig_trim_filter($string, $characterMask = null, $side = 'both') +{ + if (null === $characterMask) { + $characterMask = " \t\n\r\0\x0B"; + } + + switch ($side) { + case 'both': + return trim($string, $characterMask); + case 'left': + return ltrim($string, $characterMask); + case 'right': + return rtrim($string, $characterMask); + default: + throw new RuntimeError('Trimming side must be "left", "right" or "both".'); + } +} + +/** + * Removes whitespaces between HTML tags. + * + * @return string + */ +function twig_spaceless($content) +{ + return trim(preg_replace('/>\s+<', $content)); +} + +function twig_convert_encoding($string, $to, $from) +{ + if (!\function_exists('iconv')) { + throw new RuntimeError('Unable to convert encoding: required function iconv() does not exist. You should install ext-iconv or symfony/polyfill-iconv.'); + } + + return iconv($from, $to, $string); +} + +/** + * Returns the length of a variable. + * + * @param mixed $thing A variable + * + * @return int The length of the value + */ +function twig_length_filter(Environment $env, $thing) +{ + if (null === $thing) { + return 0; + } + + if (is_scalar($thing)) { + return mb_strlen($thing, $env->getCharset()); + } + + if ($thing instanceof \Countable || \is_array($thing) || $thing instanceof \SimpleXMLElement) { + return \count($thing); + } + + if ($thing instanceof \Traversable) { + return iterator_count($thing); + } + + if (method_exists($thing, '__toString') && !$thing instanceof \Countable) { + return mb_strlen((string) $thing, $env->getCharset()); + } + + return 1; +} + +/** + * Converts a string to uppercase. + * + * @param string $string A string + * + * @return string The uppercased string + */ +function twig_upper_filter(Environment $env, $string) +{ + return mb_strtoupper($string, $env->getCharset()); +} + +/** + * Converts a string to lowercase. + * + * @param string $string A string + * + * @return string The lowercased string + */ +function twig_lower_filter(Environment $env, $string) +{ + return mb_strtolower($string, $env->getCharset()); +} + +/** + * Returns a titlecased string. + * + * @param string $string A string + * + * @return string The titlecased string + */ +function twig_title_string_filter(Environment $env, $string) +{ + if (null !== $charset = $env->getCharset()) { + return mb_convert_case($string, MB_CASE_TITLE, $charset); + } + + return ucwords(strtolower($string)); +} + +/** + * Returns a capitalized string. + * + * @param string $string A string + * + * @return string The capitalized string + */ +function twig_capitalize_string_filter(Environment $env, $string) +{ + $charset = $env->getCharset(); + + return mb_strtoupper(mb_substr($string, 0, 1, $charset), $charset).mb_strtolower(mb_substr($string, 1, null, $charset), $charset); +} + +/** + * @internal + */ +function twig_call_macro(Template $template, string $method, array $args, int $lineno, array $context, Source $source) +{ + if (!method_exists($template, $method)) { + $parent = $template; + while ($parent = $parent->getParent($context)) { + if (method_exists($parent, $method)) { + return $parent->$method(...$args); + } + } + + throw new RuntimeError(sprintf('Macro "%s" is not defined in template "%s".', substr($method, \strlen('macro_')), $template->getTemplateName()), $lineno, $source); + } + + return $template->$method(...$args); +} + +/** + * @internal + */ +function twig_ensure_traversable($seq) +{ + if ($seq instanceof \Traversable || \is_array($seq)) { + return $seq; + } + + return []; +} + +/** + * @internal + */ +function twig_to_array($seq, $preserveKeys = true) +{ + if ($seq instanceof \Traversable) { + return iterator_to_array($seq, $preserveKeys); + } + + if (!\is_array($seq)) { + return $seq; + } + + return $preserveKeys ? $seq : array_values($seq); +} + +/** + * Checks if a variable is empty. + * + * {# evaluates to true if the foo variable is null, false, or the empty string #} + * {% if foo is empty %} + * {# ... #} + * {% endif %} + * + * @param mixed $value A variable + * + * @return bool true if the value is empty, false otherwise + */ +function twig_test_empty($value) +{ + if ($value instanceof \Countable) { + return 0 === \count($value); + } + + if ($value instanceof \Traversable) { + return !iterator_count($value); + } + + if (\is_object($value) && method_exists($value, '__toString')) { + return '' === (string) $value; + } + + return '' === $value || false === $value || null === $value || [] === $value; +} + +/** + * Checks if a variable is traversable. + * + * {# evaluates to true if the foo variable is an array or a traversable object #} + * {% if foo is iterable %} + * {# ... #} + * {% endif %} + * + * @param mixed $value A variable + * + * @return bool true if the value is traversable + */ +function twig_test_iterable($value) +{ + return $value instanceof \Traversable || \is_array($value); +} + +/** + * Renders a template. + * + * @param array $context + * @param string|array $template The template to render or an array of templates to try consecutively + * @param array $variables The variables to pass to the template + * @param bool $withContext + * @param bool $ignoreMissing Whether to ignore missing templates or not + * @param bool $sandboxed Whether to sandbox the template or not + * + * @return string The rendered template + */ +function twig_include(Environment $env, $context, $template, $variables = [], $withContext = true, $ignoreMissing = false, $sandboxed = false) +{ + $alreadySandboxed = false; + $sandbox = null; + if ($withContext) { + $variables = array_merge($context, $variables); + } + + if ($isSandboxed = $sandboxed && $env->hasExtension(SandboxExtension::class)) { + $sandbox = $env->getExtension(SandboxExtension::class); + if (!$alreadySandboxed = $sandbox->isSandboxed()) { + $sandbox->enableSandbox(); + } + } + + try { + $loaded = null; + try { + $loaded = $env->resolveTemplate($template); + } catch (LoaderError $e) { + if (!$ignoreMissing) { + throw $e; + } + } + + return $loaded ? $loaded->render($variables) : ''; + } finally { + if ($isSandboxed && !$alreadySandboxed) { + $sandbox->disableSandbox(); + } + } +} + +/** + * Returns a template content without rendering it. + * + * @param string $name The template name + * @param bool $ignoreMissing Whether to ignore missing templates or not + * + * @return string The template source + */ +function twig_source(Environment $env, $name, $ignoreMissing = false) +{ + $loader = $env->getLoader(); + try { + return $loader->getSourceContext($name)->getCode(); + } catch (LoaderError $e) { + if (!$ignoreMissing) { + throw $e; + } + } +} + +/** + * Provides the ability to get constants from instances as well as class/global constants. + * + * @param string $constant The name of the constant + * @param object|null $object The object to get the constant from + * + * @return string + */ +function twig_constant($constant, $object = null) +{ + if (null !== $object) { + $constant = \get_class($object).'::'.$constant; + } + + return \constant($constant); +} + +/** + * Checks if a constant exists. + * + * @param string $constant The name of the constant + * @param object|null $object The object to get the constant from + * + * @return bool + */ +function twig_constant_is_defined($constant, $object = null) +{ + if (null !== $object) { + $constant = \get_class($object).'::'.$constant; + } + + return \defined($constant); +} + +/** + * Batches item. + * + * @param array $items An array of items + * @param int $size The size of the batch + * @param mixed $fill A value used to fill missing items + * + * @return array + */ +function twig_array_batch($items, $size, $fill = null, $preserveKeys = true) +{ + if (!twig_test_iterable($items)) { + throw new RuntimeError(sprintf('The "batch" filter expects an array or "Traversable", got "%s".', \is_object($items) ? \get_class($items) : \gettype($items))); + } + + $size = ceil($size); + + $result = array_chunk(twig_to_array($items, $preserveKeys), $size, $preserveKeys); + + if (null !== $fill && $result) { + $last = \count($result) - 1; + if ($fillCount = $size - \count($result[$last])) { + for ($i = 0; $i < $fillCount; ++$i) { + $result[$last][] = $fill; + } + } + } + + return $result; +} + +/** + * Returns the attribute value for a given array/object. + * + * @param mixed $object The object or array from where to get the item + * @param mixed $item The item to get from the array or object + * @param array $arguments An array of arguments to pass if the item is an object method + * @param string $type The type of attribute (@see \Twig\Template constants) + * @param bool $isDefinedTest Whether this is only a defined check + * @param bool $ignoreStrictCheck Whether to ignore the strict attribute check or not + * @param int $lineno The template line where the attribute was called + * + * @return mixed The attribute value, or a Boolean when $isDefinedTest is true, or null when the attribute is not set and $ignoreStrictCheck is true + * + * @throws RuntimeError if the attribute does not exist and Twig is running in strict mode and $isDefinedTest is false + * + * @internal + */ +function twig_get_attribute(Environment $env, Source $source, $object, $item, array $arguments = [], $type = /* Template::ANY_CALL */ 'any', $isDefinedTest = false, $ignoreStrictCheck = false, $sandboxed = false, int $lineno = -1) +{ + // array + if (/* Template::METHOD_CALL */ 'method' !== $type) { + $arrayItem = \is_bool($item) || \is_float($item) ? (int) $item : $item; + + if (((\is_array($object) || $object instanceof \ArrayObject) && (isset($object[$arrayItem]) || \array_key_exists($arrayItem, (array) $object))) + || ($object instanceof ArrayAccess && isset($object[$arrayItem])) + ) { + if ($isDefinedTest) { + return true; + } + + return $object[$arrayItem]; + } + + if (/* Template::ARRAY_CALL */ 'array' === $type || !\is_object($object)) { + if ($isDefinedTest) { + return false; + } + + if ($ignoreStrictCheck || !$env->isStrictVariables()) { + return; + } + + if ($object instanceof ArrayAccess) { + $message = sprintf('Key "%s" in object with ArrayAccess of class "%s" does not exist.', $arrayItem, \get_class($object)); + } elseif (\is_object($object)) { + $message = sprintf('Impossible to access a key "%s" on an object of class "%s" that does not implement ArrayAccess interface.', $item, \get_class($object)); + } elseif (\is_array($object)) { + if (empty($object)) { + $message = sprintf('Key "%s" does not exist as the array is empty.', $arrayItem); + } else { + $message = sprintf('Key "%s" for array with keys "%s" does not exist.', $arrayItem, implode(', ', array_keys($object))); + } + } elseif (/* Template::ARRAY_CALL */ 'array' === $type) { + if (null === $object) { + $message = sprintf('Impossible to access a key ("%s") on a null variable.', $item); + } else { + $message = sprintf('Impossible to access a key ("%s") on a %s variable ("%s").', $item, \gettype($object), $object); + } + } elseif (null === $object) { + $message = sprintf('Impossible to access an attribute ("%s") on a null variable.', $item); + } else { + $message = sprintf('Impossible to access an attribute ("%s") on a %s variable ("%s").', $item, \gettype($object), $object); + } + + throw new RuntimeError($message, $lineno, $source); + } + } + + if (!\is_object($object)) { + if ($isDefinedTest) { + return false; + } + + if ($ignoreStrictCheck || !$env->isStrictVariables()) { + return; + } + + if (null === $object) { + $message = sprintf('Impossible to invoke a method ("%s") on a null variable.', $item); + } elseif (\is_array($object)) { + $message = sprintf('Impossible to invoke a method ("%s") on an array.', $item); + } else { + $message = sprintf('Impossible to invoke a method ("%s") on a %s variable ("%s").', $item, \gettype($object), $object); + } + + throw new RuntimeError($message, $lineno, $source); + } + + if ($object instanceof Template) { + throw new RuntimeError('Accessing \Twig\Template attributes is forbidden.', $lineno, $source); + } + + // object property + if (/* Template::METHOD_CALL */ 'method' !== $type) { + if (isset($object->$item) || \array_key_exists((string) $item, (array) $object)) { + if ($isDefinedTest) { + return true; + } + + if ($sandboxed) { + $env->getExtension(SandboxExtension::class)->checkPropertyAllowed($object, $item, $lineno, $source); + } + + return $object->$item; + } + } + + static $cache = []; + + $class = \get_class($object); + + // object method + // precedence: getXxx() > isXxx() > hasXxx() + if (!isset($cache[$class])) { + $methods = get_class_methods($object); + sort($methods); + $lcMethods = array_map(function ($value) { return strtr($value, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); }, $methods); + $classCache = []; + foreach ($methods as $i => $method) { + $classCache[$method] = $method; + $classCache[$lcName = $lcMethods[$i]] = $method; + + if ('g' === $lcName[0] && 0 === strpos($lcName, 'get')) { + $name = substr($method, 3); + $lcName = substr($lcName, 3); + } elseif ('i' === $lcName[0] && 0 === strpos($lcName, 'is')) { + $name = substr($method, 2); + $lcName = substr($lcName, 2); + } elseif ('h' === $lcName[0] && 0 === strpos($lcName, 'has')) { + $name = substr($method, 3); + $lcName = substr($lcName, 3); + if (\in_array('is'.$lcName, $lcMethods)) { + continue; + } + } else { + continue; + } + + // skip get() and is() methods (in which case, $name is empty) + if ($name) { + if (!isset($classCache[$name])) { + $classCache[$name] = $method; + } + + if (!isset($classCache[$lcName])) { + $classCache[$lcName] = $method; + } + } + } + $cache[$class] = $classCache; + } + + $call = false; + if (isset($cache[$class][$item])) { + $method = $cache[$class][$item]; + } elseif (isset($cache[$class][$lcItem = strtr($item, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')])) { + $method = $cache[$class][$lcItem]; + } elseif (isset($cache[$class]['__call'])) { + $method = $item; + $call = true; + } else { + if ($isDefinedTest) { + return false; + } + + if ($ignoreStrictCheck || !$env->isStrictVariables()) { + return; + } + + throw new RuntimeError(sprintf('Neither the property "%1$s" nor one of the methods "%1$s()", "get%1$s()"/"is%1$s()"/"has%1$s()" or "__call()" exist and have public access in class "%2$s".', $item, $class), $lineno, $source); + } + + if ($isDefinedTest) { + return true; + } + + if ($sandboxed) { + $env->getExtension(SandboxExtension::class)->checkMethodAllowed($object, $method, $lineno, $source); + } + + // Some objects throw exceptions when they have __call, and the method we try + // to call is not supported. If ignoreStrictCheck is true, we should return null. + try { + $ret = $object->$method(...$arguments); + } catch (\BadMethodCallException $e) { + if ($call && ($ignoreStrictCheck || !$env->isStrictVariables())) { + return; + } + throw $e; + } + + return $ret; +} + +/** + * Returns the values from a single column in the input array. + * + *
    + *  {% set items = [{ 'fruit' : 'apple'}, {'fruit' : 'orange' }] %}
    + *
    + *  {% set fruits = items|column('fruit') %}
    + *
    + *  {# fruits now contains ['apple', 'orange'] #}
    + * 
    + * + * @param array|Traversable $array An array + * @param mixed $name The column name + * @param mixed $index The column to use as the index/keys for the returned array + * + * @return array The array of values + */ +function twig_array_column($array, $name, $index = null): array +{ + if ($array instanceof Traversable) { + $array = iterator_to_array($array); + } elseif (!\is_array($array)) { + throw new RuntimeError(sprintf('The column filter only works with arrays or "Traversable", got "%s" as first argument.', \gettype($array))); + } + + return array_column($array, $name, $index); +} + +function twig_array_filter($array, $arrow) +{ + if (!twig_test_iterable($array)) { + throw new RuntimeError(sprintf('The "filter" filter expects an array or "Traversable", got "%s".', \is_object($array) ? \get_class($array) : \gettype($array))); + } + + if (\is_array($array)) { + return array_filter($array, $arrow, \ARRAY_FILTER_USE_BOTH); + } + + // the IteratorIterator wrapping is needed as some internal PHP classes are \Traversable but do not implement \Iterator + return new \CallbackFilterIterator(new \IteratorIterator($array), $arrow); +} + +function twig_array_map($array, $arrow) +{ + $r = []; + foreach ($array as $k => $v) { + $r[$k] = $arrow($v, $k); + } + + return $r; +} + +function twig_array_reduce($array, $arrow, $initial = null) +{ + if (!\is_array($array)) { + $array = iterator_to_array($array); + } + + return array_reduce($array, $arrow, $initial); +} +} diff --git a/src/bb-vendor/twig/twig/src/Lexer.php b/src/bb-vendor/twig/twig/src/Lexer.php new file mode 100644 index 000000000..16068b1b3 --- /dev/null +++ b/src/bb-vendor/twig/twig/src/Lexer.php @@ -0,0 +1,506 @@ + + */ +class Lexer +{ + private $tokens; + private $code; + private $cursor; + private $lineno; + private $end; + private $state; + private $states; + private $brackets; + private $env; + private $source; + private $options; + private $regexes; + private $position; + private $positions; + private $currentVarBlockLine; + + const STATE_DATA = 0; + const STATE_BLOCK = 1; + const STATE_VAR = 2; + const STATE_STRING = 3; + const STATE_INTERPOLATION = 4; + + const REGEX_NAME = '/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/A'; + const REGEX_NUMBER = '/[0-9]+(?:\.[0-9]+)?([Ee][\+\-][0-9]+)?/A'; + const REGEX_STRING = '/"([^#"\\\\]*(?:\\\\.[^#"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\'/As'; + const REGEX_DQ_STRING_DELIM = '/"/A'; + const REGEX_DQ_STRING_PART = '/[^#"\\\\]*(?:(?:\\\\.|#(?!\{))[^#"\\\\]*)*/As'; + const PUNCTUATION = '()[]{}?:.,|'; + + public function __construct(Environment $env, array $options = []) + { + $this->env = $env; + + $this->options = array_merge([ + 'tag_comment' => ['{#', '#}'], + 'tag_block' => ['{%', '%}'], + 'tag_variable' => ['{{', '}}'], + 'whitespace_trim' => '-', + 'whitespace_line_trim' => '~', + 'whitespace_line_chars' => ' \t\0\x0B', + 'interpolation' => ['#{', '}'], + ], $options); + + // when PHP 7.3 is the min version, we will be able to remove the '#' part in preg_quote as it's part of the default + $this->regexes = [ + // }} + 'lex_var' => '{ + \s* + (?:'. + preg_quote($this->options['whitespace_trim'].$this->options['tag_variable'][1], '#').'\s*'. // -}}\s* + '|'. + preg_quote($this->options['whitespace_line_trim'].$this->options['tag_variable'][1], '#').'['.$this->options['whitespace_line_chars'].']*'. // ~}}[ \t\0\x0B]* + '|'. + preg_quote($this->options['tag_variable'][1], '#'). // }} + ') + }Ax', + + // %} + 'lex_block' => '{ + \s* + (?:'. + preg_quote($this->options['whitespace_trim'].$this->options['tag_block'][1], '#').'\s*\n?'. // -%}\s*\n? + '|'. + preg_quote($this->options['whitespace_line_trim'].$this->options['tag_block'][1], '#').'['.$this->options['whitespace_line_chars'].']*'. // ~%}[ \t\0\x0B]* + '|'. + preg_quote($this->options['tag_block'][1], '#').'\n?'. // %}\n? + ') + }Ax', + + // {% endverbatim %} + 'lex_raw_data' => '{'. + preg_quote($this->options['tag_block'][0], '#'). // {% + '('. + $this->options['whitespace_trim']. // - + '|'. + $this->options['whitespace_line_trim']. // ~ + ')?\s*endverbatim\s*'. + '(?:'. + preg_quote($this->options['whitespace_trim'].$this->options['tag_block'][1], '#').'\s*'. // -%} + '|'. + preg_quote($this->options['whitespace_line_trim'].$this->options['tag_block'][1], '#').'['.$this->options['whitespace_line_chars'].']*'. // ~%}[ \t\0\x0B]* + '|'. + preg_quote($this->options['tag_block'][1], '#'). // %} + ') + }sx', + + 'operator' => $this->getOperatorRegex(), + + // #} + 'lex_comment' => '{ + (?:'. + preg_quote($this->options['whitespace_trim']).preg_quote($this->options['tag_comment'][1], '#').'\s*\n?'. // -#}\s*\n? + '|'. + preg_quote($this->options['whitespace_line_trim'].$this->options['tag_comment'][1], '#').'['.$this->options['whitespace_line_chars'].']*'. // ~#}[ \t\0\x0B]* + '|'. + preg_quote($this->options['tag_comment'][1], '#').'\n?'. // #}\n? + ') + }sx', + + // verbatim %} + 'lex_block_raw' => '{ + \s*verbatim\s* + (?:'. + preg_quote($this->options['whitespace_trim'].$this->options['tag_block'][1], '#').'\s*'. // -%}\s* + '|'. + preg_quote($this->options['whitespace_line_trim'].$this->options['tag_block'][1], '#').'['.$this->options['whitespace_line_chars'].']*'. // ~%}[ \t\0\x0B]* + '|'. + preg_quote($this->options['tag_block'][1], '#'). // %} + ') + }Asx', + + 'lex_block_line' => '{\s*line\s+(\d+)\s*'.preg_quote($this->options['tag_block'][1], '#').'}As', + + // {{ or {% or {# + 'lex_tokens_start' => '{ + ('. + preg_quote($this->options['tag_variable'][0], '#'). // {{ + '|'. + preg_quote($this->options['tag_block'][0], '#'). // {% + '|'. + preg_quote($this->options['tag_comment'][0], '#'). // {# + ')('. + preg_quote($this->options['whitespace_trim'], '#'). // - + '|'. + preg_quote($this->options['whitespace_line_trim'], '#'). // ~ + ')? + }sx', + 'interpolation_start' => '{'.preg_quote($this->options['interpolation'][0], '#').'\s*}A', + 'interpolation_end' => '{\s*'.preg_quote($this->options['interpolation'][1], '#').'}A', + ]; + } + + public function tokenize(Source $source) + { + $this->source = $source; + $this->code = str_replace(["\r\n", "\r"], "\n", $source->getCode()); + $this->cursor = 0; + $this->lineno = 1; + $this->end = \strlen($this->code); + $this->tokens = []; + $this->state = self::STATE_DATA; + $this->states = []; + $this->brackets = []; + $this->position = -1; + + // find all token starts in one go + preg_match_all($this->regexes['lex_tokens_start'], $this->code, $matches, PREG_OFFSET_CAPTURE); + $this->positions = $matches; + + while ($this->cursor < $this->end) { + // dispatch to the lexing functions depending + // on the current state + switch ($this->state) { + case self::STATE_DATA: + $this->lexData(); + break; + + case self::STATE_BLOCK: + $this->lexBlock(); + break; + + case self::STATE_VAR: + $this->lexVar(); + break; + + case self::STATE_STRING: + $this->lexString(); + break; + + case self::STATE_INTERPOLATION: + $this->lexInterpolation(); + break; + } + } + + $this->pushToken(/* Token::EOF_TYPE */ -1); + + if (!empty($this->brackets)) { + list($expect, $lineno) = array_pop($this->brackets); + throw new SyntaxError(sprintf('Unclosed "%s".', $expect), $lineno, $this->source); + } + + return new TokenStream($this->tokens, $this->source); + } + + private function lexData() + { + // if no matches are left we return the rest of the template as simple text token + if ($this->position == \count($this->positions[0]) - 1) { + $this->pushToken(/* Token::TEXT_TYPE */ 0, substr($this->code, $this->cursor)); + $this->cursor = $this->end; + + return; + } + + // Find the first token after the current cursor + $position = $this->positions[0][++$this->position]; + while ($position[1] < $this->cursor) { + if ($this->position == \count($this->positions[0]) - 1) { + return; + } + $position = $this->positions[0][++$this->position]; + } + + // push the template text first + $text = $textContent = substr($this->code, $this->cursor, $position[1] - $this->cursor); + + // trim? + if (isset($this->positions[2][$this->position][0])) { + if ($this->options['whitespace_trim'] === $this->positions[2][$this->position][0]) { + // whitespace_trim detected ({%-, {{- or {#-) + $text = rtrim($text); + } elseif ($this->options['whitespace_line_trim'] === $this->positions[2][$this->position][0]) { + // whitespace_line_trim detected ({%~, {{~ or {#~) + // don't trim \r and \n + $text = rtrim($text, " \t\0\x0B"); + } + } + $this->pushToken(/* Token::TEXT_TYPE */ 0, $text); + $this->moveCursor($textContent.$position[0]); + + switch ($this->positions[1][$this->position][0]) { + case $this->options['tag_comment'][0]: + $this->lexComment(); + break; + + case $this->options['tag_block'][0]: + // raw data? + if (preg_match($this->regexes['lex_block_raw'], $this->code, $match, 0, $this->cursor)) { + $this->moveCursor($match[0]); + $this->lexRawData(); + // {% line \d+ %} + } elseif (preg_match($this->regexes['lex_block_line'], $this->code, $match, 0, $this->cursor)) { + $this->moveCursor($match[0]); + $this->lineno = (int) $match[1]; + } else { + $this->pushToken(/* Token::BLOCK_START_TYPE */ 1); + $this->pushState(self::STATE_BLOCK); + $this->currentVarBlockLine = $this->lineno; + } + break; + + case $this->options['tag_variable'][0]: + $this->pushToken(/* Token::VAR_START_TYPE */ 2); + $this->pushState(self::STATE_VAR); + $this->currentVarBlockLine = $this->lineno; + break; + } + } + + private function lexBlock() + { + if (empty($this->brackets) && preg_match($this->regexes['lex_block'], $this->code, $match, 0, $this->cursor)) { + $this->pushToken(/* Token::BLOCK_END_TYPE */ 3); + $this->moveCursor($match[0]); + $this->popState(); + } else { + $this->lexExpression(); + } + } + + private function lexVar() + { + if (empty($this->brackets) && preg_match($this->regexes['lex_var'], $this->code, $match, 0, $this->cursor)) { + $this->pushToken(/* Token::VAR_END_TYPE */ 4); + $this->moveCursor($match[0]); + $this->popState(); + } else { + $this->lexExpression(); + } + } + + private function lexExpression() + { + // whitespace + if (preg_match('/\s+/A', $this->code, $match, 0, $this->cursor)) { + $this->moveCursor($match[0]); + + if ($this->cursor >= $this->end) { + throw new SyntaxError(sprintf('Unclosed "%s".', self::STATE_BLOCK === $this->state ? 'block' : 'variable'), $this->currentVarBlockLine, $this->source); + } + } + + // arrow function + if ('=' === $this->code[$this->cursor] && '>' === $this->code[$this->cursor + 1]) { + $this->pushToken(Token::ARROW_TYPE, '=>'); + $this->moveCursor('=>'); + } + // operators + elseif (preg_match($this->regexes['operator'], $this->code, $match, 0, $this->cursor)) { + $this->pushToken(/* Token::OPERATOR_TYPE */ 8, preg_replace('/\s+/', ' ', $match[0])); + $this->moveCursor($match[0]); + } + // names + elseif (preg_match(self::REGEX_NAME, $this->code, $match, 0, $this->cursor)) { + $this->pushToken(/* Token::NAME_TYPE */ 5, $match[0]); + $this->moveCursor($match[0]); + } + // numbers + elseif (preg_match(self::REGEX_NUMBER, $this->code, $match, 0, $this->cursor)) { + $number = (float) $match[0]; // floats + if (ctype_digit($match[0]) && $number <= PHP_INT_MAX) { + $number = (int) $match[0]; // integers lower than the maximum + } + $this->pushToken(/* Token::NUMBER_TYPE */ 6, $number); + $this->moveCursor($match[0]); + } + // punctuation + elseif (false !== strpos(self::PUNCTUATION, $this->code[$this->cursor])) { + // opening bracket + if (false !== strpos('([{', $this->code[$this->cursor])) { + $this->brackets[] = [$this->code[$this->cursor], $this->lineno]; + } + // closing bracket + elseif (false !== strpos(')]}', $this->code[$this->cursor])) { + if (empty($this->brackets)) { + throw new SyntaxError(sprintf('Unexpected "%s".', $this->code[$this->cursor]), $this->lineno, $this->source); + } + + list($expect, $lineno) = array_pop($this->brackets); + if ($this->code[$this->cursor] != strtr($expect, '([{', ')]}')) { + throw new SyntaxError(sprintf('Unclosed "%s".', $expect), $lineno, $this->source); + } + } + + $this->pushToken(/* Token::PUNCTUATION_TYPE */ 9, $this->code[$this->cursor]); + ++$this->cursor; + } + // strings + elseif (preg_match(self::REGEX_STRING, $this->code, $match, 0, $this->cursor)) { + $this->pushToken(/* Token::STRING_TYPE */ 7, stripcslashes(substr($match[0], 1, -1))); + $this->moveCursor($match[0]); + } + // opening double quoted string + elseif (preg_match(self::REGEX_DQ_STRING_DELIM, $this->code, $match, 0, $this->cursor)) { + $this->brackets[] = ['"', $this->lineno]; + $this->pushState(self::STATE_STRING); + $this->moveCursor($match[0]); + } + // unlexable + else { + throw new SyntaxError(sprintf('Unexpected character "%s".', $this->code[$this->cursor]), $this->lineno, $this->source); + } + } + + private function lexRawData() + { + if (!preg_match($this->regexes['lex_raw_data'], $this->code, $match, PREG_OFFSET_CAPTURE, $this->cursor)) { + throw new SyntaxError('Unexpected end of file: Unclosed "verbatim" block.', $this->lineno, $this->source); + } + + $text = substr($this->code, $this->cursor, $match[0][1] - $this->cursor); + $this->moveCursor($text.$match[0][0]); + + // trim? + if (isset($match[1][0])) { + if ($this->options['whitespace_trim'] === $match[1][0]) { + // whitespace_trim detected ({%-, {{- or {#-) + $text = rtrim($text); + } else { + // whitespace_line_trim detected ({%~, {{~ or {#~) + // don't trim \r and \n + $text = rtrim($text, " \t\0\x0B"); + } + } + + $this->pushToken(/* Token::TEXT_TYPE */ 0, $text); + } + + private function lexComment() + { + if (!preg_match($this->regexes['lex_comment'], $this->code, $match, PREG_OFFSET_CAPTURE, $this->cursor)) { + throw new SyntaxError('Unclosed comment.', $this->lineno, $this->source); + } + + $this->moveCursor(substr($this->code, $this->cursor, $match[0][1] - $this->cursor).$match[0][0]); + } + + private function lexString() + { + if (preg_match($this->regexes['interpolation_start'], $this->code, $match, 0, $this->cursor)) { + $this->brackets[] = [$this->options['interpolation'][0], $this->lineno]; + $this->pushToken(/* Token::INTERPOLATION_START_TYPE */ 10); + $this->moveCursor($match[0]); + $this->pushState(self::STATE_INTERPOLATION); + } elseif (preg_match(self::REGEX_DQ_STRING_PART, $this->code, $match, 0, $this->cursor) && \strlen($match[0]) > 0) { + $this->pushToken(/* Token::STRING_TYPE */ 7, stripcslashes($match[0])); + $this->moveCursor($match[0]); + } elseif (preg_match(self::REGEX_DQ_STRING_DELIM, $this->code, $match, 0, $this->cursor)) { + list($expect, $lineno) = array_pop($this->brackets); + if ('"' != $this->code[$this->cursor]) { + throw new SyntaxError(sprintf('Unclosed "%s".', $expect), $lineno, $this->source); + } + + $this->popState(); + ++$this->cursor; + } else { + // unlexable + throw new SyntaxError(sprintf('Unexpected character "%s".', $this->code[$this->cursor]), $this->lineno, $this->source); + } + } + + private function lexInterpolation() + { + $bracket = end($this->brackets); + if ($this->options['interpolation'][0] === $bracket[0] && preg_match($this->regexes['interpolation_end'], $this->code, $match, 0, $this->cursor)) { + array_pop($this->brackets); + $this->pushToken(/* Token::INTERPOLATION_END_TYPE */ 11); + $this->moveCursor($match[0]); + $this->popState(); + } else { + $this->lexExpression(); + } + } + + private function pushToken($type, $value = '') + { + // do not push empty text tokens + if (/* Token::TEXT_TYPE */ 0 === $type && '' === $value) { + return; + } + + $this->tokens[] = new Token($type, $value, $this->lineno); + } + + private function moveCursor($text) + { + $this->cursor += \strlen($text); + $this->lineno += substr_count($text, "\n"); + } + + private function getOperatorRegex() + { + $operators = array_merge( + ['='], + array_keys($this->env->getUnaryOperators()), + array_keys($this->env->getBinaryOperators()) + ); + + $operators = array_combine($operators, array_map('strlen', $operators)); + arsort($operators); + + $regex = []; + foreach ($operators as $operator => $length) { + // an operator that ends with a character must be followed by + // a whitespace or a parenthesis + $r = preg_quote($operator, '/'); + if (ctype_alpha($operator[$length - 1])) { + $r .= '(?=[\s()])'; + } + + // an operator that begins with a character must have a space before + // or a parenthesis + if (ctype_alpha($operator[0])) { + $r = '(?<=[\s(])'.$r; + } + + // an operator with a space can be any amount of whitespaces + $r = preg_replace('/\s+/', '\s+', $r); + + $regex[] = $r; + } + + return '/'.implode('|', $regex).'/A'; + } + + private function pushState($state) + { + $this->states[] = $this->state; + $this->state = $state; + } + + private function popState() + { + if (0 === \count($this->states)) { + throw new \LogicException('Cannot pop state without a previous state.'); + } + + $this->state = array_pop($this->states); + } +} + +class_alias('Twig\Lexer', 'Twig_Lexer'); diff --git a/src/bb-vendor/twig/twig/src/Node/SandboxNode.php b/src/bb-vendor/twig/twig/src/Node/SandboxNode.php new file mode 100644 index 000000000..fe59313bf --- /dev/null +++ b/src/bb-vendor/twig/twig/src/Node/SandboxNode.php @@ -0,0 +1,47 @@ + + */ +class SandboxNode extends Node +{ + public function __construct(Node $body, int $lineno, string $tag = null) + { + parent::__construct(['body' => $body], [], $lineno, $tag); + } + + public function compile(Compiler $compiler) + { + $compiler + ->addDebugInfo($this) + ->write("if (!\$alreadySandboxed = \$this->sandbox->isSandboxed()) {\n") + ->indent() + ->write("\$this->sandbox->enableSandbox();\n") + ->outdent() + ->write("}\n") + ->subcompile($this->getNode('body')) + ->write("if (!\$alreadySandboxed) {\n") + ->indent() + ->write("\$this->sandbox->disableSandbox();\n") + ->outdent() + ->write("}\n") + ; + } +} + +class_alias('Twig\Node\SandboxNode', 'Twig_Node_Sandbox'); diff --git a/src/bb-vendor/twig/twig/src/TokenParser/ApplyTokenParser.php b/src/bb-vendor/twig/twig/src/TokenParser/ApplyTokenParser.php new file mode 100644 index 000000000..879879a2b --- /dev/null +++ b/src/bb-vendor/twig/twig/src/TokenParser/ApplyTokenParser.php @@ -0,0 +1,58 @@ +getLine(); + $name = $this->parser->getVarName(); + + $ref = new TempNameExpression($name, $lineno); + $ref->setAttribute('always_defined', true); + + $filter = $this->parser->getExpressionParser()->parseFilterExpressionRaw($ref, $this->getTag()); + + $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); + $body = $this->parser->subparse([$this, 'decideApplyEnd'], true); + $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); + + return new Node([ + new SetNode(true, $ref, $body, $lineno, $this->getTag()), + new PrintNode($filter, $lineno, $this->getTag()), + ]); + } + + public function decideApplyEnd(Token $token) + { + return $token->test('endapply'); + } + + public function getTag() + { + return 'apply'; + } +} diff --git a/src/build.xml b/src/build.xml new file mode 100644 index 000000000..c37e60803 --- /dev/null +++ b/src/build.xml @@ -0,0 +1,152 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/composer.json b/src/composer.json index 7d3bb624a..d5273d11a 100644 --- a/src/composer.json +++ b/src/composer.json @@ -12,7 +12,8 @@ } ], "require": { - "php": ">=7.2.0", + + "php": ">=7.4.9", "ext-curl": "*", "ext-zlib": "*", "ext-PDO": "*", @@ -20,13 +21,15 @@ "pimple/pimple": "v3.3.0", "twig/twig": "v2.13.0", "twig/extensions": "1.5.4", - "rev42/tfpdf": "v1.24", - "geoip2/geoip2": "v2.1.0", + "mpdf/mpdf": "v8.0.4", + "geoip2/geoip2": "v2.10.0", "ircmaxell/password-compat": "v1.0.4", "phpmailer/phpmailer": "6.1.6", "mustangostang/spyc": "0.5.1", - "michelf/php-markdown": "1.9.0", - "stripe/stripe-php": "2.1.1" + "michelf/php-markdown": "1.7.0", + "stripe/stripe-php": "2.1.1", + "guzzlehttp/guzzle": "^v3.8.1" + }, "suggest": { "ext-gettext": "*" @@ -48,3 +51,4 @@ "psr-0": { "": "../tests/bb-library" } } } + diff --git a/src/composer.lock b/src/composer.lock index 87c2b8ce7..43129f9f5 100644 --- a/src/composer.lock +++ b/src/composer.lock @@ -4,36 +4,108 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "61556a0e814aa34603e8a0f8ce034fbc", + + "content-hash": "bd8ef69354426d14d8383eaa001c6090", "packages": [ { - "name": "geoip2/geoip2", - "version": "v2.1.0", + "name": "composer/ca-bundle", + "version": "1.2.8", "source": { "type": "git", - "url": "https://github.com/maxmind/GeoIP2-php.git", - "reference": "64f226209342c4a2f54b82ba3f0707db944f7d70" + "url": "https://github.com/composer/ca-bundle.git", + "reference": "8a7ecad675253e4654ea05505233285377405215" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/maxmind/GeoIP2-php/zipball/64f226209342c4a2f54b82ba3f0707db944f7d70", - "reference": "64f226209342c4a2f54b82ba3f0707db944f7d70", + "url": "https://api.github.com/repos/composer/ca-bundle/zipball/8a7ecad675253e4654ea05505233285377405215", + "reference": "8a7ecad675253e4654ea05505233285377405215", "shasum": "" }, "require": { - "guzzle/guzzle": "3.*", - "maxmind-db/reader": "~1.0", - "php": ">=5.3.1" + "ext-openssl": "*", + "ext-pcre": "*", + "php": "^5.3.2 || ^7.0 || ^8.0" }, "require-dev": { - "phpunit/phpunit": "4.2.*", - "satooshi/php-coveralls": "dev-master" + "phpunit/phpunit": "^4.8.35 || ^5.7 || 6.5 - 8", + "psr/log": "^1.0", + "symfony/process": "^2.5 || ^3.0 || ^4.0 || ^5.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.x-dev" + } + }, + "autoload": { + "psr-4": { + "Composer\\CaBundle\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + } + ], + "description": "Lets you find a path to the system CA bundle, and includes a fallback to the Mozilla CA bundle.", + "keywords": [ + "cabundle", + "cacert", + "certificate", + "ssl", + "tls" + ], + "funding": [ + { + "url": "https://packagist.com", + "type": "custom" + }, + { + "url": "https://github.com/composer", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/composer/composer", + "type": "tidelift" + } + ], + "time": "2020-08-23T12:54:47+00:00" + }, + { + "name": "geoip2/geoip2", + "version": "v2.10.0", + "source": { + "type": "git", + "url": "https://github.com/maxmind/GeoIP2-php.git", + "reference": "419557cd21d9fe039721a83490701a58c8ce784a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/maxmind/GeoIP2-php/zipball/419557cd21d9fe039721a83490701a58c8ce784a", + "reference": "419557cd21d9fe039721a83490701a58c8ce784a", + "shasum": "" + }, + "require": { + "ext-json": "*", + "maxmind-db/reader": "~1.5", + "maxmind/web-service-common": "~0.6", + "php": ">=5.6" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "2.*", + "phpunit/phpunit": "5.*", + "squizlabs/php_codesniffer": "3.*" }, "type": "library", "autoload": { - "psr-0": { - "GeoIp2": "src/", - "JsonSerializable": "compat/" + "psr-4": { + "GeoIp2\\": "src" } }, "notification-url": "https://packagist.org/downloads/", @@ -44,7 +116,7 @@ { "name": "Gregory J. Oschwald", "email": "goschwald@maxmind.com", - "homepage": "http://www.maxmind.com/" + "homepage": "https://www.maxmind.com/" } ], "description": "MaxMind GeoIP2 PHP API", @@ -56,26 +128,26 @@ "geolocation", "maxmind" ], - "time": "2014-10-29T17:11:44+00:00" + "time": "2019-12-12T18:48:39+00:00" }, { - "name": "guzzle/guzzle", - "version": "v3.9.3", + "name": "guzzlehttp/guzzle", + "version": "v3.8.1", "source": { "type": "git", - "url": "https://github.com/guzzle/guzzle3.git", - "reference": "0645b70d953bc1c067bbc8d5bc53194706b628d9" + "url": "https://github.com/guzzle/guzzle.git", + "reference": "4de0618a01b34aa1c8c33a3f13f396dcd3882eba" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/guzzle/guzzle3/zipball/0645b70d953bc1c067bbc8d5bc53194706b628d9", - "reference": "0645b70d953bc1c067bbc8d5bc53194706b628d9", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/4de0618a01b34aa1c8c33a3f13f396dcd3882eba", + "reference": "4de0618a01b34aa1c8c33a3f13f396dcd3882eba", "shasum": "" }, "require": { "ext-curl": "*", "php": ">=5.3.3", - "symfony/event-dispatcher": "~2.1" + "symfony/event-dispatcher": ">=2.1" }, "replace": { "guzzle/batch": "self.version", @@ -102,21 +174,18 @@ "guzzle/stream": "self.version" }, "require-dev": { - "doctrine/cache": "~1.3", - "monolog/monolog": "~1.0", + "doctrine/cache": "*", + "monolog/monolog": "1.*", "phpunit/phpunit": "3.7.*", - "psr/log": "~1.0", - "symfony/class-loader": "~2.1", - "zendframework/zend-cache": "2.*,<2.3", - "zendframework/zend-log": "2.*,<2.3" - }, - "suggest": { - "guzzlehttp/guzzle": "Guzzle 5 has moved to a new package name. The package you have installed, Guzzle 3, is deprecated." + "psr/log": "1.0.*", + "symfony/class-loader": "*", + "zendframework/zend-cache": "<2.3", + "zendframework/zend-log": "<2.3" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "3.9-dev" + "dev-master": "3.8-dev" } }, "autoload": { @@ -140,7 +209,7 @@ "homepage": "https://github.com/guzzle/guzzle/contributors" } ], - "description": "PHP HTTP client. This library is deprecated in favor of https://packagist.org/packages/guzzlehttp/guzzle", + "description": "Guzzle is a PHP HTTP client library and framework for building RESTful web service clients", "homepage": "http://guzzlephp.org/", "keywords": [ "client", @@ -151,8 +220,210 @@ "rest", "web service" ], - "abandoned": "guzzlehttp/guzzle", - "time": "2015-03-18T18:23:50+00:00" + "time": "2014-01-28T22:29:15+00:00" + }, + { + "name": "guzzlehttp/guzzle", + "version": "7.0.1", + "source": { + "type": "git", + "url": "https://github.com/guzzle/guzzle.git", + "reference": "2d9d3c186a6637a43193e66b097c50e4451eaab2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/2d9d3c186a6637a43193e66b097c50e4451eaab2", + "reference": "2d9d3c186a6637a43193e66b097c50e4451eaab2", + "shasum": "" + }, + "require": { + "ext-json": "*", + "guzzlehttp/promises": "^1.0", + "guzzlehttp/psr7": "^1.6.1", + "php": "^7.2.5", + "psr/http-client": "^1.0" + }, + "provide": { + "psr/http-client-implementation": "1.0" + }, + "require-dev": { + "ergebnis/composer-normalize": "^2.0", + "ext-curl": "*", + "php-http/client-integration-tests": "dev-phpunit8", + "phpunit/phpunit": "^8.5.5", + "psr/log": "^1.1" + }, + "suggest": { + "ext-curl": "Required for CURL handler support", + "ext-intl": "Required for Internationalized Domain Name (IDN) support", + "psr/log": "Required for using the Log middleware" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "7.0-dev" + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://sagikazarmark.hu" + } + ], + "description": "Guzzle is a PHP HTTP client library", + "homepage": "http://guzzlephp.org/", + "keywords": [ + "client", + "curl", + "framework", + "http", + "http client", + "psr-18", + "psr-7", + "rest", + "web service" + ], + "time": "2020-06-27T10:33:25+00:00" + }, + { + "name": "guzzlehttp/promises", + "version": "v1.3.1", + "source": { + "type": "git", + "url": "https://github.com/guzzle/promises.git", + "reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/promises/zipball/a59da6cf61d80060647ff4d3eb2c03a2bc694646", + "reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646", + "shasum": "" + }, + "require": { + "php": ">=5.5.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.4-dev" + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "description": "Guzzle promises library", + "keywords": [ + "promise" + ], + "time": "2016-12-20T10:07:11+00:00" + }, + { + "name": "guzzlehttp/psr7", + "version": "1.6.1", + "source": { + "type": "git", + "url": "https://github.com/guzzle/psr7.git", + "reference": "239400de7a173fe9901b9ac7c06497751f00727a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/239400de7a173fe9901b9ac7c06497751f00727a", + "reference": "239400de7a173fe9901b9ac7c06497751f00727a", + "shasum": "" + }, + "require": { + "php": ">=5.4.0", + "psr/http-message": "~1.0", + "ralouphie/getallheaders": "^2.0.5 || ^3.0.0" + }, + "provide": { + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "ext-zlib": "*", + "phpunit/phpunit": "~4.8.36 || ^5.7.27 || ^6.5.8" + }, + "suggest": { + "zendframework/zend-httphandlerrunner": "Emit PSR-7 responses" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.6-dev" + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Schultze", + "homepage": "https://github.com/Tobion" + } + ], + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "http", + "message", + "psr-7", + "request", + "response", + "stream", + "uri", + "url" + ], + "time": "2019-07-01T23:21:34+00:00" }, { "name": "ircmaxell/password-compat", @@ -256,6 +527,52 @@ ], "time": "2020-08-07T22:10:05+00:00" }, + { + "name": "maxmind/web-service-common", + "version": "v0.7.0", + "source": { + "type": "git", + "url": "https://github.com/maxmind/web-service-common-php.git", + "reference": "74c996c218ada5c639c8c2f076756e059f5552fc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/maxmind/web-service-common-php/zipball/74c996c218ada5c639c8c2f076756e059f5552fc", + "reference": "74c996c218ada5c639c8c2f076756e059f5552fc", + "shasum": "" + }, + "require": { + "composer/ca-bundle": "^1.0.3", + "ext-curl": "*", + "ext-json": "*", + "php": ">=5.6" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "2.*", + "phpunit/phpunit": "^4.8.36 || ^5.7 || ^6.5 || ^7.0", + "squizlabs/php_codesniffer": "3.*" + }, + "type": "library", + "autoload": { + "psr-4": { + "MaxMind\\Exception\\": "src/Exception", + "MaxMind\\WebService\\": "src/WebService" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "Gregory Oschwald", + "email": "goschwald@maxmind.com" + } + ], + "description": "Internal MaxMind Web Service API", + "homepage": "https://github.com/maxmind/web-service-common-php", + "time": "2020-05-06T14:07:26+00:00" + }, { "name": "michelf/php-markdown", "version": "1.7.0", @@ -307,6 +624,75 @@ ], "time": "2016-10-29T18:58:20+00:00" }, + { + "name": "mpdf/mpdf", + "version": "v8.0.4", + "source": { + "type": "git", + "url": "https://github.com/mpdf/mpdf.git", + "reference": "d3147a0d790b6d11936fd9c73fa31a7ed45e3f6f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/mpdf/mpdf/zipball/d3147a0d790b6d11936fd9c73fa31a7ed45e3f6f", + "reference": "d3147a0d790b6d11936fd9c73fa31a7ed45e3f6f", + "shasum": "" + }, + "require": { + "ext-gd": "*", + "ext-mbstring": "*", + "myclabs/deep-copy": "^1.7", + "paragonie/random_compat": "^1.4|^2.0|9.99.99", + "php": "^5.6 || ~7.0.0 || ~7.1.0 || ~7.2.0 || ~7.3.0 || ~7.4.0", + "psr/log": "^1.0", + "setasign/fpdi": "^2.1" + }, + "require-dev": { + "mockery/mockery": "^0.9.5", + "mpdf/qrcode": "^1.0.0", + "phpunit/phpunit": "^5.0", + "squizlabs/php_codesniffer": "^3.5.0", + "tracy/tracy": "^2.4" + }, + "suggest": { + "ext-bcmath": "Needed for generation of some types of barcodes", + "ext-xml": "Needed mainly for SVG manipulation", + "ext-zlib": "Needed for compression of embedded resources, such as fonts" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-development": "7.x-dev" + } + }, + "autoload": { + "psr-4": { + "Mpdf\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "GPL-2.0-only" + ], + "authors": [ + { + "name": "Matěj Humpál", + "role": "Developer, maintainer" + }, + { + "name": "Ian Back", + "role": "Developer (retired)" + } + ], + "description": "PHP library generating PDF files from UTF-8 encoded HTML", + "homepage": "https://mpdf.github.io", + "keywords": [ + "pdf", + "php", + "utf-8" + ], + "time": "2019-11-28T09:39:33+00:00" + }, { "name": "mustangostang/spyc", "version": "0.5.1", @@ -354,6 +740,105 @@ ], "time": "2013-02-21T10:52:01+00:00" }, + { + "name": "myclabs/deep-copy", + "version": "1.10.1", + "source": { + "type": "git", + "url": "https://github.com/myclabs/DeepCopy.git", + "reference": "969b211f9a51aa1f6c01d1d2aef56d3bd91598e5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/969b211f9a51aa1f6c01d1d2aef56d3bd91598e5", + "reference": "969b211f9a51aa1f6c01d1d2aef56d3bd91598e5", + "shasum": "" + }, + "require": { + "php": "^7.1 || ^8.0" + }, + "replace": { + "myclabs/deep-copy": "self.version" + }, + "require-dev": { + "doctrine/collections": "^1.0", + "doctrine/common": "^2.6", + "phpunit/phpunit": "^7.1" + }, + "type": "library", + "autoload": { + "psr-4": { + "DeepCopy\\": "src/DeepCopy/" + }, + "files": [ + "src/DeepCopy/deep_copy.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Create deep copies (clones) of your objects", + "keywords": [ + "clone", + "copy", + "duplicate", + "object", + "object graph" + ], + "funding": [ + { + "url": "https://tidelift.com/funding/github/packagist/myclabs/deep-copy", + "type": "tidelift" + } + ], + "time": "2020-06-29T13:22:24+00:00" + }, + { + "name": "paragonie/random_compat", + "version": "v9.99.99", + "source": { + "type": "git", + "url": "https://github.com/paragonie/random_compat.git", + "reference": "84b4dfb120c6f9b4ff7b3685f9b8f1aa365a0c95" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/paragonie/random_compat/zipball/84b4dfb120c6f9b4ff7b3685f9b8f1aa365a0c95", + "reference": "84b4dfb120c6f9b4ff7b3685f9b8f1aa365a0c95", + "shasum": "" + }, + "require": { + "php": "^7" + }, + "require-dev": { + "phpunit/phpunit": "4.*|5.*", + "vimeo/psalm": "^1" + }, + "suggest": { + "ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes." + }, + "type": "library", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Paragon Initiative Enterprises", + "email": "security@paragonie.com", + "homepage": "https://paragonie.com" + } + ], + "description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7", + "keywords": [ + "csprng", + "polyfill", + "pseudorandom", + "random" + ], + "time": "2018-07-02T15:55:56+00:00" + }, { "name": "phpmailer/phpmailer", "version": "v6.1.6", @@ -522,42 +1007,360 @@ "time": "2017-02-14T16:28:37+00:00" }, { - "name": "rev42/tfpdf", - "version": "v1.24", + + "name": "psr/event-dispatcher", + "version": "1.0.0", "source": { "type": "git", - "url": "https://github.com/rev42/tfpdf.git", - "reference": "a6c61aa39be95a8604fb863026e8c2b969ae4113" + "url": "https://github.com/php-fig/event-dispatcher.git", + "reference": "dbefd12671e8a14ec7f180cab83036ed26714bb0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/rev42/tfpdf/zipball/a6c61aa39be95a8604fb863026e8c2b969ae4113", - "reference": "a6c61aa39be95a8604fb863026e8c2b969ae4113", + "url": "https://api.github.com/repos/php-fig/event-dispatcher/zipball/dbefd12671e8a14ec7f180cab83036ed26714bb0", + "reference": "dbefd12671e8a14ec7f180cab83036ed26714bb0", "shasum": "" }, + "require": { + "php": ">=7.2.0" + + "name": "psr/http-client", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-client.git", + "reference": "2dfb5f6c5eff0e91e20e913f8c5452ed95b86621" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-client/zipball/2dfb5f6c5eff0e91e20e913f8c5452ed95b86621", + "reference": "2dfb5f6c5eff0e91e20e913f8c5452ed95b86621", + "shasum": "" + }, + "require": { + "php": "^7.0 || ^8.0", + "psr/http-message": "^1.0" + + }, "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, "autoload": { - "psr-0": { - "tFPDF": "src/" + "psr-4": { + + "Psr\\EventDispatcher\\": "src/" + + "Psr\\Http\\Client\\": "src/" + } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "LGPL" + "MIT" ], "authors": [ { - "name": "Ian Back", - "email": "ianb@bpm1.com" + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" } ], - "description": "tFPDF", - "homepage": "http://fpdf.org/fr/script/script92.php", + + "description": "Standard interfaces for event handling.", "keywords": [ + "events", + "psr", + "psr-14" + ], + "time": "2019-01-08T18:20:26+00:00" + + "description": "Common interface for HTTP clients", + "homepage": "https://github.com/php-fig/http-client", + "keywords": [ + "http", + "http-client", + "psr", + "psr-18" + ], + "time": "2020-06-29T06:28:15+00:00" + }, + { + "name": "psr/http-message", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "time": "2016-08-06T14:39:51+00:00" + + }, + { + "name": "psr/log", + "version": "1.1.3", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "0f73288fd15629204f9d42b7055f72dacbe811fc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/0f73288fd15629204f9d42b7055f72dacbe811fc", + "reference": "0f73288fd15629204f9d42b7055f72dacbe811fc", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Log\\": "Psr/Log/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + + } + ], + "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "time": "2020-03-23T09:12:05+00:00" + }, + { + "name": "ralouphie/getallheaders", + "version": "3.0.3", + "source": { + "type": "git", + "url": "https://github.com/ralouphie/getallheaders.git", + "reference": "120b605dfeb996808c31b6477290a714d356e822" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822", + "reference": "120b605dfeb996808c31b6477290a714d356e822", + "shasum": "" + }, + "require": { + "php": ">=5.6" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^2.1", + "phpunit/phpunit": "^5 || ^6.5" + }, + "type": "library", + "autoload": { + "files": [ + "src/getallheaders.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "description": "A polyfill for getallheaders.", + "time": "2019-03-08T08:55:37+00:00" + }, + { + "name": "setasign/fpdi", + "version": "v2.3.4", + "source": { + "type": "git", + "url": "https://github.com/Setasign/FPDI.git", + "reference": "2b5fb811c04f937ef257ef3f798cebeded33c136" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Setasign/FPDI/zipball/2b5fb811c04f937ef257ef3f798cebeded33c136", + "reference": "2b5fb811c04f937ef257ef3f798cebeded33c136", + "shasum": "" + }, + "require": { + "ext-zlib": "*", + "php": "^5.6 || ^7.0" + }, + "conflict": { + "setasign/tfpdf": "<1.31" + }, + "require-dev": { + "phpunit/phpunit": "~5.7", + "setasign/fpdf": "~1.8", + "setasign/tfpdf": "1.31", + "squizlabs/php_codesniffer": "^3.5", + "tecnickcom/tcpdf": "~6.2" + }, + "suggest": { + "setasign/fpdf": "FPDI will extend this class but as it is also possible to use TCPDF or tFPDF as an alternative. There's no fixed dependency configured." + }, + "type": "library", + "autoload": { + "psr-4": { + "setasign\\Fpdi\\": "src/" + + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + + "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "time": "2020-03-23T09:12:05+00:00" + }, + { + "name": "setasign/fpdi", + "version": "v2.3.4", + "source": { + "type": "git", + "url": "https://github.com/Setasign/FPDI.git", + "reference": "2b5fb811c04f937ef257ef3f798cebeded33c136" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Setasign/FPDI/zipball/2b5fb811c04f937ef257ef3f798cebeded33c136", + "reference": "2b5fb811c04f937ef257ef3f798cebeded33c136", + "shasum": "" + }, + "require": { + "ext-zlib": "*", + "php": "^5.6 || ^7.0" + }, + "conflict": { + "setasign/tfpdf": "<1.31" + }, + "require-dev": { + "phpunit/phpunit": "~5.7", + "setasign/fpdf": "~1.8", + "setasign/tfpdf": "1.31", + "squizlabs/php_codesniffer": "^3.5", + "tecnickcom/tcpdf": "~6.2" + }, + "suggest": { + "setasign/fpdf": "FPDI will extend this class but as it is also possible to use TCPDF or tFPDF as an alternative. There's no fixed dependency configured." + }, + "type": "library", + "autoload": { + "psr-4": { + "setasign\\Fpdi\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jan Slabon", + "email": "jan.slabon@setasign.com", + "homepage": "https://www.setasign.com" + }, + { + "name": "Maximilian Kresse", + "email": "maximilian.kresse@setasign.com", + "homepage": "https://www.setasign.com" + } + ], + "description": "FPDI is a collection of PHP classes facilitating developers to read pages from existing PDF documents and use them as templates in FPDF. Because it is also possible to use FPDI with TCPDF, there are no fixed dependencies defined. Please see suggestions for packages which evaluates the dependencies automatically.", + "homepage": "https://www.setasign.com/fpdi", + "keywords": [ + + "authors": [ + { + "name": "Jan Slabon", + "email": "jan.slabon@setasign.com", + "homepage": "https://www.setasign.com" + }, + { + "name": "Maximilian Kresse", + "email": "maximilian.kresse@setasign.com", + "homepage": "https://www.setasign.com" + } + ], + "description": "FPDI is a collection of PHP classes facilitating developers to read pages from existing PDF documents and use them as templates in FPDF. Because it is also possible to use FPDI with TCPDF, there are no fixed dependencies defined. Please see suggestions for packages which evaluates the dependencies automatically.", + "homepage": "https://www.setasign.com/fpdi", + "keywords": [ + + "fpdf", + "fpdi", "pdf" ], - "abandoned": "docnet/tFPDF", - "time": "2014-01-19T09:18:44+00:00" + "funding": [ + { + "url": "https://tidelift.com/funding/github/packagist/setasign/fpdi", + "type": "tidelift" + } + ], + "time": "2020-08-27T06:55:47+00:00" }, { "name": "stripe/stripe-php", @@ -615,28 +1418,104 @@ "time": "2015-03-02T05:44:40+00:00" }, { - "name": "symfony/event-dispatcher", - "version": "v2.8.52", + "name": "symfony/deprecation-contracts", + "version": "v2.1.3", "source": { "type": "git", - "url": "https://github.com/symfony/event-dispatcher.git", - "reference": "a77e974a5fecb4398833b0709210e3d5e334ffb0" + "url": "https://github.com/symfony/deprecation-contracts.git", + "reference": "5e20b83385a77593259c9f8beb2c43cd03b2ac14" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/a77e974a5fecb4398833b0709210e3d5e334ffb0", - "reference": "a77e974a5fecb4398833b0709210e3d5e334ffb0", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/5e20b83385a77593259c9f8beb2c43cd03b2ac14", + "reference": "5e20b83385a77593259c9f8beb2c43cd03b2ac14", "shasum": "" }, "require": { - "php": ">=5.3.9" + "php": ">=7.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.1-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "autoload": { + "files": [ + "function.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "A generic function and convention to trigger deprecation notices", + "homepage": "https://symfony.com", + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2020-06-06T08:49:21+00:00" + }, + { + "name": "symfony/event-dispatcher", + "version": "v5.1.5", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher.git", + "reference": "94871fc0a69c3c5da57764187724cdce0755899c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/94871fc0a69c3c5da57764187724cdce0755899c", + "reference": "94871fc0a69c3c5da57764187724cdce0755899c", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "symfony/deprecation-contracts": "^2.1", + "symfony/event-dispatcher-contracts": "^2", + "symfony/polyfill-php80": "^1.15" + }, + "conflict": { + "symfony/dependency-injection": "<4.4" + }, + "provide": { + "psr/event-dispatcher-implementation": "1.0", + "symfony/event-dispatcher-implementation": "2.0" }, "require-dev": { "psr/log": "~1.0", - "symfony/config": "^2.0.5|~3.0.0", - "symfony/dependency-injection": "~2.6|~3.0.0", - "symfony/expression-language": "~2.6|~3.0.0", - "symfony/stopwatch": "~2.3|~3.0.0" + "symfony/config": "^4.4|^5.0", + "symfony/dependency-injection": "^4.4|^5.0", + "symfony/expression-language": "^4.4|^5.0", + "symfony/http-foundation": "^4.4|^5.0", + "symfony/service-contracts": "^1.1|^2", + "symfony/stopwatch": "^4.4|^5.0" }, "suggest": { "symfony/dependency-injection": "", @@ -645,7 +1524,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "2.8-dev" + "dev-master": "5.1-dev" } }, "autoload": { @@ -672,7 +1551,97 @@ ], "description": "Symfony EventDispatcher Component", "homepage": "https://symfony.com", - "time": "2018-11-21T14:20:20+00:00" + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2020-08-13T14:19:42+00:00" + }, + { + "name": "symfony/event-dispatcher-contracts", + "version": "v2.1.3", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher-contracts.git", + "reference": "f6f613d74cfc5a623fc36294d3451eb7fa5a042b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher-contracts/zipball/f6f613d74cfc5a623fc36294d3451eb7fa5a042b", + "reference": "f6f613d74cfc5a623fc36294d3451eb7fa5a042b", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "psr/event-dispatcher": "^1" + }, + "suggest": { + "symfony/event-dispatcher-implementation": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.1-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Contracts\\EventDispatcher\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to dispatching event", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2020-07-06T13:23:11+00:00" }, { "name": "symfony/polyfill-ctype", @@ -827,6 +1796,86 @@ ], "time": "2020-07-14T12:35:20+00:00" }, + { + "name": "symfony/polyfill-php80", + "version": "v1.18.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php80.git", + "reference": "d87d5766cbf48d72388a9f6b85f280c8ad51f981" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/d87d5766cbf48d72388a9f6b85f280c8ad51f981", + "reference": "d87d5766cbf48d72388a9f6b85f280c8ad51f981", + "shasum": "" + }, + "require": { + "php": ">=7.0.8" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.18-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Php80\\": "" + }, + "files": [ + "bootstrap.php" + ], + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2020-07-14T12:35:20+00:00" + }, { "name": "twig/extensions", "version": "v1.5.4", @@ -1041,72 +2090,18 @@ ], "time": "2020-05-29T17:27:14+00:00" }, - { - "name": "myclabs/deep-copy", - "version": "1.10.1", - "source": { - "type": "git", - "url": "https://github.com/myclabs/DeepCopy.git", - "reference": "969b211f9a51aa1f6c01d1d2aef56d3bd91598e5" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/969b211f9a51aa1f6c01d1d2aef56d3bd91598e5", - "reference": "969b211f9a51aa1f6c01d1d2aef56d3bd91598e5", - "shasum": "" - }, - "require": { - "php": "^7.1 || ^8.0" - }, - "replace": { - "myclabs/deep-copy": "self.version" - }, - "require-dev": { - "doctrine/collections": "^1.0", - "doctrine/common": "^2.6", - "phpunit/phpunit": "^7.1" - }, - "type": "library", - "autoload": { - "psr-4": { - "DeepCopy\\": "src/DeepCopy/" - }, - "files": [ - "src/DeepCopy/deep_copy.php" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "description": "Create deep copies (clones) of your objects", - "keywords": [ - "clone", - "copy", - "duplicate", - "object", - "object graph" - ], - "funding": [ - { - "url": "https://tidelift.com/funding/github/packagist/myclabs/deep-copy", - "type": "tidelift" - } - ], - "time": "2020-06-29T13:22:24+00:00" - }, { "name": "nikic/php-parser", - "version": "v4.8.0", + "version": "v4.9.1", "source": { "type": "git", "url": "https://github.com/nikic/PHP-Parser.git", - "reference": "8c58eb4cd4f3883f82611abeac2efbc3dbed787e" + "reference": "88e519766fc58bd46b8265561fb79b54e2e00b28" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/8c58eb4cd4f3883f82611abeac2efbc3dbed787e", - "reference": "8c58eb4cd4f3883f82611abeac2efbc3dbed787e", + "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/88e519766fc58bd46b8265561fb79b54e2e00b28", + "reference": "88e519766fc58bd46b8265561fb79b54e2e00b28", "shasum": "" }, "require": { @@ -1114,7 +2109,7 @@ "php": ">=7.0" }, "require-dev": { - "ircmaxell/php-yacc": "^0.0.6", + "ircmaxell/php-yacc": "^0.0.7", "phpunit/phpunit": "^6.5 || ^7.0 || ^8.0 || ^9.0" }, "bin": [ @@ -1123,7 +2118,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "4.8-dev" + "dev-master": "4.9-dev" } }, "autoload": { @@ -1145,7 +2140,7 @@ "parser", "php" ], - "time": "2020-08-09T10:23:20+00:00" + "time": "2020-08-30T16:15:20+00:00" }, { "name": "phar-io/manifest", @@ -1301,16 +2296,16 @@ }, { "name": "phpdocumentor/reflection-docblock", - "version": "5.2.0", + "version": "5.2.1", "source": { "type": "git", "url": "https://github.com/phpDocumentor/ReflectionDocBlock.git", - "reference": "3170448f5769fe19f456173d833734e0ff1b84df" + "reference": "d870572532cd70bc3fab58f2e23ad423c8404c44" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/3170448f5769fe19f456173d833734e0ff1b84df", - "reference": "3170448f5769fe19f456173d833734e0ff1b84df", + "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/d870572532cd70bc3fab58f2e23ad423c8404c44", + "reference": "d870572532cd70bc3fab58f2e23ad423c8404c44", "shasum": "" }, "require": { @@ -1349,7 +2344,7 @@ } ], "description": "With this component, a library can provide support for annotations via DocBlocks or otherwise retrieve information that is embedded in a DocBlock.", - "time": "2020-07-20T20:05:34+00:00" + "time": "2020-08-15T11:14:08+00:00" }, { "name": "phpdocumentor/type-resolver", @@ -1461,16 +2456,29 @@ }, { "name": "phpunit/php-code-coverage", - "version": "9.1.3", + + "version": "9.1.7", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-code-coverage.git", - "reference": "4abbce3b0ad05f2e7143ea5f775d5513cb5261e4" + "reference": "2ef92bec3186a827faf7362ff92ae4e8ec2e49d2" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/4abbce3b0ad05f2e7143ea5f775d5513cb5261e4", - "reference": "4abbce3b0ad05f2e7143ea5f775d5513cb5261e4", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/2ef92bec3186a827faf7362ff92ae4e8ec2e49d2", + "reference": "2ef92bec3186a827faf7362ff92ae4e8ec2e49d2", + + "version": "9.1.8", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-code-coverage.git", + "reference": "f98f8466126d83b55b924a94d2244c53c216b8fb" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/f98f8466126d83b55b924a94d2244c53c216b8fb", + "reference": "f98f8466126d83b55b924a94d2244c53c216b8fb", + "shasum": "" }, "require": { @@ -1530,7 +2538,10 @@ "type": "github" } ], - "time": "2020-08-10T17:45:51+00:00" + + + "time": "2020-09-07T08:07:10+00:00" + }, { "name": "phpunit/php-file-iterator", @@ -1759,16 +2770,16 @@ }, { "name": "phpunit/phpunit", - "version": "9.3.7", + "version": "9.3.8", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit.git", - "reference": "c638a0cac77347980352485912de48c99b42ad00" + "reference": "93d78d8e2a06393a0d0c1ead6fe9984f1af1f88c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/c638a0cac77347980352485912de48c99b42ad00", - "reference": "c638a0cac77347980352485912de48c99b42ad00", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/93d78d8e2a06393a0d0c1ead6fe9984f1af1f88c", + "reference": "93d78d8e2a06393a0d0c1ead6fe9984f1af1f88c", "shasum": "" }, "require": { @@ -1784,11 +2795,12 @@ "phar-io/version": "^3.0.2", "php": "^7.3 || ^8.0", "phpspec/prophecy": "^1.11.1", - "phpunit/php-code-coverage": "^9.1.1", + "phpunit/php-code-coverage": "^9.1.5", "phpunit/php-file-iterator": "^3.0.4", "phpunit/php-invoker": "^3.1", "phpunit/php-text-template": "^2.0.2", "phpunit/php-timer": "^5.0.1", + "sebastian/cli-parser": "^1.0", "sebastian/code-unit": "^1.0.5", "sebastian/comparator": "^4.0.3", "sebastian/diff": "^4.0.2", @@ -1853,7 +2865,59 @@ "type": "github" } ], - "time": "2020-08-11T15:36:12+00:00" + "time": "2020-08-27T06:30:58+00:00" + }, + { + "name": "sebastian/cli-parser", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/cli-parser.git", + "reference": "2a4a38c56e62f7295bedb8b1b7439ad523d4ea82" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/cli-parser/zipball/2a4a38c56e62f7295bedb8b1b7439ad523d4ea82", + "reference": "2a4a38c56e62f7295bedb8b1b7439ad523d4ea82", + "shasum": "" + }, + "require": { + "php": "^7.3 || ^8.0" + }, + "require-dev": { + "phpunit/phpunit": "^9.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library for parsing CLI options", + "homepage": "https://github.com/sebastianbergmann/cli-parser", + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2020-08-12T10:49:21+00:00" }, { "name": "sebastian/code-unit", @@ -2880,7 +3944,7 @@ "prefer-stable": false, "prefer-lowest": false, "platform": { - "php": ">=7.2.0", + "php": ">=7.4.9", "ext-curl": "*", "ext-zlib": "*", "ext-pdo": "*", diff --git a/src/test/test.cgi b/src/test/test.cgi new file mode 100644 index 000000000..3600e6875 --- /dev/null +++ b/src/test/test.cgi @@ -0,0 +1,32 @@ +#!/usr/bin/perl + +print < + + + + + + + + + +HTML + +my $class; + +foreach (sort keys %ENV) { + next unless /^HTTP_|^REQUEST_/; + $class = ($class ne 'normal')? 'normal': 'alt'; + print < +HTML +} + +print < + + +HTML
    NameValue
    $_$ENV{$_}