diff --git a/.gitignore b/.gitignore index 637d92c6..b5de88c7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,28 @@ +# SVN +.svn/ + +# Documentazione interna +DOCUMENTAZIONE_OJS35.md + + +# File di debug +app/app-debug.js + +# OS +Thumbs.db +.DS_Store +*:Zone.Identifier +*.Identifier + +# IDE .idea/ -node_modules/ \ No newline at end of file +.vscode/ + +# Testing +.phpunit.result.cache + +# Compiled locale +locale/**/*.mo + +# Submodules + JATSParser/vendor/ \ No newline at end of file diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index da2d0a52..00000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "JATSParser"] - path = JATSParser - url = https://github.com/Vitaliy-1/JATSParser.git diff --git a/FullTextArticleHandler.inc.php b/FullTextArticleHandler.inc.php deleted file mode 100644 index 11f05a2b..00000000 --- a/FullTextArticleHandler.inc.php +++ /dev/null @@ -1,68 +0,0 @@ -_plugin = PluginRegistry::getPlugin('generic', JATSPARSER_PLUGIN_NAME); - } - - /** - * @param $args - * @param $request - * @brief download supplementary files for article's full-text - */ - function downloadFullTextAssoc($args, $request) { - $fileId = $args[2]; - $dispatcher = $request->getDispatcher(); /** @var $dispatcher Dispatcher */ - if (empty($fileId) || !$this->article || !$this->publication) $dispatcher->handle404(); - - if (!$this->userCanViewGalley($request, $this->article->getId())) { - header('HTTP/1.0 403 Forbidden'); - echo '403 Forbidden
'; - exit; - } - - $fullTextFileIds = $this->publication->getData('jatsParser::fullTextFileId'); - if (empty($fullTextFileIds)) $dispatcher->handle404(); - - // Find if the file is an image dependent from the XML file, from which full-text was generated. - import('lib.pkp.classes.submission.SubmissionFile'); // const - $dependentFilesIterator = Services::get('submissionFile')->getMany([ - 'assocTypes' => [ASSOC_TYPE_SUBMISSION_FILE], - 'assocIds' => array_values($fullTextFileIds), - 'submissionIds' => [$this->article->getId()], - 'fileStages' => [SUBMISSION_FILE_DEPENDENT], - 'includeDependentFiles' => true, - ]); - - if (is_null($dependentFilesIterator->current())) $dispatcher->handle404(); - - $submissionFile = null; - foreach ($dependentFilesIterator as $dependentFile) { - if ($fileId == $dependentFile->getData('fileId')) { - $submissionFile = $dependentFile; - break; - } - } - - if (!$submissionFile) $dispatcher->handle404(); - - if (!in_array($submissionFile->getData('mimetype'), $this->_plugin::getSupportedSupplFileTypes())) $dispatcher->handle404(); - - // Download file if exists - if (!Services::get('file')->fs->has($submissionFile->getData('path'))) { - $request->getDispatcher()->handle404(); - } - - $filename = Services::get('file')->formatFilename($submissionFile->getData('path'), $submissionFile->getLocalizedData('name')); - Services::get('file')->download($submissionFile->getData('fileId'), $filename); - } -} diff --git a/FullTextArticleHandler.php b/FullTextArticleHandler.php new file mode 100644 index 00000000..c7e410ab --- /dev/null +++ b/FullTextArticleHandler.php @@ -0,0 +1,93 @@ +pluginName = $pluginName; + $this->_plugin = PluginRegistry::getPlugin('generic', $pluginName); + parent::__construct(); + } + + /** + * @param array $args + * @param \APP\core\Request $request + * @brief download supplementary files for article's full-text + */ + public function downloadFullTextAssoc(array $args, $request): void + { + $fileId = $args[2]; + if (empty($fileId) || !$this->article || !$this->publication) { + throw new NotFoundHttpException(); + } + + if (!$this->userCanViewGalley($request, $this->article->getId())) { + header('HTTP/1.0 403 Forbidden'); + echo '403 Forbidden
'; + exit; + } + + $fullTextFileIds = $this->publication->getData('jatsParser::fullTextFileId'); + if (empty($fullTextFileIds)) { + throw new NotFoundHttpException(); + } + + // Find if the file is an image dependent from the XML file, from which full-text was generated. + $dependentFilesIterator = Repo::submissionFile() + ->getCollector() + ->filterByAssoc(\APP\core\Application::ASSOC_TYPE_SUBMISSION_FILE, array_values($fullTextFileIds)) + ->filterBySubmissionIds([$this->article->getId()]) + ->filterByFileStages([\PKP\submissionFile\SubmissionFile::SUBMISSION_FILE_DEPENDENT]) + ->includeDependentFiles() + ->getMany(); + + if ($dependentFilesIterator->isEmpty()) { + throw new NotFoundHttpException(); + } + + $submissionFile = null; + foreach ($dependentFilesIterator as $dependentFile) { + if ($fileId == $dependentFile->getData('fileId')) { + $submissionFile = $dependentFile; + break; + } + } + + if (!$submissionFile) { + throw new NotFoundHttpException(); + } + + if (!in_array($submissionFile->getData('mimetype'), JatsParserPlugin::getSupportedSupplFileTypes())) { + throw new NotFoundHttpException(); + } + + // Download file if exists + if (!app()->get('file')->fs->has($submissionFile->getData('path'))) { + throw new NotFoundHttpException(); + } + + $filename = app()->get('file')->formatFilename($submissionFile->getData('path'), $submissionFile->getLocalizedData('name')); + app()->get('file')->download($submissionFile->getData('fileId'), $filename); + } +} diff --git a/JATSParser b/JATSParser deleted file mode 160000 index fb756f99..00000000 --- a/JATSParser +++ /dev/null @@ -1 +0,0 @@ -Subproject commit fb756f9983286bf10e43f1e0dbad706d964e891f diff --git a/JATSParser/LICENSE b/JATSParser/LICENSE new file mode 100644 index 00000000..94a9ed02 --- /dev/null +++ b/JATSParser/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/JATSParser/README.md b/JATSParser/README.md new file mode 100644 index 00000000..b970006f --- /dev/null +++ b/JATSParser/README.md @@ -0,0 +1,8 @@ +# JATSParser +JATSParser is aimed to be integrated with Open Journal Systems 3.0+ for transforming JATS XML to various formats +## Usage +* Install composer dependencies +* See [example.php](examples/example.php) +* Doesn't deal with JATS XML metadata as it by design it should be transfered from OJS +* Transforms JATS to HTML and PDF, uses TCPDF for the latter conversion +* Has dependency from citeproc-php for support for different citation style formats diff --git a/JATSParser/composer.json b/JATSParser/composer.json new file mode 100644 index 00000000..ed6f656b --- /dev/null +++ b/JATSParser/composer.json @@ -0,0 +1,54 @@ +{ + "name": "doc/jatsparser", + "description": "JATS XML parser", + "type": "library", + "license": "GPLv3", + "authors": [ + { + "name": "Vitaliy Bezsheiko", + "email": "vitaliybezsh@gmail.com" + } + ], + "minimum-stability": "dev", + "repositories": [ + { + "type": "package", + "package": { + "name": "citation-style-language/locales", + "version":"1.0.0", + "source": { + "type": "git", + "url": "https://github.com/citation-style-language/locales.git", + "reference": "master" + } + } + }, + { + "type": "package", + "package": { + "name": "citation-style-language/styles-distribution", + "version":"1.0.0", + "source": { + "type": "git", + "url": "https://github.com/citation-style-language/styles-distribution.git", + "reference": "master" + } + } + } + ], + "require": { + "php": "^8.2", + "tecnickcom/tcpdf": "^6.2.17", + "citation-style-language/locales":"@dev", + "citation-style-language/styles-distribution":"@dev", + "seboettg/citeproc-php": "^2" + }, + "autoload": { + "psr-4": { + "JATSParser\\": "src/JATSParser" + } + }, + "require-dev": { + "phpunit/phpunit": "^10.0" + } +} diff --git a/JATSParser/composer.lock b/JATSParser/composer.lock new file mode 100644 index 00000000..c2469990 --- /dev/null +++ b/JATSParser/composer.lock @@ -0,0 +1,1983 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "ca59de6ba700af4fabf2e9ec45699fd7", + "packages": [ + { + "name": "citation-style-language/locales", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/citation-style-language/locales.git", + "reference": "master" + }, + "type": "library" + }, + { + "name": "citation-style-language/styles-distribution", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/citation-style-language/styles-distribution.git", + "reference": "master" + }, + "type": "library" + }, + { + "name": "myclabs/php-enum", + "version": "1.8.0", + "source": { + "type": "git", + "url": "https://github.com/myclabs/php-enum.git", + "reference": "46cf3d8498b095bd33727b13fd5707263af99421" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/myclabs/php-enum/zipball/46cf3d8498b095bd33727b13fd5707263af99421", + "reference": "46cf3d8498b095bd33727b13fd5707263af99421", + "shasum": "" + }, + "require": { + "ext-json": "*", + "php": "^7.3 || ^8.0" + }, + "require-dev": { + "phpunit/phpunit": "^9.5", + "squizlabs/php_codesniffer": "1.*", + "vimeo/psalm": "^4.5.1" + }, + "type": "library", + "autoload": { + "psr-4": { + "MyCLabs\\Enum\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP Enum contributors", + "homepage": "https://github.com/myclabs/php-enum/graphs/contributors" + } + ], + "description": "PHP Enum implementation", + "homepage": "http://github.com/myclabs/php-enum", + "keywords": [ + "enum" + ], + "time": "2021-02-15T16:11:48+00:00" + }, + { + "name": "seboettg/citeproc-php", + "version": "v2.2.5", + "source": { + "type": "git", + "url": "https://github.com/seboettg/citeproc-php.git", + "reference": "53e94194a8269adf87cbf95a2d47876baf91f5d8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/seboettg/citeproc-php/zipball/53e94194a8269adf87cbf95a2d47876baf91f5d8", + "reference": "53e94194a8269adf87cbf95a2d47876baf91f5d8", + "shasum": "" + }, + "require": { + "ext-intl": "*", + "ext-json": "*", + "ext-simplexml": "*", + "myclabs/php-enum": "^1.5", + "php": ">=7.1", + "seboettg/collection": "^2.1", + "symfony/polyfill-mbstring": "^1.10" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^1", + "phpmd/phpmd": "^2.8", + "phpunit/phpunit": "^7.5", + "squizlabs/php_codesniffer": "^3.5" + }, + "type": "library", + "autoload": { + "psr-4": { + "Seboettg\\CiteProc\\": "src/" + }, + "files": [ + "src/functions.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Sebastian Böttger", + "email": "seboettg@gmail.com", + "homepage": "http://sebastianboettger.net", + "role": "Developer" + } + ], + "description": "Full-featured CSL processor (https://citationstyles.org)", + "time": "2020-12-06T10:15:17+00:00" + }, + { + "name": "seboettg/collection", + "version": "v2.1.0", + "source": { + "type": "git", + "url": "https://github.com/seboettg/Collection.git", + "reference": "9c0cfb53068026b4d34515126cfddd1830ddb518" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/seboettg/Collection/zipball/9c0cfb53068026b4d34515126cfddd1830ddb518", + "reference": "9c0cfb53068026b4d34515126cfddd1830ddb518", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "require-dev": { + "phpunit/phpunit": "6.5.*", + "satooshi/php-coveralls": "2.*" + }, + "type": "library", + "autoload": { + "psr-4": { + "Seboettg\\Collection\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Sebastian Böttger", + "email": "seboettg@gmail.com" + } + ], + "description": "Collection is a set of useful PHP wrapper classes for arrays, similar to Java Collection. Contains ArrayList, Stack, Queue.", + "keywords": [ + "OOP", + "array", + "arraylist", + "basic-data-structures", + "collections", + "comparable", + "comparable-interface", + "comparator", + "datastructures", + "filter", + "map", + "queue", + "sort", + "stack" + ], + "time": "2019-12-24T13:10:16+00:00" + }, + { + "name": "symfony/polyfill-mbstring", + "version": "dev-main", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-mbstring.git", + "reference": "5232de97ee3b75b0360528dae24e73db49566ab1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/5232de97ee3b75b0360528dae24e73db49566ab1", + "reference": "5232de97ee3b75b0360528dae24e73db49566ab1", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.22-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Mbstring\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for the Mbstring extension", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "mbstring", + "polyfill", + "portable", + "shim" + ], + "time": "2021-01-22T09:19:47+00:00" + }, + { + "name": "tecnickcom/tcpdf", + "version": "6.3.5", + "source": { + "type": "git", + "url": "https://github.com/tecnickcom/TCPDF.git", + "reference": "19a535eaa7fb1c1cac499109deeb1a7a201b4549" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/tecnickcom/TCPDF/zipball/19a535eaa7fb1c1cac499109deeb1a7a201b4549", + "reference": "19a535eaa7fb1c1cac499109deeb1a7a201b4549", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "autoload": { + "classmap": [ + "config", + "include", + "tcpdf.php", + "tcpdf_parser.php", + "tcpdf_import.php", + "tcpdf_barcodes_1d.php", + "tcpdf_barcodes_2d.php", + "include/tcpdf_colors.php", + "include/tcpdf_filters.php", + "include/tcpdf_font_data.php", + "include/tcpdf_fonts.php", + "include/tcpdf_images.php", + "include/tcpdf_static.php", + "include/barcodes/datamatrix.php", + "include/barcodes/pdf417.php", + "include/barcodes/qrcode.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-3.0-only" + ], + "authors": [ + { + "name": "Nicola Asuni", + "email": "info@tecnick.com", + "role": "lead" + } + ], + "description": "TCPDF is a PHP class for generating PDF documents and barcodes.", + "homepage": "http://www.tcpdf.org/", + "keywords": [ + "PDFD32000-2008", + "TCPDF", + "barcodes", + "datamatrix", + "pdf", + "pdf417", + "qrcode" + ], + "time": "2020-02-14T14:20:12+00:00" + } + ], + "packages-dev": [ + { + "name": "myclabs/deep-copy", + "version": "1.x-dev", + "source": { + "type": "git", + "url": "https://github.com/myclabs/DeepCopy.git", + "reference": "5ee4e978b7fec6dbd844282126a5a32daa2044c6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/5ee4e978b7fec6dbd844282126a5a32daa2044c6", + "reference": "5ee4e978b7fec6dbd844282126a5a32daa2044c6", + "shasum": "" + }, + "require": { + "php": "^7.1 || ^8.0" + }, + "conflict": { + "doctrine/collections": "<1.6.8", + "doctrine/common": "<2.13.3 || >=3 <3.2.2" + }, + "require-dev": { + "doctrine/collections": "^1.6.8", + "doctrine/common": "^2.13.3 || ^3.2.2", + "phpspec/prophecy": "^1.10", + "phpunit/phpunit": "^7.5.20 || ^8.5.23 || ^9.5.13" + }, + "default-branch": true, + "type": "library", + "autoload": { + "files": [ + "src/DeepCopy/deep_copy.php" + ], + "psr-4": { + "DeepCopy\\": "src/DeepCopy/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Create deep copies (clones) of your objects", + "keywords": [ + "clone", + "copy", + "duplicate", + "object", + "object graph" + ], + "support": { + "issues": "https://github.com/myclabs/DeepCopy/issues", + "source": "https://github.com/myclabs/DeepCopy/tree/1.x" + }, + "funding": [ + { + "url": "https://tidelift.com/funding/github/packagist/myclabs/deep-copy", + "type": "tidelift" + } + ], + "time": "2025-12-30T16:10:21+00:00" + }, + { + "name": "nikic/php-parser", + "version": "dev-master", + "source": { + "type": "git", + "url": "https://github.com/nikic/PHP-Parser.git", + "reference": "50f0d9c9d0e3cff1163c959c50aaaaa4a7115f08" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/50f0d9c9d0e3cff1163c959c50aaaaa4a7115f08", + "reference": "50f0d9c9d0e3cff1163c959c50aaaaa4a7115f08", + "shasum": "" + }, + "require": { + "ext-ctype": "*", + "ext-json": "*", + "ext-tokenizer": "*", + "php": ">=7.4" + }, + "require-dev": { + "ircmaxell/php-yacc": "^0.0.7", + "phpunit/phpunit": "^9.0" + }, + "default-branch": true, + "bin": [ + "bin/php-parse" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "5.x-dev" + } + }, + "autoload": { + "psr-4": { + "PhpParser\\": "lib/PhpParser" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Nikita Popov" + } + ], + "description": "A PHP parser written in PHP", + "keywords": [ + "parser", + "php" + ], + "support": { + "issues": "https://github.com/nikic/PHP-Parser/issues", + "source": "https://github.com/nikic/PHP-Parser/tree/master" + }, + "time": "2026-02-26T13:20:22+00:00" + }, + { + "name": "phar-io/manifest", + "version": "dev-master", + "source": { + "type": "git", + "url": "https://github.com/phar-io/manifest.git", + "reference": "c581d4941e196459bf76c945a8ca922963a66708" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phar-io/manifest/zipball/c581d4941e196459bf76c945a8ca922963a66708", + "reference": "c581d4941e196459bf76c945a8ca922963a66708", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-libxml": "*", + "ext-phar": "*", + "ext-xmlwriter": "*", + "phar-io/version": "^3.0.1", + "php": "^7.2 || ^8.0" + }, + "default-branch": true, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Arne Blankerts", + "email": "arne@blankerts.de", + "role": "Developer" + }, + { + "name": "Sebastian Heuer", + "email": "sebastian@phpeople.de", + "role": "Developer" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "Developer" + } + ], + "description": "Component for reading phar.io manifest information from a PHP Archive (PHAR)", + "support": { + "issues": "https://github.com/phar-io/manifest/issues", + "source": "https://github.com/phar-io/manifest/tree/master" + }, + "funding": [ + { + "url": "https://github.com/theseer", + "type": "github" + } + ], + "time": "2025-11-27T15:23:09+00:00" + }, + { + "name": "phar-io/version", + "version": "3.2.1", + "source": { + "type": "git", + "url": "https://github.com/phar-io/version.git", + "reference": "4f7fd7836c6f332bb2933569e566a0d6c4cbed74" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phar-io/version/zipball/4f7fd7836c6f332bb2933569e566a0d6c4cbed74", + "reference": "4f7fd7836c6f332bb2933569e566a0d6c4cbed74", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "type": "library", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Arne Blankerts", + "email": "arne@blankerts.de", + "role": "Developer" + }, + { + "name": "Sebastian Heuer", + "email": "sebastian@phpeople.de", + "role": "Developer" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "Developer" + } + ], + "description": "Library for handling version information and constraints", + "support": { + "issues": "https://github.com/phar-io/version/issues", + "source": "https://github.com/phar-io/version/tree/3.2.1" + }, + "time": "2022-02-21T01:04:05+00:00" + }, + { + "name": "phpunit/php-code-coverage", + "version": "10.1.16", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-code-coverage.git", + "reference": "7e308268858ed6baedc8704a304727d20bc07c77" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/7e308268858ed6baedc8704a304727d20bc07c77", + "reference": "7e308268858ed6baedc8704a304727d20bc07c77", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-libxml": "*", + "ext-xmlwriter": "*", + "nikic/php-parser": "^4.19.1 || ^5.1.0", + "php": ">=8.1", + "phpunit/php-file-iterator": "^4.1.0", + "phpunit/php-text-template": "^3.0.1", + "sebastian/code-unit-reverse-lookup": "^3.0.0", + "sebastian/complexity": "^3.2.0", + "sebastian/environment": "^6.1.0", + "sebastian/lines-of-code": "^2.0.2", + "sebastian/version": "^4.0.1", + "theseer/tokenizer": "^1.2.3" + }, + "require-dev": { + "phpunit/phpunit": "^10.1" + }, + "suggest": { + "ext-pcov": "PHP extension that provides line coverage", + "ext-xdebug": "PHP extension that provides line coverage as well as branch and path coverage" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "10.1.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library that provides collection, processing, and rendering functionality for PHP code coverage information.", + "homepage": "https://github.com/sebastianbergmann/php-code-coverage", + "keywords": [ + "coverage", + "testing", + "xunit" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-code-coverage/issues", + "security": "https://github.com/sebastianbergmann/php-code-coverage/security/policy", + "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/10.1.16" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-08-22T04:31:57+00:00" + }, + { + "name": "phpunit/php-file-iterator", + "version": "4.1.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-file-iterator.git", + "reference": "a95037b6d9e608ba092da1b23931e537cadc3c3c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/a95037b6d9e608ba092da1b23931e537cadc3c3c", + "reference": "a95037b6d9e608ba092da1b23931e537cadc3c3c", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "require-dev": { + "phpunit/phpunit": "^10.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "FilterIterator implementation that filters files based on a list of suffixes.", + "homepage": "https://github.com/sebastianbergmann/php-file-iterator/", + "keywords": [ + "filesystem", + "iterator" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-file-iterator/issues", + "security": "https://github.com/sebastianbergmann/php-file-iterator/security/policy", + "source": "https://github.com/sebastianbergmann/php-file-iterator/tree/4.1.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2023-08-31T06:24:48+00:00" + }, + { + "name": "phpunit/php-invoker", + "version": "4.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-invoker.git", + "reference": "f5e568ba02fa5ba0ddd0f618391d5a9ea50b06d7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-invoker/zipball/f5e568ba02fa5ba0ddd0f618391d5a9ea50b06d7", + "reference": "f5e568ba02fa5ba0ddd0f618391d5a9ea50b06d7", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "require-dev": { + "ext-pcntl": "*", + "phpunit/phpunit": "^10.0" + }, + "suggest": { + "ext-pcntl": "*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Invoke callables with a timeout", + "homepage": "https://github.com/sebastianbergmann/php-invoker/", + "keywords": [ + "process" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-invoker/issues", + "source": "https://github.com/sebastianbergmann/php-invoker/tree/4.0.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2023-02-03T06:56:09+00:00" + }, + { + "name": "phpunit/php-text-template", + "version": "3.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-text-template.git", + "reference": "0c7b06ff49e3d5072f057eb1fa59258bf287a748" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/0c7b06ff49e3d5072f057eb1fa59258bf287a748", + "reference": "0c7b06ff49e3d5072f057eb1fa59258bf287a748", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "require-dev": { + "phpunit/phpunit": "^10.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Simple template engine.", + "homepage": "https://github.com/sebastianbergmann/php-text-template/", + "keywords": [ + "template" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-text-template/issues", + "security": "https://github.com/sebastianbergmann/php-text-template/security/policy", + "source": "https://github.com/sebastianbergmann/php-text-template/tree/3.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2023-08-31T14:07:24+00:00" + }, + { + "name": "phpunit/php-timer", + "version": "6.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-timer.git", + "reference": "e2a2d67966e740530f4a3343fe2e030ffdc1161d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/e2a2d67966e740530f4a3343fe2e030ffdc1161d", + "reference": "e2a2d67966e740530f4a3343fe2e030ffdc1161d", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "require-dev": { + "phpunit/phpunit": "^10.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "6.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Utility class for timing", + "homepage": "https://github.com/sebastianbergmann/php-timer/", + "keywords": [ + "timer" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-timer/issues", + "source": "https://github.com/sebastianbergmann/php-timer/tree/6.0.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2023-02-03T06:57:52+00:00" + }, + { + "name": "phpunit/phpunit", + "version": "10.5.x-dev", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/phpunit.git", + "reference": "56a16ccb2315cc144e133100260c6e12285e980c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/56a16ccb2315cc144e133100260c6e12285e980c", + "reference": "56a16ccb2315cc144e133100260c6e12285e980c", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-json": "*", + "ext-libxml": "*", + "ext-mbstring": "*", + "ext-xml": "*", + "ext-xmlwriter": "*", + "myclabs/deep-copy": "^1.13.4", + "phar-io/manifest": "^2.0.4", + "phar-io/version": "^3.2.1", + "php": ">=8.1", + "phpunit/php-code-coverage": "^10.1.16", + "phpunit/php-file-iterator": "^4.1.0", + "phpunit/php-invoker": "^4.0.0", + "phpunit/php-text-template": "^3.0.1", + "phpunit/php-timer": "^6.0.0", + "sebastian/cli-parser": "^2.0.1", + "sebastian/code-unit": "^2.0.0", + "sebastian/comparator": "^5.0.5", + "sebastian/diff": "^5.1.1", + "sebastian/environment": "^6.1.0", + "sebastian/exporter": "^5.1.4", + "sebastian/global-state": "^6.0.2", + "sebastian/object-enumerator": "^5.0.0", + "sebastian/recursion-context": "^5.0.1", + "sebastian/type": "^4.0.0", + "sebastian/version": "^4.0.1" + }, + "suggest": { + "ext-soap": "To be able to generate mocks based on WSDL files" + }, + "bin": [ + "phpunit" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "10.5-dev" + } + }, + "autoload": { + "files": [ + "src/Framework/Assert/Functions.php" + ], + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "The PHP Unit Testing framework.", + "homepage": "https://phpunit.de/", + "keywords": [ + "phpunit", + "testing", + "xunit" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/phpunit/issues", + "security": "https://github.com/sebastianbergmann/phpunit/security/policy", + "source": "https://github.com/sebastianbergmann/phpunit/tree/10.5" + }, + "funding": [ + { + "url": "https://phpunit.de/sponsoring.html", + "type": "other" + } + ], + "time": "2026-05-17T07:17:44+00:00" + }, + { + "name": "sebastian/cli-parser", + "version": "2.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/cli-parser.git", + "reference": "c34583b87e7b7a8055bf6c450c2c77ce32a24084" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/cli-parser/zipball/c34583b87e7b7a8055bf6c450c2c77ce32a24084", + "reference": "c34583b87e7b7a8055bf6c450c2c77ce32a24084", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "require-dev": { + "phpunit/phpunit": "^10.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "2.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library for parsing CLI options", + "homepage": "https://github.com/sebastianbergmann/cli-parser", + "support": { + "issues": "https://github.com/sebastianbergmann/cli-parser/issues", + "security": "https://github.com/sebastianbergmann/cli-parser/security/policy", + "source": "https://github.com/sebastianbergmann/cli-parser/tree/2.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-03-02T07:12:49+00:00" + }, + { + "name": "sebastian/code-unit", + "version": "2.0.x-dev", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/code-unit.git", + "reference": "807b5e65ab7b7b16e1928d924c7973aa451fa295" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/code-unit/zipball/807b5e65ab7b7b16e1928d924c7973aa451fa295", + "reference": "807b5e65ab7b7b16e1928d924c7973aa451fa295", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "require-dev": { + "phpunit/phpunit": "^10.5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "2.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Collection of value objects that represent the PHP code units", + "homepage": "https://github.com/sebastianbergmann/code-unit", + "support": { + "issues": "https://github.com/sebastianbergmann/code-unit/issues", + "security": "https://github.com/sebastianbergmann/code-unit/security/policy", + "source": "https://github.com/sebastianbergmann/code-unit/tree/2.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2025-01-01T09:30:48+00:00" + }, + { + "name": "sebastian/code-unit-reverse-lookup", + "version": "3.0.x-dev", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/code-unit-reverse-lookup.git", + "reference": "9f7c12369107fdb7a91016bf88f27d39872a88ea" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/code-unit-reverse-lookup/zipball/9f7c12369107fdb7a91016bf88f27d39872a88ea", + "reference": "9f7c12369107fdb7a91016bf88f27d39872a88ea", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "require-dev": { + "phpunit/phpunit": "^10.5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Looks up which function or method a line of code belongs to", + "homepage": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/", + "support": { + "issues": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/issues", + "security": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/security/policy", + "source": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/tree/3.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2025-01-01T09:31:34+00:00" + }, + { + "name": "sebastian/comparator", + "version": "5.0.5", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/comparator.git", + "reference": "55dfef806eb7dfeb6e7a6935601fef866f8ca48d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/55dfef806eb7dfeb6e7a6935601fef866f8ca48d", + "reference": "55dfef806eb7dfeb6e7a6935601fef866f8ca48d", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-mbstring": "*", + "php": ">=8.1", + "sebastian/diff": "^5.0", + "sebastian/exporter": "^5.0" + }, + "require-dev": { + "phpunit/phpunit": "^10.5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "5.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Volker Dusch", + "email": "github@wallbash.com" + }, + { + "name": "Bernhard Schussek", + "email": "bschussek@2bepublished.at" + } + ], + "description": "Provides the functionality to compare PHP values for equality", + "homepage": "https://github.com/sebastianbergmann/comparator", + "keywords": [ + "comparator", + "compare", + "equality" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/comparator/issues", + "security": "https://github.com/sebastianbergmann/comparator/security/policy", + "source": "https://github.com/sebastianbergmann/comparator/tree/5.0.5" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/sebastian/comparator", + "type": "tidelift" + } + ], + "time": "2026-01-24T09:25:16+00:00" + }, + { + "name": "sebastian/complexity", + "version": "3.2.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/complexity.git", + "reference": "68ff824baeae169ec9f2137158ee529584553799" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/complexity/zipball/68ff824baeae169ec9f2137158ee529584553799", + "reference": "68ff824baeae169ec9f2137158ee529584553799", + "shasum": "" + }, + "require": { + "nikic/php-parser": "^4.18 || ^5.0", + "php": ">=8.1" + }, + "require-dev": { + "phpunit/phpunit": "^10.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.2-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library for calculating the complexity of PHP code units", + "homepage": "https://github.com/sebastianbergmann/complexity", + "support": { + "issues": "https://github.com/sebastianbergmann/complexity/issues", + "security": "https://github.com/sebastianbergmann/complexity/security/policy", + "source": "https://github.com/sebastianbergmann/complexity/tree/3.2.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2023-12-21T08:37:17+00:00" + }, + { + "name": "sebastian/diff", + "version": "5.1.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/diff.git", + "reference": "c41e007b4b62af48218231d6c2275e4c9b975b2e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/c41e007b4b62af48218231d6c2275e4c9b975b2e", + "reference": "c41e007b4b62af48218231d6c2275e4c9b975b2e", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "require-dev": { + "phpunit/phpunit": "^10.0", + "symfony/process": "^6.4" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "5.1-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Kore Nordmann", + "email": "mail@kore-nordmann.de" + } + ], + "description": "Diff implementation", + "homepage": "https://github.com/sebastianbergmann/diff", + "keywords": [ + "diff", + "udiff", + "unidiff", + "unified diff" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/diff/issues", + "security": "https://github.com/sebastianbergmann/diff/security/policy", + "source": "https://github.com/sebastianbergmann/diff/tree/5.1.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-03-02T07:15:17+00:00" + }, + { + "name": "sebastian/environment", + "version": "6.1.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/environment.git", + "reference": "8074dbcd93529b357029f5cc5058fd3e43666984" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/8074dbcd93529b357029f5cc5058fd3e43666984", + "reference": "8074dbcd93529b357029f5cc5058fd3e43666984", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "require-dev": { + "phpunit/phpunit": "^10.0" + }, + "suggest": { + "ext-posix": "*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "6.1-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Provides functionality to handle HHVM/PHP environments", + "homepage": "https://github.com/sebastianbergmann/environment", + "keywords": [ + "Xdebug", + "environment", + "hhvm" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/environment/issues", + "security": "https://github.com/sebastianbergmann/environment/security/policy", + "source": "https://github.com/sebastianbergmann/environment/tree/6.1.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-03-23T08:47:14+00:00" + }, + { + "name": "sebastian/exporter", + "version": "5.1.4", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/exporter.git", + "reference": "0735b90f4da94969541dac1da743446e276defa6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/0735b90f4da94969541dac1da743446e276defa6", + "reference": "0735b90f4da94969541dac1da743446e276defa6", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "php": ">=8.1", + "sebastian/recursion-context": "^5.0" + }, + "require-dev": { + "phpunit/phpunit": "^10.5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "5.1-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Volker Dusch", + "email": "github@wallbash.com" + }, + { + "name": "Adam Harvey", + "email": "aharvey@php.net" + }, + { + "name": "Bernhard Schussek", + "email": "bschussek@gmail.com" + } + ], + "description": "Provides the functionality to export PHP variables for visualization", + "homepage": "https://www.github.com/sebastianbergmann/exporter", + "keywords": [ + "export", + "exporter" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/exporter/issues", + "security": "https://github.com/sebastianbergmann/exporter/security/policy", + "source": "https://github.com/sebastianbergmann/exporter/tree/5.1.4" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/sebastian/exporter", + "type": "tidelift" + } + ], + "time": "2025-09-24T06:09:11+00:00" + }, + { + "name": "sebastian/global-state", + "version": "6.0.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/global-state.git", + "reference": "987bafff24ecc4c9ac418cab1145b96dd6e9cbd9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/987bafff24ecc4c9ac418cab1145b96dd6e9cbd9", + "reference": "987bafff24ecc4c9ac418cab1145b96dd6e9cbd9", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "sebastian/object-reflector": "^3.0", + "sebastian/recursion-context": "^5.0" + }, + "require-dev": { + "ext-dom": "*", + "phpunit/phpunit": "^10.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "6.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Snapshotting of global state", + "homepage": "https://www.github.com/sebastianbergmann/global-state", + "keywords": [ + "global state" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/global-state/issues", + "security": "https://github.com/sebastianbergmann/global-state/security/policy", + "source": "https://github.com/sebastianbergmann/global-state/tree/6.0.2" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-03-02T07:19:19+00:00" + }, + { + "name": "sebastian/lines-of-code", + "version": "2.0.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/lines-of-code.git", + "reference": "856e7f6a75a84e339195d48c556f23be2ebf75d0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/lines-of-code/zipball/856e7f6a75a84e339195d48c556f23be2ebf75d0", + "reference": "856e7f6a75a84e339195d48c556f23be2ebf75d0", + "shasum": "" + }, + "require": { + "nikic/php-parser": "^4.18 || ^5.0", + "php": ">=8.1" + }, + "require-dev": { + "phpunit/phpunit": "^10.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "2.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library for counting the lines of code in PHP source code", + "homepage": "https://github.com/sebastianbergmann/lines-of-code", + "support": { + "issues": "https://github.com/sebastianbergmann/lines-of-code/issues", + "security": "https://github.com/sebastianbergmann/lines-of-code/security/policy", + "source": "https://github.com/sebastianbergmann/lines-of-code/tree/2.0.2" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2023-12-21T08:38:20+00:00" + }, + { + "name": "sebastian/object-enumerator", + "version": "5.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/object-enumerator.git", + "reference": "202d0e344a580d7f7d04b3fafce6933e59dae906" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/object-enumerator/zipball/202d0e344a580d7f7d04b3fafce6933e59dae906", + "reference": "202d0e344a580d7f7d04b3fafce6933e59dae906", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "sebastian/object-reflector": "^3.0", + "sebastian/recursion-context": "^5.0" + }, + "require-dev": { + "phpunit/phpunit": "^10.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "5.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Traverses array structures and object graphs to enumerate all referenced objects", + "homepage": "https://github.com/sebastianbergmann/object-enumerator/", + "support": { + "issues": "https://github.com/sebastianbergmann/object-enumerator/issues", + "source": "https://github.com/sebastianbergmann/object-enumerator/tree/5.0.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2023-02-03T07:08:32+00:00" + }, + { + "name": "sebastian/object-reflector", + "version": "3.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/object-reflector.git", + "reference": "24ed13d98130f0e7122df55d06c5c4942a577957" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/object-reflector/zipball/24ed13d98130f0e7122df55d06c5c4942a577957", + "reference": "24ed13d98130f0e7122df55d06c5c4942a577957", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "require-dev": { + "phpunit/phpunit": "^10.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Allows reflection of object attributes, including inherited and non-public ones", + "homepage": "https://github.com/sebastianbergmann/object-reflector/", + "support": { + "issues": "https://github.com/sebastianbergmann/object-reflector/issues", + "source": "https://github.com/sebastianbergmann/object-reflector/tree/3.0.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2023-02-03T07:06:18+00:00" + }, + { + "name": "sebastian/recursion-context", + "version": "5.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/recursion-context.git", + "reference": "47e34210757a2f37a97dcd207d032e1b01e64c7a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/47e34210757a2f37a97dcd207d032e1b01e64c7a", + "reference": "47e34210757a2f37a97dcd207d032e1b01e64c7a", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "require-dev": { + "phpunit/phpunit": "^10.5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "5.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Adam Harvey", + "email": "aharvey@php.net" + } + ], + "description": "Provides functionality to recursively process PHP variables", + "homepage": "https://github.com/sebastianbergmann/recursion-context", + "support": { + "issues": "https://github.com/sebastianbergmann/recursion-context/issues", + "security": "https://github.com/sebastianbergmann/recursion-context/security/policy", + "source": "https://github.com/sebastianbergmann/recursion-context/tree/5.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/sebastian/recursion-context", + "type": "tidelift" + } + ], + "time": "2025-08-10T07:50:56+00:00" + }, + { + "name": "sebastian/type", + "version": "4.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/type.git", + "reference": "462699a16464c3944eefc02ebdd77882bd3925bf" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/type/zipball/462699a16464c3944eefc02ebdd77882bd3925bf", + "reference": "462699a16464c3944eefc02ebdd77882bd3925bf", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "require-dev": { + "phpunit/phpunit": "^10.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Collection of value objects that represent the types of the PHP type system", + "homepage": "https://github.com/sebastianbergmann/type", + "support": { + "issues": "https://github.com/sebastianbergmann/type/issues", + "source": "https://github.com/sebastianbergmann/type/tree/4.0.0" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2023-02-03T07:10:45+00:00" + }, + { + "name": "sebastian/version", + "version": "4.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/version.git", + "reference": "c51fa83a5d8f43f1402e3f32a005e6262244ef17" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/c51fa83a5d8f43f1402e3f32a005e6262244ef17", + "reference": "c51fa83a5d8f43f1402e3f32a005e6262244ef17", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library that helps with managing the version number of Git-hosted PHP projects", + "homepage": "https://github.com/sebastianbergmann/version", + "support": { + "issues": "https://github.com/sebastianbergmann/version/issues", + "source": "https://github.com/sebastianbergmann/version/tree/4.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2023-02-07T11:34:05+00:00" + }, + { + "name": "theseer/tokenizer", + "version": "1.3.1", + "source": { + "type": "git", + "url": "https://github.com/theseer/tokenizer.git", + "reference": "b7489ce515e168639d17feec34b8847c326b0b3c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/theseer/tokenizer/zipball/b7489ce515e168639d17feec34b8847c326b0b3c", + "reference": "b7489ce515e168639d17feec34b8847c326b0b3c", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-tokenizer": "*", + "ext-xmlwriter": "*", + "php": "^7.2 || ^8.0" + }, + "type": "library", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Arne Blankerts", + "email": "arne@blankerts.de", + "role": "Developer" + } + ], + "description": "A small library for converting tokenized PHP source code into XML and potentially other formats", + "support": { + "issues": "https://github.com/theseer/tokenizer/issues", + "source": "https://github.com/theseer/tokenizer/tree/1.3.1" + }, + "funding": [ + { + "url": "https://github.com/theseer", + "type": "github" + } + ], + "time": "2025-11-17T20:03:58+00:00" + } + ], + "aliases": [], + "minimum-stability": "dev", + "stability-flags": { + "citation-style-language/locales": 20, + "citation-style-language/styles-distribution": 20 + }, + "prefer-stable": false, + "prefer-lowest": false, + "platform": { + "php": "^8.2" + }, + "platform-dev": {}, + "plugin-api-version": "2.9.0" +} diff --git a/JATSParser/logo/logo.jpg b/JATSParser/logo/logo.jpg new file mode 100644 index 00000000..e8b368c9 Binary files /dev/null and b/JATSParser/logo/logo.jpg differ diff --git a/JATSParser/src/JATSParser/Back/AbstractReference.php b/JATSParser/src/JATSParser/Back/AbstractReference.php new file mode 100644 index 00000000..3c65879b --- /dev/null +++ b/JATSParser/src/JATSParser/Back/AbstractReference.php @@ -0,0 +1,197 @@ +xpath = Document::getXpath(); + $this->authors = $this->extractAuthors($reference); + $this->editors = $this->extractEditors($reference); + $this->id = $this->extractId($reference); + $this->year = $this->extractFromElement($reference, './/year[1]'); + $this->url = $this->extractFromElement($reference, './/ext-link[@ext-link-type="uri"]'); + $this->pubIdType = $this->extractPubIdType($reference); + + $citNodes = $this->xpath->query('mixed-citation|element-citation', $reference); + if ($citNodes->length > 0) { + $citNode = $citNodes->item(0); + if ($citNode->tagName === 'mixed-citation') $this->isMixed = true; + $this->rawReference = $citNode->nodeValue; + } + } + + protected function extractFromElement(\DOMElement $reference, string $xpathExpression) + { + $property = ''; + $searchNodes = $this->xpath->query($xpathExpression, $reference); + if ($searchNodes->length > 0) { + foreach ($searchNodes as $searchNode) { + $property = htmlspecialchars(trim($searchNode->nodeValue)); + } + } + return $property; + } + + private function extractId(\DOMElement $reference) + { + $id = ''; + if ($reference->hasAttribute("id")) { + $id = $reference->getAttribute("id"); + } + return $id; + } + + private function extractAuthors(\DOMElement $reference) + { + $authors = array(); + + $nameNodes = $this->xpath->query(".//name|.//collab", $reference); + if ($nameNodes->length > 0) { + /* @var $nameNode \DOMElement */ + foreach ($nameNodes as $nameNode) { + $parentOfName = $nameNode->parentNode; + if ($nameNode->nodeName === 'name' && ($parentOfName->nodeName !== 'person-group' || $parentOfName->getAttribute('person-group-type') === 'author')) { + $individual = new Individual($nameNode); + $authors[] = $individual; + } elseif ($nameNode->nodeName === 'collab' && ($parentOfName->nodeName !== 'person-group' || $parentOfName->getAttribute('person-group-type') === 'author')) { + $collaborator = new Collaboration($nameNode); + $authors[] = $collaborator; + } + } + } + return $authors; + } + + private function extractEditors(\DOMElement $reference) { + $editors = array(); + + $nameNodes = $this->xpath->query(".//name|.//collab", $reference); + if ($nameNodes->length > 0) { + /* @var $nameNode \DOMElement */ + foreach ($nameNodes as $nameNode) { + $parentOfName = $nameNode->parentNode; + if ($nameNode->nodeName === 'name' && $parentOfName->getAttribute('person-group-type') === 'editor') { + $individual = new Individual($nameNode); + $editors[] = $individual; + } elseif ($nameNode->nodeName === 'collab' && $parentOfName->getAttribute('person-group-type') === 'editor') { + $collaborator = new Collaboration($nameNode); + $editors[] = $collaborator; + } + } + } + return $editors; + } + + /** + * @return array + * Key => Publication ID Typy (DOI, PMID, PMCID), Value => Valid URL + */ + + private function extractPubIdType(\DOMElement $reference): array + { + $pubIdType = array(); + + $pubIdNodes = $this->xpath->query('.//pub-id', $reference); + if ($pubIdNodes->length > 0) { + /* @var $pubIdNode \DOMElement */ + foreach ($pubIdNodes as $pubIdNode) { + if ($pubIdNode->getAttribute('pub-id-type')) { + /* Ideally, we should retrieve Pub ID Type as a key and URL here as an array value */ + $pubIdKey = $pubIdNode->getAttribute('pub-id-type'); + $pubIdValue = $pubIdNode->nodeValue; + + switch (trim($pubIdKey)) { + /* TODO It's quite probably that we will need additional checks here */ + case "doi": + filter_var($pubIdValue, FILTER_VALIDATE_URL) ? $pubIdType[$pubIdKey] = $pubIdValue : $pubIdType[$pubIdKey] = DOI_REFERENCE_PREFIX . trim($pubIdValue); + break; + case "pmid": + filter_var($pubIdValue, FILTER_VALIDATE_URL) ? $pubIdType[$pubIdKey] = $pubIdValue : $pubIdType[$pubIdKey] = PMID_REFERENCE_PREFIX . trim($pubIdValue); + break; + case "pmcid": + filter_var($pubIdValue, FILTER_VALIDATE_URL) ? $pubIdType[$pubIdKey] = $pubIdValue : $pubIdType[$pubIdKey] = PMCID_REFERENCE_PREFIX . trim($pubIdValue); + break; + } + } + } + } + return $pubIdType; + } + + /** + * @return bool + * @brief check if it's mixed citation (may have untagged text) + */ + public function isMixed(): bool { + return $this->isMixed; + } + + /** + * @return string + * @brief contains only the text/nodeValue of the reference node + */ + public function getRawReference(): string { + return $this->rawReference; + } + + /** + * @param \DOMElement $el + * @return \DOMElement|null + * @brief return the first child element that is a DOMElement, e.g., to avoid DOMText children + */ + protected function getFirstChildElement(\DOMElement $el): ?\DOMElement { + foreach ($el->childNodes as $refChild) { + if ($refChild->nodeType === XML_ELEMENT_NODE) { + return $refChild; + } + } + return null; + } +} diff --git a/JATSParser/src/JATSParser/Back/Book.php b/JATSParser/src/JATSParser/Back/Book.php new file mode 100644 index 00000000..e52b3412 --- /dev/null +++ b/JATSParser/src/JATSParser/Back/Book.php @@ -0,0 +1,97 @@ +title = $this->extractFromElement($reference, ".//source[1]"); + $this->publisherLoc = $this->extractFromElement($reference, ".//publisher-loc[1]"); + $this->publisherName = $this->extractFromElement($reference, ".//publisher-name[1]"); + $this->url = $this->extractFromElement($reference, ".//ext-link[1]"); + } + + /** + * @return string + */ + public function getId(): string + { + return $this->id; + } + + /** + * @return string + */ + public function getTitle(): string { + return $this->title; + } + + /** + * @return array + */ + public function getAuthors(): array + { + return $this->authors; + } + + + /** + * @return array + */ + public function getEditors(): array + { + return $this->editors; + } + + /** + * @return string + */ + public function getYear(): string + { + return $this->year; + } + + /** + * @return string + */ + public function getUrl(): string + { + return $this->url; + } + + /** + * @return string + */ + public function getPublisherLoc(): string + { + return $this->publisherLoc; + } + + /** + * @return string + */ + public function getPublisherName(): string + { + return $this->publisherName; + } + + /** + * @return array + */ + public function getPubIdType(): array + { + return $this->pubIdType; + } +} diff --git a/JATSParser/src/JATSParser/Back/Chapter.php b/JATSParser/src/JATSParser/Back/Chapter.php new file mode 100644 index 00000000..4f8b7d24 --- /dev/null +++ b/JATSParser/src/JATSParser/Back/Chapter.php @@ -0,0 +1,134 @@ +title = $this->extractFromElement($reference, ".//chapter-title[1]"); + $this->book = $this->extractFromElement($reference, ".//source[1]"); + $this->publisherLoc = $this->extractFromElement($reference, ".//publisher-loc[1]"); + $this->publisherName = $this->extractFromElement($reference, ".//publisher-name[1]"); + $this->fpage = $this->extractFromElement($reference, './/fpage[1]'); + $this->lpage = $this->extractFromElement($reference, './/lpage[1]'); + } + + /** + * @return string + */ + public function getId(): string + { + return $this->id; + } + + /** + * @return string + */ + public function getTitle(): string + { + return $this->title; + } + + /** + * @return array + */ + public function getAuthors(): array + { + return $this->authors; + } + + /** + * @return array + */ + public function getEditors(): array + { + return $this->editors; + } + + /** + * @return string + */ + public function getYear(): string + { + return $this->year; + } + + /** + * @return string + */ + public function getUrl(): string + { + return $this->url; + } + + /** + * @return string + */ + public function getFpage(): string + { + return $this->fpage; + } + + /** + * @return string + */ + public function getLpage(): string + { + return $this->lpage; + } + + /** + * @return array + */ + public function getPubIdType(): array + { + return $this->pubIdType; + } + + /** + * @return string + */ + public function getBook(): string + { + return $this->book; + } + + /** + * @return string + */ + public function getPublisherName(): string + { + return $this->publisherName; + } + + /** + * @return string + */ + public function getPublisherLoc(): string + { + return $this->publisherLoc; + } +} \ No newline at end of file diff --git a/JATSParser/src/JATSParser/Back/Collaboration.php b/JATSParser/src/JATSParser/Back/Collaboration.php new file mode 100644 index 00000000..4769a558 --- /dev/null +++ b/JATSParser/src/JATSParser/Back/Collaboration.php @@ -0,0 +1,37 @@ +name = $collabNode->nodeValue; + + $parentNode = $collabNode->parentNode; + $personGroupType = $parentNode->getAttribute('person-group-type'); + if (isset($personGroupType)) { + $this->type = $personGroupType; + } + } + + /** + * @return string + */ + public function getType(): string { + return $this->type; + } + + /** + * @return string + */ + public function getName(): string + { + return $this->name; + } +} \ No newline at end of file diff --git a/JATSParser/src/JATSParser/Back/Conference.php b/JATSParser/src/JATSParser/Back/Conference.php new file mode 100644 index 00000000..1ba3d1de --- /dev/null +++ b/JATSParser/src/JATSParser/Back/Conference.php @@ -0,0 +1,111 @@ +title = $this->extractFromElement($reference, ".//source"); + $this->confName = $this->extractFromElement($reference, ".//conf-name"); + $this->confLoc = $this->extractFromElement($reference, ".//conf-loc"); + $this->confDate = $this->extractFromElement($reference, ".//conf-date"); + } + + /** + * @return string + */ + public function getId() + { + return $this->id; + } + + /** + * @return string + */ + public function getTitle(): string + { + return $this->title; + } + + /** + * @return array + */ + public function getAuthors(): array + { + return $this->authors; + } + + + /** + * @return array + */ + public function getEditors(): array + { + return $this->editors; + } + + /** + * @return string + */ + public function getYear(): string + { + return $this->year; + } + + /** + * @return string + */ + public function getUrl(): string + { + return $this->url; + } + + /** + * @return string + */ + public function getConfDate(): string + { + return $this->confDate; + } + + /** + * @return string + */ + public function getConfLoc(): string + { + return $this->confLoc; + } + + /** + * @return string + */ + public function getConfName(): string + { + return $this->confName; + } + + /** + * @return array + */ + public function getPubIdType(): array + { + return $this->pubIdType; + } +} + diff --git a/JATSParser/src/JATSParser/Back/Individual.php b/JATSParser/src/JATSParser/Back/Individual.php new file mode 100644 index 00000000..03cad29f --- /dev/null +++ b/JATSParser/src/JATSParser/Back/Individual.php @@ -0,0 +1,67 @@ +query('child::surname[1]', $individualNode); + if ($surnameNodes->length > 0) { + foreach ($surnameNodes as $surnameNode) { + $this->surname = $surnameNode->nodeValue; + } + } + + $givenNamesNodes = $xpath->query('child::given-names[1]', $individualNode); + if ($givenNamesNodes->length > 0) { + foreach ($givenNamesNodes as $givenNamesNode) { + $this->givenNames = $givenNamesNode->nodeValue; + } + } + + $parentNode = $individualNode->parentNode; + $personGroupType = $parentNode->getAttribute('person-group-type'); + if (isset($personGroupType)) { + $this->type = $personGroupType; + } else { + $this->type = 'author'; + } + + } + + /** + * @return string + */ + public function getType(): ?string { + return $this->type; + } + + /** + * @return string + */ + public function getSurname(): ?string + { + return $this->surname; + } + + /** + * @return string + */ + public function getGivenNames(): ?string + { + return $this->givenNames; + } +} diff --git a/JATSParser/src/JATSParser/Back/Journal.php b/JATSParser/src/JATSParser/Back/Journal.php new file mode 100644 index 00000000..f7745cd3 --- /dev/null +++ b/JATSParser/src/JATSParser/Back/Journal.php @@ -0,0 +1,144 @@ +title = $this->extractFromElement($reference, ".//article-title[1]"); + $this->journal = $this->extractFromElement($reference, ".//source[1]"); + $this->volume = $this->extractFromElement($reference, ".//volume[1]"); + $this->issue = $this->extractFromElement($reference, ".//issue[1]"); + $this->fpage = $this->extractFromElement($reference, ".//fpage[1]"); + $this->lpage = $this->extractFromElement($reference, ".//lpage[1]"); + } + + /** + * @return string + */ + public function getId() + { + return $this->id; + } + + /** + * @return string + */ + public function getTitle(): string + { + return $this->title; + } + + /** + * @return array + */ + public function getAuthors(): array + { + return $this->authors; + } + + + /** + * @return array + */ + public function getEditors(): array + { + return $this->editors; + } + + /** + * @return string + */ + public function getYear(): string + { + return $this->year; + } + + /** + * @return string + */ + public function getFpage(): string + { + return $this->fpage; + } + + /** + * @return string + */ + public function getLpage(): string + { + return $this->lpage; + } + + /** + * @return string + */ + public function getIssue(): string + { + return $this->issue; + } + + /** + * @return string + */ + public function getVolume(): string + { + return $this->volume; + } + + /** + * @return array + */ + public function getPubIdType(): array + { + return $this->pubIdType; + } + + /** + * @return string + */ + public function getUrl(): string + { + return $this->url; + } + + /** + * @return string + */ + public function getJournal(): string + { + return $this->journal; + } + + public function getPages(): string + { + $pages = ''; + + if (!empty($this->getFpage()) && !empty($this->getLpage())) $pages = $this->getFpage() . '-' . $this->getLpage(); + + return $pages; + } +} diff --git a/JATSParser/src/JATSParser/Back/PersonGroup.php b/JATSParser/src/JATSParser/Back/PersonGroup.php new file mode 100644 index 00000000..66b5909d --- /dev/null +++ b/JATSParser/src/JATSParser/Back/PersonGroup.php @@ -0,0 +1,7 @@ +xpath = Document::getXpath(); + } + + protected function extractFromElement(string $xpathExpression, \DOMElement $domElement = null): ?string + { + + $nodeTextValue = null; + $domElement !== null ? $searchNodes = $this->xpath->evaluate($xpathExpression, $domElement) : $searchNodes = $this->xpath->evaluate($xpathExpression); + if ($searchNodes->length > 0) { + foreach ($searchNodes as $searchNode) { + $nodeTextValue = $searchNode->nodeValue; + } + } + + return $nodeTextValue; + } + + protected function extractFromElements(string $xpathExpression, \DOMElement $domElement = null): ?array + { + + $nodeTextValues = array(); + $domElement !== null ? $searchNodes = $this->xpath->evaluate($xpathExpression, $domElement) : $searchNodes = $this->xpath->evaluate($xpathExpression); + if ($searchNodes->length > 0) { + foreach ($searchNodes as $searchNode) { + $nodeTextValues[] = $searchNode->nodeValue; + } + } + + return $nodeTextValues; + } + + protected function extractFormattedText(string $xpathExpression, \DOMElement $domElement = null): array + { + $nodeTextValues = array(); + $xpathExpression .= "//text()"; + $domElement !== null ? $searchNodes = $this->xpath->evaluate($xpathExpression, $domElement) : $searchNodes = $this->xpath->evaluate($xpathExpression); + if ($searchNodes->length > 0) { + foreach ($searchNodes as $searchNode) { + $jatsText = new Text($searchNode); + $nodeTextValues[] = $jatsText; + } + } + + return $nodeTextValues; + } + + protected function extractTitleOrCaption(\DOMElement $element, $extractType): ?array + { + $titleOrCaption = array(); + $captionNodes = $this->xpath->query(".//caption", $element); + foreach ($captionNodes as $captionNode) { + if ($extractType === self::JATS_EXTRACT_TITLE) { + $titleElements = $this->xpath->query(".//title//text()", $captionNode); + if ($titleElements->length > 0) { + foreach ($titleElements as $titleElement) { + $jatsText = new Text($titleElement); + $titleOrCaption[] = $jatsText; + } + } + + } elseif ($extractType === self::JATS_EXTRACT_CAPTION) { + $captionParagraphs = $this->xpath->query(".//p", $captionNode); + foreach ($captionParagraphs as $captionParagraph) { + $par = new Par($captionParagraph); + $titleOrCaption[] = $par; + } + } + } + + return $titleOrCaption; + } + + static function mappedBlockElements() + { + //return ["Figure" => "fig", "Table" => "table-wrap"]; + return [ + "Figure" => "fig", + "Table" => "table-wrap", + "BoxedText" => "boxed-text", + "DefList" => "def-list", + "Preformat" => "preformat", + "DispFormula" => "disp-formula", + ]; + } +} + + diff --git a/JATSParser/src/JATSParser/Body/BoxedText.php b/JATSParser/src/JATSParser/Body/BoxedText.php new file mode 100644 index 00000000..805f4ad8 --- /dev/null +++ b/JATSParser/src/JATSParser/Body/BoxedText.php @@ -0,0 +1,6 @@ + instead of
+} diff --git a/JATSParser/src/JATSParser/Body/Cell.php b/JATSParser/src/JATSParser/Body/Cell.php new file mode 100644 index 00000000..bd3808d2 --- /dev/null +++ b/JATSParser/src/JATSParser/Body/Cell.php @@ -0,0 +1,84 @@ +type = $cellNode->nodeName; + + $content = array(); + $xpath = Document::getXpath(); + $childNodes = $xpath->query("child::node()", $cellNode); + foreach ($childNodes as $childNode) { + if ($childNode->nodeName === "p") { + $par = new Par($childNode); + $content[] = $par; + } elseif ($childNode->nodeName === "inline-graphic" && $childNode->nodeType === XML_ELEMENT_NODE) { + $content[] = new InlineGraphic($childNode); + } else { + $jatsTextNodes = $xpath->query(".//self::text()", $childNode); + foreach ($jatsTextNodes as $jatsTextNode){ + $jatsText = new Text($jatsTextNode); + $content[] = $jatsText; + } + } + } + + $this->content = $content; + + $cellNode->hasAttribute("colspan") ? $this->colspan = $cellNode->getAttribute("colspan") : $this->colspan = 1; + + $cellNode->hasAttribute("rowspan") ? $this->rowspan = $cellNode->getAttribute("rowspan") : $this->rowspan = 1; + + } + + /** + * @return array + */ + + public function getContent(): array { + return $this->content; + } + + /** + * @return string + */ + + public function getType(): string { + return $this->type; + } + + /** + * @return int + */ + public function getColspan(): int + { + return $this->colspan; + } + + /** + * @return int + */ + public function getRowspan(): int + { + return $this->rowspan; + } +} diff --git a/JATSParser/src/JATSParser/Body/DefList.php b/JATSParser/src/JATSParser/Body/DefList.php new file mode 100644 index 00000000..c8f15c13 --- /dev/null +++ b/JATSParser/src/JATSParser/Body/DefList.php @@ -0,0 +1,41 @@ +xpath->query("title", $element); + if ($titleNodes->length > 0) { + $this->title = $titleNodes->item(0)->textContent; + } + + $defItems = $this->xpath->query("def-item", $element); + foreach ($defItems as $defItem) { + $termNodes = $this->xpath->query(".//term//text()", $defItem); + $termTexts = []; + foreach ($termNodes as $termNode) { + $termTexts[] = new Text($termNode); + } + + $defNodes = $this->xpath->query(".//def//text()", $defItem); + $defTexts = []; + foreach ($defNodes as $defNode) { + $defTexts[] = new Text($defNode); + } + + $this->items[] = ['term' => $termTexts, 'def' => $defTexts]; + } + } + + public function getContent(): array { + return $this->items; + } + + public function getTitle(): ?string { + return $this->title; + } +} diff --git a/JATSParser/src/JATSParser/Body/DispFormula.php b/JATSParser/src/JATSParser/Body/DispFormula.php new file mode 100644 index 00000000..a0fb2dd1 --- /dev/null +++ b/JATSParser/src/JATSParser/Body/DispFormula.php @@ -0,0 +1,61 @@ +id = $element->getAttribute('id') ?: null; + $this->label = $this->extractFromElement("label", $element); + + // Prefer tex-math content for LaTeX rendering + $texMath = $this->xpath->query("tex-math", $element); + if ($texMath->length > 0) { + $this->texContent = trim($texMath->item(0)->textContent); + } + + // Full text content minus the label text + $fullText = $element->textContent; + if ($this->label !== null) { + $fullText = str_replace($this->label, '', $fullText); + } + $this->textContent = trim($fullText); + } + + public function getContent(): string + { + return $this->textContent; + } + + public function getId(): ?string + { + return $this->id; + } + + public function getLabel(): ?string + { + return $this->label; + } + + public function getTexContent(): ?string + { + return $this->texContent; + } + + public function getTextContent(): string + { + return $this->textContent; + } + + public function hasLatex(): bool + { + return $this->texContent !== null; + } +} diff --git a/JATSParser/src/JATSParser/Body/DispQuote.php b/JATSParser/src/JATSParser/Body/DispQuote.php new file mode 100644 index 00000000..d4ed852d --- /dev/null +++ b/JATSParser/src/JATSParser/Body/DispQuote.php @@ -0,0 +1,32 @@ +attrib = $this->extractFormattedText(".//attrib", $element); + } + + // Cannot contain sections + public function getChildSectionsTitles(): array + { + return array(); + } + + /** + * @return array|null + */ + public function getAttrib(): array + { + return $this->attrib; + } +} diff --git a/JATSParser/src/JATSParser/Body/Document.php b/JATSParser/src/JATSParser/Body/Document.php new file mode 100644 index 00000000..3d0aabaa --- /dev/null +++ b/JATSParser/src/JATSParser/Body/Document.php @@ -0,0 +1,184 @@ +document = $document->load($documentPath); + self::$xpath = new \DOMXPath($document); + + $this->extractContent(); + $this->extractReferences(); + } + + public static function getXpath() : \DOMXPath { + return self::$xpath; + } + + public function getDocumentPath () : string { + return $this->documentPath; + } + + public function getArticleSections() : array { + return $this->articleContent; + } + + public function getReferences() : array { + return $this->references; + } + + /* @brief Constructor for references + * JATS XML can give us a little, if not at all, information about reference type; + * Here we are trying to determine the type of citation by element-citation node attribute or names of nodes which reference contains; + * Supported types are: journal, book, chapter, and conference. + */ + private function extractReferences() { + $references = array(); + foreach(self::$xpath->evaluate("/article/back/ref-list/ref") as $reference ) { + /* @var $reference \DOMElement */ + $citationTypeNodes = self::$xpath->query(".//element-citation[1]/@publication-type|.//mixed-citation[1]/@publication-type|.//citation-alternatives[1]/@publication-type", $reference ); + if ($citationTypeNodes->length > 0) { + foreach ($citationTypeNodes as $citationTypeNode) { + /* @var $citationTypeNode \DOMAttr */ + switch ($citationTypeNode->nodeValue) { + case "journal": + $journal = new Journal($reference); + $references[] = $journal; + break; + case "book": + $book = new Book($reference); + $references[] = $book; + break; + case "chapter": + $chapter = new Chapter($reference); + $references[] = $chapter; + break; + case "conference": + $conference = new Conference($reference); + $references[] = $conference; + break; + default: + $defaultRef = new Journal($reference); + $references[] = $defaultRef; + break; + } + } + } else { + $chapterTitleNode = self::$xpath->query(".//chapter-title", $reference); + if ($chapterTitleNode->length > 0) { + $probablyChapter = new Chapter($reference); + $references[] = $probablyChapter; + } else { + $publisherName = self::$xpath->query(".//publisher-name", $reference); + if($publisherName->length > 0) { + $probablyBook = new Book($reference); + $references[] = $probablyBook; + } else { + $confNameNode = self::$xpath->query(".//conf-name", $reference); + if($confNameNode->length > 0) { + $probablyConference = new Conference($reference); + $references[] = $probablyConference; + } else { + $probablyJournal = new Journal($reference); + $references[] = $probablyJournal; + } + } + } + } + } + $this->references = $references; + } + + private function extractContent(): void + { + $articleContent = array(); + foreach (self::$xpath->evaluate("/article/body") as $body) { + foreach (self::$xpath->evaluate(".//sec|./p|./list|./table-wrap|./fig|./media|./disp-quote|./verse-group|./boxed-text|./def-list|./preformat|./code|./disp-formula", $body) as $content) { + switch ($content->nodeName) { + case "sec": + $articleSection = new Section($content); + $articleContent[] = $articleSection; + break; + case "p": + $par = new Par($content); + $articleContent[] = $par; + if (!empty($par->getBlockElements())) { + foreach ($par->getBlockElements() as $blockElement) { + $articleContent[] = $blockElement; + } + } + break; + case "list": + $list = new Listing($content); + $articleContent[] = $list; + break; + case "table-wrap": + $table = new Table($content); + $articleContent[] = $table; + break; + case "fig": + $figure = new Figure($content); + $articleContent[] = $figure; + break; + case "media": + $media = new Media($content); + $articleContent[] = $media; + break; + case "disp-quote": + $dispQuote = new DispQuote($content); + $articleContent[] = $dispQuote; + break; + case "verse-group": + $verse = new Verse($content); + $articleContent[] = $verse; + break; + case "boxed-text": + $boxedText = new BoxedText($content); + $articleContent[] = $boxedText; + break; + case "def-list": + $defList = new DefList($content); + $articleContent[] = $defList; + break; + case "preformat": + case "code": + $preformat = new Preformat($content); + $articleContent[] = $preformat; + break; + case "disp-formula": + $dispFormula = new DispFormula($content); + $articleContent[] = $dispFormula; + break; + } + } + } + $this->articleContent = $articleContent; + } + +} diff --git a/JATSParser/src/JATSParser/Body/Figure.php b/JATSParser/src/JATSParser/Body/Figure.php new file mode 100644 index 00000000..095d2923 --- /dev/null +++ b/JATSParser/src/JATSParser/Body/Figure.php @@ -0,0 +1,52 @@ +label = $this->extractFromElement(".//label", $figureElement); + $this->link = $this->extractFromElement(".//graphic/@xlink:href", $figureElement); + $this->id = $this->extractFromElement( "./@id", $figureElement); + $this->title = $this->extractTitleOrCaption($figureElement, self::JATS_EXTRACT_TITLE); + $this->content = $this->extractTitleOrCaption($figureElement, self::JATS_EXTRACT_CAPTION); + + } + + public function getContent(): ?array { + return $this->content; + } + + public function getLink(): ?string { + return $this->link; + } + + public function getId(): ?string { + return $this->id; + } + + public function getTitle(): ?array { + return $this->title; + } + + public function getLabel(): ?string { + return $this->label; + } +} diff --git a/JATSParser/src/JATSParser/Body/InlineGraphic.php b/JATSParser/src/JATSParser/Body/InlineGraphic.php new file mode 100644 index 00000000..68e96133 --- /dev/null +++ b/JATSParser/src/JATSParser/Body/InlineGraphic.php @@ -0,0 +1,26 @@ + element (an image embedded inline in text flow). + */ +class InlineGraphic implements JATSElement { + + /** @var string xlink:href value (filename/path of the image) */ + private string $href; + + public function __construct(\DOMElement $element) { + $xpath = Document::getXpath(); + $hrefNodes = $xpath->query('./@xlink:href', $element); + $this->href = ($hrefNodes->length > 0) ? $hrefNodes->item(0)->nodeValue : ''; + } + + public function getHref(): string { + return $this->href; + } + + public function getContent(): array { + return []; + } +} diff --git a/JATSParser/src/JATSParser/Body/JATSElement.php b/JATSParser/src/JATSParser/Body/JATSElement.php new file mode 100644 index 00000000..3dea4d01 --- /dev/null +++ b/JATSParser/src/JATSParser/Body/JATSElement.php @@ -0,0 +1,7 @@ + list, sublist, subsublist, etc. + * default is 1 + */ + private $type; + + /* @var string: "unordered", "ordered" */ + private $style; + + private $content; + + public function __construct(\DOMElement $list) { + $xpath = Document::getXpath(); + $content = array(); + $list->hasAttribute("list-type") ? $this->style = $list->getAttribute("list-type") : $this->style = "unordered"; + $this->type = self::listElementLevel($list); + + $listItemNodes = $xpath->query("list-item", $list); + foreach ($listItemNodes as $listItemNode) { + $listItem = array(); // represents list item + $insideListItems = $xpath->query("child::node()", $listItemNode); + + foreach ($insideListItems as $insideJatsListItem) { + + if ($insideJatsListItem->nodeName === "p"){ + $par = new Par($insideJatsListItem); + $listItem[] = $par; + + } elseif ($insideJatsListItem->nodeName === "list") { + $insideListing = new Listing($insideJatsListItem); + $listItem[] = $insideListing; + } else { + $listItemTexts = $xpath->query("self::text()|.//text()", $insideJatsListItem); + foreach ($listItemTexts as $listItemText) { + /* We must ensure that picking up Text Node from the current list level -> avoiding parsing nested lists */ + if (self::listElementLevel($listItemText) === $this->type) { + $jatsText = new Text($listItemText); + $listItem[] = $jatsText; + } + } + } + + } + + $content[] = $listItem; + } + + $this->content = $content; + } + + public function getContent(): array { + return $this->content; + } + + /** + * @return int + */ + public function getType(): int { + return $this->type; + } + + /** + * @return string + */ + public function getStyle(): string { + return $this->style; + } + + /** + * @return boolean + */ + + private function listElementLevel(\DOMNode $textNode) { + $count = preg_match_all("/\blist\b[^-]|\blist\b$/", $textNode->getNodePath(), $mathes); + return $count; + } + +} diff --git a/JATSParser/src/JATSParser/Body/Media.php b/JATSParser/src/JATSParser/Body/Media.php new file mode 100644 index 00000000..bd2d8e9e --- /dev/null +++ b/JATSParser/src/JATSParser/Body/Media.php @@ -0,0 +1,72 @@ +label = $this->extractFromElement(".//label", $mediaElement); + $this->link = $this->extractFromElement("./@xlink:href", $mediaElement); + $this->id = $this->extractFromElement("./@id", $mediaElement); + $this->title = $this->extractTitleOrCaption($mediaElement, self::JATS_EXTRACT_TITLE); + $this->content = $this->extractTitleOrCaption($mediaElement, self::JATS_EXTRACT_CAPTION); + + } + + /** + * @return array + */ + public function getContent(): array { + return $this->content; + } + + /** + * @return string + */ + public function getLabel(): ?string + { + return $this->label; + } + + /** + * @return string + */ + public function getLink(): ?string + { + return $this->link; + } + + /** + * @return string + */ + public function getId(): ?string + { + return $this->id; + } + + /** + * @return array + */ + public function getTitle(): array + { + return $this->title; + } + +} diff --git a/JATSParser/src/JATSParser/Body/Par.php b/JATSParser/src/JATSParser/Body/Par.php new file mode 100644 index 00000000..d0f90b3b --- /dev/null +++ b/JATSParser/src/JATSParser/Body/Par.php @@ -0,0 +1,71 @@ +findExtractRemoveBlockElements($paragraph, $xpath); + + // Parse content: text nodes and inline-graphic elements in document order + $content = array(); + $parNodes = $xpath->query(".//text()|.//inline-graphic", $paragraph); + foreach ($parNodes as $parNode) { + if ($parNode->nodeType === XML_TEXT_NODE) { + $content[] = new Text($parNode); + } elseif ($parNode->nodeType === XML_ELEMENT_NODE) { + $content[] = new InlineGraphic($parNode); + } + } + $this->content = $content; + } + + public function getContent(): array { + return $this->content; + } + + public function getBlockElements() { + return $this->blockElements; + } + + /** + * @param \DOMElement $paragraph + * @param \DOMXPath $xpath + * @brief Method aimed at finding block elements inside the paragraph, save as an array property and delete them from the DOM + */ + private function findExtractRemoveBlockElements(\DOMElement $paragraph, \DOMXPath $xpath): void + { + $expression = ""; + $blockNodesMappedArray = AbstractElement::mappedBlockElements(); + $lastKey = array_key_last($blockNodesMappedArray); + foreach ($blockNodesMappedArray as $key => $nodeString) { + $expression .= ".//" . $nodeString; + if ($key !== $lastKey) { + $expression .= "|"; + } + } + + $blockElements = $xpath->query($expression, $paragraph); + if (empty($blockElements)) return; + + foreach ($blockElements as $blockElement) { + if ($className = array_search($blockElement->tagName, $blockNodesMappedArray)) { + $className = "JATSParser\Body\\" . $className; + $jatsBlockEl = new $className($blockElement); + $this->blockElements[] = $jatsBlockEl; + } + + $blockElement->parentNode->removeChild($blockElement); + } + + } +} diff --git a/JATSParser/src/JATSParser/Body/Preformat.php b/JATSParser/src/JATSParser/Body/Preformat.php new file mode 100644 index 00000000..659ab3f8 --- /dev/null +++ b/JATSParser/src/JATSParser/Body/Preformat.php @@ -0,0 +1,21 @@ +content = $element->textContent; + $this->contentType = $element->nodeName; // 'preformat' or 'code' + } + + public function getContent(): string { + return $this->content; + } + + public function getContentType(): string { + return $this->contentType; + } +} diff --git a/JATSParser/src/JATSParser/Body/Row.php b/JATSParser/src/JATSParser/Body/Row.php new file mode 100644 index 00000000..f81ae540 --- /dev/null +++ b/JATSParser/src/JATSParser/Body/Row.php @@ -0,0 +1,53 @@ +parentNode; + switch ($rowParents->nodeName) { + case "thead": + $this->type = 1; + break; + case "tbody": + $this->type = 2; + break; + case "table": + $this->type = 3; + break; + default: + $this->type = 3; + break; + } + + $content = array(); + $cellNodes = $this->xpath->query(".//td|.//th", $rowNode); + foreach ($cellNodes as $cellNode) { + $cell = new Cell($cellNode); + $content[] = $cell; + } + $this->content = $content; + } + + public function getContent(): array { + return $this->content; + } + + public function getType(): int { + return $this->type; + } +} \ No newline at end of file diff --git a/JATSParser/src/JATSParser/Body/Section.php b/JATSParser/src/JATSParser/Body/Section.php new file mode 100644 index 00000000..cb741a12 --- /dev/null +++ b/JATSParser/src/JATSParser/Body/Section.php @@ -0,0 +1,152 @@ + what means section, subsection, subsubsection, etc. */ + private $type; + + /* unique section id */ + private $id; + + /* @var $content array */ + private $content; + + private $hasSections; + + private $childSectionsTitles = array(); + + function __construct(\DOMElement $section) { + parent::__construct($section); + + $this->title = $this->extractFromElement("title", $section); + $this->id = $this->extractFromElement("./@id", $section); + + $this->extractType($section); + $this->ifHasSections($section); + $this->extractContent($section); + } + + public function getTitle() : ?string { + return $this->title; + } + + public function getContent() : array { + return $this->content; + } + + public function getType() : int { + return $this->type; + } + + public function hasSections() : bool { + return $this->hasSections; + } + + public function getChildSectionsTitles(): array + { + return $this->childSectionsTitles; + } + + + private function extractType(\DOMElement $section) { + $parentElements = $this->xpath->query("parent::sec", $section); + if (!is_null($parentElements)) { + $this->type += 1; + foreach ($parentElements as $parentElement) { + $this->extractType($parentElement); + } + } + } + + private function ifHasSections (\DOMElement $section) { + $childSections = $this->xpath->query("sec", $section); + if ($childSections->length > 0) { + $this->hasSections = true; + } else { + $this->hasSections = false; + } + $sectionsTitles = $this->xpath->query("sec/title", $section); + foreach ($sectionsTitles as $sectionsTitle) { + $this->childSectionsTitles[] = $sectionsTitle->textContent; + } + } + + private function extractContent (\DOMElement $section) { + $content = array(); + $sectionNodes = $this->xpath->evaluate("./node()", $section); + foreach ($sectionNodes as $key => $sectionElement) { + switch ($sectionElement->nodeName) { + case "p": + $par = new Par($sectionElement); + $content[] = $par; + if (!empty($par->getBlockElements())) { + foreach ($par->getBlockElements() as $blockElement) { + $content[] = $blockElement; + } + } + break; + case "list": + $list = new Listing($sectionElement); + $content[] = $list; + break; + case "table-wrap": + $table = new Table($sectionElement); + $content[] = $table; + break; + case "fig": + $figure = new Figure($sectionElement); + $content[] = $figure; + break; + case "media": + $media = new Media($sectionElement); + $content[] = $media; + break; + case "disp-quote": + $dispQuote = new DispQuote($sectionElement); + $content[] = $dispQuote; + break; + case "#text": + if (trim($sectionElement->nodeValue) != "") { + $text = new Text($sectionElement); + $content[] = $text; + } + break; + case "verse-group": + $versa = new Verse($sectionElement); + $content[] = $versa; + break; + case "boxed-text": + $boxedText = new BoxedText($sectionElement); + $content[] = $boxedText; + break; + case "def-list": + $defList = new DefList($sectionElement); + $content[] = $defList; + break; + case "preformat": + case "code": // block-level code element + $preformat = new Preformat($sectionElement); + $content[] = $preformat; + break; + case "disp-formula": + $dispFormula = new DispFormula($sectionElement); + $content[] = $dispFormula; + break; + } + } + $this->content = $content; + } + +} diff --git a/JATSParser/src/JATSParser/Body/Table.php b/JATSParser/src/JATSParser/Body/Table.php new file mode 100644 index 00000000..3dd49b52 --- /dev/null +++ b/JATSParser/src/JATSParser/Body/Table.php @@ -0,0 +1,89 @@ +label = $this->extractFromElement(".//label", $tableWraper); + $this->link = $this->extractFromElement("./@xlink:href", $tableWraper); + $this->id = $this->extractFromElement("./@id", $tableWraper); + $this->title = $this->extractTitleOrCaption($tableWraper, self::JATS_EXTRACT_TITLE); + $this->notes = $this->extractTitleOrCaption($tableWraper, self::JATS_EXTRACT_CAPTION); + + $this->extractContent($tableWraper); + } + + public function getContent(): ?array { + return $this->content; + } + + public function getId(): ?string { + return $this->id; + } + + public function getLabel(): ?string { + return $this->label; + } + + public function getTitle(): ?array { + return $this->title; + } + + public function getNotes(): ?array { + return $this->notes; + } + + + private function extractContent(\DOMElement $tableWraper) { + $content = array(); + + $tableHeadNode = $this->xpath->query(".//thead", $tableWraper); + if ($tableHeadNode->length > 0) { + $this->hasHead = TRUE; + } else { + $this->hasHead = FALSE; + } + + $tableBodyNode = $this->xpath->query(".//tbody", $tableWraper); + if ($tableBodyNode->length > 0) { + $this->hasBody = TRUE; + } else { + $this->hasBody = FALSE; + } + + $rowNodes = $this->xpath->query(".//tr", $tableWraper); + foreach ($rowNodes as $rowNode) { + $row = new Row($rowNode); + $content[] = $row; + } + $this->content = $content; + } + +} diff --git a/JATSParser/src/JATSParser/Body/Text.php b/JATSParser/src/JATSParser/Body/Text.php new file mode 100644 index 00000000..3068fdda --- /dev/null +++ b/JATSParser/src/JATSParser/Body/Text.php @@ -0,0 +1,77 @@ + 2 dimensional array where key is actual xref element's attribute and value - it's value + * sup + * sub + */ + + private $type; + + private $content; + + //private static $nodeCheck = array("bold", "italic", "sup", "sub", "xref", "underline", "monospace", "ext-link", "sc", "strike", "named-content", "styled-content", "abbrev", "code", "comment"); + private static $nodeCheck = array("bold", "italic", "sup", "sub", "xref", "underline", "monospace", "ext-link", "sc", "strike", "named-content", "styled-content", "abbrev", "code", "comment", "roman", "overline", "email", "uri", "inline-formula"); + + + public function __construct(\DOMText $paragraphContent) { + $this->content = $paragraphContent->textContent; + $this->extractTextNodeModifiers($paragraphContent); + /* assign normal as a value to a text run if it has non */ + if ($this->type === NULL) { + $this->type[] = "normal"; + } + } + + /** + * @return string + */ + + public function getContent() : string { + return $this->content; + } + + /** + * @return string[] + */ + public function getType(): array { + return $this->type; + } + + /** + * @return string[] + */ + public static function getNodeCheck(): array { + return self::$nodeCheck; + } + + /** + * @param \DOMText \DOMElement + */ + private function extractTextNodeModifiers($paragraphContent) { + /* @var $parentNode \DOMElement */ + $parentNode = $paragraphContent->parentNode; + if (in_array($parentNode->nodeName, self::$nodeCheck)) { + $this->extractTextNodeModifiers($parentNode); + if ($parentNode->nodeName === 'xref' || $parentNode->nodeName === 'ext-link') { + $attributes = Document::getXpath()->query('@*', $parentNode); + /* Need to rewrite DOMNodeList to a simple associative array */ + $xrefAttributes = array(); + foreach ($attributes as $attribute => $value) { + $xrefAttributes[$value->nodeName] = $value->nodeValue; + } + $this->type[][$parentNode->nodeName] = $xrefAttributes; + } else { + $this->type[] = $parentNode->nodeName; + } + } + } +} diff --git a/JATSParser/src/JATSParser/Body/Verse.php b/JATSParser/src/JATSParser/Body/Verse.php new file mode 100644 index 00000000..d735417c --- /dev/null +++ b/JATSParser/src/JATSParser/Body/Verse.php @@ -0,0 +1,31 @@ +xpath->query("verse-line", $element); + foreach ($verseItemNodes as $verseItemNode) { + $verseItem = $this->extractFormattedText(".", $verseItemNode); + $this->content[] = $verseItem; + } + + $this->attrib = $this->extractFormattedText(".//attrib", $element); + + } + + public function getContent(): array { + return $this->content; + } + + public function getAttrib(): array { + return $this->attrib; + } +} diff --git a/JATSParser/src/JATSParser/HTML/Cell.php b/JATSParser/src/JATSParser/HTML/Cell.php new file mode 100644 index 00000000..b5fd9dd9 --- /dev/null +++ b/JATSParser/src/JATSParser/HTML/Cell.php @@ -0,0 +1,46 @@ +getColspan()) { + $this->setAttribute("colspan", $cell->getColspan()); + } + + + if ($cell->getRowspan()) { + $this->setAttribute("rowspan", $cell->getRowspan()); + } + + // set some style + + if ($cell->getColspan() > 1) { + $this->setAttribute("align", "center"); + } + + foreach ($cell->getContent() as $cellContents) { + switch (get_class($cellContents)) { + case "JATSParser\Body\Par": + $par = new Par(); + $this->appendChild($par); + $par->setContent($cellContents); + break; + case "JATSParser\Body\Text": + case "JATSParser\Body\InlineGraphic": + HTMLText::extractText($cellContents, $this); + break; + } + } + } +} diff --git a/JATSParser/src/JATSParser/HTML/Document.php b/JATSParser/src/JATSParser/HTML/Document.php new file mode 100644 index 00000000..e49e745c --- /dev/null +++ b/JATSParser/src/JATSParser/HTML/Document.php @@ -0,0 +1,454 @@ +preserveWhiteSpace = false; + $this->formatOutput = true; + $this->jatsDocument = $jatsDocument; + + $articleSections = $this->jatsDocument->getArticleSections(); + $this->extractContent($articleSections); + } + + /** + * @param string $citationStyle see: https://github.com/citation-style-language/styles + * @param string $lang language for citation styling + * @param bool $styleInTextLinks whether to style in-text links to references + */ + public function setReferences(string $citationStyle = JATSPARSER_CITEPROC_STYLE_DEFAULT, string $lang = JATSPARSER_CITEPROC_LANG_DEFAULT, bool $styleInTextLinks = false): void { + $this->citationStyle = $citationStyle; + $this->citationLang = $lang; + $this->styleInTextLinks = $styleInTextLinks; + if (!empty($this->jatsDocument->getReferences())) { + $this->extractReferences($this->jatsDocument->getReferences()); + } + } + + public function getHmtlForGalley() { + return $this->saveHTML(); + } + + public function getHtmlForTCPDF() { + + // set text-wide styles; + $xpath = new \DOMXPath($this); + $referenceLinks = $xpath->evaluate("//a[@class=\"bibr\"]"); + foreach ($referenceLinks as $referenceLink) { + $referenceLink->setAttribute("style", "background-color:#e6f2ff; color:#1B6685; text-decoration:none;"); + } + + $tableAndFigureLinks = $xpath->evaluate("//a[@class=\"table\"]|//a[@class=\"fig\"]"); + foreach ($tableAndFigureLinks as $tableAndFigureLink) { + $tableAndFigureLink->setAttribute("style", "background-color:#c6ecc6; color:#495A11; text-decoration:none;"); + } + + $headerOnes = $xpath->evaluate("//h2"); + foreach ($headerOnes as $headerOne) { + $headerOne->setAttribute("style", "color: #343a40; font-size:20px;"); + } + + $headerTwos = $xpath->evaluate("//h3"); + foreach ($headerTwos as $headerTwo) { + $headerTwo->setAttribute("style", "color: #343a40; font-size: 16px;"); + } + + // set style for figures and table + $tableNodes = $xpath->evaluate("//table"); + foreach ($tableNodes as $tableNode) { + $tableNode->setAttribute("style", "font-size:10px;"); + $tableNode->setAttribute("border", "1"); + $tableNode->setAttribute("cellpadding", "2"); + } + + $captionNodes = $xpath->evaluate("//figure/p[@class=\"caption\"]|//table/caption"); + + foreach ($captionNodes as $captionNode) { + $captionNode->setAttribute("style", "font-size:10px;display:block;"); + $forBoldNodes = $xpath->evaluate("span[@class=\"label\"]", $captionNode); + foreach ($forBoldNodes as $forBoldNode) { + $forBoldNode->setAttribute("style", "font-weight:bold;font-size:10px;"); + $emptyTextNode = $this->createTextNode(" "); + $forBoldNode->appendChild($emptyTextNode); + } + $forItalicNodes = $xpath->evaluate("span[@class=\"title\"]", $captionNode); + foreach ($forItalicNodes as $forItalicNode) { + $forItalicNode->setAttribute("style", "font-style:italic;font-size:10px;"); + $emptyTextNode = $this->createTextNode(" "); + $forItalicNode->appendChild($emptyTextNode); + } + $forNotesNodes = $xpath->evaluate("span[@class=\"notes\"]", $captionNode); + foreach ($forNotesNodes as $forNotesNode) { + $forNotesNode->setAttribute("style", "font-size:10px;"); + } + } + + $tableCaptions = $xpath->evaluate("//table/caption"); + foreach ($tableCaptions as $tableCaption) { + /* @var $tableNode \DOMNode */ + $tableNode = $tableCaption->parentNode; + $divNode = $this->createElement("div"); + $nextToTableNode = $tableNode->nextSibling; + if ($nextToTableNode) { + $tableNode->parentNode->insertBefore($divNode, $nextToTableNode); + } + $divNode->appendChild($tableCaption); + + } + + // final preparations + $htmlString = $this->saveHTML(); + /* For HTML editing in UTF-8 should be used: $htmlString = $this->saveHTML($this); */ + + $htmlString = preg_replace("/
  • \s*/", "
  • ", $htmlString); + + return $htmlString; + } + + /** + * @param $articleSections array; + */ + protected function extractContent(array $articleSections, \DOMElement $element = null): void { + + if ($element) { + $parentEl = $element; + } else { + $parentEl = $this; + } + + foreach ($articleSections as $articleSection) { + + switch (get_class($articleSection)) { + case "JATSParser\Body\Par": + $par = new Par(); + $parentEl->appendChild($par); + $par->setContent($articleSection); + break; + case "JATSParser\Body\Listing": + $listing = new Listing($articleSection->getStyle()); + $parentEl->appendChild($listing); + $listing->setContent($articleSection); + break; + case "JATSParser\Body\Table": + $table = new Table(); + $parentEl->appendChild($table); + $table->setContent($articleSection); + break; + case "JATSParser\Body\Figure": + $figure = new Figure(); + $parentEl->appendChild($figure); + $figure->setContent($articleSection); + break; + case "JATSParser\Body\Media": + $media = new Media(); + $parentEl->appendChild($media); + $media->setContent($articleSection); + break; + case "JATSParser\Body\Section": + if ($articleSection->getTitle()) { + $sectionElement = $this->createElement("h" . ($articleSection->getType() + 1), $articleSection->getTitle()); + $sectionElement->setAttribute("class", "article-section-title"); + $parentEl->appendChild($sectionElement); + } + $this->extractContent($articleSection->getContent()); + break; + case "JATSParser\Body\DispQuote": + $blockQuote = $this->createElement("blockquote"); + if ($articleSection->getTitle()) { + $sectionElement = $this->createElement("h" . ($articleSection->getType() + 1), $articleSection->getTitle()); + $sectionElement->setAttribute("class", "article-dispquote-title"); + $blockQuote->appendChild($sectionElement); + } + $parentEl->appendChild($blockQuote); + $this->extractContent($articleSection->getContent(), $blockQuote); + if (!empty($quoteAttribTexts = $articleSection->getAttrib())) { + $quoteCite = $this->createElement("cite"); + $blockQuote->appendChild($quoteCite); + foreach ($quoteAttribTexts as $quoteAttribText) { + Text::extractText($quoteAttribText, $quoteCite); + } + } + break; + case "JATSParser\Body\Verse": + $verseGroup = new Verse(); + $parentEl->appendChild($verseGroup); + $verseGroup->setContent($articleSection); + break; + case "JATSParser\Body\Text": + // For elements that extend Section, like disp-quote + Text::extractText($articleSection, $parentEl); + break; + case "JATSParser\Body\BoxedText": + $boxedDiv = $this->createElement('div'); + $boxedDiv->setAttribute('class', 'boxed-text'); + if ($articleSection->getTitle()) { + $titleEl = $this->createElement('p'); + $titleEl->setAttribute('class', 'boxed-text-title'); + $titleEl->nodeValue = htmlspecialchars($articleSection->getTitle()); + $boxedDiv->appendChild($titleEl); + } + $parentEl->appendChild($boxedDiv); + $this->extractContent($articleSection->getContent(), $boxedDiv); + break; + case "JATSParser\Body\DefList": + $dl = $this->createElement('dl'); + if ($articleSection->getTitle()) { + $titleEl = $this->createElement('p'); + $titleEl->setAttribute('class', 'def-list-title'); + $titleEl->nodeValue = htmlspecialchars($articleSection->getTitle()); + $dl->appendChild($titleEl); + } + foreach ($articleSection->getContent() as $item) { + $dt = $this->createElement('dt'); + foreach ($item['term'] as $termText) { + Text::extractText($termText, $dt); + } + $dl->appendChild($dt); + $dd = $this->createElement('dd'); + foreach ($item['def'] as $defText) { + Text::extractText($defText, $dd); + } + $dl->appendChild($dd); + } + $parentEl->appendChild($dl); + break; + case "JATSParser\Body\Preformat": + $pre = $this->createElement('pre'); + $code = $this->createElement('code'); + $code->appendChild($this->createTextNode($articleSection->getContent())); + $pre->appendChild($code); + $parentEl->appendChild($pre); + break; + case "JATSParser\Body\DispFormula": + $formulaDiv = $this->createElement('div'); + $formulaDiv->setAttribute('class', 'disp-formula'); + if ($articleSection->getId()) { + $formulaDiv->setAttribute('id', $articleSection->getId()); + } + if ($articleSection->hasLatex()) { + $formulaSpan = $this->createElement('span'); + $formulaSpan->setAttribute('class', 'math display'); + $formulaSpan->appendChild($this->createTextNode('\[' . $articleSection->getTexContent() . '\]')); + $formulaDiv->appendChild($formulaSpan); + } else { + $formulaDiv->appendChild($this->createTextNode($articleSection->getTextContent())); + } + if ($articleSection->getLabel()) { + $labelSpan = $this->createElement('span'); + $labelSpan->setAttribute('class', 'label'); + $labelSpan->nodeValue = htmlspecialchars($articleSection->getLabel()); + $formulaDiv->appendChild($labelSpan); + } + $parentEl->appendChild($formulaDiv); + break; + } + } + } + + protected function extractReferences (array $references): void { + + $referencesHeading = $this->createElement("h2"); + $referencesHeading->setAttribute("class", "article-section-title"); + $referencesHeading->setAttribute("id", "reference-title"); + $referencesHeading->nodeValue = "References"; + $this->appendChild($referencesHeading); + + $data = []; + $rawData = []; + foreach ($references as $reference) { + $citeProcRef = new Reference($reference); + if (!$citeProcRef->refIsEmpty()) { + $data[] = $citeProcRef->getContent(); + } elseif ($citeProcRef->getJatsReference()->isMixed() && !empty(trim($citeProcRef->getJatsReference()->getRawReference()))) { + $rawData[] =$citeProcRef->getJatsReference(); + } else { + error_log("WARNING: reference with id " . $reference->getId() . " is invalid and cannot be parsed"); + } + } + + $this->citeProcReferences = $data; + + $style = StyleSheet::loadStyleSheet($this->getCitationStyle()); + + $wrapIntoListItem = function($cslItem, $renderedText) { + return '
  • ' . $renderedText . '
  • '; + }; + + $additionalMarkup = [ + 'bibliography' => [ + 'csl-entry' => $wrapIntoListItem + ] + ]; + + $citeProc = new CiteProc($style, $this->citationLang, $additionalMarkup); + $htmlString = $citeProc->render($data, 'bibliography'); + + if ($this->styleInTextLinks) { + $this->setInTextLinks($citeProc, $data); + } + + $this->getCiteBody($htmlString, $rawData); + } + + protected function getCiteBody(string $htmlString, array $rawData) { + $document = new \DOMDocument('1.0', 'utf-8'); + $document->loadXML($htmlString); + + $listEl = $this->createElement('ol'); + $listEl->setAttribute('class', 'references'); + $listEl->setAttribute('id', JATSPARSER_REFERENCE_ELEMENT_ID); + $this->appendChild($listEl); + + $xpath = new \DOMXPath($document); + $listItemEls = $xpath->query('//li'); + foreach ($listItemEls as $listItemEl) { + $newListItemEl = $this->createElement('li'); + $newListItemEl->setAttribute('id', $listItemEl->getAttribute('id')); + $listEl->appendChild($newListItemEl); + + $nodeList = $xpath->query('div[@class="csl-right-inline"]/node()', $listItemEl); + if ($nodeList->count() > 0) { + foreach ($nodeList as $node) { + $newNode = $this->importNode($node, true); + $newListItemEl->appendChild($newNode); + } + } else { + $nodeList = $xpath->query('node()', $listItemEl); { + foreach ($nodeList as $node) { + $newNode = $this->importNode($node, true); + $newListItemEl->appendChild($newNode); + } + } + } + } + // Append data from mixed citation nodes that don't contain valid ref data for CSL + foreach ($rawData as $rawRefObject) { + $newListItemEl = $this->createElement('li'); + $newListItemEl->setAttribute('id', $rawRefObject->getId()); + $textRefNode = $this->createTextNode(trim($rawRefObject->getRawReference())); + $newListItemEl->appendChild($textRefNode); + $listEl->appendChild($newListItemEl); + } + } + + protected function setInTextLinks($citeProc, $data) { + + $xpath = new \DOMXPath($this); + $links = $xpath->query('//a[@class="bibr"]'); + foreach ($links as $link) { + $linkId = $link->getAttribute('href'); + if ($linkId) { + $citeObject = new \stdClass(); + $citeObject->id = str_replace("#", "", $linkId); + $link->nodeValue = $citeProc->render($data, "citation", [$citeObject]); + } + } + } + + public function getCitationStyle(): string { + return $this->citationStyle; + } + + public function saveAsValidHTML(string $documentTitle, bool $prettyPrint = false): string { + if ($prettyPrint) { + $xpath = new \DOMXPath($this); + $nodes = $xpath->query('//text()'); + foreach ($nodes as $node) { + $node->nodeValue = preg_replace("/[\\s]{2,}/", " ", $node->nodeValue); + } + } + + $htmlString = $this->saveAsHTML(); + + $htmlString = + '' . "\n" . + '' . "\n" . + '' . "\n" . + "\t" . '' . "\n" . + "\t" . '' . htmlspecialchars($documentTitle) . '' . "\n" . + '' . "\n" . + '' . "\n" . + $htmlString . + ''. "\n" . + ''; + + return $htmlString; + + } + + public function saveAsHTML($element = null) { + + $htmlString = $element ? $this->saveXML($element) : $this->saveXML($this); + + $xmlDeclaration = ''; + $pos = strpos($htmlString, $xmlDeclaration); + if ($pos !== false) { + $htmlString = substr_replace($htmlString, '', $pos, strlen($xmlDeclaration)); + } + + return $htmlString; + } + + /** + * @param string $filename path to the file to write a file + * @param string $documentTitle document title that is required for HTML to be valid + * @param bool $prettyPrint + * @return void + */ + public function saveAsValidHTMLFile(string $filename, string $documentTitle, bool $prettyPrint = true): void { + file_put_contents($filename, $this->saveAsValidHTML($documentTitle, $prettyPrint)); + } + + /** + * @return array of references, where key is unique id, ordered according to appearance in JATS XML + */ + public function getRawReferences(): array { + $references = []; + + $refListEl = null; + + // DOMDocument::getElementById or xpath analog won't work presumably because the absence of a root element + foreach ($this->getElementsByTagName('ol') as $ol) { + if ($ol->getAttribute('id') == JATSPARSER_REFERENCE_ELEMENT_ID) { + $refListEl = $ol; + } + } + + if (!$refListEl) return $references; + + foreach ($refListEl->childNodes as $refItemEl) { + $htmlString = ''; + foreach ($refItemEl->childNodes as $refContent) { + $htmlString .= $this->saveAsHTML($refContent); + } + + if ($refItemEl->hasAttribute('id')) { + $references[$refItemEl->getAttribute('id')] = $htmlString; + } else { + $references[] = $htmlString; + } + } + + return $references; + } +} diff --git a/JATSParser/src/JATSParser/HTML/Figure.php b/JATSParser/src/JATSParser/HTML/Figure.php new file mode 100644 index 00000000..91d8da60 --- /dev/null +++ b/JATSParser/src/JATSParser/HTML/Figure.php @@ -0,0 +1,68 @@ +ownerDocument->createElement("div"); + $divNode->setAttribute("class", "figure"); + $this->appendChild($divNode); + + $srcNode = $this->ownerDocument->createElement("img"); + $divNode->appendChild($srcNode); + $srcNode->setAttribute("src", rawurlencode($jatsFigure->getLink())); + + $titleNode = $this->ownerDocument->createElement("p"); + $titleNode->setAttribute("class", "caption"); + $this->appendChild($titleNode); + + // Set figure id. Needed for links from referenceces to the figure + $this->setAttribute("id", $jatsFigure->getId()); + + // Set figure label (e.g., Figure 1) + if ($jatsFigure->getLabel()) { + $spanLabel = $this->ownerDocument->createElement("span"); + $spanLabel->setAttribute("class", "label"); + $titleNode->appendChild($spanLabel); + $textNode = $this->ownerDocument->createTextNode(HTMLText::checkPunctuation($jatsFigure->getLabel())); + $spanLabel->appendChild($textNode); + } + + /* Set figure title + * @var $figureTitle JATSText + */ + if (count($jatsFigure->getTitle()) > 0) { + $spanTitle = $this->ownerDocument->createElement("span"); + $spanTitle->setAttribute("class", "title"); + $titleNode->appendChild($spanTitle); + foreach ($jatsFigure->getTitle() as $figureTitle) { + HTMLText::extractText($figureTitle, $spanTitle); + } + } + + /* Set figure notes + * @var $figureContent JATSPar + */ + if (count($jatsFigure->getContent()) > 0) { + foreach ($jatsFigure->getContent() as $figureContent) { + $par = new Par("span"); + $titleNode->appendChild($par); + $par->setAttribute("class", "notes"); + $par->setContent($figureContent); + } + } + } + +} diff --git a/JATSParser/src/JATSParser/HTML/HTMLElement.php b/JATSParser/src/JATSParser/HTML/HTMLElement.php new file mode 100644 index 00000000..6dbe34b6 --- /dev/null +++ b/JATSParser/src/JATSParser/HTML/HTMLElement.php @@ -0,0 +1,6 @@ +getContent() as $jatsListItem) { + $listItem = $this->ownerDocument->createElement("li"); + $this->appendChild($listItem); + foreach ($jatsListItem as $jatsListText) { + if (get_class($jatsListText) === "JATSParser\Body\Text") { + HTMLText::extractText($jatsListText, $listItem); + } elseif (get_class($jatsListText) === "JATSParser\Body\Listing") { + /* @var $jatsListText JATSListing */ + $nestedList = new Listing($jatsListText->getStyle()); + $listItem->appendChild($nestedList); + $nestedList->setContent($jatsListText); + } elseif (get_class($jatsListText) === "JATSParser\Body\Par") { + foreach ($jatsListText->getContent() as $jatsInsideText) { + HTMLText::extractText($jatsInsideText, $listItem); + } + + /* Paragraphs inside list are not supported by TCPDF + * + $listPar = new Par(); + $listItem->appendChild($listPar); + $listPar->setContent($jatsListText); + */ + } + } + } + } + +} diff --git a/JATSParser/src/JATSParser/HTML/Media.php b/JATSParser/src/JATSParser/HTML/Media.php new file mode 100644 index 00000000..864cdaef --- /dev/null +++ b/JATSParser/src/JATSParser/HTML/Media.php @@ -0,0 +1,63 @@ +setAttribute("class", "media-wrapper"); + + $imageIframe = $this->ownerDocument->createElement("iframe"); + $imageIframe->setAttribute("src", $jatsMedia->getLink()); + $this->appendChild($imageIframe); + + + $captionNode = $this->ownerDocument->createElement("div"); + $captionNode->setAttribute("class", "caption"); + $this->appendChild($captionNode); + + // Set media label (e.g., Figure 1) + + if ($jatsMedia->getLabel()) { + $spanLabel = $this->ownerDocument->createElement("span"); + $spanLabel->setAttribute("class", "label"); + $captionNode->appendChild($spanLabel); + $textNode = $this->ownerDocument->createTextNode(HTMLText::checkPunctuation($jatsMedia->getLabel())); + $spanLabel->appendChild($textNode); + } + + /* Set media title + * @var $mediaTitle JATSText + */ + + if ($jatsMedia->getTitle() && count($jatsMedia->getTitle()) > 0) { + $spanTitle = $this->ownerDocument->createElement("span"); + $spanTitle->setAttribute("class", "title"); + $captionNode->appendChild($spanTitle); + foreach ($jatsMedia->getTitle() as $mediaTitle) { + HTMLText::extractText($mediaTitle, $spanTitle); + } + } + + /* Set media caption + * @var $mediaCaption JATSText + */ + + if ($jatsMedia->getContent() && count($jatsMedia->getContent()) > 0) { + foreach ($jatsMedia->getContent() as $jatsContent) { + $par = new Par("span"); + $captionNode->appendChild($par); + $par->setAttribute("class", "notes"); + $par->setContent($jatsContent); + } + } + } +} \ No newline at end of file diff --git a/JATSParser/src/JATSParser/HTML/Par.php b/JATSParser/src/JATSParser/HTML/Par.php new file mode 100644 index 00000000..8ccba91d --- /dev/null +++ b/JATSParser/src/JATSParser/HTML/Par.php @@ -0,0 +1,19 @@ +getContent() as $jatsContent) { + HTMLText::extractText($jatsContent, $this); + } + } +} diff --git a/JATSParser/src/JATSParser/HTML/Reference.php b/JATSParser/src/JATSParser/HTML/Reference.php new file mode 100644 index 00000000..17645c6c --- /dev/null +++ b/JATSParser/src/JATSParser/HTML/Reference.php @@ -0,0 +1,162 @@ +jatsReference = $jatsReference; + $this->setContent(); + } + + public function setContent() { + if (!isset($this->content)) $this->content = new \stdClass(); + + $this->setSimpleProperty('id', 'getId'); + + if (!empty($this->jatsReference->getAuthors())) { + foreach ($this->jatsReference->getAuthors() as $individual) { + if (get_class($individual) == 'JATSParser\Back\Individual') { /** @var $individual Individual */ + $author = new \stdClass(); + if (!empty($individual->getGivenNames())) { + $author->family = $individual->getSurname(); + } + + if (!empty($individual->getSurname())) { + $author->given = $individual->getGivenNames(); + } + + $this->content->author[] = $author; + + } + } + } + + if (!empty($this->jatsReference->getEditors())) { + foreach ($this->jatsReference->getEditors() as $individual) { + if (get_class($individual) == 'JATSParser\Back\Individual') { /** @var $individual Individual */ + $editor = new \stdClass(); + if (!empty($individual->getGivenNames())) { + $editor->family = $individual->getSurname(); + } + + if (!empty($individual->getSurname())) { + $editor->given = $individual->getGivenNames(); + } + + $this->content->editor[] = $editor; + } + } + } + + $this->setSimpleProperty('url', 'getUrl'); + $this->setSimpleProperty('title', 'getTitle'); + + // specific properties + if (checkdate(1, 1, (int) $this->jatsReference->getYear())) { + $this->setDate('issued', 'getYear'); + } + $this->setSimpleProperty('container-title', 'getJournal'); + $this->setSimpleProperty('journal', 'getJournal'); + $this->setSimpleProperty('volume', 'getVolume'); + $this->setSimpleProperty('issue', 'getIssue'); + $this->setSimpleProperty('page-first', 'getFpage'); + $this->setSimpleProperty('page', 'getPages'); + + if (method_exists($this->jatsReference, 'getPubIdType') && array_key_exists('doi', $this->jatsReference->getPubIdType())) { + $this->content->{'DOI'} = $this->jatsReference->getPubIdType()['doi']; + } + + $this->setSimpleProperty('publisher', 'getPublisherName'); + $this->setSimpleProperty('publisher-place', 'getPublisherLoc'); + $this->setSimpleProperty('container-title', 'getBook'); + $this->setSimpleProperty('event', 'getConfName'); + $this->setDate('event-date', 'getConfDate'); + $this->setSimpleProperty('event-place', 'getConfLoc'); + + switch (get_class($this->jatsReference)) { + + case "JATSParser\Back\Journal": + + /* @var $jatsReference Journal */ + $this->content->type = 'article-journal'; + break; + + case "JATSParser\Back\Book": + + /* @var $jatsReference Book */ + $this->content->type = 'book'; + + break; + + case "JATSParser\Back\Chapter": + + /* @var $jatsReference Chapter */ + $this->content->type = 'chapter'; + + break; + + case "JATSParser\Back\Conference": + + /* @var $jatsReference Conference */ + $this->content->type = 'conference'; + + break; + } + } + + /** + * @return array + */ + public function getContent(): \stdClass + { + return $this->content; + } + + /** + * @param $property string JSON property + * @param $method string method to retrieve property from JATS Parser Reference + * @return void + */ + protected function setSimpleProperty(string $property, string $method): void { + if (method_exists($this->jatsReference, $method) && !empty($this->jatsReference->$method())) { + $this->content->{$property} = $this->jatsReference->$method(); + } + } + + protected function setDate(string $property, string $method): void { + if (method_exists($this->jatsReference, $method) && !empty($this->jatsReference->$method())) { + $date = new \stdClass(); + $date->{'date-parts'}[][] = $this->jatsReference->$method(); + $this->content->{$property} = $date; + } + } + + /** + * @return bool + * @brief checks if generated CJSON-CSL doesn't contain ref specific info, e.g., title, authors, year. + * TODO find a better way of CSL validation + */ + public function refIsEmpty(): bool { + $csl = (array) $this->content; + // ID and type are assigned irrespectively to the reference content + unset($csl['id']); + unset($csl['type']); + return empty($csl); + } + + public function getJatsReference(): AbstractReference { + return $this->jatsReference; + } +} diff --git a/JATSParser/src/JATSParser/HTML/ReferenceMethods.php b/JATSParser/src/JATSParser/HTML/ReferenceMethods.php new file mode 100644 index 00000000..bba5e71c --- /dev/null +++ b/JATSParser/src/JATSParser/HTML/ReferenceMethods.php @@ -0,0 +1,134 @@ +getAuthors() as $key => $author) { + if (get_class($author) === "JATSParser\Back\Individual") { + + /* @var $author Individual */ + + if ($author->getSurname()) { + $htmlSurname = $domElement->ownerDocument->createTextNode($author->getSurname()); + $domElement->appendChild($htmlSurname); + } + + if ($author->getGivenNames() && $key + 1 < count($jatsReference->getAuthors())) { + $htmlGivenName = $domElement->ownerDocument->createTextNode(" " . $author->getGivenNames() . ", "); + $domElement->appendChild($htmlGivenName); + } elseif ($author->getGivenNames() && $key + 1 === count($jatsReference->getAuthors())) { + $htmlGivenName = $domElement->ownerDocument->createTextNode(" " . $author->getGivenNames() . "."); + $domElement->appendChild($htmlGivenName); + } + } elseif (get_class($author) === "JATSParser\Back\Collaboration") { + + /* @var $author Collaboration */ + if ($author->getName() && $key === 0 && $key + 1 === count($jatsReference->getAuthors())) { + $htmlCollab = $domElement->ownerDocument->createTextNode(trim($author->getName()) . "."); + $domElement->appendChild($htmlCollab); + } elseif ($author->getName() && $key === 0 && $key + 1 < count($jatsReference->getAuthors())) { + $htmlCollab = $domElement->ownerDocument->createTextNode(trim($author->getName()) . ", "); + $domElement->appendChild($htmlCollab); + } elseif ($author->getName() && $key + 1 < count($jatsReference->getAuthors())) { + $htmlCollab = $domElement->ownerDocument->createTextNode(" " . trim($author->getName()) . ", "); + $domElement->appendChild($htmlCollab); + } elseif ($author->getName() && $key + 1 === count($jatsReference->getAuthors())) { + $htmlCollab = $domElement->ownerDocument->createTextNode(" " . trim($author->getName()) . "."); + $domElement->appendChild($htmlCollab); + } + } + } + } + + public static function extractLinks (AbstractReference $jatsReference, \DOMElement $domElement): void { + if ($jatsReference->getUrl() !== "" && !empty($jatsReference->getPubIdType())) { + $urlLink = $domElement->ownerDocument->createElement('a'); + $urlLink->setAttribute("href", $jatsReference->getUrl()); + $urlLink->nodeValue = "Publisher Full Text"; + $domElement->appendChild($urlLink); + + $delimeter = $domElement->ownerDocument->createTextNode(' | '); + $domElement->appendChild($delimeter); + } elseif ($jatsReference->getUrl() !== '') { + $urlLink = $domElement->ownerDocument->createElement('a'); + $urlLink->setAttribute("href", $jatsReference->getUrl()); + $urlLink->nodeValue = "Publisher Full Text"; + $domElement->appendChild($urlLink); + } + + if ($jatsReference->getPubIdType() !== ''){ + $number = 0; + foreach ($jatsReference->getPubIdType() as $key => $pubId) { + if ($key == 'doi') { + $number += 1; + $doiLink = $domElement->ownerDocument->createElement('a'); + $doiLink->setAttribute("href", $pubId); + $doiLink->nodeValue = "DOI"; + $domElement->appendChild($doiLink); + } elseif ($key == "pmid") { + if ($number > 0) { + $pmidDelimeter = $domElement->ownerDocument->createTextNode(' | '); + $domElement->appendChild($pmidDelimeter); + } + $number += 1; + $pmidLink = $domElement->ownerDocument->createElement('a'); + $pmidLink->setAttribute("href", $pubId); + $pmidLink->nodeValue = "PubMed"; + $domElement->appendChild($pmidLink); + } elseif ($key == "pmcid") { + if ($number > 0) { + $pmidDelimeter = $domElement->ownerDocument->createTextNode(' | '); + $domElement->appendChild($pmidDelimeter); + } + $number += 1; + $pmcidLink = $domElement->ownerDocument->createElement('a'); + $pmcidLink->setAttribute("href", $pubId); + $pmcidLink->nodeValue = "PubMed Central"; + + } + } + } + } + + public static function extractEditors(AbstractReference $jatsReference, \DOMElement $domElement) { + foreach ($jatsReference->getEditors() as $key => $author) { + if (get_class($author) === "JATSParser\Back\Individual") { + + /* @var $author Individual */ + + if ($author->getSurname()) { + $htmlSurname = $domElement->ownerDocument->createTextNode($author->getSurname()); + $domElement->appendChild($htmlSurname); + } + + if ($author->getGivenNames() && $key + 1 < count($jatsReference->getEditors())) { + $htmlGivenName = $domElement->ownerDocument->createTextNode(" " . $author->getGivenNames() . ", "); + $domElement->appendChild($htmlGivenName); + } elseif ($author->getGivenNames() && $key + 1 === count($jatsReference->getEditors())) { + $htmlGivenName = $domElement->ownerDocument->createTextNode(" " . $author->getGivenNames() . "."); + $domElement->appendChild($htmlGivenName); + } + } elseif (get_class($author) === "JATSParser\Back\Collaboration") { + + /* @var $author Collaboration */ + if ($author->getName() && $key === 0 && $key + 1 === count($jatsReference->getEditors())) { + $htmlCollab = $domElement->ownerDocument->createTextNode(trim($author->getName()) . "."); + $domElement->appendChild($htmlCollab); + } elseif ($author->getName() && $key === 0 && $key + 1 < count($jatsReference->getEditors())) { + $htmlCollab = $domElement->ownerDocument->createTextNode(trim($author->getName()) . ", "); + $domElement->appendChild($htmlCollab); + } elseif ($author->getName() && $key + 1 < count($jatsReference->getEditors())) { + $htmlCollab = $domElement->ownerDocument->createTextNode(" " . trim($author->getName()) . ", "); + $domElement->appendChild($htmlCollab); + } elseif ($author->getName() && $key + 1 === count($jatsReference->getEditors())) { + $htmlCollab = $domElement->ownerDocument->createTextNode(" " . trim($author->getName()) . "."); + $domElement->appendChild($htmlCollab); + } + } + } + } +} \ No newline at end of file diff --git a/JATSParser/src/JATSParser/HTML/Table.php b/JATSParser/src/JATSParser/HTML/Table.php new file mode 100644 index 00000000..1faab49b --- /dev/null +++ b/JATSParser/src/JATSParser/HTML/Table.php @@ -0,0 +1,121 @@ +ownerDocument->createElement("thead"); + $htmlBody = $this->ownerDocument->createElement("tbody"); + + foreach ($jatsTable->getContent() as $row) { + /* @var $row JATSRow */ + switch ($row->getType()) { + case 1: + $hasHead = true; + $hasHead = true; + $htmlRow = $this->ownerDocument->createElement("tr"); + $htmlHead->appendChild($htmlRow); + foreach ($row->getContent() as $cell) { + + /* @var $cell JATSCell */ + $htmlCell = new Cell($cell->getType()); + $htmlRow->appendChild($htmlCell); + $htmlCell->setContent($cell); + + } + break; + case 2: + $hasBody = true; + $this->extractRowsAndCells($htmlBody, $row); + break; + case 3: + $this->extractRowsAndCells($this, $row); + break; + } + } + + if ($hasHead) { + $this->appendChild($htmlHead); + } + + if ($hasBody) { + $this->appendChild($htmlBody); + } + + // Retrieving caption + $titleNode = $this->ownerDocument->createElement("caption"); + $this->appendChild($titleNode); + + // Set table id for table-wrap. Needed for links from referenceces to the table + $this->setAttribute("id", $jatsTable->getId()); + + // Set figure label (e.g., Figure 1) + if ($jatsTable->getLabel()) { + $spanLabel = $this->ownerDocument->createElement("span"); + $spanLabel->setAttribute("class", "label"); + $titleNode->appendChild($spanLabel); + $textNode = $this->ownerDocument->createTextNode(HTMLText::checkPunctuation($jatsTable->getLabel())); + $spanLabel->appendChild($textNode); + } + + /* Set table title + * @var $tableTitle JATSText + */ + if (count($jatsTable->getTitle()) > 0) { + $spanTitle = $this->ownerDocument->createElement("span"); + $spanTitle->setAttribute("class", "title"); + $titleNode->appendChild($spanTitle); + foreach ($jatsTable->getTitle() as $tableTitle) { + HTMLText::extractText($tableTitle, $spanTitle); + } + } + + /* Set table notes + * @var $jatsTable JATSPar + */ + if (count($jatsTable->getNotes()) > 0) { + foreach ($jatsTable->getNotes() as $tableContent) { + $par = new Par("span"); + $titleNode->appendChild($par); + $par->setAttribute("class", "notes"); + $par->setContent($tableContent); + } + } + + } + + /** + * @param $htmlHead \DOMElement + * @param $row JATSRow + */ + private function extractRowsAndCells(\DOMElement $htmlElement, JATSRow $row): void + { + $htmlRow = $this->ownerDocument->createElement("tr"); + $htmlElement->appendChild($htmlRow); + foreach ($row->getContent() as $cell) { + + /* @var $cell JATSCell */ + $htmlCell = new Cell($cell->getType()); + $htmlRow->appendChild($htmlCell); + $htmlCell->setContent($cell); + + } + } +} \ No newline at end of file diff --git a/JATSParser/src/JATSParser/HTML/Text.php b/JATSParser/src/JATSParser/HTML/Text.php new file mode 100644 index 00000000..88ac1828 --- /dev/null +++ b/JATSParser/src/JATSParser/HTML/Text.php @@ -0,0 +1,190 @@ +getHref(); + if ($href) { + $domDocument = $domElement->ownerDocument ?? $domElement; + $img = $domDocument->createElement('img'); + $img->setAttribute('src', rawurlencode($href)); + $img->setAttribute('alt', ''); + $domElement->appendChild($img); + } + return; + } + // Get DOMDocument + $domDocument = $domElement->ownerDocument; + if (!$domDocument) $domDocument = $domElement; + + // Dealing with simple text (without any properties) + $nodeTypes = $jatsText->getType(); + if (in_array("normal", $nodeTypes)) { + $textNode = $domDocument->createTextNode($jatsText->getContent()); + $domElement->appendChild($textNode); + unset($nodeTypes); + } + + // Renaming text properties into standard HTML node element + $typeArray = array(); + if (isset($nodeTypes)) { + foreach ($nodeTypes as $nodeType) { + switch ($nodeType) { + case "italic": + $typeArray[] = "i"; + break; + case "bold": + $typeArray[] = "b"; + break; + case "sup": + $typeArray[] = "sup"; + break; + case "sub": + $typeArray[] = "sub"; + break; + case "underline": + $typeArray[] = "u"; + break; + case "monospace": + case "code": + $typeArray[] = "code"; + break; + case "sc": + $typeArray[] = ["span" => ["class" => "small-caps"]]; + break; + case "strike": + $typeArray[] = "s"; + break; + case "named-content": + $typeArray[] = ["span" => ["class" => "named-content"]]; + break; + case "styled-content": + $typeArray[] = ["span" => ["class" => "styled-content"]]; + break; + case "abbrev": + $typeArray[] = "abbr"; + break; + case "comment": + $typeArray[] = ["span" => ["class" => "annotation"]]; + break; + case "roman": + $typeArray[] = ["span" => ["class" => "roman"]]; + break; + case "overline": + $typeArray[] = ["span" => ["style" => "text-decoration:overline"]]; + break; + case "email": + $typeArray[] = ["a" => ["href" => "mailto:" . $jatsText->getContent(), "class" => "email"]]; + break; + case "uri": + $typeArray[] = ["a" => ["href" => $jatsText->getContent()]]; + break; + case "inline-formula": + $typeArray[] = ["span" => ["class" => "inline-formula"]]; + break; + case is_array($nodeType): + foreach ($nodeType as $elementName => $elementAttrs) { + if ($elementName === "xref") { + $newArray = array(); + foreach ($elementAttrs as $attrKey => $attrValue) { + if ($attrKey === "rid") { + $newArray ["href"] = "#" . $attrValue; + } elseif ($attrKey === "ref-type") { + $newArray ["class"] = $attrValue; + } else { + $newArray[$attrKey] = $attrValue; + } + } + $typeArray[]["a"] = $newArray; + } else if ($elementName = "ext-link") { + $newArray = array(); + foreach ($elementAttrs as $attrKey => $attrValue) { + if ($attrKey === "xlink:href") { + $newArray["href"] = $attrValue; + } else if ($attrKey = "ext-link-type") { + $newArray["class"] = "JATSParser__link-" . $attrValue; + } + } + $typeArray[]["a"] = $newArray; + } + } + break; + } + } + } + + // Dealing with text that has only one property, e.g. italic, bold, link + if (count($typeArray) === 1) { + foreach ($typeArray as $typeKey => $type) { + if (!is_array($type)) { + $nodeElement = $domDocument->createElement($type); + $nodeElement->nodeValue = htmlspecialchars($jatsText->getContent()); + $domElement->appendChild($nodeElement); + } else { + foreach ($type as $insideKey => $insideType) { + $nodeElement = $domDocument->createElement($insideKey); + $nodeElement->nodeValue = trim(htmlspecialchars($jatsText->getContent())); + if (is_array($insideType)) { + foreach ($insideType as $nodeAttrKey => $nodeAttrValue) { + $nodeElement->setAttribute($nodeAttrKey, $nodeAttrValue); + } + } + $domElement->appendChild($nodeElement); + } + + } + } + + // Dealing with complex cases -> text with several properties + } else { + /* @var $prevElement array of DOMElements */ + $prevElements = array(); + foreach ($typeArray as $key => $type) { + if (!is_array($type)) { + $nodeElement = $domDocument->createElement($type); + } else { + foreach ($type as $insideKey => $insideType) { + $nodeElement = $domDocument->createElement($insideKey); + if (is_array($insideType)) { + foreach ($insideType as $nodeAttrKey => $nodeAttrValue) { + $nodeElement->setAttribute($nodeAttrKey, $nodeAttrValue); + } + } + } + } + + array_push($prevElements, $nodeElement); + + if ($key === 0) { + $domElement->appendChild($prevElements[0]); + } elseif (($key === (count($typeArray) - 1))) { + $nodeElement->nodeValue = htmlspecialchars($jatsText->getContent()); + + foreach ($prevElements as $prevKey => $prevElement) { + if ($prevKey !== (count($prevElements) - 1)) { + $prevElement->appendChild(next($prevElements)); + } + } + } + } + } + } + + public static function checkPunctuation(string $label) + { + $label = trim($label); + if (preg_match("/\.$|:$/", $label, $matches) === 0) { + $label .= "."; + } + return $label; + } + +} diff --git a/JATSParser/src/JATSParser/HTML/Verse.php b/JATSParser/src/JATSParser/HTML/Verse.php new file mode 100644 index 00000000..c7edc5b1 --- /dev/null +++ b/JATSParser/src/JATSParser/HTML/Verse.php @@ -0,0 +1,30 @@ +getContent())) { + foreach ($jatsVerse->getContent() as $item) { + foreach ($item as $text) { + HTMLText::extractText($text, $this); + } + $this->appendChild($this->ownerDocument->createElement("br")); + } + } + + if (!empty($attribTexts = $jatsVerse->getAttrib())) { + $citeElement = $this->ownerDocument->createElement("cite"); + $this->appendChild($citeElement); + foreach ($attribTexts as $attribText) { + Text::extractText($attribText, $citeElement); + } + } + } +} diff --git a/JATSParser/src/JATSParser/PDF/TCPDFDocument.php b/JATSParser/src/JATSParser/PDF/TCPDFDocument.php new file mode 100644 index 00000000..1631c91d --- /dev/null +++ b/JATSParser/src/JATSParser/PDF/TCPDFDocument.php @@ -0,0 +1,90 @@ +header_xobjid === false) { + // start a new XObject Template + $this->header_xobjid = $this->startTemplate($this->w, $this->tMargin); + $headerfont = $this->getHeaderFont(); + $headerdata = $this->getHeaderData(); + $this->y = $this->header_margin; + if ($this->rtl) { + $this->x = $this->w - $this->original_rMargin; + } else { + $this->x = $this->original_lMargin; + } + if (($headerdata['logo']) AND ($headerdata['logo'] != K_BLANK_IMAGE)) { + $imgtype = \TCPDF_IMAGES::getImageFileType($headerdata['logo']); + $headerdata['logo_width'] = 12; + if (($imgtype == 'eps') OR ($imgtype == 'ai')) { + $this->ImageEps($headerdata['logo'], '', '', $headerdata['logo_width']); + } elseif ($imgtype == 'svg') { + $this->ImageSVG($headerdata['logo'], '', '', $headerdata['logo_width']); + } else { + $this->Image($headerdata['logo'], '', 5, $headerdata['logo_width'], 12); + } + $imgy = $this->getImageRBY(); + } else { + $imgy = $this->y; + } + $cell_height = $this->getCellHeight($headerfont[2] / $this->k); + // set starting margin for text data cell + if ($this->getRTL()) { + $header_x = $this->original_rMargin + ($headerdata['logo_width'] * 1.2); + } else { + $header_x = $this->original_lMargin + ($headerdata['logo_width'] * 1.2); + } + $cw = $this->w - $this->original_lMargin - $this->original_rMargin - ($headerdata['logo_width'] * 1.2); + $this->SetTextColorArray($this->header_text_color); + // header title + $this->SetFont('dejavuserif', 'BI', 11); + $this->SetX($header_x); + $this->Cell($cw, $cell_height, $headerdata['title'], 0, 1, '', 0, '', 0); + // header string + $this->SetFont('dejavuserif', '', 9); + $this->SetX($header_x); + $this->MultiCell($cw, $cell_height, $headerdata['string'], 0, '', 0, 1, '', '', true, 0, false, true, 0, 'T', false); + // print an ending header line + $this->SetLineStyle(array('width' => 0.85 / $this->k, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $headerdata['line_color'])); + $this->SetY((2.835 / $this->k) + max($imgy, $this->y)); + if ($this->rtl) { + $this->SetX($this->original_rMargin); + } else { + $this->SetX($this->original_lMargin); + } + $this->Cell(($this->w - $this->original_lMargin - $this->original_rMargin), 0, '', 'T', 0, 'C'); + $this->endTemplate(); + } + // print header template + $x = 0; + $dx = 0; + if (!$this->header_xobj_autoreset AND $this->booklet AND (($this->page % 2) == 0)) { + // adjust margins for booklet mode + $dx = ($this->original_lMargin - $this->original_rMargin); + } + if ($this->rtl) { + $x = $this->w + $dx; + } else { + $x = 0 + $dx; + } + $this->printTemplate($this->header_xobjid, $x, 0, 0, 0, '', '', false); + if ($this->header_xobj_autoreset) { + // reset header xobject template at each page + $this->header_xobjid = false; + } + } + +} \ No newline at end of file diff --git a/JatsParserPlugin.inc.php b/JatsParserPlugin.inc.php deleted file mode 100644 index f6ce1ecf..00000000 --- a/JatsParserPlugin.inc.php +++ /dev/null @@ -1,1032 +0,0 @@ -getEnabled()) { - // Add data to the publication - HookRegistry::register('Template::Workflow::Publication', array($this, 'publicationTemplateData')); - HookRegistry::register('Schema::get::publication', array($this, 'addToSchema')); - HookRegistry::register('LoadHandler', array($this, 'loadFullTextAssocHandler')); - HookRegistry::register('Publication::edit', array($this, 'editPublicationFullText')); - HookRegistry::register('Templates::Article::Main', array($this, 'displayFullText')); - HookRegistry::register('TemplateManager::display', array($this, 'themeSpecificStyles')); - HookRegistry::register('Form::config::before', array($this, 'addCitationsFormFields')); - HookRegistry::register('Publication::edit', array($this, 'editPublicationReferences')); - HookRegistry::register('Publication::edit', array($this, 'createPdfGalley'), HOOK_SEQUENCE_LAST); - } - - return true; - } - return false; - } - - /** - * Get the plugin display name. - * @return string - */ - function getDisplayName() { - return __('plugins.generic.jatsParser.displayName'); - } - - /** - * Get the plugin description. - * @return string - */ - function getDescription() { - return __('plugins.generic.jatsParser.description'); - } - - /** - * @copydoc Plugin::getActions() - */ - function getActions($request, $verb) { - $router = $request->getRouter(); - import('lib.pkp.classes.linkAction.request.AjaxModal'); - return array_merge( - $this->getEnabled()?array( - new LinkAction( - 'settings', - new AjaxModal( - $router->url($request, null, null, 'manage', null, array('verb' => 'settings', 'plugin' => $this->getName(), 'category' => 'generic')), - $this->getDisplayName() - ), - __('manager.plugins.settings'), - null - ), - ):array(), - parent::getActions($request, $verb) - ); - } - /** - * @copydoc Plugin::manage() - */ - function manage($args, $request) { - switch ($request->getUserVar('verb')) { - case 'settings': - $context = $request->getContext(); - AppLocale::requireComponents(LOCALE_COMPONENT_APP_COMMON, LOCALE_COMPONENT_PKP_MANAGER); - $this->import('JatsParserSettingsForm'); - $form = new JatsParserSettingsForm($this, $context->getId()); - if ($request->getUserVar('save')) { - $form->readInputData(); - if ($form->validate()) { - $form->execute(); - return new JSONMessage(true); - } - } else { - $form->initData(); - } - return new JSONMessage(true, $form->fetch($request)); - } - return parent::manage($args, $request); - } - - private function pdfCreation(string $htmlString, Publication $publication, Request $request, string $localeKey): string - { - // HTML preparation - $context = $request->getContext(); /* @var $context Journal */ - $submission = Repo::submission()->get($publication->getData('submissionId')); /* @var $submission Submission */ - $issueDao = DAORegistry::getDAO('IssueDAO'); - $issue = $issueDao->getById($publication->getData('issueId'), $context->getId()); - - //$this->imageUrlReplacement($xmlGalley, $xpath); - //$this->ojsCitationsExtraction($article, $templateMgr, $htmlDocument, $request); - - // extends TCPDF object - $pdfDocument = new TCPDFDocument(); - - $pdfDocument->setTitle($publication->getLocalizedFullTitle($localeKey)); - - // get the logo - $journal = $request->getContext(); - $thumb = $journal->getLocalizedData('journalThumbnail'); - if (!empty($thumb)) { - $journalFilesPath = __DIR__ . '/../../../' . Config::getVar('files', 'public_files_dir') . '/journals/' . $journal->getId() . '/'; // TCPDF accepts only relative path - $pdfHeaderLogo = $journalFilesPath . $thumb['uploadName']; - } else { - $pdfHeaderLogo = __DIR__ . "/JATSParser/logo/logo.jpg"; - } - - $pdfDocument->SetCreator(PDF_CREATOR); - $userGroupDao = DAORegistry::getDAO('UserGroupDAO'); /* @var $userGroupDao UserGroupDAO */ - $userGroups = $userGroupDao->getByContextId($context->getId())->toArray(); - $pdfDocument->SetAuthor($publication->getAuthorString($userGroups)); - $pdfDocument->SetSubject($publication->getLocalizedData('subject', $localeKey)); - - $articleDataString = ''; - - if ($issue && $issueIdentification = $issue->getIssueIdentification()) { - $articleDataString .= $issueIdentification; - } - - if ($pages = $publication->getLocalizedData('subject', $localeKey)) { - $articleDataString .= ", ". $pages; - } - - if ($doi = $publication->getData('pub-id::doi')) { - $articleDataString .= "\n" . __('plugins.pubIds.doi.readerDisplayName', null, $localeKey) . ': ' . $doi; - } - - $pdfDocument->SetHeaderData($pdfHeaderLogo, PDF_HEADER_LOGO_WIDTH, $journal->getName($localeKey), $articleDataString); - - $pdfDocument->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN)); - $pdfDocument->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA)); - $pdfDocument->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); - $pdfDocument->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); - $pdfDocument->SetHeaderMargin(PDF_MARGIN_HEADER); - $pdfDocument->SetFooterMargin(PDF_MARGIN_FOOTER); - $pdfDocument->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); - $pdfDocument->setImageScale(PDF_IMAGE_SCALE_RATIO); - - $pdfDocument->AddPage(); - - // Article title - - $pdfDocument->SetFillColor(255, 255, 255); - $pdfDocument->SetFont('dejavuserif', 'B', 20); - $pdfDocument->MultiCell('', '', $publication->getLocalizedFullTitle($localeKey), 0, 'L', 1, 1, '' ,'', true); - $pdfDocument->Ln(6); - - // Article's authors - $authors = $publication->getData('authors'); - if (count($authors) > 0) { - /* @var $author Author */ - foreach ($authors as $author) { - $pdfDocument->SetFont('dejavuserif', 'I', 10); - - // Calculating the line height for author name and affiliation - $authorName = htmlspecialchars($author->getGivenName($localeKey)) . ' ' . htmlspecialchars($author->getFamilyName($localeKey)); - $affiliation = htmlspecialchars($author->getAffiliation($localeKey)); - - $authorLineWidth = 60; - $authorNameStringHeight = $pdfDocument->getStringHeight($authorLineWidth, $authorName); - - $affiliationLineWidth = 110; - $afilliationStringHeight = $pdfDocument->getStringHeight(110, $affiliation); - - $authorNameStringHeight > $afilliationStringHeight ? $cellHeight = $authorNameStringHeight : $cellHeight = $afilliationStringHeight; - - // Writing affiliations into cells - $pdfDocument->MultiCell($authorLineWidth, 0, $authorName, 0, 'L', 1, 0, 19, '', true, 0, false, true, 0, "T", true); - $pdfDocument->SetFont('dejavuserif', '', 10); - $pdfDocument->MultiCell($affiliationLineWidth, $cellHeight, $affiliation, 0, 'L', 1, 1, '', '', true, 0, false, true, 0, "T", true); - } - $pdfDocument->Ln(6); - } - - // Abstract - if ($abstract = $publication->getLocalizedData('abstract', $localeKey)) { - $pdfDocument->setCellPaddings(5, 5, 5, 5); - $pdfDocument->SetFillColor(248, 248, 255); - $pdfDocument->SetFont('dejavuserif', '', 10); - $pdfDocument->SetLineStyle(array('width' => 0.5, 'cap' => 'butt', 'join' => 'miter', 'dash' => 4, 'color' => array(255, 140, 0))); - $pdfDocument->writeHTMLCell('', '', '', '', $abstract, 'B', 1, 1, true, 'J', true); - $pdfDocument->Ln(4); - } - - // Text (goes from JATSParser - $pdfDocument->setCellPaddings(0, 0, 0, 0); - $pdfDocument->SetFont('dejavuserif', '', 10); - - $htmlString .= "\n" . ''; - $htmlString = $this->_prepareForPdfGalley($htmlString); - $pdfDocument->writeHTML($htmlString, true, false, true, false, ''); - - return $pdfDocument->Output('article.pdf', 'S'); - } - - /** - * @param string $htmlString - * @return string Preprocessed HTML string for TCPDF - */ - private function _prepareForPdfGalley(string $htmlString): string { - - $dom = new DOMDocument('1.0', 'utf-8'); - $htmlHead = "\n"; - $htmlHead .= ''; - $htmlHead .= "\t" . ''; - $htmlHead .= "\n"; - $htmlHead .= ''; - $dom->loadHTML($htmlHead . $htmlString); - - // set style for figures and table - $xpath = new \DOMXPath($dom); - - $tableNodes = $xpath->evaluate('//table'); - foreach ($tableNodes as $tableNode) { - $tableNode->setAttribute('border', '1'); - $tableNode->setAttribute('cellpadding', '2'); - } - - $captionNodes = $xpath->evaluate('//figure/p[@class="caption"]|//table/caption'); - foreach ($captionNodes as $captionNode) { - $captionParts = $xpath->evaluate('span[@class="label"]|span[@class="title"]', $captionNode); - foreach ($captionParts as $captionPart) { - $emptyTextNode = $dom->createTextNode(' '); - $captionPart->appendChild($emptyTextNode); - } - } - - // TCPDF doesn't recognize display property, insert div - $tableCaptions = $xpath->evaluate('//table/caption'); - foreach ($tableCaptions as $tableCaption) { - /* @var $tableNode \DOMNode */ - $tableNode = $tableCaption->parentNode; - $divNode = $dom->createElement('div'); - $divNode->setAttribute('class', 'caption'); - $nextToTableNode = $tableNode->nextSibling; - if ($nextToTableNode) { - $tableNode->parentNode->insertBefore($divNode, $nextToTableNode); - } - $divNode->appendChild($tableCaption); - } - - // Remove redundant whitespaces before caption label - $modifiedHtmlString = $dom->saveHTML(); - $modifiedHtmlString = preg_replace('/\s*/', '
    ' . '', $modifiedHtmlString); - $modifiedHtmlString = preg_replace('/

    \s*/', '

    ', $modifiedHtmlString); - - return $modifiedHtmlString; - } - - /** - * Add a property to the publication schema - * - * @param $hookName string `Schema::get::publication` - * @param $args [[ - * @option object Publication schema - * ]] - */ - public function addToSchema($hookName, $args) { - $schema = $args[0]; - $propId = '{ - "type": "integer", - "multilingual": true, - "apiSummary": true, - "validation": [ - "nullable" - ] - }'; - $propText = '{ - "type": "string", - "multilingual": true, - "apiSummary": true, - "validation": [ - "nullable" - ] - }'; - $schema->properties->{'jatsParser::fullTextFileId'} = json_decode($propId); - $schema->properties->{'jatsParser::fullText'} = json_decode($propText); - } - - /** - * @param string $hookname - * @param array $args [string, TemplateManager] - */ - function publicationTemplateData(string $hookname, array $args): void { - /** - * @var $templateMgr TemplateManager - * @var $submission Submission - * @var $submissionFileDao SubmissionFileDAO - * @var $submissionFile SubmissionFile - */ - $templateMgr = $args[1]; - $request = $this->getRequest(); - $context = $request->getContext(); - $submission = $templateMgr->getTemplateVars('submission'); - $latestPublication = $submission->getLatestPublication(); - $latestPublicationApiUrl = $request->getDispatcher()->url($request, ROUTE_API, $context->getData('urlPath'), 'submissions/' . $submission->getId() . '/publications/' . $latestPublication->getId()); - - $supportedSubmissionLocales = $context->getSupportedSubmissionLocales(); - $localeNames = AppLocale::getAllLocales(); - $locales = array_map(function($localeKey) use ($localeNames) { - return ['key' => $localeKey, 'label' => $localeNames[$localeKey]]; - }, $supportedSubmissionLocales); - - $submissionFiles = Services::get('submissionFile')->getMany([ - 'submissionIds' => [$submission->getId()], - 'fileStages' => [SUBMISSION_FILE_PRODUCTION_READY], - ]); - - $submissionFilesXML = array(); - foreach ($submissionFiles as $submissionFile) { - if (in_array($submissionFile->getData('mimetype'), array("application/xml", "text/xml"))) { - $submissionFilesXML[] = $submissionFile; - } - } - - $dispatcher = $request->getDispatcher(); - $currentPath = $dispatcher->url($request, ROUTE_PAGE, null, 'workflow', 'fullTextPreview', $submission->getId(), $submission->getData('stageId')); - if (!empty($submissionFilesXML)) { - $msg = $templateMgr->smartyTranslate(array( - 'key' => 'plugins.generic.jatsParser.publication.jats.description', - 'params' => array("previewPath" => $currentPath) - ), $templateMgr); - } else { - $msg = $templateMgr->smartyTranslate(array( - 'key' => 'plugins.generic.jatsParser.publication.jats.descriptionEmpty' - ), $templateMgr); - } - - $form = new PublicationJATSUploadForm($latestPublicationApiUrl, $locales, $latestPublication, $submissionFilesXML, $msg); - $state = $templateMgr->getTemplateVars('state'); - $state['components'][FORM_PUBLICATION_JATS_FULLTEXT] = $form->getConfig(); - $state['publicationFormIds'][] = FORM_PUBLICATION_JATS_FULLTEXT; - $templateMgr->assign('state', $state); - - $templateMgr->display($this->getTemplateResource("workflowJatsFulltext.tpl")); - } - - /** - * @param $hookName string - * @param $args array - * @brief Handle associated files of the full-text, only images are supported - */ - function loadFullTextAssocHandler($hookName, $args) { - $page = $args[0]; - $op = $args[1]; - - if ($page == 'article' && $op == 'downloadFullTextAssoc') { - define('HANDLER_CLASS', 'FullTextArticleHandler'); - define('JATSPARSER_PLUGIN_NAME', $this->getName()); - $args[2] = $this->getPluginPath() . DIRECTORY_SEPARATOR . 'FullTextArticleHandler.inc.php'; - } - } - - /** - * @param string $hookname - * @param array $args [ - * Publication -> new publication - * Publication - * array parameters/publication properties to be saved - * Request - * ] - * @return bool - */ - function editPublicationFullText(string $hookname, array $args) { - $newPublication = $args[0]; - $params = $args[2]; - if (!array_key_exists('jatsParser::fullTextFileId', $params)) return false; - - $localePare = $params['jatsParser::fullTextFileId']; - foreach ($localePare as $localeKey => $fileId) { - if (empty($fileId)) { - $newPublication->setData('jatsParser::fullText', null, $localeKey); - $newPublication->setData('jatsParser::fullTextFileId', null, $localeKey); - continue; - } - $submissionFile = Services::get('submissionFile')->get($fileId); - $htmlDocument = $this->getFullTextFromJats($submissionFile); - $newPublication->setData('jatsParser::fullText', $htmlDocument->saveAsHTML(), $localeKey); - } - - return false; - } - - /** - * @param string $hookname - * @param array $args - * @return bool - * @brief modify citationsRaw property based on parsed citations from JATS XML - */ - function editPublicationReferences(string $hookname, array $args) { - $newPublication = $args[0]; - $params = $args[2]; - if (!array_key_exists('jatsParser::references', $params)) return false; - - $fileId = $params['jatsParser::references']; - if (!$fileId) return false; - - $submissionFile = Services::get('submissionFile')->get($fileId); - $htmlDocument = $this->getFullTextFromJats($submissionFile); - - $request = $this->getRequest(); - $context = $request->getContext(); - - // Get citations style, define default if not set - $citationStyle = $this->getCitationStyle($context); - - $lang = str_replace('_', '-', $submissionFile->getSubmissionLocale()); - $htmlDocument->setReferences($citationStyle, $lang, false); - - $this->_importCitations($htmlDocument, $newPublication); - - return false; - } - - /** - * @param string $hookname - * @param array $args - * @return false - * @brief creates a PDF file and saves as a galley - */ - function createPdfGalley(string $hookname, array $args) { - $newPublication = $args[0]; /* @var $newPublication Publication */ - $params = $args[2]; - $request = $args[3]; - - if (!array_key_exists('jatsParser::pdfGalley', $params)) return false; - if (!$this->getSetting($request->getContext()->getId(), 'convertToPdf')) return false; - - $articleGalleyDao = DAORegistry::getDAO('ArticleGalleyDAO'); /* @var $articleGalleyDao ArticleGalleyDAO */ - - $localePare = $params['jatsParser::pdfGalley']; - foreach ($localePare as $localeKey => $createPdf) { - $fullText = $newPublication->getData('jatsParser::fullText', $localeKey); - if (empty($fullText)) continue; - if (!$createPdf) continue; - - // Set real path to images, attached to the original JATS XML file - $jatsFileId = $newPublication->getData('jatsParser::fullTextFileId', $localeKey); - $jatsSubmissionFile = Services::get('submissionFile')->get($jatsFileId); - if ($jatsSubmissionFile) { - $fullText = $this->_setSupplImgPath($jatsSubmissionFile, $fullText); - } - - // Add required locale components - AppLocale::requireComponents(LOCALE_COMPONENT_PKP_SUBMISSION, $localeKey); - AppLocale::registerLocaleFile($localeKey, 'plugins/pubIds/doi/locale/' . $localeKey . '/locale.po'); - - // Set references - $fullText = $this->_setReferences($newPublication, $localeKey, $fullText); - - // Finally, convert and receive TCPDF output as a binary string - $pdf = $this->pdfCreation($fullText, $newPublication, $request, $localeKey); - - // Create a PDF Galley - $galleyId = $this->createGalley($localeKey, $newPublication); - $galley = $articleGalleyDao->getByBestGalleyId($galleyId, $newPublication->getId()); - - // Create associated submission file and update the galley - $submissionFile = $this->_setPdfSubmissionFile($pdf, $newPublication, $galley); - if ($submissionFile) { - $galley->setData('fileId', $submissionFile->getData('fileId')); - $articleGalleyDao->updateObject($galley); - } - // remove galley if submission file is missing - else { - $articleGalleyDao->deleteObject($galley); - } - } - - return false; - } - - /** - * @param string $galleyLocale - * @param Publication $publication - * @return int - * @brief create an empty galley - */ - function createGalley(string $galleyLocale, Publication $publication): int { - $articleGalleyDao = DAORegistry::getDAO('ArticleGalleyDAO'); /* @var $articleGalleyDao ArticleGalleyDAO */ - $articleGalley = $articleGalleyDao->newDataObject(); - $articleGalley->setLocale($galleyLocale); - $articleGalley->setData('publicationId', $publication->getId()); - $articleGalley->setLabel(__('plugins.generic.jatsParser.publication.galley.pdf.label')); - return $articleGalleyDao->insertObject($articleGalley); - } - - /** - * @param string $pdfBinaryString output of the TCPDF, binary string - * @param Publication $publication publication associated with a submission file - * @brief creates a new PDF submission file - */ - private function _setPdfSubmissionFile(string $pdfBinaryString, Publication $publication, ArticleGalley $galley) { - $submission = Repo::submission()->get($publication->getData('submissionId')); /* @var $submission Submission */ - $request = $this->getRequest(); - - // Create a temporary file - $tmpFile = tempnam(sys_get_temp_dir(), 'jatsParser'); - file_put_contents($tmpFile, $pdfBinaryString); - - // Set main Submission File data - $submissionFileDao = DAORegistry::getDAO('SubmissionFileDAO'); /* @var $submissionFileDao SubmissionFileDAO */ - $submissionDir = Services::get('submissionFile')->getSubmissionDir($submission->getData('contextId'), $submission->getId()); - $fileId = Services::get('file')->add( - $tmpFile, - $submissionDir . DIRECTORY_SEPARATOR . uniqid() . '.pdf' - ); - - // Set original filename, get it from the JATS XML file - $jatsFileId = $publication->getData('jatsParser::fullTextFileId', $galley->getLocale()); - $jatsFile = Services::get('submissionFile')->get($jatsFileId); - - $name = []; - foreach ($jatsFile->getData('name') as $locale => $sourceName) { - $name[$locale] = pathinfo($sourceName)['filename'] . '.pdf'; - } - - // Finally transfer data to PDF galley - $genreDAO = DAORegistry::getDAO('GenreDAO'); - $genre = $genreDAO->getByKey('SUBMISSION', $submission->getData('contextId')); - $submissionFile = $submissionFileDao->newDataObject(); - $submissionFile->setAllData( - [ - 'fileId' => $fileId, - 'assocType' => ASSOC_TYPE_GALLEY, - 'assocId' => $galley->getId(), - 'fileStage' => SUBMISSION_FILE_PROOF, - 'mimetype' => 'application/pdf', - 'locale' => $galley->getData('locale'), - 'genreId' => $genre->getId(), - 'name' => $name, - 'submissionId' => $submission->getId(), - ]); - $submissionFile = Services::get('submissionFile')->add($submissionFile, $request); - - unlink($tmpFile); // remove temporary file - return $submissionFile; - } - - /** - * @param Publication $publication - * @param string $locale - * @param string $htmlString - * @return string - * @brief set references for PDF galley - */ - private function _setReferences(Publication $publication, string $locale, string $htmlString): string { - $rawCitations = $publication->getData('citationsRaw'); - if (empty($rawCitations)) return $htmlString; - - // Use OJS raw citations tokenizer - $citationTokenizer = new \PKP\citation\CitationListTokenizerFilter(); - $citationStrings = $citationTokenizer->execute($rawCitations); - - if (!is_array($citationStrings) || empty($citationStrings)) return $htmlString; - $htmlString .= '

    ' . __('submission.citations', null, $locale) . '

    '; - $htmlString .= "\n"; - $htmlString .= '
      '; - $htmlString .= "\n"; - foreach ($citationStrings as $citationString) { - $htmlString .= "\t"; - $htmlString .= '
    1. ' . $citationString . '
    2. '; - $htmlString .= "\n"; - } - $htmlString .= '
    '; - - return $htmlString; - } - - /** - * @param Journal $context Journal - * @return string - * @brief Retrieve citation style format that should be supported by citeproc-php - * use own format defined in settings if set - * use CitationStyleLanguagePlugin if set - * use vancouver style otherwise - */ - function getCitationStyle(Journal $context): string { - - $contextId = $context->getId(); - - $citationStyle = $this->getSetting($contextId, 'citationStyle'); - - if ($citationStyle) return $citationStyle; - - $pluginSettingsDAO = DAORegistry::getDAO('PluginSettingsDAO'); - $cslPluginSettings = $pluginSettingsDAO->getPluginSettings($contextId, 'CitationStyleLanguagePlugin'); - - if ($cslPluginSettings && - array_key_exists('enabled', $cslPluginSettings) && - $cslPluginSettings['enabled'] && - array_key_exists('primaryCitationStyle', $cslPluginSettings) && - $cslPrimaryCitStyle = $cslPluginSettings['primaryCitationStyle'] - ) $citationStyle = $cslPrimaryCitStyle; - - if ($citationStyle) return $citationStyle; - - $lastCslKey = array_key_last(self::getSupportedCitationStyles()); - return self::getSupportedCitationStyles()[$lastCslKey]['id']; // vancouver - } - - /** - * @param HTMLDocument $htmlDocument - * @param Publication $newPublication - * @return void - * @brief saves parsed citeproc references as raw citations - */ - private function _importCitations(HTMLDocument $htmlDocument, Publication $newPublication): void { - $refs = $htmlDocument->getRawReferences(); - $publicationId = $newPublication->getId(); - $citationDao = DAORegistry::getDAO('CitationDAO'); /** @var $citationDao CitationDAO */ - - $citationDao->deleteByPublicationId($publicationId); - $rawCitations = ''; - - foreach ($refs as $key => $ref) { - $rawCitations .= $ref . "\n"; - } - - $newPublication->setData('citationsRaw', $rawCitations); - } - - /** - * @param SubmissionFile $submissionFile - * @return HTMLDocument - * @brief retrieves PHP DOM representation of the article's full-text - */ - public function getFullTextFromJats (SubmissionFile $submissionFile): HTMLDocument { - $fileMgr = new \PKP\file\PrivateFileManager(); - $htmlDocument = new HTMLDocument(new Document($fileMgr->getBasePath() . DIRECTORY_SEPARATOR . $submissionFile->getData('path'))); - return $htmlDocument; - } - - /** - * @param string $hookname - * @param array $args - * @return bool - * @brief Displays full-text on article landing page - */ - function displayFullText(string $hookname, array $args) { - $templateMgr =& $args[1]; - $output =& $args[2]; - $publication = $templateMgr->getTemplateVars('publication'); - $submission = $templateMgr->getTemplateVars('article'); - $fullTexts = $publication->getData('jatsParser::fullText'); - - $submissionFileId = 0; - $submissionFile = null; - - $request = $this->getRequest(); - $html = null; - - if (empty($fullTexts)) return false; - $currentLocale = AppLocale::getLocale(); - if (array_key_exists($currentLocale, $fullTexts)) { - $html = $fullTexts[$currentLocale]; - - $submissionFileId = $publication->getData('jatsParser::fullTextFileId', $currentLocale); - $submissionFile = Services::get('submissionFile')->get($submissionFileId); - } else { - $locales = AppLocale::getAllLocales(); - $msg = __('plugins.generic.jatsParser.article.fulltext.availableLocale'); - if (count($fullTexts) > 1) { - $msg = __('plugins.generic.jatsParser.article.fulltext.availableLocales'); - } - - $html = '

    ' . $msg; - foreach ($fullTexts as $localeKey => $fullText) { - $html .= ' ' . $locales[$localeKey] . ''; - if ($fullText !== end($fullTexts)) { - $html .= ', '; - } else { - $html .= '.'; - } - } - $html .= '

    '; - } - - if (is_null($html)) return false; - - if ($submissionFileId && $submissionFile) { - $html = $this->_setSupplImgPath($submissionFile, $html); - } - - $templateMgr->assign('fullText', $html); - $output .= $templateMgr->fetch($this->getTemplateResource('articleMainView.tpl')); - - return false; - } - - /** - * @param SubmissionFile $submissionFile - * @param string $htmlString - * @return string - * @brief Substitute path to attached images for full-text HTML - */ - function _setSupplImgPath(SubmissionFile $submissionFile, string $htmlString): string { - $dependentFilesIterator = Services::get('submissionFile')->getMany([ - 'assocTypes' => [ASSOC_TYPE_SUBMISSION_FILE], - 'assocIds' => [$submissionFile->getId()], - 'submissionIds' => [$submissionFile->getData('submissionId')], - 'fileStages' => [SUBMISSION_FILE_DEPENDENT], - 'includeDependentFiles' => true, - ]); - $request = $this->getRequest(); - $imageFiles = []; - - $privateFileManager = new PrivateFileManager(); - $genreDao = DAORegistry::getDAO('GenreDAO'); - foreach ($dependentFilesIterator as $dependentFile) { - $genre = $genreDao->getById($dependentFile->getData('genreId')); - if ($genre && $genre->getCategory() !== GENRE_CATEGORY_ARTWORK) continue; // only art works are supported - if (!in_array($dependentFile->getData('mimetype'), self::getSupportedSupplFileTypes())) continue; // check if MIME type is supported - $submissionId = $submissionFile->getData('submissionId'); - switch ($request->getRequestedOp()) { - case 'view': - $filePath = $request->url(null, 'article', 'downloadFullTextAssoc', array($submissionId, $dependentFile->getData('assocId'), $dependentFile->getData('fileId'))); - break; - case 'editPublication': - // API Handler cannot process $op, $path or $anchor in url() - $image = file_get_contents($privateFileManager->getBasePath() . DIRECTORY_SEPARATOR . $dependentFile->getData('path')); - $imageBase64 = base64_encode($image); - $filePath = '@' . $imageBase64; // Format, supported by TCPDF - break; - } - - $imageFileNames = array_values($dependentFile->getData('name')); // localized - foreach ($imageFileNames as $imageFileName) { - if (empty($imageFileName)) continue; - if (array_key_exists($imageFileName, $imageFiles)) continue; - $imageFiles[$imageFileName] = $filePath; - } - } - - if (empty($imageFiles)) return $htmlString; - - // Solution from HtmlArticleGalleyPlugin::_getHTMLContents - foreach ($imageFiles as $originalFileName => $filePath) { - $pattern = preg_quote(rawurlencode($originalFileName)); - - $htmlString = preg_replace( - '/([Ss][Rr][Cc]|[Hh][Rr][Ee][Ff]|[Dd][Aa][Tt][Aa])\s*=\s*"([^"]*' . $pattern . ')"/', - '\1="' . $filePath . '"', - $htmlString - ); - } - - return $htmlString; - } - - /** - * @return array - * @brief get the list of types of files that are dependent from an original JATS XML (from which full-text was generated) and are accessible to public - */ - public static function getSupportedSupplFileTypes() { - return [ - 'image/png', - 'image/jpeg' - ]; - } - - public static function getSupportedCitationStyles() { - return [ - [ - 'id' => 'acm-sig-proceedings', - 'title' => 'plugins.generic.jatsParser.style.acm-sig-proceedings', - ], - [ - 'id' => 'acs-nano', - 'title' => 'plugins.generic.jatsParser.style.acs-nano', - ], - [ - 'id' => 'apa', - 'title' => 'plugins.generic.jatsParser.style.apa', - ], - [ - 'id' => 'associacao-brasileira-de-normas-tecnicas', - 'title' => 'plugins.generic.jatsParser.style.associacao-brasileira-de-normas-tecnicas', - ], - [ - 'id' => 'chicago-author-date', - 'title' => 'plugins.generic.jatsParser.style.chicago-author-date', - ], - [ - 'id' => 'harvard-cite-them-right', - 'title' => 'plugins.generic.jatsParser.style.harvard-cite-them-right', - ], - [ - 'id' => 'ieee', - 'title' => 'plugins.generic.jatsParser.style.ieee', - ], - [ - 'id' => 'modern-language-association', - 'title' => 'plugins.generic.jatsParser.style.modern-language-association', - ], - [ - 'id' => 'turabian-fullnote-bibliography', - 'title' => 'plugins.generic.jatsParser.style.turabian-fullnote-bibliography', - ], - [ - 'id' => 'vancouver', - 'title' => 'plugins.generic.jatsParser.style.vancouver', - ], - ]; - } - - /** - * @param string $hookname - * @param array $args - * @return bool - * @brief theme-specific styles for galley and article landing page - */ - function themeSpecificStyles(string $hookname, array $args) { - $templateMgr = $args[0]; - $template = $args[1]; - - if ($template !== "frontend/pages/article.tpl") return false; - - $request = $this->getRequest(); - $baseUrl = $request->getBaseUrl() . '/' . $this->getPluginPath(); - - $themePlugins = PluginRegistry::getPlugins('themes'); - foreach ($themePlugins as $themePlugin) { - if ($themePlugin->isActive()) { - $parentTheme = $themePlugin->parent; - // Chances are that child theme of a Default also need this styling - if ($themePlugin->getName() == "defaultthemeplugin" || ($parentTheme && $parentTheme->getName() == "defaultthemeplugin")) { - $templateMgr->addStyleSheet('jatsParserThemeStyles', $baseUrl . '/resources/styles/default/article.css'); - } - } - } - - return false; - } - - /** - * @return void - * @brief iterate through all submissions and add full-text from galleys - */ - public function importGalleys() { - $submissionFileDao = DAORegistry::getDAO('SubmissionFileDAO'); /* @var $submissionFileDao SubmissionFileDAO */ - $request = $this->getRequest(); - $context = $request->getContext(); - $user = $request->getUser(); - $publicationDao = DAORegistry::getDAO('PublicationDAO'); - $fileManager = new PrivateFileManager(); - $submissions = Repo::submission()->getMany( - Repo::submission() - ->getCollector() - ->filterByContextIds([$context->getId()]) - ->filterByStageIds([WORKFLOW_STAGE_ID_PRODUCTION]) - ); - - foreach ($submissions as $submission) { - $publication = $submission->getCurrentPublication(); - $galleys = $publication->getData('galleys'); - - if (empty($galleys)) continue; - - foreach ($galleys as $galley) { - if (!in_array($galley->getFileType(), array("application/xml", "text/xml"))) continue; - - $galleyLocale = $galley->getLocale(); - $localizedFullTextFileSetting = $publication->getData('jatsParser::fullTextFileId', $galleyLocale); - if ($localizedFullTextFileSetting) continue; - - $submissionFile = $galley->getFile(); - /** @var $submissionFile SubmissionFile */ - $document = new Document($fileManager->getBasePath() . DIRECTORY_SEPARATOR . $submissionFile->getData('path')); - if (empty($document->getArticleSections())) continue; - - // Copy galley as a production ready submission file - $submissionDir = Services::get('submissionFile')->getSubmissionDir($request->getContext()->getId(), $submission->getId()); - $fileId = Services::get('file')->add( - $fileManager->getBasePath() . DIRECTORY_SEPARATOR . $submissionFile->getData('path'), - $submissionDir . '/' . uniqid() . '.xml' - ); - - $newSubmissionFile = $submissionFileDao->newDataObject(); - $newSubmissionFile->setAllData( - [ - 'fileId' => $fileId, - 'uploaderUserId' => $user->getId(), - 'fileStage' => SUBMISSION_FILE_PRODUCTION_READY, - 'submissionId' => $submission->getId(), - 'genreId' => $submissionFile->getData('genreId'), - 'name' => $submissionFile->getData('name'), - ], - ); - $newSubmissionFile = Services::get('submissionFile')->add($newSubmissionFile, $request); - - // copy and attach dependent files, only images are supported - $assocFiles = Services::get('submissionFile')->getMany( - [ - 'assocTypes' => [ASSOC_TYPE_SUBMISSION_FILE], - 'assocIds' => [$submissionFile->getId()], - 'submissionIds' => [$submission->getId()], - 'fileStages' => [SUBMISSION_FILE_DEPENDENT], - 'includeDependentFiles' => true, - ] - ); - foreach ($assocFiles as $assocFile) { - /** @var $assocFile SubmissionFile */ - if (in_array($assocFile->getData('mimetype'), $this->getSupportedSupplFileTypes())) { - $newAssocFileId = Services::get('file')->add( - $fileManager->getBasePath() . DIRECTORY_SEPARATOR . $assocFile->getData('path'), - $submissionDir . '/' . uniqid() . '.' . $fileManager->parseFileExtension($assocFile->getData('path')) - ); - - $assocSubmissionFile = $submissionFileDao->newDataObject(); - $assocSubmissionFile->setAllData([ - 'fileId' => $newAssocFileId, - 'assocId' => $newSubmissionFile->getId(), - 'assocType' => ASSOC_TYPE_SUBMISSION_FILE, - 'uploaderUserId' => $user->getId(), - 'fileStage' => SUBMISSION_FILE_DEPENDENT, - 'submissionId' => $submission->getId(), - 'genreId' => $assocFile->getData('genreId'), - 'name' => $assocFile->getData('name'), - 'caption' => $assocFile->getData('caption'), - 'copyrightOwner' => $assocFile->getData('copyrightOwner'), - 'credit' => $assocFile->getData('credit'), - 'terms' =>$assocFile->getData('terms'), - ]); - Services::get('submissionFile')->add($assocSubmissionFile, $request); - } - } - - $htmlDocument = new HTMLDocument($document); - $htmlString = $htmlDocument->saveAsHTML(); - $publication->setData('jatsParser::fullTextFileId', $newSubmissionFile->getId(), $galleyLocale); - $publication->setData('jatsParser::fullText', $htmlString, $galleyLocale); - $publicationDao->updateObject($publication); - } - } - } - - /** - * @param $hookName string Form::config::before - * @param $form FormComponent The form object - */ - public function addCitationsFormFields(string $hookName, FormComponent $form): void { - if ($form->id !== 'citations' || !empty($form->errors)) return; - - $path = parse_url($form->action)['path']; - if (!$path) return; - - $args = explode('/', $path); - $publicationId = 0; - if ($key = array_search('publications', $args)) { - if (array_key_exists($key+1, $args)) { - $publicationId = intval($args[$key+1]); - } - } - - if (!$publicationId) return; - - $publication = Repo::publication()->get($publicationId); - if (!$publication) return; - - $submissionFileIds = array_unique($publication->getData('jatsParser::fullTextFileId') ?? []); - if (empty($submissionFileIds)) return; - - $submissionFileDao = DAORegistry::getDAO('SubmissionFileDAO'); - - $submissionFiles = []; - foreach ($submissionFileIds as $submissionFileId) { - // Check if file ID is valid and object can be returned - if ($submissionFile = $submissionFileDao->getById($submissionFileId)) { - $submissionFiles[] = $submissionFile; - } - } - - if (empty($submissionFiles)) return; - - $options = []; - foreach ($submissionFiles as $submissionFile) { - $options[] = [ - 'value' => $submissionFile->getId(), - 'label' => $submissionFile->getLocalizedData('name'), - ]; - } - - $options[] = [ - 'value' => null, - 'label' => __('common.default'), - ]; - - $form->addField(new \PKP\components\forms\FieldOptions('jatsParser::references', [ - 'label' => __('plugins.generic.jatsParser.publication.jats.references.label'), - 'description' => __('plugins.generic.jatsParser.publication.jats.references.description'), - 'type' => 'radio', - 'options' => $options, - 'value' => null - ])); - - } -} diff --git a/JatsParserPlugin.php b/JatsParserPlugin.php new file mode 100644 index 00000000..b446781c --- /dev/null +++ b/JatsParserPlugin.php @@ -0,0 +1,1116 @@ +getEnabled()) { + Hook::add('Schema::get::publication', [$this, 'addToSchema']); + Hook::add('LoadHandler', [$this, 'loadFullTextAssocHandler']); + Hook::add('Templates::Article::Main', [$this, 'displayFullText']); + Hook::add('TemplateManager::display', [$this, 'themeSpecificStyles']); + Hook::add('TemplateManager::display', [$this, 'addWorkflowComponent']); + Hook::add('Form::config::before', [$this, 'addCitationsFormFields']); + Hook::add('Publication::edit', [$this, 'editPublicationReferences']); + Hook::add('Publication::edit', [$this, 'createPdfGalley'], Hook::SEQUENCE_LAST); + } + return true; + } + return false; + } + + public function getDisplayName() + { + return __('plugins.generic.jatsParser.displayName'); + } + + public function getDescription() + { + return __('plugins.generic.jatsParser.description'); + } + + public function getActions($request, $verb) + { + $router = $request->getRouter(); + return array_merge( + $this->getEnabled() ? [ + new \PKP\linkAction\LinkAction( + 'settings', + new \PKP\linkAction\request\AjaxModal( + $router->url($request, null, null, 'manage', null, ['verb' => 'settings', 'plugin' => $this->getName(), 'category' => 'generic']), + $this->getDisplayName() + ), + __('manager.plugins.settings'), + null + ), + ] : [], + parent::getActions($request, $verb) + ); + } + + public function manage($args, $request) + { + switch ($request->getUserVar('verb')) { + case 'settings': + $context = $request->getContext(); + $form = new JatsParserSettingsForm($this, $context->getId()); + if ($request->getUserVar('save')) { + $form->readInputData(); + if ($form->validate()) { + $form->execute(); + return new \PKP\core\JSONMessage(true); + } + } else { + $form->initData(); + } + return new \PKP\core\JSONMessage(true, $form->fetch($request)); + } + return parent::manage($args, $request); + } + + /** + * Add a property to the publication schema + * + * @param string $hookName `Schema::get::publication` + * @param array $args + */ + public function addToSchema(string $hookName, array $args): bool + { + $schema = $args[0]; + $propId = '{ + "type": "integer", + "multilingual": true, + "apiSummary": true, + "validation": [ + "nullable" + ] + }'; + $propText = '{ + "type": "string", + "multilingual": true, + "apiSummary": true, + "validation": [ + "nullable" + ] + }'; + $schema->properties->{'jatsParser::fullTextFileId'} = json_decode($propId); + $schema->properties->{'jatsParser::fullText'} = json_decode($propText); + return Hook::CONTINUE; + } + + /** + * Handle associated files of the full-text, only images are supported + * + * @param string $hookName + * @param array $args [string $page, string $op, string $sourceFile, mixed $handler] + */ + public function loadFullTextAssocHandler(string $hookName, array $args): bool + { + $page = $args[0]; + $op = $args[1]; + + if ($page === 'article' && $op === 'downloadFullTextAssoc') { + $args[3] = new FullTextArticleHandler($this->getName()); + return Hook::ABORT; + } + + if ($page === 'jatsParser' && in_array($op, ['processSubmission', 'clearFullText', 'getWorkflowFiles'])) { + $args[3] = new JatsParserWorkflowHandler($this->getName()); + return Hook::ABORT; + } + + return Hook::CONTINUE; + } + + /** + * Auto-process a JATS file when it is uploaded via the native JATS tab + * + * @param string $hookName + * @param array $args [$submissionFile] + */ + public function onJatsFileAdded(string $hookName, array $args): bool + { + /** @var SubmissionFile $submissionFile */ + $submissionFile = $args[0]; + + if ($submissionFile->getData('fileStage') !== SubmissionFile::SUBMISSION_FILE_JATS) { + return Hook::CONTINUE; + } + + $publicationId = $submissionFile->getData('assocId'); + $publication = Repo::publication()->get($publicationId); + if (!$publication) { + return Hook::CONTINUE; + } + + try { + $htmlDocument = $this->getFullTextFromJats($submissionFile); + } catch (\Throwable $e) { + error_log('JATSParser onJatsFileAdded error for file id=' . $submissionFile->getId() . ': ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine()); + return Hook::CONTINUE; + } + + // Determine locale from submission + $submission = Repo::submission()->get($publication->getData('submissionId')); + $locale = $submission->getData('locale'); + + Repo::publication()->edit($publication, [ + 'jatsParser::fullTextFileId' => array_merge( + (array) ($publication->getData('jatsParser::fullTextFileId') ?? []), + [$locale => $submissionFile->getId()] + ), + 'jatsParser::fullText' => array_merge( + (array) ($publication->getData('jatsParser::fullText') ?? []), + [$locale => $htmlDocument->saveAsHTML()] + ), + ]); + + return Hook::CONTINUE; + } + + /** + * @param string $hookname + * @param array $args + * @return bool + * @brief modify citationsRaw property based on parsed citations from JATS XML + */ + public function editPublicationReferences(string $hookname, array $args): bool + { + $newPublication = $args[0]; + $params = $args[2]; + if (!array_key_exists('jatsParser::references', $params)) { + return Hook::CONTINUE; + } + + $fileId = $params['jatsParser::references']; + if (!$fileId) { + return Hook::CONTINUE; + } + + $submissionFile = Repo::submissionFile()->get((int) $fileId); + if (!$submissionFile) { + return Hook::CONTINUE; + } + + // Extract references directly from JATS XML, bypassing CiteProc + // (CiteProc may throw when lang is null, causing the hook to fail silently) + try { + $htmlDocument = $this->getFullTextFromJats($submissionFile); + } catch (\Throwable $e) { + error_log('JATSParser editPublicationReferences error for file id=' . $submissionFile->getId() . ': ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine()); + return Hook::CONTINUE; + } + + $jatsRefs = $htmlDocument->jatsDocument->getReferences(); + + if (empty($jatsRefs)) { + return Hook::CONTINUE; + } + + $rawCitations = ''; + foreach ($jatsRefs as $ref) { + $rawText = trim($ref->getRawReference()); + if (!empty($rawText)) { + $rawCitations .= $rawText . "\n"; + } + } + + if (!empty(trim($rawCitations))) { + // Setting citationsRaw triggers OJS to re-import structured citations via DAO + $newPublication->setData('citationsRaw', trim($rawCitations)); + } + + return Hook::CONTINUE; + } + + /** + * @param string $hookname + * @param array $args + * @return bool + * @brief creates a PDF file and saves as a galley + */ + public function createPdfGalley(string $hookname, array $args): bool + { + $newPublication = $args[0]; /* @var $newPublication \APP\publication\Publication */ + $params = $args[2]; + $request = $args[3]; + + if (!array_key_exists('jatsParser::fullText', $params)) { + return Hook::CONTINUE; + } + if (!$this->getSetting($request->getContext()->getId(), 'convertToPdf')) { + return Hook::CONTINUE; + } + + $fullTextByLocale = $params['jatsParser::fullText']; + if (empty($fullTextByLocale) || !is_array($fullTextByLocale)) { + return Hook::CONTINUE; + } + + foreach ($fullTextByLocale as $localeKey => $fullText) { + if (empty($fullText)) { + continue; + } + + // Evita duplicati: se esiste già una galley PDF per questo locale, aggiorna quella + $pdfLabel = __('plugins.generic.jatsParser.publication.galley.pdf.label'); + $existingGalley = null; + foreach ($newPublication->getData('galleys') ?? [] as $g) { + if ($g->getLocale() === $localeKey && $g->getLabel() === $pdfLabel) { + $existingGalley = $g; + break; + } + } + + // Set real path to images, attached to the original JATS XML file + $jatsFileId = $newPublication->getData('jatsParser::fullTextFileId', $localeKey); + $jatsSubmissionFile = $jatsFileId ? Repo::submissionFile()->get($jatsFileId) : null; + if ($jatsSubmissionFile) { + $fullText = $this->_setSupplImgPath($jatsSubmissionFile, $fullText, true); + } + + // Set references + $fullText = $this->_setReferences($newPublication, $localeKey, $fullText); + + // Finally, convert and receive TCPDF output as a binary string + $pdf = $this->pdfCreation($fullText, $newPublication, $request, $localeKey); + + // Riusa la galley esistente o creane una nuova + if ($existingGalley) { + $galley = $existingGalley; + } else { + $galleyId = $this->createGalley($localeKey, $newPublication); + $galley = Repo::galley()->get($galleyId); + } + + // Create associated submission file and update the galley + $submissionFile = $this->_setPdfSubmissionFile($pdf, $newPublication, $galley, $localeKey); + if ($submissionFile) { + Repo::galley()->edit($galley, ['submissionFileId' => $submissionFile->getId()]); + } else { + Repo::galley()->delete($galley); + } + } + + return Hook::CONTINUE; + } + + /** + * @param string $galleyLocale + * @param \APP\publication\Publication $publication + * @return int + * @brief create an empty galley + */ + public function createGalley(string $galleyLocale, $publication): int + { + $galley = Repo::galley()->newDataObject(); + $galley->setLocale($galleyLocale); + $galley->setData('publicationId', $publication->getId()); + $galley->setLabel(__('plugins.generic.jatsParser.publication.galley.pdf.label')); + return Repo::galley()->add($galley); + } + + /** + * @param string $pdfBinaryString output of the TCPDF, binary string + * @param \APP\publication\Publication $publication publication associated with a submission file + * @param \PKP\galley\Galley $galley + * @brief creates a new PDF submission file + */ + private function _setPdfSubmissionFile(string $pdfBinaryString, $publication, $galley, string $localeKey) + { + $submission = Repo::submission()->get($publication->getData('submissionId')); + $request = $this->getRequest(); + + // Create a temporary file + $tmpFile = tempnam(sys_get_temp_dir(), 'jatsParser'); + file_put_contents($tmpFile, $pdfBinaryString); + + // Store file + $submissionDir = Repo::submissionFile()->getSubmissionDir($submission->getData('contextId'), $submission->getId()); + $fileId = app()->get('file')->add( + $tmpFile, + $submissionDir . DIRECTORY_SEPARATOR . uniqid() . '.pdf' + ); + + // Set original filename from the JATS XML file + // Usiamo $localeKey esplicitamente invece di $galley->getLocale() che può essere null + $jatsFileId = $publication->getData('jatsParser::fullTextFileId', $localeKey); + $jatsFile = $jatsFileId ? Repo::submissionFile()->get((int) $jatsFileId) : null; + + $name = []; + if ($jatsFile) { + foreach ($jatsFile->getData('name') as $locale => $sourceName) { + $name[$locale] = pathinfo($sourceName)['filename'] . '.pdf'; + } + } + if (empty($name)) { + $name = [$localeKey => 'article.pdf']; + } + + $genreDAO = DAORegistry::getDAO('GenreDAO'); + $genre = $genreDAO->getByKey('SUBMISSION', $submission->getData('contextId')); + + $submissionFile = Repo::submissionFile()->newDataObject([ + 'fileId' => $fileId, + 'assocType' => Application::ASSOC_TYPE_GALLEY, + 'assocId' => $galley->getId(), + 'fileStage' => SubmissionFile::SUBMISSION_FILE_PROOF, + 'mimetype' => 'application/pdf', + 'locale' => $galley->getData('locale'), + 'genreId' => $genre->getId(), + 'name' => $name, + 'submissionId' => $submission->getId(), + ]); + + $submissionFileId = Repo::submissionFile()->add($submissionFile); + + unlink($tmpFile); + return Repo::submissionFile()->get($submissionFileId); + } + + /** + * @param \APP\publication\Publication $publication + * @param string $locale + * @param string $htmlString + * @return string + * @brief set references for PDF galley + */ + private function _setReferences($publication, string $locale, string $htmlString): string + { + // In OJS 3.5 citationsRaw è un Stringable@anonymous (lazy proxy) - va castato a string + $rawCitations = (string) ($publication->getData('citationsRaw') ?? ''); + if (empty($rawCitations)) { + return $htmlString; + } + + $citationTokenizer = new CitationListTokenizerFilter(); + $citationStrings = $citationTokenizer->execute($rawCitations); + + if (!is_array($citationStrings) || empty($citationStrings)) { + return $htmlString; + } + $htmlString .= '

    ' . __('submission.citations', [], $locale) . '

    '; + $htmlString .= "\n"; + $htmlString .= '
      '; + $htmlString .= "\n"; + foreach ($citationStrings as $citationString) { + $htmlString .= "\t"; + $htmlString .= '
    1. ' . $citationString . '
    2. '; + $htmlString .= "\n"; + } + $htmlString .= '
    '; + + return $htmlString; + } + + /** + * @param \APP\journal\Journal $context Journal + * @return string + * @brief Retrieve citation style format + */ + public function getCitationStyle($context): string + { + $contextId = $context->getId(); + + $citationStyle = $this->getSetting($contextId, 'citationStyle'); + if ($citationStyle) { + return $citationStyle; + } + + $pluginSettingsDAO = DAORegistry::getDAO('PluginSettingsDAO'); + $cslPluginSettings = $pluginSettingsDAO->getPluginSettings($contextId, 'CitationStyleLanguagePlugin'); + + if ($cslPluginSettings && + array_key_exists('enabled', $cslPluginSettings) && + $cslPluginSettings['enabled'] && + array_key_exists('primaryCitationStyle', $cslPluginSettings) && + $cslPrimaryCitStyle = $cslPluginSettings['primaryCitationStyle'] + ) { + $citationStyle = $cslPrimaryCitStyle; + } + + if ($citationStyle) { + return $citationStyle; + } + + $lastCslKey = array_key_last(self::getSupportedCitationStyles()); + return self::getSupportedCitationStyles()[$lastCslKey]['id']; // vancouver + } + + /** + * @param HTMLDocument $htmlDocument + * @param \APP\publication\Publication $newPublication + * @return void + * @brief saves parsed citeproc references as raw citations + */ + private function _importCitations(HTMLDocument $htmlDocument, $newPublication): void + { + $refs = $htmlDocument->getRawReferences(); + $publicationId = $newPublication->getId(); + $citationDao = DAORegistry::getDAO('CitationDAO'); + + $citationDao->deleteByPublicationId($publicationId); + $rawCitations = ''; + + foreach ($refs as $key => $ref) { + $rawCitations .= $ref . "\n"; + } + + $newPublication->setData('citationsRaw', $rawCitations); + } + + /** + * @param SubmissionFile $submissionFile + * @return HTMLDocument + * @brief retrieves PHP DOM representation of the article's full-text + */ + public function getFullTextFromJats(SubmissionFile $submissionFile): HTMLDocument + { + $fileMgr = new PrivateFileManager(); + $filePath = $fileMgr->getBasePath() . DIRECTORY_SEPARATOR . $submissionFile->getData('path'); + if (!file_exists($filePath)) { + throw new \RuntimeException( + 'JATSParser: XML file not found on disk (submission file id=' . $submissionFile->getId() . ', path=' . $filePath . ')' + ); + } + $htmlDocument = new HTMLDocument(new Document($filePath)); + return $htmlDocument; + } + + /** + * @param string $hookname + * @param array $args + * @return bool + * @brief Displays full-text on article landing page + */ + public function displayFullText(string $hookname, array $args): bool + { + $templateMgr =& $args[1]; + $output =& $args[2]; + $publication = $templateMgr->getTemplateVars('publication'); + $submission = $templateMgr->getTemplateVars('article'); + $fullTexts = $publication->getData('jatsParser::fullText'); + + $submissionFileId = 0; + $submissionFile = null; + + $request = $this->getRequest(); + $html = null; + + if (empty($fullTexts)) { + return Hook::CONTINUE; + } + $currentLocale = Locale::getLocale(); + if (array_key_exists($currentLocale, $fullTexts)) { + $html = $fullTexts[$currentLocale]; + + $submissionFileId = $publication->getData('jatsParser::fullTextFileId', $currentLocale); + $submissionFile = Repo::submissionFile()->get($submissionFileId); + } else { + $availableLocales = Locale::getLocales(); + $msg = __('plugins.generic.jatsParser.article.fulltext.availableLocale'); + if (count($fullTexts) > 1) { + $msg = __('plugins.generic.jatsParser.article.fulltext.availableLocales'); + } + + $html = '

    ' . $msg; + foreach ($fullTexts as $localeKey => $fullText) { + $localeName = isset($availableLocales[$localeKey]) ? $availableLocales[$localeKey]->getDisplayName() : $localeKey; + $html .= ' ' . $localeName . ''; + if ($fullText !== end($fullTexts)) { + $html .= ', '; + } else { + $html .= '.'; + } + } + $html .= '

    '; + } + + if (is_null($html)) { + return Hook::CONTINUE; + } + + if ($submissionFileId && $submissionFile) { + $html = $this->_setSupplImgPath($submissionFile, $html); + } + + $templateMgr->assign('fullText', $html); + $output .= $templateMgr->fetch($this->getTemplateResource('articleMainView.tpl')); + + return Hook::CONTINUE; + } + + /** + * @param SubmissionFile $submissionFile + * @param string $htmlString + * @return string + * @brief Substitute path to attached images for full-text HTML + */ + public function _setSupplImgPath(SubmissionFile $submissionFile, string $htmlString, bool $forPdf = false): string + { + $dependentFilesIterator = Repo::submissionFile() + ->getCollector() + ->filterByAssoc(Application::ASSOC_TYPE_SUBMISSION_FILE, [$submissionFile->getId()]) + ->filterBySubmissionIds([$submissionFile->getData('submissionId')]) + ->filterByFileStages([SubmissionFile::SUBMISSION_FILE_DEPENDENT]) + ->includeDependentFiles() + ->getMany(); + + $request = $this->getRequest(); + $imageFiles = []; + + $privateFileManager = new PrivateFileManager(); + $genreDao = DAORegistry::getDAO('GenreDAO'); + foreach ($dependentFilesIterator as $dependentFile) { + $genre = $genreDao->getById($dependentFile->getData('genreId')); + if (!$genre || $genre->getCategory() !== Genre::GENRE_CATEGORY_ARTWORK) { + continue; + } + if (!in_array($dependentFile->getData('mimetype'), self::getSupportedSupplFileTypes())) { + continue; + } + $submissionId = $submissionFile->getData('submissionId'); + if ($forPdf) { + $image = file_get_contents($privateFileManager->getBasePath() . DIRECTORY_SEPARATOR . $dependentFile->getData('path')); + $imageBase64 = base64_encode($image); + $mime = $dependentFile->getData('mimetype'); + $filePath = 'data:' . $mime . ';base64,' . $imageBase64; + } else { + switch ($request->getRequestedOp()) { + case 'view': + $filePath = $request->url(null, 'article', 'downloadFullTextAssoc', [$submissionId, $dependentFile->getData('assocId'), $dependentFile->getData('fileId')]); + break; + case 'editPublication': + $image = file_get_contents($privateFileManager->getBasePath() . DIRECTORY_SEPARATOR . $dependentFile->getData('path')); + $imageBase64 = base64_encode($image); + $filePath = '@' . $imageBase64; + break; + default: + continue 2; + } + } + + $imageFileNames = array_values($dependentFile->getData('name')); + foreach ($imageFileNames as $imageFileName) { + if (empty($imageFileName)) { + continue; + } + if (array_key_exists($imageFileName, $imageFiles)) { + continue; + } + $imageFiles[$imageFileName] = $filePath; + } + } + + if (empty($imageFiles)) { + return $htmlString; + } + + foreach ($imageFiles as $originalFileName => $filePath) { + $pattern = preg_quote(rawurlencode($originalFileName)); + + $htmlString = preg_replace( + '/([Ss][Rr][Cc]|[Hh][Rr][Ee][Ff]|[Dd][Aa][Tt][Aa])\s*=\s*"([^"]*' . $pattern . ')"/', + '\1="' . $filePath . '"', + $htmlString + ); + } + + return $htmlString; + } + + /** + * @return array + */ + public static function getSupportedSupplFileTypes(): array + { + return [ + 'image/png', + 'image/jpeg', + ]; + } + + public static function getSupportedCitationStyles(): array + { + return [ + ['id' => 'acm-sig-proceedings', 'title' => 'plugins.generic.jatsParser.style.acm-sig-proceedings'], + ['id' => 'acs-nano', 'title' => 'plugins.generic.jatsParser.style.acs-nano'], + ['id' => 'apa', 'title' => 'plugins.generic.jatsParser.style.apa'], + ['id' => 'associacao-brasileira-de-normas-tecnicas', 'title' => 'plugins.generic.jatsParser.style.associacao-brasileira-de-normas-tecnicas'], + ['id' => 'chicago-author-date', 'title' => 'plugins.generic.jatsParser.style.chicago-author-date'], + ['id' => 'harvard-cite-them-right', 'title' => 'plugins.generic.jatsParser.style.harvard-cite-them-right'], + ['id' => 'ieee', 'title' => 'plugins.generic.jatsParser.style.ieee'], + ['id' => 'modern-language-association', 'title' => 'plugins.generic.jatsParser.style.modern-language-association'], + ['id' => 'turabian-fullnote-bibliography', 'title' => 'plugins.generic.jatsParser.style.turabian-fullnote-bibliography'], + ['id' => 'vancouver', 'title' => 'plugins.generic.jatsParser.style.vancouver'], + ]; + } + + /** + * Load the workflow Vue component for the editorial JATS tab + * + * @param string $hookName `TemplateManager::display` + * @param array $args [$templateMgr, $template] + */ + public function addWorkflowComponent(string $hookName, array $args): bool + { + $templateMgr = $args[0]; + $template = $args[1]; + + if ($template !== 'dashboard/editors.tpl') { + return Hook::CONTINUE; + } + + $request = Application::get()->getRequest(); + $context = $request->getContext(); + + // Inject the processing URL and locale strings as global JS variables. + // We inject locale strings directly to avoid relying on the pkp.localeKeys cache. + $processUrl = $request->url($context->getPath(), 'jatsParser', 'processSubmission'); + $clearUrl = $request->url($context->getPath(), 'jatsParser', 'clearFullText'); + $filesUrl = $request->url($context->getPath(), 'jatsParser', 'getWorkflowFiles'); + $localeStrings = [ + 'selectFile' => __('plugins.generic.jatsParser.workflow.selectFile'), + 'noProductionFiles' => __('plugins.generic.jatsParser.workflow.noProductionFiles'), + 'currentlyProcessed' => __('plugins.generic.jatsParser.workflow.currentlyProcessed'), + 'process' => __('plugins.generic.jatsParser.workflow.process'), + 'reprocess' => __('plugins.generic.jatsParser.workflow.reprocess'), + 'processSuccess' => __('plugins.generic.jatsParser.workflow.processSuccess'), + 'processError' => __('plugins.generic.jatsParser.workflow.processError'), + 'noJatsFile' => __('plugins.generic.jatsParser.workflow.noJatsFile'), + 'clearFullText' => __('plugins.generic.jatsParser.workflow.clearFullText'), + 'clearSuccess' => __('plugins.generic.jatsParser.workflow.clearSuccess'), + 'clearError' => __('plugins.generic.jatsParser.workflow.clearError'), + 'confirmClear' => __('plugins.generic.jatsParser.workflow.confirmClear'), + 'tabLabel' => __('plugins.generic.jatsParser.workflow.tab.label'), + 'assetsTitle' => __('plugins.generic.jatsParser.workflow.assets.title'), + 'uploadInfo' => __('plugins.generic.jatsParser.workflow.assets.uploadInfo'), + 'loading' => __('common.loading'), + ]; + $templateMgr->addJavaScript( + 'jatsparser-workflow-config', + 'window.jatsParserConfig = { processUrl: ' . json_encode($processUrl) . ', clearUrl: ' . json_encode($clearUrl) . ', filesUrl: ' . json_encode($filesUrl) . ', locale: ' . json_encode($localeStrings) . ' };', + ['inline' => true, 'contexts' => 'backend'] + ); + + // Load the workflow component JS + $templateMgr->addJavaScript( + 'jatsparser-workflow-component', + $request->getBaseUrl() . '/' . $this->getPluginPath() . '/js/jatsParserWorkflow.js', + ['contexts' => 'backend', 'priority' => TemplateManager::STYLE_SEQUENCE_LAST] + ); + + return Hook::CONTINUE; + } + + /** + * @param string $hookname + * @param array $args + * @return bool + * @brief theme-specific styles for galley and article landing page + */ + public function themeSpecificStyles(string $hookname, array $args): bool + { + $templateMgr = $args[0]; + $template = $args[1]; + + if ($template !== 'frontend/pages/article.tpl') { + return Hook::CONTINUE; + } + + $request = $this->getRequest(); + $baseUrl = $request->getBaseUrl() . '/' . $this->getPluginPath(); + + $themePlugins = PluginRegistry::getPlugins('themes'); + foreach ($themePlugins as $themePlugin) { + if ($themePlugin->isActive()) { + $parentTheme = $themePlugin->parent; + if ($themePlugin->getName() === 'defaultthemeplugin' || ($parentTheme && $parentTheme->getName() === 'defaultthemeplugin')) { + $templateMgr->addStyleSheet('jatsParserThemeStyles', $baseUrl . '/resources/styles/default/article.css'); + } + } + } + + return Hook::CONTINUE; + } + + /** + * @return void + * @brief iterate through all submissions and add full-text from galleys + */ + public function importGalleys(): void + { + $request = $this->getRequest(); + $context = $request->getContext(); + $user = $request->getUser(); + $fileManager = new PrivateFileManager(); + + $submissions = Repo::submission() + ->getCollector() + ->filterByContextIds([$context->getId()]) + ->filterByStageIds([WORKFLOW_STAGE_ID_PRODUCTION]) + ->getMany(); + + foreach ($submissions as $submission) { + $publication = $submission->getCurrentPublication(); + $galleys = $publication->getData('galleys'); + + if (empty($galleys)) { + continue; + } + + foreach ($galleys as $galley) { + $galleyFileId = $galley->getData('fileId'); + if (!$galleyFileId) { + continue; + } + $submissionFile = Repo::submissionFile()->get((int) $galleyFileId); + if (!$submissionFile) { + continue; + } + if (!in_array($submissionFile->getData('mimetype'), ['application/xml', 'text/xml', 'application/jats+xml'])) { + continue; + } + + $galleyLocale = $galley->getLocale(); + $localizedFullTextFileSetting = $publication->getData('jatsParser::fullTextFileId', $galleyLocale); + if ($localizedFullTextFileSetting) { + continue; + } + + $document = new Document($fileManager->getBasePath() . DIRECTORY_SEPARATOR . $submissionFile->getData('path')); + if (empty($document->getArticleSections())) { + continue; + } + + // Copy galley as a production ready submission file + $submissionDir = Repo::submissionFile()->getSubmissionDir($request->getContext()->getId(), $submission->getId()); + $fileId = app()->get('file')->add( + $fileManager->getBasePath() . DIRECTORY_SEPARATOR . $submissionFile->getData('path'), + $submissionDir . '/' . uniqid() . '.xml' + ); + + $newSubmissionFile = Repo::submissionFile()->newDataObject([ + 'fileId' => $fileId, + 'uploaderUserId' => $user->getId(), + 'fileStage' => SubmissionFile::SUBMISSION_FILE_PRODUCTION_READY, + 'submissionId' => $submission->getId(), + 'genreId' => $submissionFile->getData('genreId'), + 'name' => $submissionFile->getData('name'), + ]); + $newSubmissionFileId = Repo::submissionFile()->add($newSubmissionFile); + $newSubmissionFile = Repo::submissionFile()->get($newSubmissionFileId); + + // copy and attach dependent files, only images are supported + $assocFiles = Repo::submissionFile() + ->getCollector() + ->filterByAssoc(Application::ASSOC_TYPE_SUBMISSION_FILE, [$submissionFile->getId()]) + ->filterBySubmissionIds([$submission->getId()]) + ->filterByFileStages([SubmissionFile::SUBMISSION_FILE_DEPENDENT]) + ->includeDependentFiles() + ->getMany(); + + foreach ($assocFiles as $assocFile) { + /** @var SubmissionFile $assocFile */ + if (in_array($assocFile->getData('mimetype'), $this->getSupportedSupplFileTypes())) { + $newAssocFileId = app()->get('file')->add( + $fileManager->getBasePath() . DIRECTORY_SEPARATOR . $assocFile->getData('path'), + $submissionDir . '/' . uniqid() . '.' . $fileManager->parseFileExtension($assocFile->getData('path')) + ); + + $assocSubmissionFile = Repo::submissionFile()->newDataObject([ + 'fileId' => $newAssocFileId, + 'assocId' => $newSubmissionFile->getId(), + 'assocType' => Application::ASSOC_TYPE_SUBMISSION_FILE, + 'uploaderUserId' => $user->getId(), + 'fileStage' => SubmissionFile::SUBMISSION_FILE_DEPENDENT, + 'submissionId' => $submission->getId(), + 'genreId' => $assocFile->getData('genreId'), + 'name' => $assocFile->getData('name'), + 'caption' => $assocFile->getData('caption'), + 'copyrightOwner' => $assocFile->getData('copyrightOwner'), + 'credit' => $assocFile->getData('credit'), + 'terms' => $assocFile->getData('terms'), + ]); + Repo::submissionFile()->add($assocSubmissionFile); + } + } + + $htmlDocument = new HTMLDocument($document); + $htmlString = $htmlDocument->saveAsHTML(); + $publication->setData('jatsParser::fullTextFileId', $newSubmissionFile->getId(), $galleyLocale); + $publication->setData('jatsParser::fullText', $htmlString, $galleyLocale); + Repo::publication()->dao->update($publication); + } + } + } + + /** + * @param string $hookName Form::config::before + * @param FormComponent $form The form object + */ + public function addCitationsFormFields(string $hookName, FormComponent $form): void + { + if ($form->id !== 'citations' || !empty($form->errors)) { + return; + } + + $path = parse_url($form->action)['path']; + if (!$path) { + return; + } + + $args = explode('/', $path); + $publicationId = 0; + if ($key = array_search('publications', $args)) { + if (array_key_exists($key + 1, $args)) { + $publicationId = intval($args[$key + 1]); + } + } + + if (!$publicationId) { + return; + } + + $publication = Repo::publication()->get($publicationId); + if (!$publication) { + return; + } + + $submissionFileIds = array_unique($publication->getData('jatsParser::fullTextFileId') ?? []); + if (empty($submissionFileIds)) { + return; + } + + $submissionFiles = []; + foreach ($submissionFileIds as $submissionFileId) { + if ($submissionFile = Repo::submissionFile()->get($submissionFileId)) { + $submissionFiles[] = $submissionFile; + } + } + + if (empty($submissionFiles)) { + return; + } + + $options = []; + foreach ($submissionFiles as $submissionFile) { + $options[] = [ + 'value' => $submissionFile->getId(), + 'label' => $submissionFile->getLocalizedData('name'), + ]; + } + + $options[] = [ + 'value' => null, + 'label' => __('common.default'), + ]; + + $form->addField(new \PKP\components\forms\FieldOptions('jatsParser::references', [ + 'label' => __('plugins.generic.jatsParser.publication.jats.references.label'), + 'description' => __('plugins.generic.jatsParser.publication.jats.references.description'), + 'type' => 'radio', + 'options' => $options, + 'value' => null, + ])); + } + + /** + * @param string $htmlString + * @param \APP\publication\Publication $publication + * @param \APP\core\Request $request + * @param string $localeKey + * @return string + */ + private function pdfCreation(string $htmlString, $publication, $request, string $localeKey): string + { + $context = $request->getContext(); + $submission = Repo::submission()->get($publication->getData('submissionId')); + $issue = Repo::issue()->getBySubmissionId($submission->getId()); + + $pdfDocument = new TCPDFDocument(); + + $pdfDocument->setTitle($publication->getLocalizedFullTitle($localeKey)); + + $journal = $request->getContext(); + $thumb = $journal->getLocalizedData('journalThumbnail'); + if (!empty($thumb)) { + $journalFilesPath = __DIR__ . '/../../../' . Config::getVar('files', 'public_files_dir') . '/journals/' . $journal->getId() . '/'; + $pdfHeaderLogo = $journalFilesPath . $thumb['uploadName']; + } else { + $pdfHeaderLogo = __DIR__ . '/JATSParser/logo/logo.jpg'; + } + + $pdfDocument->SetCreator(PDF_CREATOR); + $userGroups = UserGroup::withContextIds([$context->getId()])->get(); + $pdfDocument->SetAuthor($publication->getAuthorString($userGroups)); + $pdfDocument->SetSubject($publication->getLocalizedData('subject', $localeKey)); + + $articleDataString = ''; + + if ($issue && $issueIdentification = $issue->getIssueIdentification()) { + $articleDataString .= $issueIdentification; + } + + if ($pages = $publication->getLocalizedData('subject', $localeKey)) { + $articleDataString .= ', ' . $pages; + } + + if ($doi = $publication->getData('pub-id::doi')) { + $articleDataString .= "\n" . __('plugins.pubIds.doi.readerDisplayName', [], $localeKey) . ': ' . $doi; + } + + $pdfDocument->SetHeaderData($pdfHeaderLogo, PDF_HEADER_LOGO_WIDTH, $journal->getName($localeKey), $articleDataString); + + $pdfDocument->setHeaderFont([PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN]); + $pdfDocument->setFooterFont([PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA]); + $pdfDocument->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); + $pdfDocument->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); + $pdfDocument->SetHeaderMargin(PDF_MARGIN_HEADER); + $pdfDocument->SetFooterMargin(PDF_MARGIN_FOOTER); + $pdfDocument->SetAutoPageBreak(true, PDF_MARGIN_BOTTOM); + $pdfDocument->setImageScale(PDF_IMAGE_SCALE_RATIO); + + $pdfDocument->AddPage(); + + $pdfDocument->SetFillColor(255, 255, 255); + $pdfDocument->SetFont('dejavuserif', 'B', 20); + $pdfDocument->MultiCell('', '', $publication->getLocalizedFullTitle($localeKey), 0, 'L', 1, 1, '', '', true); + $pdfDocument->Ln(6); + + $authors = $publication->getData('authors'); + if (count($authors) > 0) { + foreach ($authors as $author) { + $pdfDocument->SetFont('dejavuserif', 'I', 10); + + $authorName = htmlspecialchars($author->getGivenName($localeKey)) . ' ' . htmlspecialchars($author->getFamilyName($localeKey)); + $affiliation = htmlspecialchars($author->getLocalizedAffiliationNamesAsString($localeKey)); + + $authorLineWidth = 60; + $authorNameStringHeight = $pdfDocument->getStringHeight($authorLineWidth, $authorName); + + $affiliationLineWidth = 110; + $afilliationStringHeight = $pdfDocument->getStringHeight(110, $affiliation); + + $authorNameStringHeight > $afilliationStringHeight ? $cellHeight = $authorNameStringHeight : $cellHeight = $afilliationStringHeight; + + $pdfDocument->MultiCell($authorLineWidth, 0, $authorName, 0, 'L', 1, 0, 19, '', true, 0, false, true, 0, 'T', true); + $pdfDocument->SetFont('dejavuserif', '', 10); + $pdfDocument->MultiCell($affiliationLineWidth, $cellHeight, $affiliation, 0, 'L', 1, 1, '', '', true, 0, false, true, 0, 'T', true); + } + $pdfDocument->Ln(6); + } + + if ($abstract = $publication->getLocalizedData('abstract', $localeKey)) { + $pdfDocument->setCellPaddings(5, 5, 5, 5); + $pdfDocument->SetFillColor(248, 248, 255); + $pdfDocument->SetFont('dejavuserif', '', 10); + $pdfDocument->SetLineStyle(['width' => 0.5, 'cap' => 'butt', 'join' => 'miter', 'dash' => 4, 'color' => [255, 140, 0]]); + $pdfDocument->writeHTMLCell('', '', '', '', $abstract, 'B', 1, 1, true, 'J', true); + $pdfDocument->Ln(4); + } + + $pdfDocument->setCellPaddings(0, 0, 0, 0); + $pdfDocument->SetFont('dejavuserif', '', 10); + + $htmlString .= "\n" . ''; + $htmlString = $this->_prepareForPdfGalley($htmlString); + + $previousErrorReporting = error_reporting(); + error_reporting(E_ERROR); + + $pdfDocument->writeHTML($htmlString, true, false, true, false, ''); + $pdfOutput = $pdfDocument->Output('article.pdf', 'S'); + + error_reporting($previousErrorReporting); + + return $pdfOutput; + } + + /** + * @param string $htmlString + * @return string Preprocessed HTML string for TCPDF + */ + private function _prepareForPdfGalley(string $htmlString): string + { + $dom = new \DOMDocument('1.0', 'utf-8'); + $htmlHead = "\n"; + $htmlHead .= ''; + $htmlHead .= "\t" . ''; + $htmlHead .= "\n"; + $htmlHead .= ''; + $dom->loadHTML($htmlHead . $htmlString); + + $xpath = new \DOMXPath($dom); + + $tableNodes = $xpath->evaluate('//table'); + foreach ($tableNodes as $tableNode) { + $tableNode->setAttribute('border', '1'); + $tableNode->setAttribute('cellpadding', '2'); + } + + $captionNodes = $xpath->evaluate('//figure/p[@class="caption"]|//table/caption'); + foreach ($captionNodes as $captionNode) { + $captionParts = $xpath->evaluate('span[@class="label"]|span[@class="title"]', $captionNode); + foreach ($captionParts as $captionPart) { + $emptyTextNode = $dom->createTextNode(' '); + $captionPart->appendChild($emptyTextNode); + } + } + + $tableCaptions = $xpath->evaluate('//table/caption'); + foreach ($tableCaptions as $tableCaption) { + $tableNode = $tableCaption->parentNode; + $divNode = $dom->createElement('div'); + $divNode->setAttribute('class', 'caption'); + $nextToTableNode = $tableNode->nextSibling; + if ($nextToTableNode) { + $tableNode->parentNode->insertBefore($divNode, $nextToTableNode); + } + $divNode->appendChild($tableCaption); + } + + $modifiedHtmlString = $dom->saveHTML(); + $modifiedHtmlString = preg_replace('/\s*/', '
    ' . '', $modifiedHtmlString); + $modifiedHtmlString = preg_replace('/

    \s*/', '

    ', $modifiedHtmlString); + + return $modifiedHtmlString; + } +} diff --git a/JatsParserSettingsForm.inc.php b/JatsParserSettingsForm.inc.php deleted file mode 100644 index d93c8afe..00000000 --- a/JatsParserSettingsForm.inc.php +++ /dev/null @@ -1,103 +0,0 @@ -_journalId = $journalId; - $this->_plugin = $plugin; - - parent::__construct($plugin->getTemplateResource('settingsForm.tpl')); - - $this->addCheck(new FormValidatorPost($this)); - $this->addCheck(new FormValidatorCSRF($this)); - - } - - /** - * Initialize form data. - */ - function initData() { - $contextId = $this->_journalId ; - $plugin = $this->_plugin; - - $this->setData('convertToPdf', $plugin->getSetting($contextId, 'convertToPdf')); - $this->setData('citationStyle', $plugin->getSetting($contextId, 'citationStyle')); - } - - /** - * Assign form data to user-submitted data. - */ - function readInputData() { - $this->readUserVars(array('convertToPdf', 'citationStyle', 'customStyleInput', 'galleysImport')); - } - - /** - * Fetch the form. - * @copydoc Form::fetch() - */ - function fetch($request, $template = null, $display = false) { - $templateMgr = TemplateManager::getManager($request); - $templateMgr->assign([ - 'pluginName' => $this->_plugin->getName(), - 'citationStyles' => $this->_plugin::getSupportedCitationStyles() - ]); - return parent::fetch($request, $template, $display); - } - - /** - * Save settings. - */ - function execute(...$functionArgs) { - $plugin = $this->_plugin; - $contextId = $this->_journalId ; - - $convertToPdf = $this->getData('convertToPdf'); - if (!$convertToPdf) { - $convertToPdf = false; - } else { - $convertToPdf = true; - } - $plugin->updateSetting($contextId, 'convertToPdf', $convertToPdf); - - // Citation Style Format - $citationStyle = $this->getData('citationStyle'); - if ($citationStyle == 'customStyle') { - $plugin->updateSetting($contextId, 'citationStyle', $this->getData('customStyleInput')); - } else { - $plugin->updateSetting($contextId, 'citationStyle', $this->getData('citationStyle')); - } - - // Import galleys - if ($importGalleys = $this->getData('galleysImport')) { - $plugin->importGalleys(); - } - - parent::execute(...$functionArgs); - } -} diff --git a/JatsParserSettingsForm.php b/JatsParserSettingsForm.php new file mode 100644 index 00000000..db31e328 --- /dev/null +++ b/JatsParserSettingsForm.php @@ -0,0 +1,82 @@ +_journalId = $journalId; + $this->_plugin = $plugin; + + parent::__construct($plugin->getTemplateResource('settingsForm.tpl')); + + $this->addCheck(new \PKP\form\validation\FormValidatorPost($this)); + $this->addCheck(new \PKP\form\validation\FormValidatorCSRF($this)); + } + + public function initData(): void + { + $contextId = $this->_journalId; + $plugin = $this->_plugin; + + $this->setData('convertToPdf', $plugin->getSetting($contextId, 'convertToPdf')); + $this->setData('citationStyle', $plugin->getSetting($contextId, 'citationStyle')); + } + + public function readInputData(): void + { + $this->readUserVars(['convertToPdf', 'citationStyle', 'customStyleInput', 'galleysImport']); + } + + public function fetch($request, $template = null, $display = false) + { + $templateMgr = \APP\template\TemplateManager::getManager($request); + $templateMgr->assign([ + 'pluginName' => $this->_plugin->getName(), + 'citationStyles' => $this->_plugin::getSupportedCitationStyles(), + ]); + return parent::fetch($request, $template, $display); + } + + public function execute(...$functionArgs) + { + $plugin = $this->_plugin; + $contextId = $this->_journalId; + + $convertToPdf = (bool) $this->getData('convertToPdf'); + $plugin->updateSetting($contextId, 'convertToPdf', $convertToPdf); + + $citationStyle = $this->getData('citationStyle'); + if ($citationStyle === 'customStyle') { + $plugin->updateSetting($contextId, 'citationStyle', $this->getData('customStyleInput')); + } else { + $plugin->updateSetting($contextId, 'citationStyle', $citationStyle); + } + + if ($this->getData('galleysImport')) { + $plugin->importGalleys(); + } + + parent::execute(...$functionArgs); + } +} diff --git a/JatsParserWorkflowHandler.php b/JatsParserWorkflowHandler.php new file mode 100644 index 00000000..4c2a97aa --- /dev/null +++ b/JatsParserWorkflowHandler.php @@ -0,0 +1,287 @@ +_plugin = PluginRegistry::getPlugin('generic', $pluginName); + parent::__construct(); + + $this->addRoleAssignment( + [ + Role::ROLE_ID_MANAGER, + Role::ROLE_ID_SITE_ADMIN, + Role::ROLE_ID_SUB_EDITOR, + Role::ROLE_ID_ASSISTANT, + ], + ['processSubmission', 'clearFullText', 'getWorkflowFiles'] + ); + } + + /** + * @copydoc PKPHandler::authorize() + */ + public function authorize($request, &$args, $roleAssignments) + { + $this->addPolicy(new ContextRequiredPolicy($request)); + + $rolePolicy = new PolicySet(PolicySet::COMBINING_PERMIT_OVERRIDES); + foreach ($roleAssignments as $role => $operations) { + $rolePolicy->addPolicy(new RoleBasedHandlerOperationPolicy($request, $role, $operations)); + } + $this->addPolicy($rolePolicy); + + return parent::authorize($request, $args, $roleAssignments); + } + + /** + * Process a Production-Ready XML file for a given publication. + * + * The file to process is taken (in order of priority): + * 1. `fileId` POST param — explicit selection from the UI + * 2. Previously stored `jatsParser::fullTextFileId` for the locale (re-process) + * + * @param array $args + * @param \APP\core\Request $request + */ + public function processSubmission(array $args, $request): JSONMessage + { + if (!$request->isPost() || !$request->checkCSRF()) { + return new JSONMessage(false, __('api.400.badRequest')); + } + + $submissionId = (int) $request->getUserVar('submissionId'); + $publicationId = (int) $request->getUserVar('publicationId'); + $requestedFileId = (int) $request->getUserVar('fileId'); // explicit selection + + if (!$submissionId || !$publicationId) { + return new JSONMessage(false, __('api.400.badRequest')); + } + + $submission = Repo::submission()->get($submissionId); + if (!$submission) { + return new JSONMessage(false, __('api.404.resourceNotFound')); + } + + $publication = Repo::publication()->get($publicationId); + if (!$publication || $publication->getData('submissionId') !== $submission->getId()) { + return new JSONMessage(false, __('api.404.resourceNotFound')); + } + + $locale = $submission->getData('locale'); + $storedFileIds = (array) ($publication->getData('jatsParser::fullTextFileId') ?? []); + + // 1. Explicit file selected from the UI + $submissionFile = null; + if ($requestedFileId) { + $submissionFile = Repo::submissionFile()->get($requestedFileId); + } + + // 2. Previously stored file (re-process without changing the source) + if (!$submissionFile && !empty($storedFileIds[$locale])) { + $submissionFile = Repo::submissionFile()->get((int) $storedFileIds[$locale]); + } + + if (!$submissionFile) { + return new JSONMessage(false, '', '0', ['errorCode' => 'noJatsFile']); + } + + try { + $htmlDocument = $this->_plugin->getFullTextFromJats($submissionFile); + } catch (\Throwable $e) { + error_log('JATSParser processSubmission error: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine()); + return new JSONMessage(false, '', '0', ['errorCode' => 'processError', 'errorMessage' => $e->getMessage()]); + } + + Repo::publication()->edit($publication, [ + 'jatsParser::fullTextFileId' => array_merge( + $storedFileIds, + [$locale => $submissionFile->getId()] + ), + 'jatsParser::fullText' => array_merge( + (array) ($publication->getData('jatsParser::fullText') ?? []), + [$locale => $htmlDocument->saveAsHTML()] + ), + ]); + + return new JSONMessage(true, [ + 'fileId' => $submissionFile->getId(), + 'locale' => $locale, + ]); + } + + /** + * Clear the JATS full-text data for a given publication. + * Removes the generated HTML and the source file reference from + * publication_settings; the original XML file is not deleted. + * + * @param array $args + * @param \APP\core\Request $request + */ + public function clearFullText(array $args, $request): JSONMessage + { + if (!$request->isPost() || !$request->checkCSRF()) { + return new JSONMessage(false, __('api.400.badRequest')); + } + + $submissionId = (int) $request->getUserVar('submissionId'); + $publicationId = (int) $request->getUserVar('publicationId'); + + if (!$submissionId || !$publicationId) { + return new JSONMessage(false, __('api.400.badRequest')); + } + + $submission = Repo::submission()->get($submissionId); + if (!$submission) { + return new JSONMessage(false, __('api.404.resourceNotFound')); + } + + $publication = Repo::publication()->get($publicationId); + if (!$publication || $publication->getData('submissionId') !== $submission->getId()) { + return new JSONMessage(false, __('api.404.resourceNotFound')); + } + + $locale = $submission->getData('locale'); + + $fullTextFileIds = (array) ($publication->getData('jatsParser::fullTextFileId') ?? []); + unset($fullTextFileIds[$locale]); + + $fullTexts = (array) ($publication->getData('jatsParser::fullText') ?? []); + unset($fullTexts[$locale]); + + Repo::publication()->edit($publication, [ + 'jatsParser::fullTextFileId' => empty($fullTextFileIds) ? null : $fullTextFileIds, + 'jatsParser::fullText' => empty($fullTexts) ? null : $fullTexts, + ]); + + return new JSONMessage(true, ['locale' => $locale]); + } + + /** + * Return the Production-Ready XML files available for this submission, + * plus the image assets attached to the currently processed file. + * + * Response content: + * - productionFiles : [{id, name, isSelected}] + * - assets : [{id, name, mimetype}] + * - selectedFileId : int|null + * - selectedFileName: string|null + * + * @param array $args + * @param \APP\core\Request $request + */ + public function getWorkflowFiles(array $args, $request): JSONMessage + { + $submissionId = (int) $request->getUserVar('submissionId'); + $publicationId = (int) $request->getUserVar('publicationId'); + + if (!$submissionId || !$publicationId) { + return new JSONMessage(false, __('api.400.badRequest')); + } + + $submission = Repo::submission()->get($submissionId); + if (!$submission) { + return new JSONMessage(false, __('api.404.resourceNotFound')); + } + + $publication = Repo::publication()->get($publicationId); + if (!$publication || $publication->getData('submissionId') !== $submission->getId()) { + return new JSONMessage(false, __('api.404.resourceNotFound')); + } + + $locale = $submission->getData('locale'); + $storedFileIds = (array) ($publication->getData('jatsParser::fullTextFileId') ?? []); + $selectedFileId = $storedFileIds[$locale] ?? null; + + // ── Production-Ready XML files ──────────────────────────────────────── + $productionFiles = []; + $allProductionFiles = Repo::submissionFile() + ->getCollector() + ->filterBySubmissionIds([$submissionId]) + ->filterByFileStages([SubmissionFile::SUBMISSION_FILE_PRODUCTION_READY]) + ->getMany(); + + foreach ($allProductionFiles as $file) { + $mime = $file->getData('mimetype'); + if (!in_array($mime, ['application/xml', 'text/xml', 'application/jats+xml'])) { + continue; + } + $productionFiles[] = [ + 'id' => $file->getId(), + 'name' => $file->getLocalizedData('name'), + 'isSelected' => ($file->getId() == $selectedFileId), + ]; + } + + // ── Assets (dependent image files) of the currently processed file ──── + $assets = []; + $selectedFileName = null; + + if ($selectedFileId) { + $selectedFile = Repo::submissionFile()->get((int) $selectedFileId); + if ($selectedFile) { + $selectedFileName = $selectedFile->getLocalizedData('name'); + $genreDao = DAORegistry::getDAO('GenreDAO'); + + $dependentFiles = Repo::submissionFile() + ->getCollector() + ->filterByAssoc(Application::ASSOC_TYPE_SUBMISSION_FILE, [(int) $selectedFileId]) + ->filterBySubmissionIds([$submissionId]) + ->filterByFileStages([SubmissionFile::SUBMISSION_FILE_DEPENDENT]) + ->includeDependentFiles() + ->getMany(); + + foreach ($dependentFiles as $depFile) { + $genre = $genreDao->getById($depFile->getData('genreId')); + if (!$genre || $genre->getCategory() !== Genre::GENRE_CATEGORY_ARTWORK) { + continue; + } + $assets[] = [ + 'id' => $depFile->getId(), + 'name' => $depFile->getLocalizedData('name'), + 'mimetype' => $depFile->getData('mimetype'), + ]; + } + } + } + + return new JSONMessage(true, [ + 'productionFiles' => $productionFiles, + 'assets' => $assets, + 'selectedFileId' => $selectedFileId, + 'selectedFileName' => $selectedFileName, + ]); + } +} diff --git a/README.md b/README.md index 159cd9f4..478ba893 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # JATSParserPlugin OJS3 Plugin for parsing JATS XML and displaying it on article detail page. -## Features +## Features * JATS XML to HTML conversion. * JATS XML to PDF conversion. * Article's metadata now is taken directly from OJS (no need to populate JATS XML meta nodes). @@ -8,14 +8,14 @@ OJS3 Plugin for parsing JATS XML and displaying it on article detail page. * Support for figures attached to the XML through OJS dashboard. ## How to use? ### Installation -1. Download the [latest release](https://github.com/Vitaliy-1/JATSParserPlugin/releases) +1. Download the [latest release](https://github.com/Vitaliy-1/JATSParserPlugin/releases) 2. Upload the plugin from the admin dashboard `Website Settings -> Plugins -> Upload a New Plugin` (make sure php.ini variables `upload_max_filesize` and `post_max_size` a set to equal or more than 16M) or unpack the archive into the `plugins/generic/` folder. 3. Activate the plugin from the dashboard. 4. To change image logo in resulted PDF just replace `JATSParser/logo/logo.jpg` file by yours. ### Usage After activation the plugin adds new item to the publication form: -![Screenshot from the publication page when plugin is activated](https://github.com/Vitaliy-1/JATSParserPlugin/blob/main/images/jatsParser_scr_1.png?raw=true) -The first select option contains the list of XML files uploaded to the production ready stage where is possible to pick the file that will be converted and saved as article's full-text. Before saving, a result of a conversion can be previewed. +![Screenshot from the publication page when plugin is activated](https://github.com/Vitaliy-1/JATSParserPlugin/blob/master/images/jatsParser_scr_1.png?raw=true) +The first select option contains the list of XML files uploaded to the production ready stage where is possible to pick the file that will be converted and saved as article's full-text. Before saving, a result of a conversion can be previewed. Under the hood the conversion process transforms JATS XML into HTML and saves the results in the database. After publication full-text will be shown on the article landing page under the abstract. @@ -23,16 +23,16 @@ After publication full-text will be shown on the article landing page under the ### Installation for development 1. Navigate to `plugins/generic` folder starting from OJS webroot. 2. `git clone --recursive https://github.com/Vitaliy-1/JATSParserPlugin.git jatsParser`. -3. To install support for JATS to PDF conversion: `cd jatsParser/JATSParser` and `composer install`. +3. To install support for JATS to PDF conversion: `cd jatsParser/JATSParser` and `composer install`. ## Requirements * PHP 7.3 or higher * OJS 3.1+ * Lens Galley Plugin must be turned off ## Examples -* Example of the JATS XML: https://github.com/Vitaliy-1/JATSParser/blob/main/examples/example.xml -* HTML example: https://e-medjournal.com/index.php/psp/article/view/213 -* PDF example: https://uk.e-medjournal.com/index.php/psp/article/view/296/486 +* Example of the JATS XML: https://github.com/Vitaliy-1/JATSParser/blob/master/example.xml +* HTML example: http://ojsdemo.e-medjournal.com/index.php/jatsparser/article/view/8/8 +* PDF example: http://ojsdemo.e-medjournal.com/index.php/jatsparser/article/view/8/8?download=pdf ## Release notes ### 2.2.0 -Starting from this version JATS Parser Plugin starts to serve HTML statically and will no longer support rendering of the full-text on the fly on the galley page. Instead full-text is generated on demand from production ready JATS XML files and saved as a part of the publication. +Starting from this version JATS Parser Plugin starts to serve HTML statically and will no longer support rendering of the full-text on the fly on the galley page. Instead full-text is generated on demand from production ready JATS XML files and saved as a part of the publication. diff --git a/classes/JATSParserDocument.php b/classes/JATSParserDocument.php new file mode 100644 index 00000000..4ccd4e51 --- /dev/null +++ b/classes/JATSParserDocument.php @@ -0,0 +1,40 @@ +parseReferences = $parseReferences; + + parent::__construct($jatsDocument, $parseReferences); + + $this->jatsDocument = $jatsDocument; + } + + public function useOjsReferences(): bool + { + if (!$this->jatsDocument->getReferences()) { + return true; + } + return false; + } +} diff --git a/index.php b/index.php index 71588594..5c487a6b 100644 --- a/index.php +++ b/index.php @@ -11,8 +11,8 @@ * */ -require_once('JatsParserPlugin.inc.php'); +require_once('JatsParserPlugin.php'); -return new JatsParserPlugin(); +return new \APP\plugins\generic\jatsParser\JatsParserPlugin(); ?> diff --git a/js/jatsParserWorkflow.js b/js/jatsParserWorkflow.js new file mode 100644 index 00000000..15b22ec4 --- /dev/null +++ b/js/jatsParserWorkflow.js @@ -0,0 +1,370 @@ +/** + * @file plugins/generic/jatsParser/js/jatsParserWorkflow.js + * + * Copyright (c) 2017-2024 Vitalii Bezsheiko + * Distributed under the GNU GPL v3. + * + * @brief Vue.js component for the "JATS Full Text" custom tab in the editorial workflow. + * + * XML files are read from the Production stage (Production-Ready files). + * The native OJS JATS tab is not used. + * + * Registers the component and: + * 1. Extends getMenuItems → adds a custom "JATS Full Text" secondary tab under Publication. + * 2. Extends getPrimaryItems → injects the component into that tab. + */ + +pkp.registry.registerComponent('JatsParserWorkflowSection', { + name: 'JatsParserWorkflowSection', + + template: + '

    ' + + + // ── Loading ────────────────────────────────────────────────────────── + '
    ' + + ' {{ t(\'loading\') }}…' + + '
    ' + + + // ── Main content ───────────────────────────────────────────────────── + '
    ' + + + // No XML files in Production + '
    ' + + ' {{ t(\'noProductionFiles\') }}' + + '
    ' + + + // File selector + '
    ' + + '
    ' + + ' {{ t(\'selectFile\') }}' + + '
    ' + + '
    ' + + ' ' + + ' ' + + '
    ' + + '
    ' + + + // Action buttons + '
    ' + + ' ' + + ' {{ selectedRadioFileId && selectedRadioFileId == selectedFileId ? t(\'reprocess\') : t(\'process\') }}' + + ' ' + + ' ' + + ' {{ t(\'clearFullText\') }}' + + ' ' + + '
    ' + + + // Feedback message + '
    ' + + ' {{ message }}' + + '
    ' + + + // Assets section + '
    ' + + '
    ' + + ' {{ t(\'assetsTitle\') }}' + + '
    ' + + '
      ' + + '
    • {{ asset.name }}
    • ' + + '
    ' + + '
    ' + + + // Upload hint + '

    ' + + ' {{ t(\'uploadInfo\') }}' + + '

    ' + + + '
    ' + // end v-else + '
    ', + + props: { + submission: { + type: Object, + required: true, + }, + publication: { + type: Object, + required: true, + }, + canEdit: { + type: Boolean, + default: false, + }, + }, + + data() { + return { + isLoading: true, + isBusy: false, + message: '', + messageIsError: false, + productionFiles: [], // PRODUCTION_READY XML files + assets: [], // dependent image files of the selected XML + selectedFileId: null, // file currently stored in publication settings + selectedFileName: null, + selectedRadioFileId: null, // user's radio selection in the UI + }; + }, + + computed: { + isProcessed() { + return !!this.selectedFileId; + }, + + messageStyle() { + return this.messageIsError + ? 'background:#fde8e8;color:#c00;' + : 'background:#e8f5e9;color:#2e7d32;'; + }, + }, + + mounted() { + this.loadFiles(); + }, + + methods: { + t(key) { + var cfg = window.jatsParserConfig; + if (cfg && cfg.locale && cfg.locale[key] !== undefined) { + return cfg.locale[key]; + } + return key; + }, + + /** + * Load Production-Ready XML files and asset list from the server. + */ + async loadFiles() { + var cfg = window.jatsParserConfig; + if (!cfg || !cfg.filesUrl) { + this.isLoading = false; + return; + } + + this.isLoading = true; + + var formData = new FormData(); + formData.append('submissionId', this.submission.id); + formData.append('publicationId', this.publication.id); + formData.append('csrfToken', pkp.currentUser.csrfToken); + + try { + var response = await fetch(cfg.filesUrl, { + method: 'POST', + body: formData, + }); + var data = await response.json(); + + if (data.status === true && data.content) { + this.productionFiles = data.content.productionFiles || []; + this.assets = data.content.assets || []; + this.selectedFileId = data.content.selectedFileId || null; + this.selectedFileName = data.content.selectedFileName || null; + // Pre-select the currently processed file in the radio list + this.selectedRadioFileId = this.selectedFileId; + } + } catch (e) { + // Silently ignore load errors + } + + this.isLoading = false; + }, + + /** + * Process the selected Production-Ready XML file. + */ + async process() { + if (!this.selectedRadioFileId) { + return; + } + + this.isBusy = true; + this.message = ''; + this.messageIsError = false; + + var cfg = window.jatsParserConfig; + var formData = new FormData(); + formData.append('submissionId', this.submission.id); + formData.append('publicationId', this.publication.id); + formData.append('fileId', this.selectedRadioFileId); + formData.append('csrfToken', pkp.currentUser.csrfToken); + + try { + var response = await fetch(cfg.processUrl, { + method: 'POST', + body: formData, + }); + var data = await response.json(); + + if (data.status === true) { + this.message = this.t('processSuccess'); + this.messageIsError = false; + + // Update local state so isProcessed and the check-mark refresh + if (data.content && data.content.fileId) { + this.selectedFileId = data.content.fileId; + if (!this.publication['jatsParser::fullTextFileId']) { + this.publication['jatsParser::fullTextFileId'] = {}; + } + this.publication['jatsParser::fullTextFileId'][data.content.locale] = + data.content.fileId; + } + + // Reload to refresh isSelected flags and asset list + await this.loadFiles(); + } else if (data.errorCode === 'noJatsFile') { + this.message = this.t('noJatsFile'); + this.messageIsError = true; + } else { + this.message = this.t('processError'); + this.messageIsError = true; + } + } catch (e) { + this.message = this.t('processError'); + this.messageIsError = true; + } + + this.isBusy = false; + }, + + /** + * Remove the generated full text (the XML file in Production is kept). + */ + async clear() { + if (!confirm(this.t('confirmClear'))) { + return; + } + + this.isBusy = true; + this.message = ''; + this.messageIsError = false; + + var cfg = window.jatsParserConfig; + var formData = new FormData(); + formData.append('submissionId', this.submission.id); + formData.append('publicationId', this.publication.id); + formData.append('csrfToken', pkp.currentUser.csrfToken); + + try { + var response = await fetch(cfg.clearUrl, { + method: 'POST', + body: formData, + }); + var data = await response.json(); + + if (data.status === true) { + this.message = this.t('clearSuccess'); + this.messageIsError = false; + // Clear processed-file state; keep radio selection so the user + // can immediately re-process if desired + this.selectedFileId = null; + this.selectedFileName = null; + this.assets = []; + this.publication['jatsParser::fullTextFileId'] = null; + // Refresh the isSelected flags in productionFiles + this.productionFiles = this.productionFiles.map(function (f) { + return Object.assign({}, f, {isSelected: false}); + }); + } else { + this.message = this.t('clearError'); + this.messageIsError = true; + } + } catch (e) { + this.message = this.t('clearError'); + this.messageIsError = true; + } + + this.isBusy = false; + }, + }, +}); + +/** + * Add a custom "JATS Full Text" secondary tab under the Publication primary menu. + */ +pkp.registry.storeExtendFn('workflow', 'getMenuItems', function (originalItems, args) { + var tabLabel = + window.jatsParserConfig && + window.jatsParserConfig.locale && + window.jatsParserConfig.locale.tabLabel + ? window.jatsParserConfig.locale.tabLabel + : 'JATS Full Text'; + return originalItems.map(function (item) { + if (item.key === 'publication' && Array.isArray(item.items)) { + return Object.assign({}, item, { + items: item.items.concat([ + { + key: 'publication_jatsparser', + label: tabLabel, + state: { + primaryMenuItem: 'publication', + secondaryMenuItem: 'jatsparser', + title: tabLabel, + }, + }, + ]), + }); + } + return item; + }); +}); + +/** + * Inject JatsParserWorkflowSection into the custom "jatsparser" publication tab. + */ +pkp.registry.storeExtendFn( + 'workflow', + 'getPrimaryItems', + function (originalItems, args) { + if ( + args.selectedMenuState && + args.selectedMenuState.primaryMenuItem === 'publication' && + args.selectedMenuState.secondaryMenuItem === 'jatsparser' + ) { + return [ + { + component: 'JatsParserWorkflowSection', + props: { + submission: args.submission, + publication: + args.submission.publications.find(function (p) { + return p.status === 1; + }) || + args.submission.publications[ + args.submission.publications.length - 1 + ], + canEdit: args.permissions + ? args.permissions.canEditPublication + : false, + }, + }, + ]; + } + + return originalItems; + }, +); diff --git a/locale/en/locale.po b/locale/en/locale.po index 4e6f897f..18cf3146 100644 --- a/locale/en/locale.po +++ b/locale/en/locale.po @@ -29,7 +29,7 @@ msgstr "JATS Parser Settings" msgid "plugins.generic.jatsParser.settings.description" msgstr "JATSParser plugin settings menu" -msgid "plugins.generic.jatsParser.settings.covert.pdf" +msgid "plugins.generic.jatsParser.settings.convert.pdf" msgstr "Activate JATS XML to PDF conversion" msgid "plugins.generic.jatsParser.galley.import" @@ -110,5 +110,53 @@ msgstr "e.g.: american-medical-association" msgid "plugins.generic.jatsParser.publication.jats.links.label" msgstr "Format in-text links to references?" -msgid "plugins.generic.jatsParser.settings.convert.pdf" -msgstr "Enable PDF conversion" +msgid "plugins.generic.jatsParser.workflow.processed" +msgstr "Full text has been processed from JATS XML." + +msgid "plugins.generic.jatsParser.workflow.notProcessed" +msgstr "No JATS full text has been processed yet. Upload a JATS XML file in the section above to process it automatically, or use the button below if a file already exists." + +msgid "plugins.generic.jatsParser.workflow.process" +msgstr "Process JATS" + +msgid "plugins.generic.jatsParser.workflow.reprocess" +msgstr "Re-process JATS" + +msgid "plugins.generic.jatsParser.workflow.processSuccess" +msgstr "JATS file processed successfully." + +msgid "plugins.generic.jatsParser.workflow.processError" +msgstr "An error occurred while processing the JATS file." + +msgid "plugins.generic.jatsParser.workflow.noJatsFile" +msgstr "No JATS file found for this publication." + +msgid "plugins.generic.jatsParser.workflow.clearFullText" +msgstr "Remove Full Text" + +msgid "plugins.generic.jatsParser.workflow.clearSuccess" +msgstr "Full text removed successfully. The JATS XML file remains in the production stage." + +msgid "plugins.generic.jatsParser.workflow.clearError" +msgstr "An error occurred while removing the full text." + +msgid "plugins.generic.jatsParser.workflow.confirmClear" +msgstr "Are you sure you want to remove the processed full text? The JATS XML file will not be deleted, only the generated HTML will be cleared." + +msgid "plugins.generic.jatsParser.workflow.tab.label" +msgstr "JATS Full Text" + +msgid "plugins.generic.jatsParser.workflow.selectFile" +msgstr "Select an XML file from the Production stage:" + +msgid "plugins.generic.jatsParser.workflow.noProductionFiles" +msgstr "No XML files found in the Production stage. Upload an XML file (Production Ready) and, optionally, attach images as dependent files." + +msgid "plugins.generic.jatsParser.workflow.currentlyProcessed" +msgstr "currently processed" + +msgid "plugins.generic.jatsParser.workflow.assets.title" +msgstr "Attached Images" + +msgid "plugins.generic.jatsParser.workflow.assets.uploadInfo" +msgstr "Upload the XML file and attach images as dependent files in the Production stage, then select the file above." diff --git a/locale/es/locale.po b/locale/es/locale.po index a11e49e2..a96cab8d 100644 --- a/locale/es/locale.po +++ b/locale/es/locale.po @@ -2,17 +2,14 @@ msgid "" msgstr "" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2021-03-01T09:34:56+00:00\n" -"PO-Revision-Date: 2022-07-01 20:52+0000\n" -"Last-Translator: Juan Pablo Alperin \n" -"Language-Team: Spanish \n" -"Language: es_ES\n" +"Last-Translator: \n" +"Language-Team: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=2; plural=n != 1;\n" -"X-Generator: Weblate 3.9.1\n" +"POT-Creation-Date: 2021-03-01T09:34:56+00:00\n" +"PO-Revision-Date: 2021-03-01T09:34:56+00:00\n" +"Language: \n" msgid "plugins.generic.jatsParser.displayName" msgstr "Módulo JATSParser" @@ -37,111 +34,3 @@ msgstr "Acceso libre" msgid "jatsParser.references.link" msgstr "Buscar en el texto" - -msgid "plugins.generic.jatsParser.settings.convert.pdf" -msgstr "Habilitar conversión a PDF" - -msgid "plugins.generic.jatsParser.publication.jats.links.label" -msgstr "Cambiar enlaces en el texto a referencias?" - -msgid "plugins.generic.jatsParser.style.label" -msgstr "e.j.: american-medical-association" - -msgid "plugins.generic.jatsParser.style.description" -msgstr "" -"Este formato de referencias fue generado por el plugin. Para otros estilos, " -"visite el repository CSL." - -msgid "plugins.generic.jatsParser.style.custom" -msgstr "Otros formatos de citas" - -msgid "plugins.generic.jatsParser.style.vancouver" -msgstr "Vancouver" - -msgid "plugins.generic.jatsParser.style.turabian-fullnote-bibliography" -msgstr "Turabian" - -msgid "plugins.generic.jatsParser.style.modern-language-association" -msgstr "MLA" - -msgid "plugins.generic.jatsParser.style.ieee" -msgstr "IEEE" - -msgid "plugins.generic.jatsParser.style.harvard-cite-them-right" -msgstr "Harvard" - -msgid "plugins.generic.jatsParser.style.chicago-author-date" -msgstr "Chicago" - -msgid "plugins.generic.jatsParser.style.associacao-brasileira-de-normas-tecnicas" -msgstr "ABNT" - -msgid "plugins.generic.jatsParser.style.apa" -msgstr "APA" - -msgid "plugins.generic.jatsParser.style.acs-nano" -msgstr "ACS" - -msgid "plugins.generic.jatsParser.style.acm-sig-proceedings" -msgstr "ACM" - -msgid "plugins.generic.jatsParser.publication.galley.pdf.label" -msgstr "PDF" - -msgid "plugins.generic.jatsParser.publication.jats.pdf.label" -msgstr "¿Crear galerada de PDF?" - -msgid "plugins.generic.jatsParser.publication.jats.references.description" -msgstr "" -"La lista de referencias se importarán del JATS XML y se guardarán como parte " -"de la publicación. Si las referencias ya existen en la publicación, serán " -"remplazadas con las del JATS XML." - -msgid "plugins.generic.jatsParser.publication.jats.references.label" -msgstr "Importar referencias del JATS XML?" - -msgid "plugins.generic.jatsParser.publication.jats.descriptionEmpty" -msgstr "" -"La lista de archivos JATS XML está vacia. Por favor, suba un archivo al area " -"de producción y aparecerá debajo para la generación del texto completo." - -msgid "plugins.generic.jatsParser.publication.jats.description" -msgstr "Seleccione un archivo de JATS XML para crear el texto completo." - -msgid "plugins.generic.jatsParser.publication.jats.label" -msgstr "Crear texto completo" - -msgid "plugins.generic.jatsParser.publication.jats.fulltext.success" -msgstr "Texto completo subido existosamente" - -msgid "plugins.generic.jatsParser.publication.jats.fulltext" -msgstr "Text Completo" - -msgid "plugins.generic.jatsParser.galley.import.title" -msgstr "Importar galeradas de texto completo" - -msgid "plugins.generic.jatsParser.galley.import.description" -msgstr "" -"Está opción le permite guardar las galeradas JATS XML como texto completo en " -"todas las publicaciones de la revista. No se importa si la publicación ya " -"tiene una galerada de texto completo. La importación comiensa al guardar el " -"formulario" - -msgid "plugins.generic.jatsParser.galley.import" -msgstr "Importar galeradas de JATS XML" - -msgid "plugins.generic.jatsParser.settings.covert.pdf" -msgstr "Activar Conversión JATS XML a PDF" - -msgid "plugins.generic.jatsParser.settings.description" -msgstr "Menú de configuración del Plugin JATSParser" - -msgid "plugins.generic.jatsParser.workflow.settings" -msgstr "Configuración del JATS Parser" - -msgid "plugins.generic.jatsParser.article.fulltext.availableLocales" -msgstr "El texto completo del artículo está disponible en estos idiomas:" - -msgid "plugins.generic.jatsParser.article.fulltext.availableLocale" -msgstr "El texto completo del artículo está disponible en este idioma:" diff --git a/locale/it/locale.po b/locale/it/locale.po new file mode 100644 index 00000000..db7a1b5f --- /dev/null +++ b/locale/it/locale.po @@ -0,0 +1,163 @@ +msgid "" +msgstr "" +"Project-Id-Version: \n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2021-03-01T09:34:26+00:00\n" +"PO-Revision-Date: 2026-05-17 10:32+0200\n" +"Last-Translator: \n" +"Language-Team: \n" +"Language: it\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"X-Generator: Poedit 3.4.1\n" + +msgid "plugins.generic.jatsParser.displayName" +msgstr "Plugin JATSParser" + +msgid "plugins.generic.jatsParser.description" +msgstr "Il plugin trasforma JATS XML in HTML e PDF per la visualizzazione nel front-end della rivista" + +msgid "plugins.generic.jatsParser.article.fulltext.availableLocale" +msgstr "Il Full-text dell'articolo è disponibile in questa lingua:" + +msgid "plugins.generic.jatsParser.article.fulltext.availableLocales" +msgstr "Il Full-text dell'articolo è disponibile in queste lingue:" + +msgid "plugins.generic.jatsParser.workflow.settings" +msgstr "Impostazioni JATS Parser" + +msgid "plugins.generic.jatsParser.settings.description" +msgstr "Menu impostazioni per plugin JATSParser" + +msgid "plugins.generic.jatsParser.settings.convert.pdf" +msgstr "Attiva la conversione JATS XML a PDF" + +msgid "plugins.generic.jatsParser.galley.import" +msgstr "Importazione delle bozze JATS XML" + +msgid "plugins.generic.jatsParser.galley.import.description" +msgstr "Questa opzione consente di salvare le bozze JATS XML come full-text in tutte le pubblicazioni della rivista. L'importazione viene omessa se una pubblicazione ha già il Full-text per una determinata bozza. L'importazione inizia subito dopo il salvataggio del modulo." + +msgid "plugins.generic.jatsParser.galley.import.title" +msgstr "Importazione di Full-text dalle bozze" + +msgid "plugins.generic.jatsParser.publication.jats.fulltext" +msgstr "Full Text" + +msgid "plugins.generic.jatsParser.publication.jats.fulltext.success" +msgstr "Caricamento del Full-text completato con successo" + +msgid "plugins.generic.jatsParser.publication.jats.label" +msgstr "Crea full text" + +msgid "plugins.generic.jatsParser.publication.jats.description" +msgstr "Seleziona un file pronto per la produzione in formato JATS XML per creare il Full-text." + +msgid "plugins.generic.jatsParser.publication.jats.descriptionEmpty" +msgstr "La lista dei files JATS XML è vuota. Carica il file nella fase di produzione e apparirà qui sotto per la generazione del Full-text." + +msgid "plugins.generic.jatsParser.publication.jats.references.label" +msgstr "Recuperare i riferimenti bibliografici dal file JATS XML?" + +msgid "plugins.generic.jatsParser.publication.jats.references.description" +msgstr "La lista dei riferimenti bibliografici verrà recuperata dal file JATS XML e salvata come parte della pubblicazione. Se i riferimenti sono già inclusi nella pubblicazione, verranno sovrascritti." + +msgid "plugins.generic.jatsParser.publication.jats.pdf.label" +msgstr "Creare la bozza PDF?" + +msgid "plugins.generic.jatsParser.publication.galley.pdf.label" +msgstr "PDF" + +msgid "plugins.generic.jatsParser.style.acm-sig-proceedings" +msgstr "ACM" + +msgid "plugins.generic.jatsParser.style.acs-nano" +msgstr "ACS" + +msgid "plugins.generic.jatsParser.style.apa" +msgstr "APA" + +msgid "plugins.generic.jatsParser.style.associacao-brasileira-de-normas-tecnicas" +msgstr "ABNT" + +msgid "plugins.generic.jatsParser.style.chicago-author-date" +msgstr "Chicago" + +msgid "plugins.generic.jatsParser.style.harvard-cite-them-right" +msgstr "Harvard" + +msgid "plugins.generic.jatsParser.style.ieee" +msgstr "IEEE" + +msgid "plugins.generic.jatsParser.style.modern-language-association" +msgstr "MLA" + +msgid "plugins.generic.jatsParser.style.turabian-fullnote-bibliography" +msgstr "Turabian" + +msgid "plugins.generic.jatsParser.style.vancouver" +msgstr "Vancouver" + +msgid "plugins.generic.jatsParser.style.custom" +msgstr "Altri formati di stile citazione" + +msgid "plugins.generic.jatsParser.style.description" +msgstr "Il formato di stile per i riferimenti elaborati dal plugin. Per altri stili, visita il repository CSL per verificare se è supportato." + +msgid "plugins.generic.jatsParser.style.label" +msgstr "es.: american-medical-association" + +msgid "plugins.generic.jatsParser.publication.jats.links.label" +msgstr "Formattare i links in-text come riferimenti?" + +msgid "plugins.generic.jatsParser.workflow.processed" +msgstr "Il full text è stato processato dal JATS XML." + +msgid "plugins.generic.jatsParser.workflow.notProcessed" +msgstr "Nessun full test JATS è stato ancora elaborato. Carica un file JATS XML nella sezione sopra per elaborarlo automaticamente, oppure usa il pulsante qui sotto se un file esiste già." + +msgid "plugins.generic.jatsParser.workflow.process" +msgstr "Elabora JATS" + +msgid "plugins.generic.jatsParser.workflow.reprocess" +msgstr "Rielabora JATS" + +msgid "plugins.generic.jatsParser.workflow.processSuccess" +msgstr "File JATS elaborato con successo." + +msgid "plugins.generic.jatsParser.workflow.processError" +msgstr "Si è verificato un errore durante l'elaborazione del file JATS." + +msgid "plugins.generic.jatsParser.workflow.noJatsFile" +msgstr "Nessun file JATS trovato per questa pubblicazione." + +msgid "plugins.generic.jatsParser.workflow.clearFullText" +msgstr "Removere Full Text" + +msgid "plugins.generic.jatsParser.workflow.clearSuccess" +msgstr "Full text rimosso con successo. Il file JATS XML rimane in produzione." + +msgid "plugins.generic.jatsParser.workflow.clearError" +msgstr "Si è verificato un errore durante la rimozione del full text." + +msgid "plugins.generic.jatsParser.workflow.confirmClear" +msgstr "Sei sicuro di voler rimuovere il testo integrale elaborato? Il file JATS XML non verrà eliminato, verrà rimosso solo l'HTML generato." + +msgid "plugins.generic.jatsParser.workflow.tab.label" +msgstr "JATS Full Text" + +msgid "plugins.generic.jatsParser.workflow.selectFile" +msgstr "Selezionare un file XML dalla fase di produzione:" + +msgid "plugins.generic.jatsParser.workflow.noProductionFiles" +msgstr "Nessun file XML trovato nella fase di produzione. Carica un file XML (Pronto per la produzione) e, facoltativamente, allega le immagini come file dipendenti." + +msgid "plugins.generic.jatsParser.workflow.currentlyProcessed" +msgstr "attualmente elaborato" + +msgid "plugins.generic.jatsParser.workflow.assets.title" +msgstr "Immagini allegate" + +msgid "plugins.generic.jatsParser.workflow.assets.uploadInfo" +msgstr "Carica il file XML e allega le immagini come file dipendenti nella fase di produzione, quindi seleziona il file qui sopra." diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 00000000..194a9424 --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,12 @@ + + + + + tests/JATSParser + + + diff --git a/registry/uiLocaleKeysBackend.json b/registry/uiLocaleKeysBackend.json new file mode 100644 index 00000000..8df3b8ab --- /dev/null +++ b/registry/uiLocaleKeysBackend.json @@ -0,0 +1,8 @@ +[ + "plugins.generic.jatsParser.workflow.processed", + "plugins.generic.jatsParser.workflow.notProcessed", + "plugins.generic.jatsParser.workflow.process", + "plugins.generic.jatsParser.workflow.reprocess", + "plugins.generic.jatsParser.workflow.processSuccess", + "plugins.generic.jatsParser.workflow.processError" +] diff --git a/settings.xml b/settings.xml old mode 100755 new mode 100644 diff --git a/templates/workflowJatsFulltext.tpl b/templates/workflowJatsFulltext.tpl deleted file mode 100644 index a221efcd..00000000 --- a/templates/workflowJatsFulltext.tpl +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/tests/JATSParser/Back/ReferenceTest.php b/tests/JATSParser/Back/ReferenceTest.php new file mode 100644 index 00000000..91b5aa6c --- /dev/null +++ b/tests/JATSParser/Back/ReferenceTest.php @@ -0,0 +1,159 @@ +getReferences(); + $this->assertCount(4, $refs, 'Article should have 4 references'); + } + + public function testJournalReferenceType(): void + { + $refs = self::$doc->getReferences(); + $this->assertInstanceOf(Journal::class, $refs[0]); + } + + public function testBookReferenceType(): void + { + $refs = self::$doc->getReferences(); + $this->assertInstanceOf(Book::class, $refs[1]); + } + + public function testChapterReferenceType(): void + { + $refs = self::$doc->getReferences(); + $this->assertInstanceOf(Chapter::class, $refs[2]); + } + + public function testConferenceReferenceType(): void + { + $refs = self::$doc->getReferences(); + // confproc is not mapped; parser falls back to Journal + $this->assertInstanceOf(Journal::class, $refs[3]); + } + + // ─── getRawReference fix ───────────────────────────────────────── + + public function testGetRawReferenceReturnsContentNotLabel(): void + { + $refs = self::$doc->getReferences(); + + $rawRef = $refs[0]->getRawReference(); + + // The raw reference should contain the citation text, NOT just the label "1" + $this->assertStringContainsString('Smith', $rawRef, 'Raw reference should contain author name'); + $this->assertStringContainsString('groundbreaking study', $rawRef, 'Raw reference should contain article title'); + $this->assertStringContainsString('2023', $rawRef, 'Raw reference should contain year'); + } + + public function testGetRawReferenceNotEmpty(): void + { + $refs = self::$doc->getReferences(); + + foreach ($refs as $index => $ref) { + $rawRef = $ref->getRawReference(); + $this->assertNotEmpty($rawRef, "Reference #{$index} getRawReference() should not be empty"); + // Should be longer than just a number label + $this->assertGreaterThan(5, strlen($rawRef), + "Reference #{$index} getRawReference() should contain actual citation text, not just a label"); + } + } + + // ─── Mixed vs element citations ────────────────────────────────── + + public function testMixedCitationDetected(): void + { + $refs = self::$doc->getReferences(); + // ref-1 is mixed-citation + $this->assertTrue($refs[0]->isMixed(), 'Reference 1 should be detected as mixed-citation'); + } + + public function testElementCitationDetected(): void + { + $refs = self::$doc->getReferences(); + // ref-2 is element-citation + $this->assertFalse($refs[1]->isMixed(), 'Reference 2 should be detected as element-citation'); + } + + // ─── Reference metadata ────────────────────────────────────────── + + public function testReferenceId(): void + { + $refs = self::$doc->getReferences(); + $this->assertEquals('ref-1', $refs[0]->getId()); + $this->assertEquals('ref-2', $refs[1]->getId()); + } + + public function testReferenceYear(): void + { + $refs = self::$doc->getReferences(); + $this->assertEquals('2023', $refs[0]->getYear()); + $this->assertEquals('2022', $refs[1]->getYear()); + } + + public function testReferenceAuthors(): void + { + $refs = self::$doc->getReferences(); + $authors = $refs[0]->getAuthors(); + + $this->assertCount(2, $authors, 'Reference 1 should have 2 authors'); + } + + public function testReferenceEditors(): void + { + $refs = self::$doc->getReferences(); + // ref-3 (chapter) has an editor + $editors = $refs[2]->getEditors(); + + $this->assertCount(1, $editors, 'Reference 3 should have 1 editor'); + } + + public function testReferenceDoi(): void + { + $refs = self::$doc->getReferences(); + $pubIds = $refs[0]->getPubIdType(); + + $this->assertArrayHasKey('doi', $pubIds); + $this->assertStringContainsString('10.1234', $pubIds['doi']); + } + + public function testReferencePmid(): void + { + $refs = self::$doc->getReferences(); + $pubIds = $refs[3]->getPubIdType(); + + $this->assertArrayHasKey('pmid', $pubIds); + $this->assertStringContainsString('12345678', $pubIds['pmid']); + } + + // ─── Collaboration authors ─────────────────────────────────────── + + public function testCollaborationAuthorDetected(): void + { + $refs = self::$doc->getReferences(); + // ref-4 has a collab author "XML Working Group" + $authors = $refs[3]->getAuthors(); + + $this->assertGreaterThanOrEqual(2, count($authors), + 'Reference 4 should have individual + collaboration authors'); + } +} diff --git a/tests/JATSParser/Body/DocumentTest.php b/tests/JATSParser/Body/DocumentTest.php new file mode 100644 index 00000000..7cbf060e --- /dev/null +++ b/tests/JATSParser/Body/DocumentTest.php @@ -0,0 +1,210 @@ +getArticleSections(); + + $this->assertCount(2, $sections, 'Article should have 2 top-level sections'); + } + + public function testBasicArticleSectionTitles(): void + { + $doc = new Document(self::$fixturesPath . '/basic-article.xml'); + $sections = $doc->getArticleSections(); + + $this->assertInstanceOf(Section::class, $sections[0]); + $this->assertEquals('Introduction', $sections[0]->getTitle()); + $this->assertEquals('Methods', $sections[1]->getTitle()); + } + + public function testBasicArticleSectionContent(): void + { + $doc = new Document(self::$fixturesPath . '/basic-article.xml'); + $sections = $doc->getArticleSections(); + + $content = $sections[0]->getContent(); + // Section 1 has 2 paragraphs + $parasOnly = array_filter($content, fn($el) => $el instanceof Par); + $this->assertCount(2, $parasOnly, 'Introduction should have 2 paragraphs'); + } + + public function testBasicArticleReferences(): void + { + $doc = new Document(self::$fixturesPath . '/basic-article.xml'); + $refs = $doc->getReferences(); + + $this->assertCount(1, $refs, 'Article should have 1 reference'); + } + + // ─── Inline tags (Body\Text) ───────────────────────────────────── + + public function testInlineTagsParseWithoutErrors(): void + { + $doc = new Document(self::$fixturesPath . '/inline-tags.xml'); + $sections = $doc->getArticleSections(); + + $this->assertCount(1, $sections); + $content = $sections[0]->getContent(); + // 16 paragraphs in the fixture + $parasOnly = array_filter($content, fn($el) => $el instanceof Par); + $this->assertGreaterThanOrEqual(14, count($parasOnly)); + } + + public function testInlineGraphicParsedFromParagraph(): void + { + $doc = new Document(self::$fixturesPath . '/inline-tags.xml'); + $sections = $doc->getArticleSections(); + $content = $sections[0]->getContent(); + + // Find paragraphs that contain InlineGraphic elements + $foundInlineGraphic = false; + foreach ($content as $element) { + if ($element instanceof Par) { + foreach ($element->getContent() as $child) { + if ($child instanceof InlineGraphic) { + $foundInlineGraphic = true; + $this->assertEquals('figure1.png', $child->getHref()); + } + } + } + } + + $this->assertTrue($foundInlineGraphic, 'An InlineGraphic should be found in the parsed content'); + } + + public function testBoldTextHasBoldType(): void + { + $doc = new Document(self::$fixturesPath . '/inline-tags.xml'); + $sections = $doc->getArticleSections(); + $content = $sections[0]->getContent(); + + // Paragraph "Combined bold italic text." + // Look for a Text node with both bold and italic types + $foundBoldItalic = false; + foreach ($content as $element) { + if ($element instanceof Par) { + foreach ($element->getContent() as $child) { + if ($child instanceof Text) { + $types = $child->getType(); + if (in_array('bold', $types) && in_array('italic', $types)) { + $foundBoldItalic = true; + $this->assertEquals('bold italic', $child->getContent()); + } + } + } + } + } + + $this->assertTrue($foundBoldItalic, 'Should find a text node with both bold and italic types'); + } + + // ─── Block elements ────────────────────────────────────────────── + + public function testBoxedTextParsed(): void + { + $doc = new Document(self::$fixturesPath . '/block-elements.xml'); + $sections = $doc->getArticleSections(); + $content = $sections[0]->getContent(); + + $boxedTexts = array_filter($content, fn($el) => $el instanceof BoxedText); + $this->assertCount(1, $boxedTexts, 'Should find 1 boxed-text element'); + } + + public function testDefListParsed(): void + { + $doc = new Document(self::$fixturesPath . '/block-elements.xml'); + $sections = $doc->getArticleSections(); + $content = $sections[0]->getContent(); + + $defLists = array_values(array_filter($content, fn($el) => $el instanceof DefList)); + $this->assertCount(1, $defLists, 'Should find 1 def-list element'); + + $defList = $defLists[0]; + $this->assertEquals('Glossary', $defList->getTitle()); + + $items = $defList->getContent(); + $this->assertCount(2, $items, 'Def-list should have 2 items'); + + // Verify first item term text + $firstTermTexts = $items[0]['term']; + $this->assertNotEmpty($firstTermTexts); + $termContent = ''; + foreach ($firstTermTexts as $t) { + $termContent .= $t->getContent(); + } + $this->assertEquals('API', $termContent); + } + + public function testPreformatParsed(): void + { + $doc = new Document(self::$fixturesPath . '/block-elements.xml'); + $sections = $doc->getArticleSections(); + $content = $sections[0]->getContent(); + + $preformats = array_values(array_filter($content, fn($el) => $el instanceof Preformat)); + // Fixture has both and block + $this->assertCount(2, $preformats, 'Should find 2 preformat/code block elements'); + + $this->assertStringContainsString('function hello', $preformats[0]->getContent()); + $this->assertEquals('preformat', $preformats[0]->getContentType()); + + $this->assertStringContainsString('SELECT', $preformats[1]->getContent()); + $this->assertEquals('code', $preformats[1]->getContentType()); + } + + public function testDispFormulaParsed(): void + { + $doc = new Document(self::$fixturesPath . '/block-elements.xml'); + $sections = $doc->getArticleSections(); + $content = $sections[0]->getContent(); + + $formulas = array_values(array_filter($content, fn($el) => $el instanceof DispFormula)); + $this->assertCount(2, $formulas, 'Should find 2 disp-formula elements'); + + $this->assertEquals('eq-1', $formulas[0]->getId()); + $this->assertEquals('(1)', $formulas[0]->getLabel()); + $this->assertTrue($formulas[0]->hasLatex()); + $this->assertEquals('E = mc^2', $formulas[0]->getTexContent()); + + $this->assertEquals('eq-2', $formulas[1]->getId()); + $this->assertStringContainsString('sum_', $formulas[1]->getTexContent()); + } + + public function testDispQuoteParsed(): void + { + $doc = new Document(self::$fixturesPath . '/block-elements.xml'); + $sections = $doc->getArticleSections(); + $content = $sections[0]->getContent(); + + $quotes = array_values(array_filter($content, fn($el) => + $el instanceof DispQuote && !$el instanceof BoxedText + )); + $this->assertCount(1, $quotes, 'Should find 1 disp-quote element'); + } +} diff --git a/tests/JATSParser/HTML/DocumentTest.php b/tests/JATSParser/HTML/DocumentTest.php new file mode 100644 index 00000000..f5a4f9ba --- /dev/null +++ b/tests/JATSParser/HTML/DocumentTest.php @@ -0,0 +1,220 @@ +saveAsHTML(); + } + + // ─── Basic rendering ───────────────────────────────────────────── + + public function testBasicArticleRendersHTML(): void + { + $html = $this->getHTML('basic-article.xml'); + + $this->assertNotEmpty($html); + $this->assertStringContainsString('simple paragraph', $html); + } + + public function testBasicArticleContainsSectionHeaders(): void + { + $html = $this->getHTML('basic-article.xml'); + + $this->assertStringContainsString('Introduction', $html); + $this->assertStringContainsString('Methods', $html); + } + + public function testBoldAndItalicRendered(): void + { + $html = $this->getHTML('basic-article.xml'); + + $this->assertStringContainsString('', $html); + $this->assertStringContainsString('bold text', $html); + $this->assertStringContainsString('', $html); + $this->assertStringContainsString('italic text', $html); + } + + // ─── Inline tags rendering ─────────────────────────────────────── + + public function testMonospaceRendersAsCode(): void + { + $html = $this->getHTML('inline-tags.xml'); + $this->assertStringContainsString('monospaced code', $html); + } + + public function testSmallCapsRendersAsSpan(): void + { + $html = $this->getHTML('inline-tags.xml'); + $this->assertMatchesRegularExpression('/]*class="small-caps"[^>]*>small caps<\/span>/', $html); + } + + public function testStrikethroughRendersAsS(): void + { + $html = $this->getHTML('inline-tags.xml'); + $this->assertStringContainsString('strikethrough', $html); + } + + public function testNamedContentRendersAsSpan(): void + { + $html = $this->getHTML('inline-tags.xml'); + $this->assertMatchesRegularExpression('/]*class="named-content"[^>]*>BRCA1<\/span>/', $html); + } + + public function testStyledContentRendersAsSpan(): void + { + $html = $this->getHTML('inline-tags.xml'); + $this->assertMatchesRegularExpression('/]*class="styled-content"[^>]*>styled<\/span>/', $html); + } + + public function testAbbrevRendersAsAbbr(): void + { + $html = $this->getHTML('inline-tags.xml'); + $this->assertStringContainsString('WHO', $html); + } + + public function testInlineCodeRendersAsCode(): void + { + $html = $this->getHTML('inline-tags.xml'); + $this->assertStringContainsString('inline code', $html); + } + + public function testCommentRendersAsAnnotationSpan(): void + { + $html = $this->getHTML('inline-tags.xml'); + $this->assertMatchesRegularExpression('/]*class="annotation"[^>]*>editorial comment<\/span>/', $html); + } + + public function testRomanRendersAsSpan(): void + { + $html = $this->getHTML('inline-tags.xml'); + $this->assertMatchesRegularExpression('/]*class="roman"[^>]*>roman text<\/span>/', $html); + } + + public function testOverlineRendersWithStyle(): void + { + $html = $this->getHTML('inline-tags.xml'); + $this->assertMatchesRegularExpression('/]*style="text-decoration:overline"[^>]*>overlined text<\/span>/', $html); + } + + public function testEmailRendersAsMailtoLink(): void + { + $html = $this->getHTML('inline-tags.xml'); + $this->assertMatchesRegularExpression('/]*href="mailto:test@example\.com"[^>]*>/', $html); + $this->assertMatchesRegularExpression('/]*class="email"[^>]*>/', $html); + } + + public function testUriRendersAsLink(): void + { + $html = $this->getHTML('inline-tags.xml'); + $this->assertMatchesRegularExpression('/]*href="https:\/\/example\.com"[^>]*>/', $html); + } + + public function testInlineFormulaRendersAsSpan(): void + { + $html = $this->getHTML('inline-tags.xml'); + $this->assertMatchesRegularExpression('/]*class="inline-formula"[^>]*>/', $html); + } + + public function testInlineFormulaWithTexMathRendersContent(): void + { + // tex-math nested inside inline-formula: span wrapper is lost, + // but content is preserved (known parser limitation) + $html = $this->getHTML('inline-tags.xml'); + $this->assertStringContainsString('x + y = z', $html); + } + + public function testInlineGraphicRendersAsImg(): void + { + $html = $this->getHTML('inline-tags.xml'); + $this->assertMatchesRegularExpression('/]*src="figure1\.png"/', $html); + } + + // ─── Block elements rendering ──────────────────────────────────── + + public function testBlockElementsRenderWithoutErrors(): void + { + $html = $this->getHTML('block-elements.xml'); + $this->assertNotEmpty($html); + } + + public function testBoxedTextRendersAsDiv(): void + { + $html = $this->getHTML('block-elements.xml'); + // BoxedText extends DispQuote which renders as blockquote by default, + // but might render differently. Check for the content at minimum. + $this->assertStringContainsString('content inside a boxed text', $html); + } + + public function testDefListRendersAsDl(): void + { + $html = $this->getHTML('block-elements.xml'); + + $this->assertStringContainsString('assertStringContainsString('assertStringContainsString('assertStringContainsString('API', $html); + $this->assertStringContainsString('Application Programming Interface', $html); + } + + public function testPreformatRendersAsPre(): void + { + $html = $this->getHTML('block-elements.xml'); + + $this->assertStringContainsString('assertStringContainsString('function hello', $html); + } + + public function testCodeBlockRendersAsPre(): void + { + $html = $this->getHTML('block-elements.xml'); + + $this->assertStringContainsString('SELECT', $html); + } + + public function testDispFormulaRendered(): void + { + $html = $this->getHTML('block-elements.xml'); + + // Formula content should be present + $this->assertStringContainsString('E = mc^2', $html); + // The disp-formula div should be present + $this->assertMatchesRegularExpression('/disp-formula|formula/', $html); + } + + public function testDispFormulaLatexWrapped(): void + { + $html = $this->getHTML('block-elements.xml'); + + // LaTeX formulas should be wrapped in \[...\] for MathJax + // or otherwise marked for rendering + $this->assertStringContainsString('E = mc^2', $html); + } + + // ─── References rendering ──────────────────────────────────────── + + public function testReferencesRenderWithoutErrors(): void + { + $jatsDoc = new JATSDocument(self::$fixturesPath . '/references.xml'); + $htmlDoc = new HTMLDocument($jatsDoc); + + // Don't call setReferences() (CiteProc) — just verify the document renders + $html = $htmlDoc->saveAsHTML(); + $this->assertNotEmpty($html); + } +} diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 00000000..73674287 --- /dev/null +++ b/tests/README.md @@ -0,0 +1,56 @@ +# JATSParser Plugin — Unit Tests + +Unit tests for the JATSParser library used by the JATSParser OJS plugin. + +These tests cover the JATS XML parsing and HTML rendering pipeline without requiring OJS or database dependencies. + +## Scope + +| Test class | What it tests | +|---|---| +| `Body\DocumentTest` | JATS XML parsing: sections, paragraphs, inline tags, block elements (boxed-text, def-list, preformat, disp-formula), inline-graphic XPath fix | +| `HTML\DocumentTest` | HTML rendering: inline tag output (monospace→code, sc→small-caps, email→mailto, etc.), block element output (dl, pre, disp-formula), basic structure | +| `Back\ReferenceTest` | Reference extraction: getRawReference() fix, citation types (journal, book, chapter, conference), mixed vs element citations, DOI/PMID, collaboration authors | + +## Setup + +PHPUnit must be installed as a dev dependency. From the plugin root: + +```bash +cd JATSParser +composer require --dev phpunit/phpunit "^10.0" +cd .. +``` + +Alternatively, use a global PHPUnit install if available. + +## Running + +From the **plugin root** directory (`plugins/generic/jatsParser/`): + +```bash +./JATSParser/vendor/bin/phpunit -c phpunit.xml +``` + +Or in ddev: + +```bash +ddev exec -d /var/www/html/plugins/generic/jatsParser ./JATSParser/vendor/bin/phpunit -c phpunit.xml +``` + +## Fixtures + +Test fixtures are minimal JATS XML files in `tests/fixtures/`: + +| File | Content | +|---|---| +| `basic-article.xml` | 2 sections, bold/italic, 1 reference | +| `inline-tags.xml` | All new inline tags (monospace, sc, strike, email, uri, inline-graphic, etc.) | +| `block-elements.xml` | boxed-text, def-list, preformat, code, disp-formula, disp-quote | +| `references.xml` | 4 references: journal, book, chapter, conference with DOI/PMID | + +## Notes + +- Tests do **not** depend on OJS — they test the JATSParser library in isolation +- `setReferences()` (CiteProc) is not tested because it requires external CSL data and has known issues with locale handling in OJS 3.5 +- These tests are intended for maintenance during the OJS 3.5 LTS lifecycle diff --git a/tests/bootstrap.php b/tests/bootstrap.php new file mode 100644 index 00000000..bda45cfa --- /dev/null +++ b/tests/bootstrap.php @@ -0,0 +1,9 @@ + +
    + + + + Test Article for Unit Tests + + + + + + Introduction +

    This is a simple paragraph with no formatting.

    +

    This paragraph has bold text and italic text.

    +
    + + Methods +

    Paragraph in the second section.

    +
    + + + + + + + SmithJ + + A test article + Test Journal + 2023 + 1 + 10 + 20 + + + + +
    diff --git a/tests/fixtures/block-elements.xml b/tests/fixtures/block-elements.xml new file mode 100644 index 00000000..4e02c7e1 --- /dev/null +++ b/tests/fixtures/block-elements.xml @@ -0,0 +1,61 @@ + +
    + + + + Block Elements Test + + + + + + Block Elements + + +

    This is content inside a boxed text element.

    +

    It can contain multiple paragraphs.

    +
    + + + Glossary + + API +

    Application Programming Interface

    +
    + + XML +

    Extensible Markup Language

    +
    +
    + + +function hello() { + return "world"; +} + + + +SELECT * FROM articles WHERE status = 'published'; + + + + + E = mc^2 + + + + + \sum_{i=1}^{n} x_i = x_1 + x_2 + \cdots + x_n + + +

    A regular paragraph between block elements.

    + + +

    This is a block quote with attribution.

    + Famous Author +
    + +
    + + +
    diff --git a/tests/fixtures/inline-tags.xml b/tests/fixtures/inline-tags.xml new file mode 100644 index 00000000..ef710ab9 --- /dev/null +++ b/tests/fixtures/inline-tags.xml @@ -0,0 +1,33 @@ + +
    + + + + Inline Tags Test + + + + + + Inline Tags +

    Text with monospaced code in it.

    +

    Text with small caps styling.

    +

    Text with strikethrough content.

    +

    Text with BRCA1 annotation.

    +

    Text with styled content.

    +

    Text with WHO abbreviation.

    +

    Text with inline code element.

    +

    Text with editorial comment annotation.

    +

    Text with roman text styling.

    +

    Text with overlined text decoration.

    +

    Contact: test@example.com

    +

    Visit: https://example.com

    +

    The formula x + y = z is famous.

    +

    The formula E = mc^2 is famous.

    +

    See the image in the text.

    +

    Combined bold italic text.

    +

    Nested bold small caps text.

    +
    + + +
    diff --git a/tests/fixtures/references.xml b/tests/fixtures/references.xml new file mode 100644 index 00000000..a5009852 --- /dev/null +++ b/tests/fixtures/references.xml @@ -0,0 +1,78 @@ + +
    + + + + References Test + + + + + + Introduction +

    See references below.

    +
    + + + + + + + + SmithJohn A. + DoeJane + . + A groundbreaking study on JATS parsing. + Journal of XML Research. + 2023; + 15(3): + 100-115. + 10.1234/jxr.2023.001 + + + + + + + JohnsonRobert + + XML Processing: A Complete Guide + Academic Press + New York + 2022 + 10.5678/book.2022 + + + + + + + WilliamsAmy + . + JATS in the Modern Era. In: + + BrownDavid + , editor. + Handbook of Scholarly Publishing. + University Press; + 2021. p. + 45-67. + + + + + + + LeeMin + XML Working Group + + New approaches to JATS validation + International Conference on Scholarly Communication + 2023-06-15 + Berlin, Germany + 12345678 + + + + +
    diff --git a/version.xml b/version.xml index 97aee140..34ec0f0a 100644 --- a/version.xml +++ b/version.xml @@ -12,8 +12,8 @@ jatsParser plugins.generic - 2.1.9.3 - 2021-03-11 + 2.1.9.4 + 2026-03-11 1 JatsParserPlugin