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 @@ + + +
+ +1. What's exactly the license of FPDF? Are there any usage restrictions?
+FPDF is released under a permissive license: there is no usage restriction. You may embed it +freely in your application (commercial or not), with or without modifications. +2. I get the following error when I try to generate a PDF: Some data has already been output, can't send PDF file
+You must send nothing to the browser except the PDF itself: no HTML, no space, no carriage return. A common +case is having extra blank at the end of an included script file.ob_end_clean();
+3. Accented letters are replaced with some strange characters like é.
+Don't use UTF-8 with the standard fonts; they expect text encoded in ISO-8859-1 or windows-1252. +You can use utf8_decode() to perform a conversion to ISO-8859-1: +$str = utf8_decode($str);
+$str = iconv('UTF-8', 'windows-1252', $str);
+4. I try to display the Euro symbol but it doesn't work.
+The standard fonts have the Euro character at position 128. You can define a constant like this +for convenience: +define('EURO', chr(128));
+5. I try to display a variable in the Header method but nothing prints.
+You have to use theglobal keyword to access global variables, for example:
+function Header()
+{
+ global $title;
+
+ $this->SetFont('Arial', 'B', 15);
+ $this->Cell(0, 10, $title, 1, 1, 'C');
+}
+
+$title = 'My title';
+function Header()
+{
+ $this->SetFont('Arial', 'B', 15);
+ $this->Cell(0, 10, $this->title, 1, 1, 'C');
+}
+
+$pdf->title = 'My title';
+6. I have defined the Header and Footer methods in my PDF class but nothing shows.
+You have to create an object from the PDF class, not FPDF: +$pdf = new PDF();
+7. I can't make line breaks work. I put \n in the string printed by MultiCell but it doesn't work.
+You have to enclose your string with double quotes, not single ones. +8. I use jQuery to generate the PDF but it doesn't show.
+Don't use an AJAX request to retrieve the PDF. +9. I draw a frame with very precise dimensions, but when printed I notice some differences.
+To respect dimensions, select "None" for the Page Scaling setting instead of "Shrink to Printable Area" in the print dialog box. +10. I'd like to use the whole surface of the page, but when printed I always have some margins. How can I get rid of them?
+Printers have physical margins (different depending on the models); it is therefore impossible to remove +them and print on the whole surface of the paper. +11. How can I put a background in my PDF?
+For a picture, call Image() in the Header() method, before any other output. To set a background color, use Rect(). +12. How can I set a specific header or footer on the first page?
+Just test the page number: +function Header()
+{
+ if($this->PageNo()==1)
+ {
+ //First page
+ ...
+ }
+ else
+ {
+ //Other pages
+ ...
+ }
+}
+13. I'd like to use extensions provided by different scripts. How can I combine them?
+Use an inheritance chain. If you have two classes, say A in a.php: +require('fpdf.php');
+
+class A extends FPDF
+{
+...
+}
+require('fpdf.php');
+
+class B extends FPDF
+{
+...
+}
+require('a.php');
+
+class B extends A
+{
+...
+}
+require('b.php');
+
+class PDF extends B
+{
+...
+}
+
+$pdf = new PDF();
+14. How can I open the PDF in a new tab?
+Just do the same as you would for an HTML page or anything else: add a target="_blank" to your link or form. +15. How can I send the PDF by email?
+As for any other file, but an easy way is to use PHPMailer and +its in-memory attachment: +$mail = new PHPMailer();
+...
+$doc = $pdf->Output('S');
+$mail->AddStringAttachment($doc, 'doc.pdf', 'base64', 'application/pdf');
+$mail->Send();
+16. What's the limit of the file sizes I can generate with FPDF?
+There is no particular limit. There are some constraints, however: +17. Can I modify a PDF with FPDF?
+It's possible to import pages from an existing PDF document thanks to the +FPDI extension. +Then you can add some content to them. +18. I'd like to make a search engine in PHP and index PDF files. Can I do it with FPDF?
+No. But a GPL C utility does exist, pdftotext, which is able to extract the textual content from a PDF. +It's provided with the Xpdf package. +19. Can I convert an HTML page to PDF with FPDF?
+Not real-world pages. But a GPL C utility does exist, HTMLDOC, +which allows to do it and gives good results. +20. Can I concatenate PDF files with FPDF?
+Not directly, but it's possible to use FPDI +to perform that task. Some free command-line tools also exist: +pdftk and +mbtPdfAsm. +__construct([string orientation [, string unit [, mixed size]]])
+orientationP or PortraitL or LandscapeP.
+unitpt: pointmm: millimetercm: centimeterin: inchmm.
+sizeA3A4A5LetterLegalunit).A4.
+$pdf = new FPDF('P','mm',array(100,150));
+boolean AcceptPageBreak()
+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();
+AddFont(string family [, string style [, string file]])
+familystyleB: boldI: italicBI or IB: bold italicfile$pdf->AddFont('Comic','I');
+$pdf->AddFont('Comic','I','comici.php');
+int AddLink()
+AddPage([string orientation [, mixed size [, int rotation]]])
+orientationP or PortraitL or LandscapesizeA3A4A5LetterLegalrotation0.
+AliasNbPages([string alias])
+alias{nb}.
+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();
+Cell(float w [, float h [, string txt [, mixed border [, int ln [, string align [, boolean fill [, mixed link]]]]]]])
+w0, the cell extends up to the right margin.
+h0.
+txtborder0: no border1: frameL: leftT: topR: rightB: bottom0.
+ln0: to the right1: to the beginning of the next line2: below1 is equivalent to putting 0 and calling Ln() just after.
+Default value: 0.
+alignL or empty string: left align (default value)C: centerR: right alignfilltrue) or transparent (false).
+Default value: false.
+link// 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');
+Close()
+Error(string msg)
+msgFooter()
+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');
+}
+}
+float GetPageHeight()
+float GetPageWidth()
+float GetStringWidth(string s)
+sfloat GetX()
+float GetY()
+Header()
+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);
+}
+}
+Image(string file [, float x [, float y [, float w [, float h [, string type [, mixed link]]]]]])
+filexnull, the current abscissa
+is used.
+ynull, 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.
+whtypeJPG, JPEG, PNG and GIF.
+If not specified, the type is inferred from the file extension.
+link// 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');
+Line(float x1, float y1, float x2, float y2)
+x1y1x2y2Link(float x, float y, float w, float h, mixed link)
+xywhlinkLn([float h])
+hMultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])
+w0, they extend up to the right margin of the page.
+htxtborder0: no border1: frameL: leftT: topR: rightB: bottom0.
+alignL: left alignmentC: centerR: right alignmentJ: justification (default value)filltrue) or transparent (false).
+Default value: false.
+string Output([string dest [, string name [, boolean isUTF8]]])
+destI: send the file inline to the browser. The PDF viewer is used if available.D: send to the browser and force a file download with the name given by name.F: save to a local file with the name given by name (may include a path).S: return the document as a string.I.
+nameS.doc.pdf.
+isUTF8name is encoded in ISO-8859-1 (false) or UTF-8 (true).
+Only used for destinations I and D.false.
+int PageNo()
+Rect(float x, float y, float w, float h [, string style])
+xywhstyleD or empty string: draw. This is the default value.F: fillDF or FD: draw and fillSetAuthor(string author [, boolean isUTF8])
+authorisUTF8false) or UTF-8 (true).false.
+SetAutoPageBreak(boolean auto [, float margin])
+automarginSetCompression(boolean compress)
+compressSetCreator(string creator [, boolean isUTF8])
+creatorisUTF8false) or UTF-8 (true).false.
+SetDisplayMode(mixed zoom [, string layout])
+zoomfullpage: displays the entire page on screenfullwidth: uses maximum width of windowreal: uses real size (equivalent to 100% zoom)default: uses viewer default modelayoutsingle: displays one page at oncecontinuous: displays pages continuouslytwo: displays two pages on two columnsdefault: uses viewer default modedefault.
+SetDrawColor(int r [, int g, int b])
+rg et b are given, red component; if not, indicates the gray level.
+Value between 0 and 255.
+gbSetFillColor(int r [, int g, int b])
+rg and b are given, red component; if not, indicates the gray level.
+Value between 0 and 255.
+gbSetFont(string family [, string style [, float size]])
+FPDF_FONTPATH constant (if this constant is defined)font directory located in the same directory as fpdf.php (if it exists)include()FPDF_FONTPATH:
+define('FPDF_FONTPATH','/home/www/font');
+require('fpdf.php');
+familyCourier (fixed-width)Helvetica or Arial (synonymous; sans serif)Times (serif)Symbol (symbolic)ZapfDingbats (symbolic)styleB: boldI: italicU: underlineSymbol and ZapfDingbats.
+size// 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');
+SetFontSize(float size)
+sizeSetKeywords(string keywords [, boolean isUTF8])
+keywordsisUTF8false) or UTF-8 (true).false.
+SetLeftMargin(float margin)
+marginSetLineWidth(float width)
+widthSetLink(int link [, float y [, int page]])
+linky-1 indicates the current position.
+The default value is 0 (top of page).
+page-1 indicates the current page. This is the default value.
+SetMargins(float left, float top [, float right])
+lefttoprightSetRightMargin(float margin)
+marginSetSubject(string subject [, boolean isUTF8])
+subjectisUTF8false) or UTF-8 (true).false.
+SetTextColor(int r [, int g, int b])
+rg et b are given, red component; if not, indicates the gray level.
+Value between 0 and 255.
+gbSetTitle(string title [, boolean isUTF8])
+titleisUTF8false) or UTF-8 (true).false.
+SetTopMargin(float margin)
+marginSetX(float x)
+xSetXY(float x, float y)
+xySetY(float y [, boolean resetX])
+yresetXtrue.
+Text(float x, float y, string txt)
+xytxtWrite(float h, string txt [, mixed link])
+htxtlink// 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');
+<?php
+require('fpdf.php');
+
+$pdf = new FPDF();
+$pdf->AddPage();
+$pdf->SetFont('Arial','B',16);
+$pdf->Cell(40,10,'Hello World!');
+$pdf->Output();
+?>
+$pdf = new FPDF('P','mm','A4');
+
+L), other page sizes (such as Letter and
+Legal) and units (pt, cm, in).
+$pdf->SetFont('Arial','B',16);
+
+$pdf->Cell(40,10,'Hello World !',1);
+
+$pdf->Cell(60,10,'Powered by FPDF.',0,1,'C');
+
+<?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();
+?>
+{nb} which is substituted when the document is finished
+(provided you first called AliasNbPages()).
+<?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();
+?>
+true indicates that the background must
+be filled).
+<?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();
+?>
+<?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();
+?>
+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.
+<?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();
+?>
+MakeFont(string fontfile [, string enc [, boolean embed [, boolean subset]]])
+fontfilePath to the .ttf, .otf or .pfb file.
+encName of the encoding to use. Default value: cp1252.
embedWhether to embed the font or not. Default value: true.
subsetWhether to subset the font or not. Default value: true.
$file in the .php file accordingly.
+<?php
+require('makefont/makefont.php');
+
+MakeFont('C:\\Windows\\Fonts\\comic.ttf','cp1252');
+?>
+$pdf->AddFont('Comic','','comic.php');
+
+$pdf->AddFont('Comic','B','comicbd.php');
+
+<?php
+require('makefont/makefont.php');
+
+MakeFont('calligra.ttf','cp1252');
+?>
+<?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();
+?>
++ * 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
+ Guzzle is a PHP HTTP client
& framework for building RESTful web service clients.
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.
+ +<?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
+
+
+ <?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
+
+
+ * 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 ?: '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(' + \2\s*> # 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.: + *
` 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$tag>";
+ $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$tag>";
+ $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] = ''.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
+ |
+ [-a-zA-Z0-9:_]+\s*> # 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.
+ ? # Any opening or closing 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('{^?(?:' . $enclosing_tag_re . ')\b}', $tag))
+ {
+ // Increase/decrease nested tag count.
+ if ($tag{1} == '/') $depth--;
+ else if ($tag{strlen($tag)-2} != '/') $depth++;
+
+ if ($depth < 0) {
+ // Going out of parent element. Clean up and break so we
+ // return to the calling function.
+ $text = $tag . $text;
+ break;
+ }
+
+ $parsed .= $tag;
+ }
+ else {
+ $parsed .= $tag;
+ }
+ } while ($depth >= 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.
+ ? # Any opening or closing tag.
+ [\w:$]+ # Tag name.
+ (?:
+ (?=[\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
+ )
+ }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('{^?(?:' . $this->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('{^?' . $base_tag_name_re . '\b}', $tag)) {
+ if ($tag{1} == '/') $depth--;
+ else if ($tag{strlen($tag)-2} != '/') $depth++;
+ }
+
+ // Check for `markdown="1"` attribute and handle it.
+ if ($md_attr &&
+ preg_match($markdown_attr_re, $tag, $attr_m) &&
+ preg_match('/^1|block|span$/', $attr_m[2] . $attr_m[3]))
+ {
+ // Remove `markdown` attribute from opening tag.
+ $tag = preg_replace($markdown_attr_re, '', $tag);
+
+ // Check if text inside this tag must be parsed in span mode.
+ $this->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: 
+ // 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 = "
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 = "
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 .= "- \n";
+ $text .= $footnote . "\n";
+ $text .= "
\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 .= '' . $lContent . ' ';
+ $html .= '' . $cContent . ' ';
+ $html .= '' . $rContent . ' ';
+ $html .= '
';
+ 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 .= '' . $hdet[0] . ' ';
+ $oddhtml .= '' . $hdet[1] . ' ';
+ $oddhtml .= '' . $hdet[2] . ' ';
+ $oddhtml .= '
';
+
+ $evenhtml = '';
+ $evenhtml .= '';
+ $evenhtml .= '' . $hdet[2] . ' ';
+ $evenhtml .= '' . $hdet[1] . ' ';
+ $evenhtml .= '' . $hdet[0] . ' ';
+ $evenhtml .= '
';
+
+ } 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 .= '' . $hdet[0] . ' ';
+ $oddhtml .= '' . $hdet[1] . ' ';
+ $oddhtml .= '' . $hdet[2] . ' ';
+ $oddhtml .= '
';
+
+ $evenhtml = '';
+ $evenhtml .= '';
+ $evenhtml .= '' . $hdet[2] . ' ';
+ $evenhtml .= '' . $hdet[1] . ' ';
+ $evenhtml .= '' . $hdet[0] . ' ';
+ $evenhtml .= '
';
+
+ } 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('', '< ', $html); // Fix '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('/]*?(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('//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. and
+ 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); // ??????????????
+ 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 = "