[
  {
    "path": ".gitignore",
    "content": "vendor/\nnbproject/\n.idea/\nexample/merged.pdf\n"
  },
  {
    "path": "LICENSE",
    "content": "Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   \n   Copyright 2016-present Nexit s.r.o.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\n"
  },
  {
    "path": "README.md",
    "content": "# PDF Merge for PHP\n\nPDF Merge library for PHP.\n\nInstall with composer:\n\n`composer require jurosh/pdf-merge`\n\nShould add dependency:\n\n```json\n\"jurosh/pdf-merge\": \"^2.0\"\n```\n\n## Highlights\n\nPdf merging with modes portrait/landscape.\n\nTested in Laravel4 & Laravel5 framework (but still can be used without any framework as standalone utility).\n\n## Usage\n\n```php\n// Autoload composer classses...\n\n// and now we can use library\n$pdf = new \\Jurosh\\PDFMerge\\PDFMerger;\n\n// add as many pdfs as you want\n$pdf->addPDF('path/to/source/file.pdf', 'all', 'vertical')\n  ->addPDF('path/to/source/file1.pdf', 'all')\n  ->addPDF('path/to/source/file2.pdf', 'all', 'horizontal');\n\n// call merge, output format `file`\n$pdf->merge('file', 'path/to/export/dir/file.pdf');\n```\n\nThat's it!\n\nEnjoy and leave star if you like it :)\n"
  },
  {
    "path": "bin/.gitignore",
    "content": "*\n!composer-setup.php\n!setup.md\n!.gitignore"
  },
  {
    "path": "bin/composer-setup.php",
    "content": "<?php\n\n/*\n * This file is part of Composer.\n *\n * (c) Nils Adermann <naderman@naderman.de>\n *     Jordi Boggiano <j.boggiano@seld.be>\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nsetupEnvironment();\nprocess(is_array($argv) ? $argv : array());\n\n/**\n * Initializes various values\n *\n * @throws RuntimeException If uopz extension prevents exit calls\n */\nfunction setupEnvironment()\n{\n    ini_set('display_errors', 1);\n\n    if (extension_loaded('uopz') && !(ini_get('uopz.disable') || ini_get('uopz.exit'))) {\n        // uopz works at opcode level and disables exit calls\n        if (function_exists('uopz_allow_exit')) {\n            @uopz_allow_exit(true);\n        } else {\n            throw new RuntimeException('The uopz extension ignores exit calls and breaks this installer.');\n        }\n    }\n\n    $installer = 'ComposerInstaller';\n\n    if (defined('PHP_WINDOWS_VERSION_MAJOR')) {\n        if ($version = getenv('COMPOSERSETUP')) {\n            $installer = sprintf('Composer-Setup.exe/%s', $version);\n        }\n    }\n\n    define('COMPOSER_INSTALLER', $installer);\n}\n\n/**\n * Processes the installer\n */\nfunction process($argv)\n{\n    // Determine ANSI output from --ansi and --no-ansi flags\n    setUseAnsi($argv);\n\n    if (in_array('--help', $argv)) {\n        displayHelp();\n        exit(0);\n    }\n\n    $check      = in_array('--check', $argv);\n    $help       = in_array('--help', $argv);\n    $force      = in_array('--force', $argv);\n    $quiet      = in_array('--quiet', $argv);\n    $channel    = 'stable';\n    if (in_array('--snapshot', $argv)) {\n        $channel = 'snapshot';\n    } elseif (in_array('--preview', $argv)) {\n        $channel = 'preview';\n    } elseif (in_array('--1', $argv)) {\n        $channel = '1';\n    } elseif (in_array('--2', $argv)) {\n        $channel = '2';\n    }\n    $disableTls = in_array('--disable-tls', $argv);\n    $installDir = getOptValue('--install-dir', $argv, false);\n    $version    = getOptValue('--version', $argv, false);\n    $filename   = getOptValue('--filename', $argv, 'composer.phar');\n    $cafile     = getOptValue('--cafile', $argv, false);\n\n    if (!checkParams($installDir, $version, $cafile)) {\n        exit(1);\n    }\n\n    $ok = checkPlatform($warnings, $quiet, $disableTls, true);\n\n    if ($check) {\n        // Only show warnings if we haven't output any errors\n        if ($ok) {\n            showWarnings($warnings);\n            showSecurityWarning($disableTls);\n        }\n        exit($ok ? 0 : 1);\n    }\n\n    if ($ok || $force) {\n        $installer = new Installer($quiet, $disableTls, $cafile);\n        if ($installer->run($version, $installDir, $filename, $channel)) {\n            showWarnings($warnings);\n            showSecurityWarning($disableTls);\n            exit(0);\n        }\n    }\n\n    exit(1);\n}\n\n/**\n * Displays the help\n */\nfunction displayHelp()\n{\n    echo <<<EOF\nComposer Installer\n------------------\nOptions\n--help               this help\n--check              for checking environment only\n--force              forces the installation\n--ansi               force ANSI color output\n--no-ansi            disable ANSI color output\n--quiet              do not output unimportant messages\n--install-dir=\"...\"  accepts a target installation directory\n--preview            install the latest version from the preview (alpha/beta/rc) channel instead of stable\n--snapshot           install the latest version from the snapshot (dev builds) channel instead of stable\n--1                  install the latest stable Composer 1.x version\n--2                  install the latest stable Composer 2.x version\n--version=\"...\"      accepts a specific version to install instead of the latest\n--filename=\"...\"     accepts a target filename (default: composer.phar)\n--disable-tls        disable SSL/TLS security for file downloads\n--cafile=\"...\"       accepts a path to a Certificate Authority (CA) certificate file for SSL/TLS verification\n\nEOF;\n}\n\n/**\n * Sets the USE_ANSI define for colorizing output\n *\n * @param array $argv Command-line arguments\n */\nfunction setUseAnsi($argv)\n{\n    // --no-ansi wins over --ansi\n    if (in_array('--no-ansi', $argv)) {\n        define('USE_ANSI', false);\n    } elseif (in_array('--ansi', $argv)) {\n        define('USE_ANSI', true);\n    } else {\n        // On Windows, default to no ANSI, except in ANSICON and ConEmu.\n        // Everywhere else, default to ANSI if stdout is a terminal.\n        define(\n            'USE_ANSI',\n            (DIRECTORY_SEPARATOR == '\\\\')\n                ? (false !== getenv('ANSICON') || 'ON' === getenv('ConEmuANSI'))\n                : (function_exists('posix_isatty') && posix_isatty(1))\n        );\n    }\n}\n\n/**\n * Returns the value of a command-line option\n *\n * @param string $opt The command-line option to check\n * @param array $argv Command-line arguments\n * @param mixed $default Default value to be returned\n *\n * @return mixed The command-line value or the default\n */\nfunction getOptValue($opt, $argv, $default)\n{\n    $optLength = strlen($opt);\n\n    foreach ($argv as $key => $value) {\n        $next = $key + 1;\n        if (0 === strpos($value, $opt)) {\n            if ($optLength === strlen($value) && isset($argv[$next])) {\n                return trim($argv[$next]);\n            } else {\n                return trim(substr($value, $optLength + 1));\n            }\n        }\n    }\n\n    return $default;\n}\n\n/**\n * Checks that user-supplied params are valid\n *\n * @param mixed $installDir The required istallation directory\n * @param mixed $version The required composer version to install\n * @param mixed $cafile Certificate Authority file\n *\n * @return bool True if the supplied params are okay\n */\nfunction checkParams($installDir, $version, $cafile)\n{\n    $result = true;\n\n    if (false !== $installDir && !is_dir($installDir)) {\n        out(\"The defined install dir ({$installDir}) does not exist.\", 'info');\n        $result = false;\n    }\n\n    if (false !== $version && 1 !== preg_match('/^\\d+\\.\\d+\\.\\d+(\\-(alpha|beta|RC)\\d*)*$/', $version)) {\n        out(\"The defined install version ({$version}) does not match release pattern.\", 'info');\n        $result = false;\n    }\n\n    if (false !== $cafile && (!file_exists($cafile) || !is_readable($cafile))) {\n        out(\"The defined Certificate Authority (CA) cert file ({$cafile}) does not exist or is not readable.\", 'info');\n        $result = false;\n    }\n    return $result;\n}\n\n/**\n * Checks the platform for possible issues running Composer\n *\n * Errors are written to the output, warnings are saved for later display.\n *\n * @param array $warnings Populated by method, to be shown later\n * @param bool $quiet Quiet mode\n * @param bool $disableTls Bypass tls\n * @param bool $install If we are installing, rather than diagnosing\n *\n * @return bool True if there are no errors\n */\nfunction checkPlatform(&$warnings, $quiet, $disableTls, $install)\n{\n    getPlatformIssues($errors, $warnings, $install);\n\n    // Make openssl warning an error if tls has not been specifically disabled\n    if (isset($warnings['openssl']) && !$disableTls) {\n        $errors['openssl'] = $warnings['openssl'];\n        unset($warnings['openssl']);\n    }\n\n    if (!empty($errors)) {\n        // Composer-Setup.exe uses \"Some settings\" to flag platform errors\n        out('Some settings on your machine make Composer unable to work properly.', 'error');\n        out('Make sure that you fix the issues listed below and run this script again:', 'error');\n        outputIssues($errors);\n        return false;\n    }\n\n    if (empty($warnings) && !$quiet) {\n        out('All settings correct for using Composer', 'success');\n    }\n    return true;\n}\n\n/**\n * Checks platform configuration for common incompatibility issues\n *\n * @param array $errors Populated by method\n * @param array $warnings Populated by method\n * @param bool $install If we are installing, rather than diagnosing\n *\n * @return bool If any errors or warnings have been found\n */\nfunction getPlatformIssues(&$errors, &$warnings, $install)\n{\n    $errors = array();\n    $warnings = array();\n\n    if ($iniPath = php_ini_loaded_file()) {\n        $iniMessage = PHP_EOL.'The php.ini used by your command-line PHP is: ' . $iniPath;\n    } else {\n        $iniMessage = PHP_EOL.'A php.ini file does not exist. You will have to create one.';\n    }\n    $iniMessage .= PHP_EOL.'If you can not modify the ini file, you can also run `php -d option=value` to modify ini values on the fly. You can use -d multiple times.';\n\n    if (ini_get('detect_unicode')) {\n        $errors['unicode'] = array(\n            'The detect_unicode setting must be disabled.',\n            'Add the following to the end of your `php.ini`:',\n            '    detect_unicode = Off',\n            $iniMessage\n        );\n    }\n\n    if (extension_loaded('suhosin')) {\n        $suhosin = ini_get('suhosin.executor.include.whitelist');\n        $suhosinBlacklist = ini_get('suhosin.executor.include.blacklist');\n        if (false === stripos($suhosin, 'phar') && (!$suhosinBlacklist || false !== stripos($suhosinBlacklist, 'phar'))) {\n            $errors['suhosin'] = array(\n                'The suhosin.executor.include.whitelist setting is incorrect.',\n                'Add the following to the end of your `php.ini` or suhosin.ini (Example path [for Debian]: /etc/php5/cli/conf.d/suhosin.ini):',\n                '    suhosin.executor.include.whitelist = phar '.$suhosin,\n                $iniMessage\n            );\n        }\n    }\n\n    if (!function_exists('json_decode')) {\n        $errors['json'] = array(\n            'The json extension is missing.',\n            'Install it or recompile php without --disable-json'\n        );\n    }\n\n    if (!extension_loaded('Phar')) {\n        $errors['phar'] = array(\n            'The phar extension is missing.',\n            'Install it or recompile php without --disable-phar'\n        );\n    }\n\n    if (!extension_loaded('filter')) {\n        $errors['filter'] = array(\n            'The filter extension is missing.',\n            'Install it or recompile php without --disable-filter'\n        );\n    }\n\n    if (!extension_loaded('hash')) {\n        $errors['hash'] = array(\n            'The hash extension is missing.',\n            'Install it or recompile php without --disable-hash'\n        );\n    }\n\n    if (!extension_loaded('iconv') && !extension_loaded('mbstring')) {\n        $errors['iconv_mbstring'] = array(\n            'The iconv OR mbstring extension is required and both are missing.',\n            'Install either of them or recompile php without --disable-iconv'\n        );\n    }\n\n    if (!ini_get('allow_url_fopen')) {\n        $errors['allow_url_fopen'] = array(\n            'The allow_url_fopen setting is incorrect.',\n            'Add the following to the end of your `php.ini`:',\n            '    allow_url_fopen = On',\n            $iniMessage\n        );\n    }\n\n    if (extension_loaded('ionCube Loader') && ioncube_loader_iversion() < 40009) {\n        $ioncube = ioncube_loader_version();\n        $errors['ioncube'] = array(\n            'Your ionCube Loader extension ('.$ioncube.') is incompatible with Phar files.',\n            'Upgrade to ionCube 4.0.9 or higher or remove this line (path may be different) from your `php.ini` to disable it:',\n            '    zend_extension = /usr/lib/php5/20090626+lfs/ioncube_loader_lin_5.3.so',\n            $iniMessage\n        );\n    }\n\n    if (version_compare(PHP_VERSION, '5.3.2', '<')) {\n        $errors['php'] = array(\n            'Your PHP ('.PHP_VERSION.') is too old, you must upgrade to PHP 5.3.2 or higher.'\n        );\n    }\n\n    if (version_compare(PHP_VERSION, '5.3.4', '<')) {\n        $warnings['php'] = array(\n            'Your PHP ('.PHP_VERSION.') is quite old, upgrading to PHP 5.3.4 or higher is recommended.',\n            'Composer works with 5.3.2+ for most people, but there might be edge case issues.'\n        );\n    }\n\n    if (!extension_loaded('openssl')) {\n        $warnings['openssl'] = array(\n            'The openssl extension is missing, which means that secure HTTPS transfers are impossible.',\n            'If possible you should enable it or recompile php with --with-openssl'\n        );\n    }\n\n    if (extension_loaded('openssl') && OPENSSL_VERSION_NUMBER < 0x1000100f) {\n        // Attempt to parse version number out, fallback to whole string value.\n        $opensslVersion = trim(strstr(OPENSSL_VERSION_TEXT, ' '));\n        $opensslVersion = substr($opensslVersion, 0, strpos($opensslVersion, ' '));\n        $opensslVersion = $opensslVersion ? $opensslVersion : OPENSSL_VERSION_TEXT;\n\n        $warnings['openssl_version'] = array(\n            'The OpenSSL library ('.$opensslVersion.') used by PHP does not support TLSv1.2 or TLSv1.1.',\n            'If possible you should upgrade OpenSSL to version 1.0.1 or above.'\n        );\n    }\n\n    if (!defined('HHVM_VERSION') && !extension_loaded('apcu') && ini_get('apc.enable_cli')) {\n        $warnings['apc_cli'] = array(\n            'The apc.enable_cli setting is incorrect.',\n            'Add the following to the end of your `php.ini`:',\n            '    apc.enable_cli = Off',\n            $iniMessage\n        );\n    }\n\n    if (!$install && extension_loaded('xdebug')) {\n        $warnings['xdebug_loaded'] = array(\n            'The xdebug extension is loaded, this can slow down Composer a little.',\n            'Disabling it when using Composer is recommended.'\n        );\n\n        if (ini_get('xdebug.profiler_enabled')) {\n            $warnings['xdebug_profile'] = array(\n                'The xdebug.profiler_enabled setting is enabled, this can slow down Composer a lot.',\n                'Add the following to the end of your `php.ini` to disable it:',\n                '    xdebug.profiler_enabled = 0',\n                $iniMessage\n            );\n        }\n    }\n\n    if (!extension_loaded('zlib')) {\n        $warnings['zlib'] = array(\n            'The zlib extension is not loaded, this can slow down Composer a lot.',\n            'If possible, install it or recompile php with --with-zlib',\n            $iniMessage\n        );\n    }\n\n    if (defined('PHP_WINDOWS_VERSION_BUILD')\n        && (version_compare(PHP_VERSION, '7.2.23', '<')\n        || (version_compare(PHP_VERSION, '7.3.0', '>=')\n        && version_compare(PHP_VERSION, '7.3.10', '<')))) {\n        $warnings['onedrive'] = array(\n            'The Windows OneDrive folder is not supported on PHP versions below 7.2.23 and 7.3.10.',\n            'Upgrade your PHP ('.PHP_VERSION.') to use this location with Composer.'\n        );\n    }\n\n    if (extension_loaded('uopz') && !(ini_get('uopz.disable') || ini_get('uopz.exit'))) {\n        $warnings['uopz'] = array(\n            'The uopz extension ignores exit calls and may not work with all Composer commands.',\n            'Disabling it when using Composer is recommended.'\n        );\n    }\n\n    ob_start();\n    phpinfo(INFO_GENERAL);\n    $phpinfo = ob_get_clean();\n    if (preg_match('{Configure Command(?: *</td><td class=\"v\">| *=> *)(.*?)(?:</td>|$)}m', $phpinfo, $match)) {\n        $configure = $match[1];\n\n        if (false !== strpos($configure, '--enable-sigchild')) {\n            $warnings['sigchild'] = array(\n                'PHP was compiled with --enable-sigchild which can cause issues on some platforms.',\n                'Recompile it without this flag if possible, see also:',\n                '    https://bugs.php.net/bug.php?id=22999'\n            );\n        }\n\n        if (false !== strpos($configure, '--with-curlwrappers')) {\n            $warnings['curlwrappers'] = array(\n                'PHP was compiled with --with-curlwrappers which will cause issues with HTTP authentication and GitHub.',\n                'Recompile it without this flag if possible'\n            );\n        }\n    }\n\n    // Stringify the message arrays\n    foreach ($errors as $key => $value) {\n        $errors[$key] = PHP_EOL.implode(PHP_EOL, $value);\n    }\n\n    foreach ($warnings as $key => $value) {\n        $warnings[$key] = PHP_EOL.implode(PHP_EOL, $value);\n    }\n\n    return !empty($errors) || !empty($warnings);\n}\n\n\n/**\n * Outputs an array of issues\n *\n * @param array $issues\n */\nfunction outputIssues($issues)\n{\n    foreach ($issues as $issue) {\n        out($issue, 'info');\n    }\n    out('');\n}\n\n/**\n * Outputs any warnings found\n *\n * @param array $warnings\n */\nfunction showWarnings($warnings)\n{\n    if (!empty($warnings)) {\n        out('Some settings on your machine may cause stability issues with Composer.', 'error');\n        out('If you encounter issues, try to change the following:', 'error');\n        outputIssues($warnings);\n    }\n}\n\n/**\n * Outputs an end of process warning if tls has been bypassed\n *\n * @param bool $disableTls Bypass tls\n */\nfunction showSecurityWarning($disableTls)\n{\n    if ($disableTls) {\n        out('You have instructed the Installer not to enforce SSL/TLS security on remote HTTPS requests.', 'info');\n        out('This will leave all downloads during installation vulnerable to Man-In-The-Middle (MITM) attacks', 'info');\n    }\n}\n\n/**\n * colorize output\n */\nfunction out($text, $color = null, $newLine = true)\n{\n    $styles = array(\n        'success' => \"\\033[0;32m%s\\033[0m\",\n        'error' => \"\\033[31;31m%s\\033[0m\",\n        'info' => \"\\033[33;33m%s\\033[0m\"\n    );\n\n    $format = '%s';\n\n    if (isset($styles[$color]) && USE_ANSI) {\n        $format = $styles[$color];\n    }\n\n    if ($newLine) {\n        $format .= PHP_EOL;\n    }\n\n    printf($format, $text);\n}\n\n/**\n * Returns the system-dependent Composer home location, which may not exist\n *\n * @return string\n */\nfunction getHomeDir()\n{\n    $home = getenv('COMPOSER_HOME');\n    if ($home) {\n        return $home;\n    }\n\n    $userDir = getUserDir();\n\n    if (defined('PHP_WINDOWS_VERSION_MAJOR')) {\n        return $userDir.'/Composer';\n    }\n\n    $dirs = array();\n\n    if (useXdg()) {\n        // XDG Base Directory Specifications\n        $xdgConfig = getenv('XDG_CONFIG_HOME');\n        if (!$xdgConfig) {\n            $xdgConfig = $userDir . '/.config';\n        }\n\n        $dirs[] = $xdgConfig . '/composer';\n    }\n\n    $dirs[] = $userDir . '/.composer';\n\n    // select first dir which exists of: $XDG_CONFIG_HOME/composer or ~/.composer\n    foreach ($dirs as $dir) {\n        if (is_dir($dir)) {\n            return $dir;\n        }\n    }\n\n    // if none exists, we default to first defined one (XDG one if system uses it, or ~/.composer otherwise)\n    return $dirs[0];\n}\n\n/**\n * Returns the location of the user directory from the environment\n * @throws RuntimeException If the environment value does not exists\n *\n * @return string\n */\nfunction getUserDir()\n{\n    $userEnv = defined('PHP_WINDOWS_VERSION_MAJOR') ? 'APPDATA' : 'HOME';\n    $userDir = getenv($userEnv);\n\n    if (!$userDir) {\n        throw new RuntimeException('The '.$userEnv.' or COMPOSER_HOME environment variable must be set for composer to run correctly');\n    }\n\n    return rtrim(strtr($userDir, '\\\\', '/'), '/');\n}\n\n/**\n * @return bool\n */\nfunction useXdg()\n{\n    foreach (array_keys($_SERVER) as $key) {\n        if (strpos($key, 'XDG_') === 0) {\n            return true;\n        }\n    }\n\n    if (is_dir('/etc/xdg')) {\n        return true;\n    }\n\n    return false;\n}\n\nfunction validateCaFile($contents)\n{\n    // assume the CA is valid if php is vulnerable to\n    // https://www.sektioneins.de/advisories/advisory-012013-php-openssl_x509_parse-memory-corruption-vulnerability.html\n    if (\n        PHP_VERSION_ID <= 50327\n        || (PHP_VERSION_ID >= 50400 && PHP_VERSION_ID < 50422)\n        || (PHP_VERSION_ID >= 50500 && PHP_VERSION_ID < 50506)\n    ) {\n        return !empty($contents);\n    }\n\n    return (bool) openssl_x509_parse($contents);\n}\n\nclass Installer\n{\n    private $quiet;\n    private $disableTls;\n    private $cafile;\n    private $displayPath;\n    private $target;\n    private $tmpFile;\n    private $tmpCafile;\n    private $baseUrl;\n    private $algo;\n    private $errHandler;\n    private $httpClient;\n    private $pubKeys = array();\n    private $installs = array();\n\n    /**\n     * Constructor - must not do anything that throws an exception\n     *\n     * @param bool $quiet Quiet mode\n     * @param bool $disableTls Bypass tls\n     * @param mixed $cafile Path to CA bundle, or false\n     */\n    public function __construct($quiet, $disableTls, $caFile)\n    {\n        if (($this->quiet = $quiet)) {\n            ob_start();\n        }\n        $this->disableTls = $disableTls;\n        $this->cafile = $caFile;\n        $this->errHandler = new ErrorHandler();\n    }\n\n    /**\n     * Runs the installer\n     *\n     * @param mixed $version Specific version to install, or false\n     * @param mixed $installDir Specific installation directory, or false\n     * @param string $filename Specific filename to save to, or composer.phar\n     * @param string $channel Specific version channel to use\n     * @throws Exception If anything other than a RuntimeException is caught\n     *\n     * @return bool If the installation succeeded\n     */\n    public function run($version, $installDir, $filename, $channel)\n    {\n        try {\n            $this->initTargets($installDir, $filename);\n            $this->initTls();\n            $this->httpClient = new HttpClient($this->disableTls, $this->cafile);\n            $result = $this->install($version, $channel);\n\n            // in case --1 or --2 is passed, we leave the default channel for next self-update to stable\n            if (is_numeric($channel)) {\n                $channel = 'stable';\n            }\n\n            if ($result && $channel !== 'stable' && !$version && defined('PHP_BINARY')) {\n                $null = (defined('PHP_WINDOWS_VERSION_MAJOR') ? 'NUL' : '/dev/null');\n                @exec(escapeshellarg(PHP_BINARY) .' '.escapeshellarg($this->target).' self-update --'.$channel.' --set-channel-only -q > '.$null.' 2> '.$null, $output);\n            }\n        } catch (Exception $e) {\n            $result = false;\n        }\n\n        // Always clean up\n        $this->cleanUp($result);\n\n        if (isset($e)) {\n            // Rethrow anything that is not a RuntimeException\n            if (!$e instanceof RuntimeException) {\n                throw $e;\n            }\n            out($e->getMessage(), 'error');\n        }\n        return $result;\n    }\n\n    /**\n     * Initialization methods to set the required filenames and composer url\n     *\n     * @param mixed $installDir Specific installation directory, or false\n     * @param string $filename Specific filename to save to, or composer.phar\n     * @throws RuntimeException If the installation directory is not writable\n     */\n    protected function initTargets($installDir, $filename)\n    {\n        $this->displayPath = ($installDir ? rtrim($installDir, '/').'/' : '').$filename;\n        $installDir = $installDir ? realpath($installDir) : getcwd();\n\n        if (!is_writeable($installDir)) {\n            throw new RuntimeException('The installation directory \"'.$installDir.'\" is not writable');\n        }\n\n        $this->target = $installDir.DIRECTORY_SEPARATOR.$filename;\n        $this->tmpFile = $installDir.DIRECTORY_SEPARATOR.basename($this->target, '.phar').'-temp.phar';\n\n        $uriScheme = $this->disableTls ? 'http' : 'https';\n        $this->baseUrl = $uriScheme.'://getcomposer.org';\n    }\n\n    /**\n     * A wrapper around methods to check tls and write public keys\n     * @throws RuntimeException If SHA384 is not supported\n     */\n    protected function initTls()\n    {\n        if ($this->disableTls) {\n            return;\n        }\n\n        if (!in_array('sha384', array_map('strtolower', openssl_get_md_methods()))) {\n            throw new RuntimeException('SHA384 is not supported by your openssl extension');\n        }\n\n        $this->algo = defined('OPENSSL_ALGO_SHA384') ? OPENSSL_ALGO_SHA384 : 'SHA384';\n        $home = $this->getComposerHome();\n\n        $this->pubKeys = array(\n            'dev' => $this->installKey(self::getPKDev(), $home, 'keys.dev.pub'),\n            'tags' => $this->installKey(self::getPKTags(), $home, 'keys.tags.pub')\n        );\n\n        if (empty($this->cafile) && !HttpClient::getSystemCaRootBundlePath()) {\n            $this->cafile = $this->tmpCafile = $this->installKey(HttpClient::getPackagedCaFile(), $home, 'cacert-temp.pem');\n        }\n    }\n\n    /**\n     * Returns the Composer home directory, creating it if required\n     * @throws RuntimeException If the directory cannot be created\n     *\n     * @return string\n     */\n    protected function getComposerHome()\n    {\n        $home = getHomeDir();\n\n        if (!is_dir($home)) {\n            $this->errHandler->start();\n\n            if (!mkdir($home, 0777, true)) {\n                throw new RuntimeException(sprintf(\n                    'Unable to create Composer home directory \"%s\": %s',\n                    $home,\n                    $this->errHandler->message\n                ));\n            }\n            $this->installs[] = $home;\n            $this->errHandler->stop();\n        }\n        return $home;\n    }\n\n    /**\n     * Writes public key data to disc\n     *\n     * @param string $data The public key(s) in pem format\n     * @param string $path The directory to write to\n     * @param string $filename The name of the file\n     * @throws RuntimeException If the file cannot be written\n     *\n     * @return string The path to the saved data\n     */\n    protected function installKey($data, $path, $filename)\n    {\n        $this->errHandler->start();\n\n        $target = $path.DIRECTORY_SEPARATOR.$filename;\n        $installed = file_exists($target);\n        $write = file_put_contents($target, $data, LOCK_EX);\n        @chmod($target, 0644);\n\n        $this->errHandler->stop();\n\n        if (!$write) {\n            throw new RuntimeException(sprintf('Unable to write %s to: %s', $filename, $path));\n        }\n\n        if (!$installed) {\n            $this->installs[] = $target;\n        }\n\n        return $target;\n    }\n\n    /**\n     * The main install function\n     *\n     * @param mixed $version Specific version to install, or false\n     * @param string $channel Version channel to use\n     *\n     * @return bool If the installation succeeded\n     */\n    protected function install($version, $channel)\n    {\n        $retries = 3;\n        $result = false;\n        $infoMsg = 'Downloading...';\n        $infoType = 'info';\n\n        while ($retries--) {\n            if (!$this->quiet) {\n                out($infoMsg, $infoType);\n                $infoMsg = 'Retrying...';\n                $infoType = 'error';\n            }\n\n            if (!$this->getVersion($channel, $version, $url, $error)) {\n                out($error, 'error');\n                continue;\n            }\n\n            if (!$this->downloadToTmp($url, $signature, $error)) {\n                out($error, 'error');\n                continue;\n            }\n\n            if (!$this->verifyAndSave($version, $signature, $error)) {\n                out($error, 'error');\n                continue;\n            }\n\n            $result = true;\n            break;\n        }\n\n        if (!$this->quiet) {\n            if ($result) {\n                out(PHP_EOL.\"Composer (version {$version}) successfully installed to: {$this->target}\", 'success');\n                out(\"Use it: php {$this->displayPath}\", 'info');\n                out('');\n            } else {\n                out('The download failed repeatedly, aborting.', 'error');\n            }\n        }\n        return $result;\n    }\n\n    /**\n     * Sets the version url, downloading version data if required\n     *\n     * @param string $channel Version channel to use\n     * @param false|string $version Version to install, or set by method\n     * @param null|string $url The versioned url, set by method\n     * @param null|string $error Set by method on failure\n     *\n     * @return bool If the operation succeeded\n     */\n    protected function getVersion($channel, &$version, &$url, &$error)\n    {\n        $error = '';\n\n        if ($version) {\n            if (empty($url)) {\n                $url = $this->baseUrl.\"/download/{$version}/composer.phar\";\n            }\n            return true;\n        }\n\n        $this->errHandler->start();\n\n        if ($this->downloadVersionData($data, $error)) {\n            $this->parseVersionData($data, $channel, $version, $url);\n        }\n\n        $this->errHandler->stop();\n        return empty($error);\n    }\n\n    /**\n     * Downloads and json-decodes version data\n     *\n     * @param null|array $data Downloaded version data, set by method\n     * @param null|string $error Set by method on failure\n     *\n     * @return bool If the operation succeeded\n     */\n    protected function downloadVersionData(&$data, &$error)\n    {\n        $url = $this->baseUrl.'/versions';\n        $errFmt = 'The \"%s\" file could not be %s: %s';\n\n        if (!$json = $this->httpClient->get($url)) {\n            $error = sprintf($errFmt, $url, 'downloaded', $this->errHandler->message);\n            return false;\n        }\n\n        if (!$data = json_decode($json, true)) {\n            $error = sprintf($errFmt, $url, 'json-decoded', $this->getJsonError());\n            return false;\n        }\n        return true;\n    }\n\n    /**\n     * A wrapper around the methods needed to download and save the phar\n     *\n     * @param string $url The versioned download url\n     * @param null|string $signature Set by method on successful download\n     * @param null|string $error Set by method on failure\n     *\n     * @return bool If the operation succeeded\n     */\n    protected function downloadToTmp($url, &$signature, &$error)\n    {\n        $error = '';\n        $errFmt = 'The \"%s\" file could not be downloaded: %s';\n        $sigUrl = $url.'.sig';\n        $this->errHandler->start();\n\n        if (!$fh = fopen($this->tmpFile, 'w')) {\n            $error = sprintf('Could not create file \"%s\": %s', $this->tmpFile, $this->errHandler->message);\n\n        } elseif (!$this->getSignature($sigUrl, $signature)) {\n            $error = sprintf($errFmt, $sigUrl, $this->errHandler->message);\n\n        } elseif (!fwrite($fh, $this->httpClient->get($url))) {\n            $error = sprintf($errFmt, $url, $this->errHandler->message);\n        }\n\n        if (is_resource($fh)) {\n            fclose($fh);\n        }\n        $this->errHandler->stop();\n        return empty($error);\n    }\n\n    /**\n     * Verifies the downloaded file and saves it to the target location\n     *\n     * @param string $version The composer version downloaded\n     * @param string $signature The digital signature to check\n     * @param null|string $error Set by method on failure\n     *\n     * @return bool If the operation succeeded\n     */\n    protected function verifyAndSave($version, $signature, &$error)\n    {\n        $error = '';\n\n        if (!$this->validatePhar($this->tmpFile, $pharError)) {\n            $error = 'The download is corrupt: '.$pharError;\n\n        } elseif (!$this->verifySignature($version, $signature, $this->tmpFile)) {\n            $error = 'Signature mismatch, could not verify the phar file integrity';\n\n        } else {\n            $this->errHandler->start();\n\n            if (!rename($this->tmpFile, $this->target)) {\n                $error = sprintf('Could not write to file \"%s\": %s', $this->target, $this->errHandler->message);\n            }\n            chmod($this->target, 0755);\n            $this->errHandler->stop();\n        }\n\n        return empty($error);\n    }\n\n    /**\n     * Parses an array of version data to match the required channel\n     *\n     * @param array $data Downloaded version data\n     * @param mixed $channel Version channel to use\n     * @param false|string $version Set by method\n     * @param mixed $url The versioned url, set by method\n     */\n    protected function parseVersionData(array $data, $channel, &$version, &$url)\n    {\n        foreach ($data[$channel] as $candidate) {\n            if ($candidate['min-php'] <= PHP_VERSION_ID) {\n                $version = $candidate['version'];\n                $url = $this->baseUrl.$candidate['path'];\n                break;\n            }\n        }\n\n        if (!$version) {\n            $error = sprintf(\n                'None of the %d %s version(s) of Composer matches your PHP version (%s / ID: %d)',\n                count($data[$channel]),\n                $channel,\n                PHP_VERSION,\n                PHP_VERSION_ID\n            );\n            throw new RuntimeException($error);\n        }\n    }\n\n    /**\n     * Downloads the digital signature of required phar file\n     *\n     * @param string $url The signature url\n     * @param null|string $signature Set by method on success\n     *\n     * @return bool If the download succeeded\n     */\n    protected function getSignature($url, &$signature)\n    {\n        if (!$result = $this->disableTls) {\n            $signature = $this->httpClient->get($url);\n\n            if ($signature) {\n                $signature = json_decode($signature, true);\n                $signature = base64_decode($signature['sha384']);\n                $result = true;\n            }\n        }\n\n        return $result;\n    }\n\n    /**\n     * Verifies the signature of the downloaded phar\n     *\n     * @param string $version The composer versione\n     * @param string $signature The downloaded digital signature\n     * @param string $file The temp phar file\n     *\n     * @return bool If the operation succeeded\n     */\n    protected function verifySignature($version, $signature, $file)\n    {\n        if (!$result = $this->disableTls) {\n            $path = preg_match('{^[0-9a-f]{40}$}', $version) ? $this->pubKeys['dev'] : $this->pubKeys['tags'];\n            $pubkeyid = openssl_pkey_get_public('file://'.$path);\n\n            $result = 1 === openssl_verify(\n                file_get_contents($file),\n                $signature,\n                $pubkeyid,\n                $this->algo\n            );\n\n            // PHP 8 automatically frees the key instance and deprecates the function\n            if (PHP_VERSION_ID < 80000) {\n                openssl_free_key($pubkeyid);\n            }\n        }\n\n        return $result;\n    }\n\n    /**\n     * Validates the downloaded phar file\n     *\n     * @param string $pharFile The temp phar file\n     * @param null|string $error Set by method on failure\n     *\n     * @return bool If the operation succeeded\n     */\n    protected function validatePhar($pharFile, &$error)\n    {\n        if (ini_get('phar.readonly')) {\n            return true;\n        }\n\n        try {\n            // Test the phar validity\n            $phar = new Phar($pharFile);\n            // Free the variable to unlock the file\n            unset($phar);\n            $result = true;\n\n        } catch (Exception $e) {\n            if (!$e instanceof UnexpectedValueException && !$e instanceof PharException) {\n                throw $e;\n            }\n            $error = $e->getMessage();\n            $result = false;\n        }\n        return $result;\n    }\n\n    /**\n     * Returns a string representation of the last json error\n     *\n     * @return string The error string or code\n     */\n    protected function getJsonError()\n    {\n        if (function_exists('json_last_error_msg')) {\n            return json_last_error_msg();\n        } else {\n            return 'json_last_error = '.json_last_error();\n        }\n    }\n\n    /**\n     * Cleans up resources at the end of the installation\n     *\n     * @param bool $result If the installation succeeded\n     */\n    protected function cleanUp($result)\n    {\n        if (!$result) {\n            // Output buffered errors\n            if ($this->quiet) {\n                $this->outputErrors();\n            }\n            // Clean up stuff we created\n            $this->uninstall();\n        } elseif ($this->tmpCafile) {\n            @unlink($this->tmpCafile);\n        }\n    }\n\n    /**\n     * Outputs unique errors when in quiet mode\n     *\n     */\n    protected function outputErrors()\n    {\n        $errors = explode(PHP_EOL, ob_get_clean());\n        $shown = array();\n\n        foreach ($errors as $error) {\n            if ($error && !in_array($error, $shown)) {\n                out($error, 'error');\n                $shown[] = $error;\n            }\n        }\n    }\n\n    /**\n     * Uninstalls newly-created files and directories on failure\n     *\n     */\n    protected function uninstall()\n    {\n        foreach (array_reverse($this->installs) as $target) {\n            if (is_file($target)) {\n                @unlink($target);\n            } elseif (is_dir($target)) {\n                @rmdir($target);\n            }\n        }\n\n        if (file_exists($this->tmpFile)) {\n            @unlink($this->tmpFile);\n        }\n    }\n\n    public static function getPKDev()\n    {\n        return <<<PKDEV\n-----BEGIN PUBLIC KEY-----\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAnBDHjZS6e0ZMoK3xTD7f\nFNCzlXjX/Aie2dit8QXA03pSrOTbaMnxON3hUL47Lz3g1SC6YJEMVHr0zYq4elWi\ni3ecFEgzLcj+pZM5X6qWu2Ozz4vWx3JYo1/a/HYdOuW9e3lwS8VtS0AVJA+U8X0A\nhZnBmGpltHhO8hPKHgkJtkTUxCheTcbqn4wGHl8Z2SediDcPTLwqezWKUfrYzu1f\no/j3WFwFs6GtK4wdYtiXr+yspBZHO3y1udf8eFFGcb2V3EaLOrtfur6XQVizjOuk\n8lw5zzse1Qp/klHqbDRsjSzJ6iL6F4aynBc6Euqt/8ccNAIz0rLjLhOraeyj4eNn\n8iokwMKiXpcrQLTKH+RH1JCuOVxQ436bJwbSsp1VwiqftPQieN+tzqy+EiHJJmGf\nTBAbWcncicCk9q2md+AmhNbvHO4PWbbz9TzC7HJb460jyWeuMEvw3gNIpEo2jYa9\npMV6cVqnSa+wOc0D7pC9a6bne0bvLcm3S+w6I5iDB3lZsb3A9UtRiSP7aGSo7D72\n8tC8+cIgZcI7k9vjvOqH+d7sdOU2yPCnRY6wFh62/g8bDnUpr56nZN1G89GwM4d4\nr/TU7BQQIzsZgAiqOGXvVklIgAMiV0iucgf3rNBLjjeNEwNSTTG9F0CtQ+7JLwaE\nwSEuAuRm+pRqi8BRnQ/GKUcCAwEAAQ==\n-----END PUBLIC KEY-----\nPKDEV;\n    }\n\n    public static function getPKTags()\n    {\n        return <<<PKTAGS\n-----BEGIN PUBLIC KEY-----\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA0Vi/2K6apCVj76nCnCl2\nMQUPdK+A9eqkYBacXo2wQBYmyVlXm2/n/ZsX6pCLYPQTHyr5jXbkQzBw8SKqPdlh\nvA7NpbMeNCz7wP/AobvUXM8xQuXKbMDTY2uZ4O7sM+PfGbptKPBGLe8Z8d2sUnTO\nbXtX6Lrj13wkRto7st/w/Yp33RHe9SlqkiiS4MsH1jBkcIkEHsRaveZzedUaxY0M\nmba0uPhGUInpPzEHwrYqBBEtWvP97t2vtfx8I5qv28kh0Y6t+jnjL1Urid2iuQZf\nnoCMFIOu4vksK5HxJxxrN0GOmGmwVQjOOtxkwikNiotZGPR4KsVj8NnBrLX7oGuM\nnQvGciiu+KoC2r3HDBrpDeBVdOWxDzT5R4iI0KoLzFh2pKqwbY+obNPS2bj+2dgJ\nrV3V5Jjry42QOCBN3c88wU1PKftOLj2ECpewY6vnE478IipiEu7EAdK8Zwj2LmTr\nRKQUSa9k7ggBkYZWAeO/2Ag0ey3g2bg7eqk+sHEq5ynIXd5lhv6tC5PBdHlWipDK\ntl2IxiEnejnOmAzGVivE1YGduYBjN+mjxDVy8KGBrjnz1JPgAvgdwJ2dYw4Rsc/e\nTzCFWGk/HM6a4f0IzBWbJ5ot0PIi4amk07IotBXDWwqDiQTwyuGCym5EqWQ2BD95\nRGv89BPD+2DLnJysngsvVaUCAwEAAQ==\n-----END PUBLIC KEY-----\nPKTAGS;\n    }\n}\n\nclass ErrorHandler\n{\n    public $message;\n    protected $active;\n\n    /**\n     * Handle php errors\n     *\n     * @param mixed $code The error code\n     * @param mixed $msg The error message\n     */\n    public function handleError($code, $msg)\n    {\n        if ($this->message) {\n            $this->message .= PHP_EOL;\n        }\n        $this->message .= preg_replace('{^file_get_contents\\(.*?\\): }', '', $msg);\n    }\n\n    /**\n     * Starts error-handling if not already active\n     *\n     * Any message is cleared\n     */\n    public function start()\n    {\n        if (!$this->active) {\n            set_error_handler(array($this, 'handleError'));\n            $this->active = true;\n        }\n        $this->message = '';\n    }\n\n    /**\n     * Stops error-handling if active\n     *\n     * Any message is preserved until the next call to start()\n     */\n    public function stop()\n    {\n        if ($this->active) {\n            restore_error_handler();\n            $this->active = false;\n        }\n    }\n}\n\nclass NoProxyPattern\n{\n    private $composerInNoProxy = false;\n    private $rulePorts = array();\n\n    public function __construct($pattern)\n    {\n        $rules = preg_split('{[\\s,]+}', $pattern, null, PREG_SPLIT_NO_EMPTY);\n\n        if ($matches = preg_grep('{getcomposer\\.org(?::\\d+)?}i', $rules)) {\n            $this->composerInNoProxy = true;\n\n            foreach ($matches as $match) {\n                if (strpos($match, ':') !== false) {\n                    list(, $port) = explode(':', $match);\n                    $this->rulePorts[] = (int) $port;\n                }\n            }\n        }\n    }\n\n    /**\n     * Returns true if NO_PROXY contains getcomposer.org\n     *\n     * @param string $url http(s)://getcomposer.org\n     *\n     * @return bool\n     */\n    public function test($url)\n    {\n        if (!$this->composerInNoProxy) {\n            return false;\n        }\n\n        if (empty($this->rulePorts)) {\n            return true;\n        }\n\n        if (strpos($url, 'http://') === 0) {\n            $port = 80;\n        } else {\n            $port = 443;\n        }\n\n        return in_array($port, $this->rulePorts);\n    }\n}\n\nclass HttpClient {\n\n    private $options = array('http' => array());\n    private $disableTls = false;\n\n    public function __construct($disableTls = false, $cafile = false)\n    {\n        $this->disableTls = $disableTls;\n        if ($this->disableTls === false) {\n            if (!empty($cafile) && !is_dir($cafile)) {\n                if (!is_readable($cafile) || !validateCaFile(file_get_contents($cafile))) {\n                    throw new RuntimeException('The configured cafile (' .$cafile. ') was not valid or could not be read.');\n                }\n            }\n            $options = $this->getTlsStreamContextDefaults($cafile);\n            $this->options = array_replace_recursive($this->options, $options);\n        }\n    }\n\n    public function get($url)\n    {\n        $context = $this->getStreamContext($url);\n        $result = file_get_contents($url, false, $context);\n\n        if ($result && extension_loaded('zlib')) {\n            $decode = false;\n            foreach ($http_response_header as $header) {\n                if (preg_match('{^content-encoding: *gzip *$}i', $header)) {\n                    $decode = true;\n                    continue;\n                } elseif (preg_match('{^HTTP/}i', $header)) {\n                    $decode = false;\n                }\n            }\n\n            if ($decode) {\n                if (version_compare(PHP_VERSION, '5.4.0', '>=')) {\n                    $result = zlib_decode($result);\n                } else {\n                    // work around issue with gzuncompress & co that do not work with all gzip checksums\n                    $result = file_get_contents('compress.zlib://data:application/octet-stream;base64,'.base64_encode($result));\n                }\n\n                if (!$result) {\n                    throw new RuntimeException('Failed to decode zlib stream');\n                }\n            }\n        }\n\n        return $result;\n    }\n\n    protected function getStreamContext($url)\n    {\n        if ($this->disableTls === false) {\n            if (PHP_VERSION_ID < 50600) {\n                $this->options['ssl']['SNI_server_name'] = parse_url($url, PHP_URL_HOST);\n            }\n        }\n        // Keeping the above mostly isolated from the code copied from Composer.\n        return $this->getMergedStreamContext($url);\n    }\n\n    protected function getTlsStreamContextDefaults($cafile)\n    {\n        $ciphers = implode(':', array(\n            'ECDHE-RSA-AES128-GCM-SHA256',\n            'ECDHE-ECDSA-AES128-GCM-SHA256',\n            'ECDHE-RSA-AES256-GCM-SHA384',\n            'ECDHE-ECDSA-AES256-GCM-SHA384',\n            'DHE-RSA-AES128-GCM-SHA256',\n            'DHE-DSS-AES128-GCM-SHA256',\n            'kEDH+AESGCM',\n            'ECDHE-RSA-AES128-SHA256',\n            'ECDHE-ECDSA-AES128-SHA256',\n            'ECDHE-RSA-AES128-SHA',\n            'ECDHE-ECDSA-AES128-SHA',\n            'ECDHE-RSA-AES256-SHA384',\n            'ECDHE-ECDSA-AES256-SHA384',\n            'ECDHE-RSA-AES256-SHA',\n            'ECDHE-ECDSA-AES256-SHA',\n            'DHE-RSA-AES128-SHA256',\n            'DHE-RSA-AES128-SHA',\n            'DHE-DSS-AES128-SHA256',\n            'DHE-RSA-AES256-SHA256',\n            'DHE-DSS-AES256-SHA',\n            'DHE-RSA-AES256-SHA',\n            'AES128-GCM-SHA256',\n            'AES256-GCM-SHA384',\n            'AES128-SHA256',\n            'AES256-SHA256',\n            'AES128-SHA',\n            'AES256-SHA',\n            'AES',\n            'CAMELLIA',\n            'DES-CBC3-SHA',\n            '!aNULL',\n            '!eNULL',\n            '!EXPORT',\n            '!DES',\n            '!RC4',\n            '!MD5',\n            '!PSK',\n            '!aECDH',\n            '!EDH-DSS-DES-CBC3-SHA',\n            '!EDH-RSA-DES-CBC3-SHA',\n            '!KRB5-DES-CBC3-SHA',\n        ));\n\n        /**\n         * CN_match and SNI_server_name are only known once a URL is passed.\n         * They will be set in the getOptionsForUrl() method which receives a URL.\n         *\n         * cafile or capath can be overridden by passing in those options to constructor.\n         */\n        $options = array(\n            'ssl' => array(\n                'ciphers' => $ciphers,\n                'verify_peer' => true,\n                'verify_depth' => 7,\n                'SNI_enabled' => true,\n            )\n        );\n\n        /**\n         * Attempt to find a local cafile or throw an exception.\n         * The user may go download one if this occurs.\n         */\n        if (!$cafile) {\n            $cafile = self::getSystemCaRootBundlePath();\n        }\n        if (is_dir($cafile)) {\n            $options['ssl']['capath'] = $cafile;\n        } elseif ($cafile) {\n            $options['ssl']['cafile'] = $cafile;\n        } else {\n            throw new RuntimeException('A valid cafile could not be located automatically.');\n        }\n\n        /**\n         * Disable TLS compression to prevent CRIME attacks where supported.\n         */\n        if (version_compare(PHP_VERSION, '5.4.13') >= 0) {\n            $options['ssl']['disable_compression'] = true;\n        }\n\n        return $options;\n    }\n\n    /**\n     * function copied from Composer\\Util\\StreamContextFactory::initOptions\n     *\n     * Any changes should be applied there as well, or backported here.\n     *\n     * @param string $url URL the context is to be used for\n     * @return resource Default context\n     * @throws \\RuntimeException if https proxy required and OpenSSL uninstalled\n     */\n    protected function getMergedStreamContext($url)\n    {\n        $options = $this->options;\n\n        // Handle HTTP_PROXY/http_proxy on CLI only for security reasons\n        if ((PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') && (!empty($_SERVER['HTTP_PROXY']) || !empty($_SERVER['http_proxy']))) {\n            $proxy = parse_url(!empty($_SERVER['http_proxy']) ? $_SERVER['http_proxy'] : $_SERVER['HTTP_PROXY']);\n        }\n\n        // Prefer CGI_HTTP_PROXY if available\n        if (!empty($_SERVER['CGI_HTTP_PROXY'])) {\n            $proxy = parse_url($_SERVER['CGI_HTTP_PROXY']);\n        }\n\n        // Override with HTTPS proxy if present and URL is https\n        if (preg_match('{^https://}i', $url) && (!empty($_SERVER['HTTPS_PROXY']) || !empty($_SERVER['https_proxy']))) {\n            $proxy = parse_url(!empty($_SERVER['https_proxy']) ? $_SERVER['https_proxy'] : $_SERVER['HTTPS_PROXY']);\n        }\n\n        // Remove proxy if URL matches no_proxy directive\n        if (!empty($_SERVER['NO_PROXY']) || !empty($_SERVER['no_proxy']) && parse_url($url, PHP_URL_HOST)) {\n            $pattern = new NoProxyPattern(!empty($_SERVER['no_proxy']) ? $_SERVER['no_proxy'] : $_SERVER['NO_PROXY']);\n            if ($pattern->test($url)) {\n                unset($proxy);\n            }\n        }\n\n        if (!empty($proxy)) {\n            $proxyURL = isset($proxy['scheme']) ? $proxy['scheme'] . '://' : '';\n            $proxyURL .= isset($proxy['host']) ? $proxy['host'] : '';\n\n            if (isset($proxy['port'])) {\n                $proxyURL .= \":\" . $proxy['port'];\n            } elseif (strpos($proxyURL, 'http://') === 0) {\n                $proxyURL .= \":80\";\n            } elseif (strpos($proxyURL, 'https://') === 0) {\n                $proxyURL .= \":443\";\n            }\n\n            // check for a secure proxy\n            if (strpos($proxyURL, 'https://') === 0) {\n                if (!extension_loaded('openssl')) {\n                    throw new RuntimeException('You must enable the openssl extension to use a secure proxy.');\n                }\n                if (strpos($url, 'https://') === 0) {\n                    throw new RuntimeException('PHP does not support https requests through a secure proxy.');\n                }\n            }\n\n            // http(s):// is not supported in proxy\n            $proxyURL = str_replace(array('http://', 'https://'), array('tcp://', 'ssl://'), $proxyURL);\n\n            $options['http'] = array(\n                'proxy' => $proxyURL,\n            );\n\n            // add request_fulluri for http requests\n            if ('http' === parse_url($url, PHP_URL_SCHEME)) {\n                $options['http']['request_fulluri'] = true;\n            }\n\n            // handle proxy auth if present\n            if (isset($proxy['user'])) {\n                $auth = rawurldecode($proxy['user']);\n                if (isset($proxy['pass'])) {\n                    $auth .= ':' . rawurldecode($proxy['pass']);\n                }\n                $auth = base64_encode($auth);\n\n                $options['http']['header'] = \"Proxy-Authorization: Basic {$auth}\\r\\n\";\n            }\n        }\n\n        if (isset($options['http']['header'])) {\n            $options['http']['header'] .= \"Connection: close\\r\\n\";\n        } else {\n            $options['http']['header'] = \"Connection: close\\r\\n\";\n        }\n        if (extension_loaded('zlib')) {\n            $options['http']['header'] .= \"Accept-Encoding: gzip\\r\\n\";\n        }\n        $options['http']['header'] .= \"User-Agent: \".COMPOSER_INSTALLER.\"\\r\\n\";\n        $options['http']['protocol_version'] = 1.1;\n        $options['http']['timeout'] = 600;\n\n        return stream_context_create($options);\n    }\n\n    /**\n    * This method was adapted from Sslurp.\n    * https://github.com/EvanDotPro/Sslurp\n    *\n    * (c) Evan Coury <me@evancoury.com>\n    *\n    * For the full copyright and license information, please see below:\n    *\n    * Copyright (c) 2013, Evan Coury\n    * All rights reserved.\n    *\n    * Redistribution and use in source and binary forms, with or without modification,\n    * are permitted provided that the following conditions are met:\n    *\n    *     * Redistributions of source code must retain the above copyright notice,\n    *       this list of conditions and the following disclaimer.\n    *\n    *     * Redistributions in binary form must reproduce the above copyright notice,\n    *       this list of conditions and the following disclaimer in the documentation\n    *       and/or other materials provided with the distribution.\n    *\n    * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n    * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n    * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n    * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n    * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n    * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n    * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n    * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n    * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n    */\n    public static function getSystemCaRootBundlePath()\n    {\n        static $caPath = null;\n\n        if ($caPath !== null) {\n            return $caPath;\n        }\n\n        // If SSL_CERT_FILE env variable points to a valid certificate/bundle, use that.\n        // This mimics how OpenSSL uses the SSL_CERT_FILE env variable.\n        $envCertFile = getenv('SSL_CERT_FILE');\n        if ($envCertFile && is_readable($envCertFile) && validateCaFile(file_get_contents($envCertFile))) {\n            return $caPath = $envCertFile;\n        }\n\n        // If SSL_CERT_DIR env variable points to a valid certificate/bundle, use that.\n        // This mimics how OpenSSL uses the SSL_CERT_FILE env variable.\n        $envCertDir = getenv('SSL_CERT_DIR');\n        if ($envCertDir && is_dir($envCertDir) && is_readable($envCertDir)) {\n            return $caPath = $envCertDir;\n        }\n\n        $configured = ini_get('openssl.cafile');\n        if ($configured && strlen($configured) > 0 && is_readable($configured) && validateCaFile(file_get_contents($configured))) {\n            return $caPath = $configured;\n        }\n\n        $configured = ini_get('openssl.capath');\n        if ($configured && is_dir($configured) && is_readable($configured)) {\n            return $caPath = $configured;\n        }\n\n        $caBundlePaths = array(\n            '/etc/pki/tls/certs/ca-bundle.crt', // Fedora, RHEL, CentOS (ca-certificates package)\n            '/etc/ssl/certs/ca-certificates.crt', // Debian, Ubuntu, Gentoo, Arch Linux (ca-certificates package)\n            '/etc/ssl/ca-bundle.pem', // SUSE, openSUSE (ca-certificates package)\n            '/usr/local/share/certs/ca-root-nss.crt', // FreeBSD (ca_root_nss_package)\n            '/usr/ssl/certs/ca-bundle.crt', // Cygwin\n            '/opt/local/share/curl/curl-ca-bundle.crt', // OS X macports, curl-ca-bundle package\n            '/usr/local/share/curl/curl-ca-bundle.crt', // Default cURL CA bunde path (without --with-ca-bundle option)\n            '/usr/share/ssl/certs/ca-bundle.crt', // Really old RedHat?\n            '/etc/ssl/cert.pem', // OpenBSD\n            '/usr/local/etc/ssl/cert.pem', // FreeBSD 10.x\n            '/usr/local/etc/openssl/cert.pem', // OS X homebrew, openssl package\n            '/usr/local/etc/openssl@1.1/cert.pem', // OS X homebrew, openssl@1.1 package\n        );\n\n        foreach ($caBundlePaths as $caBundle) {\n            if (@is_readable($caBundle) && validateCaFile(file_get_contents($caBundle))) {\n                return $caPath = $caBundle;\n            }\n        }\n\n        foreach ($caBundlePaths as $caBundle) {\n            $caBundle = dirname($caBundle);\n            if (is_dir($caBundle) && glob($caBundle.'/*')) {\n                return $caPath = $caBundle;\n            }\n        }\n\n        return $caPath = false;\n    }\n\n    public static function getPackagedCaFile()\n    {\n        return <<<CACERT\n##\n## Bundle of CA Root Certificates for Let's Encrypt\n##\n## See https://letsencrypt.org/certificates/\n##\n## ISRG Root X1 (RSA 4096) expires Jun 04 11:04:38 2035 GMT\n## ISRG Root X2 (ECDSA P-384) expires Sep 17 16:00:00 2040 GMT\n## DST Root CA X3 (RSA 2048) expires Sep 30 14:01:15 2021 GMT\n##\n## Notes: DST Root CA X3 should be removed after expiry data.\n##\n\nISRG Root X1\n============\n-----BEGIN CERTIFICATE-----\nMIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\nTzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\ncmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\nWhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\nZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY\nMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc\nh77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+\n0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U\nA5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW\nT8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH\nB5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC\nB5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv\nKBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn\nOlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn\njh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw\nqHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI\nrU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\nHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq\nhkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL\nubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ\n3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK\nNFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5\nORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur\nTkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC\njNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc\noyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq\n4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA\nmRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d\nemyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=\n-----END CERTIFICATE-----\n\nISRG Root X2\n============\n-----BEGIN CERTIFICATE-----\nMIICGzCCAaGgAwIBAgIQQdKd0XLq7qeAwSxs6S+HUjAKBggqhkjOPQQDAzBPMQsw\nCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2gg\nR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMjAeFw0yMDA5MDQwMDAwMDBaFw00\nMDA5MTcxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5ldCBT\nZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgyMHYw\nEAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0HttwW\n+1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7AlF9\nItgKbppbd9/w+kHsOdx1ymgHDB/qo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0T\nAQH/BAUwAwEB/zAdBgNVHQ4EFgQUfEKWrt5LSDv6kviejM9ti6lyN5UwCgYIKoZI\nzj0EAwMDaAAwZQIwe3lORlCEwkSHRhtFcP9Ymd70/aTSVaYgLXTWNLxBo1BfASdW\ntL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1\n/q4AaOeMSQ+2b1tbFfLn\n-----END CERTIFICATE-----\n\nDST Root CA X3\n==============\n-----BEGIN CERTIFICATE-----\nMIIDSjCCAjKgAwIBAgIQRK+wgNajJ7qJMDmGLvhAazANBgkqhkiG9w0BAQUFADA/\nMSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT\nDkRTVCBSb290IENBIFgzMB4XDTAwMDkzMDIxMTIxOVoXDTIxMDkzMDE0MDExNVow\nPzEkMCIGA1UEChMbRGlnaXRhbCBTaWduYXR1cmUgVHJ1c3QgQ28uMRcwFQYDVQQD\nEw5EU1QgUm9vdCBDQSBYMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB\nAN+v6ZdQCINXtMxiZfaQguzH0yxrMMpb7NnDfcdAwRgUi+DoM3ZJKuM/IUmTrE4O\nrz5Iy2Xu/NMhD2XSKtkyj4zl93ewEnu1lcCJo6m67XMuegwGMoOifooUMM0RoOEq\nOLl5CjH9UL2AZd+3UWODyOKIYepLYYHsUmu5ouJLGiifSKOeDNoJjj4XLh7dIN9b\nxiqKqy69cK3FCxolkHRyxXtqqzTWMIn/5WgTe1QLyNau7Fqckh49ZLOMxt+/yUFw\n7BZy1SbsOFU5Q9D8/RhcQPGX69Wam40dutolucbY38EVAjqr2m7xPi71XAicPNaD\naeQQmxkqtilX4+U9m5/wAl0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNV\nHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFMSnsaR7LHH62+FLkHX/xBVghYkQMA0GCSqG\nSIb3DQEBBQUAA4IBAQCjGiybFwBcqR7uKGY3Or+Dxz9LwwmglSBd49lZRNI+DT69\nikugdB/OEIKcdBodfpga3csTS7MgROSR6cz8faXbauX+5v3gTt23ADq1cEmv8uXr\nAvHRAosZy5Q6XkjEGB5YGV8eAlrwDPGxrancWYaLbumR9YbK+rlmM6pZW87ipxZz\nR8srzJmwN0jP41ZL9c8PDHIyh8bwRLtTcm1D9SZImlJnt1ir/md2cXjbDaJWFBM5\nJDGFoqgCWjBH4d1QB7wCCZAA62RjYJsWvIjJEubSfZGL+T0yjWW06XyxV3bqxbYo\nOb8VZRzI9neWagqNdwvYkQsEjgfbKbYK7p2CNTUQ\n-----END CERTIFICATE-----\nCACERT;\n    }\n}\n"
  },
  {
    "path": "bin/setup.md",
    "content": "## Run example in Docker:\n\n```\n# Install composer (locally)\n\ndocker run -it --rm --name pdfmerge \\\n -v \"$PWD\":/usr/src/myapp \\\n -w /usr/src/myapp jurosh/php \\\n php ./bin/composer-setup.php \\\n --install-dir=bin --filename=composer\n\n# Install dependencies\n\ndocker run -it --rm --name pdfmerge \\\n -v \"$PWD\":/usr/src/myapp \\\n -w /usr/src/myapp jurosh/php \\\n php bin/composer install\n\n# Run example\n\ndocker run -it --rm --name pdfmerge \\\n -v \"$PWD\":/usr/myapp \\\n -w /usr/myapp/example jurosh/php \\\n php example.php\n```"
  },
  {
    "path": "composer.json",
    "content": "{\n  \"name\": \"jurosh/pdf-merge\",\n  \"description\": \"PHP PDF Merger\",\n  \"version\": \"2.1.0\",\n  \"keywords\": [\n    \"pdf\",\n    \"merge\"\n  ],\n  \"homepage\": \"https://github.com/jurosh/php-pdf-merge\",\n  \"license\": \"MIT\",\n  \"require\": {\n    \"php\": \">=5.6.20\",\n    \"setasign/fpdf\": \"^1.8\",\n    \"setasign/fpdi\": \"^2.3\"\n  },\n  \"authors\": [\n    {\n      \"name\": \"Juraj Husar\",\n      \"email\": \"jurosh@jurosh.com\",\n      \"homepage\": \"http://jurosh.com\"\n    }\n  ],\n  \"autoload\": {\n    \"classmap\": [\n      \"src/Jurosh/PDFMerge/PDFMerger.php\",\n      \"src/Jurosh/PDFMerge/PDFObject.php\"\n    ]\n  }\n}\n"
  },
  {
    "path": "example/example.php",
    "content": "<?php require '../vendor/autoload.php';\n\n// create merger instance\n$pdf = new \\Jurosh\\PDFMerge\\PDFMerger;\n\n// do work\n\n// add as many pdfs as you want\n// $pdf->addPDF('path/to/source/file.pdf', 'all', 'vertical')\n//  ->addPDF('path/to/source/file1.pdf', 'all')\n//  ->addPDF('path/to/source/file2.pdf', 'all', 'horizontal');\n\n// call merge\n//$pdf->merge('file', 'path/to/export/dir/file.pdf');\n//\n\n$pdf->addPDF('example1.pdf', 'all', 'vertical')\n    ->addPDF('example2.pdf', 'all', 'horizontal');\n\n$pdf->merge('file', 'merged.pdf');\n"
  },
  {
    "path": "src/Jurosh/PDFMerge/PDFMerger.php",
    "content": "<?php namespace Jurosh\\PDFMerge;\n\nuse Exception;\nuse setasign\\Fpdi\\Fpdi AS FPDI;\n\n/**\n * Basic merging of PDF files into one file\n *\n * TODO: check newer https://github.com/tecnickcom/TCPDF\n */\nclass PDFMerger {\n\n    /**\n     * @var type Array of PDFObject-s\n     */\n    private $_files;\n\n    /**\n     * Add a PDF for inclusion in the merge with a valid file path.\n     * Params are defined like array:  \n     *  'pages' => '...',\n     *  'orientation' => 'vertical / horizontal'\n     * \n     * Pages should be formatted: 1,3,6, 12-16.\n     * @param $filepath\n     * @param $param\n     * @return PDFMerger\n     */\n    public function addPDF($filepath, $pages = 'all', $orientation = 'vertical') {\n        if (file_exists($filepath)) {\n            $file = new PdfObject;\n            \n            if (strtolower($pages) != 'all') {\n                $file->pages = $this->_rewritepages($pages);\n            }\n            \n            $file->orientation = $orientation;\n            $file->path = $filepath;\n\n            $this->_files[] = $file;\n        } else {\n            throw new Exception(\"Could not locate PDF on '$filepath'\");\n        }\n\n        return $this;\n    }\n\n    /**\n     * Merge it.\n     * @param $outputmode\n     * @param $outputname\n     * @return PDF\n     */\n    public function merge($outputmode = 'browser', $outputpath = 'newfile.pdf') {\n        if (!isset($this->_files) || !is_array($this->_files)) {\n            throw new Exception(\"No PDFs to merge.\");\n        }\n\n        $fpdi = new FPDI;\n\n        // merger operations\n        /* @var $file PdfObject */\n        foreach ($this->_files as $file) {\n            $filename = $file->path;\n            $filepages = $file->pages;\n\n            $count = $fpdi->setSourceFile($filename);\n\n            //add the pages\n            if ($filepages == 'all') {\n                for ($i = 1; $i <= $count; $i++) {\n                    $template = $fpdi->importPage($i);\n                    $size = $fpdi->getTemplateSize($template);\n\n                    $fpdi->AddPage($file->getOrientationCode(), array($size['width'], $size['height']));\n                    $fpdi->useTemplate($template);\n                }\n            } else {\n                foreach ($filepages as $page) {\n                    if (!$template = $fpdi->importPage($page)) {\n                        throw new Exception(\"Could not load page '$page' in PDF '$filename'. Check that the page exists.\");\n                    }\n                    $size = $fpdi->getTemplateSize($template);\n\n                    $fpdi->AddPage($file->getOrientationCode(), array($size['w'], $size['h']));\n                    $fpdi->useTemplate($template);\n                }\n            }\n        }\n\n        //output operations\n        $mode = $this->_switchmode($outputmode);\n\n        if ($mode == 'S') {\n            return $fpdi->Output($outputpath, 'S');\n        } else {\n            if ($fpdi->Output($outputpath, $mode) == '') {\n                return true;\n            } else {\n                throw new Exception(\"Error outputting PDF to '$outputmode'.\");\n                return false;\n            }\n        }\n    }\n\n    /**\n     * FPDI uses single characters for specifying the output location. Change our more descriptive string into proper format.\n     * @param $mode\n     * @return Character\n     */\n    private function _switchmode($mode) {\n        switch (strtolower($mode)) {\n            case 'download':\n                return 'D';\n                break;\n            case 'browser':\n                return 'I';\n                break;\n            case 'file':\n                return 'F';\n                break;\n            case 'string':\n                return 'S';\n                break;\n            default:\n                return 'I';\n                break;\n        }\n    }\n\n    /**\n     * Takes our provided pages in the form of 1,3,4,16-50 and creates an array of all pages\n     * @param $pages\n     * @return unknown_type\n     */\n    private function _rewritepages($pagesParam) {\n        $pages = str_replace(' ', '', $pagesParam);\n        $part = explode(',', $pages);\n\n        //parse hyphens\n        foreach ($part as $i) {\n            $ind = explode('-', $i);\n\n            if (count($ind) == 2) {\n                $x = $ind[0]; //start page\n                $y = $ind[1]; //end page\n\n                if ($x > $y) {\n                    throw new Exception(\"Starting page, '$x' is greater than ending page '$y'.\");\n                    return false;\n                }\n\n                //add middle pages\n                while ($x <= $y) {\n                    $newpages[] = (int) $x;\n                    $x++;\n                }\n            } else {\n                $newpages[] = (int) $ind[0];\n            }\n        }\n        return $newpages;\n    }\n\n}\n"
  },
  {
    "path": "src/Jurosh/PDFMerge/PDFObject.php",
    "content": "<?php namespace Jurosh\\PDFMerge;\n\n/**\n * Description of PdfObject\n *\n * @author jurosh\n */\nclass PdfObject {\n    \n    public $path;\n    \n    // all / array of pages\n    public $pages = 'all';\n    \n    // horizontal / vertical\n    public $orientation;\n    \n    /**\n     * Get portrait() code or landscape (L)\n     * @return type\n     */\n    public function getOrientationCode() {\n        return $this->orientation == 'horizontal' \n                || $this->orientation == 'landscape' ? 'L' : 'P';\n    }\n    \n}\n"
  }
]