├── .gitignore
├── samples
├── input
│ ├── libre_mendeley.docx
│ ├── libre_mendeley.odt
│ └── msword_zotero.docx
└── output
│ ├── libre_mendeley
│ └── image1.png
│ └── msword_zotero
│ └── image1.png
├── vendor
├── composer
│ ├── installed.json
│ ├── autoload_namespaces.php
│ ├── autoload_psr4.php
│ ├── autoload_classmap.php
│ ├── installed.php
│ ├── platform_check.php
│ ├── LICENSE
│ ├── autoload_static.php
│ ├── autoload_real.php
│ ├── InstalledVersions.php
│ └── ClassLoader.php
└── autoload.php
├── composer.json
├── src
└── docx2jats
│ ├── jats
│ ├── Row.php
│ ├── Cell.php
│ ├── Element.php
│ ├── Table.php
│ ├── Figure.php
│ ├── Par.php
│ ├── Text.php
│ ├── Reference.php
│ └── Document.php
│ ├── objectModel
│ ├── body
│ │ ├── Table.php
│ │ ├── Row.php
│ │ ├── Image.php
│ │ ├── Cell.php
│ │ ├── Text.php
│ │ ├── Reference.php
│ │ ├── InfoBlock.php
│ │ ├── Field.php
│ │ └── Par.php
│ ├── DataObject.php
│ ├── traits
│ │ └── Bookmarkable.php
│ └── Document.php
│ └── DOCXArchive.php
├── composer.lock
├── example.php
├── README.md
├── docxtojats.php
└── LICENSE
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea/
2 |
--------------------------------------------------------------------------------
/samples/input/libre_mendeley.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Vitaliy-1/docxToJats/HEAD/samples/input/libre_mendeley.docx
--------------------------------------------------------------------------------
/samples/input/libre_mendeley.odt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Vitaliy-1/docxToJats/HEAD/samples/input/libre_mendeley.odt
--------------------------------------------------------------------------------
/samples/input/msword_zotero.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Vitaliy-1/docxToJats/HEAD/samples/input/msword_zotero.docx
--------------------------------------------------------------------------------
/vendor/composer/installed.json:
--------------------------------------------------------------------------------
1 | {
2 | "packages": [],
3 | "dev": true,
4 | "dev-package-names": []
5 | }
6 |
--------------------------------------------------------------------------------
/samples/output/libre_mendeley/image1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Vitaliy-1/docxToJats/HEAD/samples/output/libre_mendeley/image1.png
--------------------------------------------------------------------------------
/samples/output/msword_zotero/image1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Vitaliy-1/docxToJats/HEAD/samples/output/msword_zotero/image1.png
--------------------------------------------------------------------------------
/vendor/autoload.php:
--------------------------------------------------------------------------------
1 | array($baseDir . '/src/docx2jats'),
10 | );
11 |
--------------------------------------------------------------------------------
/vendor/composer/autoload_classmap.php:
--------------------------------------------------------------------------------
1 | $vendorDir . '/composer/InstalledVersions.php',
10 | );
11 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "doc/docx2jats",
3 | "description": "DOCX to JATS XML converter",
4 | "type": "library",
5 | "license": "GPLv3",
6 | "authors": [
7 | {
8 | "name": "Vitaliy Bezsheiko",
9 | "email": "vitaliybezsh@gmail.com"
10 | }
11 | ],
12 | "minimum-stability": "dev",
13 | "require": {
14 | "php": "^7.3|^8.0",
15 | "ext-zip": "^1.15",
16 | "ext-dom": "*",
17 | "ext-json": "*"
18 | },
19 | "autoload": {
20 | "psr-4": {
21 | "docx2jats\\": "src/docx2jats"
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/vendor/composer/installed.php:
--------------------------------------------------------------------------------
1 |
3 | array (
4 | 'pretty_version' => 'dev-main',
5 | 'version' => 'dev-main',
6 | 'aliases' =>
7 | array (
8 | ),
9 | 'reference' => 'd5ab4b12220646b40524b31073d74cd66786ca8f',
10 | 'name' => 'doc/docx2jats',
11 | ),
12 | 'versions' =>
13 | array (
14 | 'doc/docx2jats' =>
15 | array (
16 | 'pretty_version' => 'dev-main',
17 | 'version' => 'dev-main',
18 | 'aliases' =>
19 | array (
20 | ),
21 | 'reference' => 'd5ab4b12220646b40524b31073d74cd66786ca8f',
22 | ),
23 | ),
24 | );
25 |
--------------------------------------------------------------------------------
/src/docx2jats/jats/Row.php:
--------------------------------------------------------------------------------
1 | getDataObject()->getContent() as $content) {
22 | $cell = new JatsCell($content);
23 | $this->appendChild($cell);
24 | $cell->setContent();
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/composer.lock:
--------------------------------------------------------------------------------
1 | {
2 | "_readme": [
3 | "This file locks the dependencies of your project to a known state",
4 | "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
5 | "This file is @generated automatically"
6 | ],
7 | "content-hash": "e984e8442950cfa645834680280cd8ed",
8 | "packages": [],
9 | "packages-dev": [],
10 | "aliases": [],
11 | "minimum-stability": "dev",
12 | "stability-flags": [],
13 | "prefer-stable": false,
14 | "prefer-lowest": false,
15 | "platform": {
16 | "php": "^7.3|^8.0",
17 | "ext-zip": "^1.15",
18 | "ext-dom": "*",
19 | "ext-json": "*"
20 | },
21 | "platform-dev": [],
22 | "plugin-api-version": "2.0.0"
23 | }
24 |
--------------------------------------------------------------------------------
/src/docx2jats/jats/Cell.php:
--------------------------------------------------------------------------------
1 | getDataObject();
22 |
23 | $colspan = $dataObject->getColspan();
24 | $rowspan = $dataObject->getRowspan();
25 | if ($colspan > 1) {
26 | $this->setAttribute('colspan', $colspan);
27 | }
28 |
29 | if ($rowspan > 1) {
30 | $this->setAttribute('rowspan', $rowspan);
31 | }
32 |
33 | foreach ($dataObject->getContent() as $content) {
34 | $par = new Par($content);
35 | $this->appendChild($par);
36 | $par->setContent();
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/vendor/composer/platform_check.php:
--------------------------------------------------------------------------------
1 | = 70300)) {
8 | $issues[] = 'Your Composer dependencies require a PHP version ">= 7.3.0". You are running ' . PHP_VERSION . '.';
9 | }
10 |
11 | if ($issues) {
12 | if (!headers_sent()) {
13 | header('HTTP/1.1 500 Internal Server Error');
14 | }
15 | if (!ini_get('display_errors')) {
16 | if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
17 | fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL);
18 | } elseif (!headers_sent()) {
19 | echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL;
20 | }
21 | }
22 | trigger_error(
23 | 'Composer detected issues in your platform: ' . implode(' ', $issues),
24 | E_USER_ERROR
25 | );
26 | }
27 |
--------------------------------------------------------------------------------
/vendor/composer/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Copyright (c) Nils Adermann, Jordi Boggiano
3 |
4 | Permission is hereby granted, free of charge, to any person obtaining a copy
5 | of this software and associated documentation files (the "Software"), to deal
6 | in the Software without restriction, including without limitation the rights
7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | copies of the Software, and to permit persons to whom the Software is furnished
9 | to do so, subject to the following conditions:
10 |
11 | The above copyright notice and this permission notice shall be included in all
12 | copies or substantial portions of the Software.
13 |
14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 | THE SOFTWARE.
21 |
22 |
--------------------------------------------------------------------------------
/vendor/composer/autoload_static.php:
--------------------------------------------------------------------------------
1 |
11 | array (
12 | 'docx2jats\\' => 10,
13 | ),
14 | );
15 |
16 | public static $prefixDirsPsr4 = array (
17 | 'docx2jats\\' =>
18 | array (
19 | 0 => __DIR__ . '/../..' . '/src/docx2jats',
20 | ),
21 | );
22 |
23 | public static $classMap = array (
24 | 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
25 | );
26 |
27 | public static function getInitializer(ClassLoader $loader)
28 | {
29 | return \Closure::bind(function () use ($loader) {
30 | $loader->prefixLengthsPsr4 = ComposerStaticInitd38a08c226f474d77249d2c531c9a269::$prefixLengthsPsr4;
31 | $loader->prefixDirsPsr4 = ComposerStaticInitd38a08c226f474d77249d2c531c9a269::$prefixDirsPsr4;
32 | $loader->classMap = ComposerStaticInitd38a08c226f474d77249d2c531c9a269::$classMap;
33 |
34 | }, null, ClassLoader::class);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/example.php:
--------------------------------------------------------------------------------
1 | getDocument()->getContent();
22 |
23 | foreach ($contents as $content) {
24 | //echo "\n";
25 | if (get_class($content) === "docx2jats\objectModel\body\Par") {
26 | foreach ($content->getContent() as $textObject) {
27 | //echo $textObject->getContent();
28 | }
29 | //echo $content->getNumberingId();
30 | } elseif (get_class($content) === "docx2jats\objectModel\body\Table") {
31 | foreach ($content->getContent() as $textObject) {
32 | //echo $textObject->getContent();
33 | }
34 | }
35 | }
36 |
37 | // Creating JATS XML
38 | $jatsXML = new Document($docxArchive);
39 | $filename = basename($path, ".docx");
40 | $outputDir = "samples/output/";
41 | $jatsXML->getJatsFile($outputDir . $filename . ".xml");
42 | $docxArchive->getMediaFiles($outputDir);
43 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Description
2 | DocxToJats is a PHP library that converts DOCX archives that comply OOXML standards into JATS XML (Journal Article Tag Suite) format. It's tested with DOCX produced by LibreOffice, MS Word, and Google Docs.
3 | ## Requirements
4 | * The only requirement is PHP 7.3 or higher. CLI version if running from a command line
5 | ## Usage
6 | 1. `git clone https://github.com/Vitaliy-1/docxToJats.git`
7 | 2. `cd docxToJats`
8 | 3. `php docxtojats.php [/path/to/input/file.docx or /path/to/input/dir/] [/path/to/output/file.xml or /path/to/output/dir]`. E.g., to process a single file: `php docxtojats.php /mydir/file.docx /mydir/converted/file.xml` - if output filename is pointed, attached files, like figures, will be moved into the same folder; to process multiple files in a folder by relative path: `samples/input/ samples/output/`.
9 | ## Additional info
10 | * The list of supported elements: https://github.com/Vitaliy-1/docxConverter#what-article-elements-are-supported.
11 | * How to achieve the best results: https://github.com/Vitaliy-1/docxConverter#how-to-achieve-best-results
12 |
13 | DocxToJats is used as a submodule to the DOCX Converter Plugin, written for Open Journal Systems. Unfortunately DOCX archive doesn't contain much metadata and JATS `front` elements remain not populated, thus, the best way would be to integrate docxToJats with editorial manager from where article's metadata can be retrieved. DOCX Converter Plugin is such an example.
14 |
--------------------------------------------------------------------------------
/src/docx2jats/objectModel/body/Table.php:
--------------------------------------------------------------------------------
1 | properties = $this->setProperties('w:tblPr/child::node()');
25 | $this->rows = $this->setContent('w:tr');
26 | }
27 |
28 | private function setContent(string $xpathExpression) {
29 | $content = array();
30 |
31 | $contentNodes = $this->getXpath()->query($xpathExpression, $this->getDomElement());
32 | if ($contentNodes->count() > 0) {
33 | foreach ($contentNodes as $contentNode) {
34 | $row = new Row($contentNode, $this->getOwnerDocument(), $this);
35 | $content[] = $row;
36 | }
37 | }
38 |
39 | return $content;
40 | }
41 |
42 | public function getContent() {
43 | return $this->rows;
44 | }
45 |
46 | /**
47 | * @param int $currentTableId
48 | */
49 | public function setTableId(int $currentTableId): void {
50 | $this->tableId = $currentTableId;
51 | }
52 |
53 | /**
54 | * @return int
55 | */
56 | public function getId(): int {
57 | return $this->tableId;
58 | }
59 |
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/src/docx2jats/jats/Element.php:
--------------------------------------------------------------------------------
1 | dataObject = $dataObject;
22 |
23 | // Determing element name
24 | $name = '';
25 | switch (get_class($dataObject)) {
26 | case "docx2jats\objectModel\body\Par":
27 | /* @var $dataObject \docx2jats\objectModel\body\Par */
28 |
29 | $types = $dataObject->getType();
30 | // Create title tag; title shouldn't be placed inside the table cell
31 | if (in_array(Par::DOCX_PAR_HEADING, $types) && get_class($dataObject->getParent()) !== "docx2jats\objectModel\body\Cell") {
32 | $name = "title";
33 | } else {
34 | $name = "p";
35 | }
36 | break;
37 | case "docx2jats\objectModel\body\Table":
38 | $name = 'table-wrap';
39 | break;
40 | case "docx2jats\objectModel\body\Row":
41 | $name = 'tr';
42 | break;
43 | case "docx2jats\objectModel\body\Cell":
44 | $name = 'td';
45 | break;
46 | case "docx2jats\objectModel\body\Image":
47 | $name = 'fig';
48 | }
49 |
50 | /*
51 | $textString = '';
52 | foreach ($dataObject->getContent() as $text) {
53 | $textString .= $text->getContent();
54 | }
55 | */
56 |
57 | if (!empty($name)) parent::__construct($name);
58 | }
59 |
60 | protected function getDataObject() {
61 | return $this->dataObject;
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/src/docx2jats/objectModel/body/Row.php:
--------------------------------------------------------------------------------
1 | properties = $this->setProperties('w:trPr/child::node()');
24 | $this->cells = $this->setContent('w:tc');
25 | }
26 |
27 | private function setContent(string $xpathExpression) {
28 | $content = array();
29 | $contentNodes = $this->getXpath()->query($xpathExpression, $this->getDomElement());
30 | if ($contentNodes->count() > 0) {
31 | foreach ($contentNodes as $contentNode) {
32 |
33 | // calculating cell number
34 | $cellNumber = 1;
35 | $precedeSiblingNodes = $this->getXpath()->query('preceding-sibling::w:tc', $contentNode);
36 | foreach ($precedeSiblingNodes as $precedeSiblingNode) {
37 | $colspan = $this->getXpath()->query('w:tcPr/w:gridSpan/@w:val', $precedeSiblingNode);
38 | if ($colspan->count() == 0 || empty($colspan)) {
39 | $cellNumber ++;
40 | } else {
41 | $cellNumber += intval($colspan[0]->nodeValue);
42 | }
43 | }
44 | // Omit merged nodes
45 | $colspansMerged = $this->getXpath()->query('w:tcPr/w:vMerge[@w:val="continue"]', $contentNode);
46 | if (!$colspansMerged->count() > 0) {
47 | $cell = new Cell($contentNode, $cellNumber, $this->getOwnerDocument(), $this);
48 | $content[] = $cell;
49 | }
50 | }
51 | }
52 |
53 | return $content;
54 | }
55 |
56 | public function getContent() {
57 | return $this->cells;
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/vendor/composer/autoload_real.php:
--------------------------------------------------------------------------------
1 | = 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
32 | if ($useStaticLoader) {
33 | require __DIR__ . '/autoload_static.php';
34 |
35 | call_user_func(\Composer\Autoload\ComposerStaticInitd38a08c226f474d77249d2c531c9a269::getInitializer($loader));
36 | } else {
37 | $map = require __DIR__ . '/autoload_namespaces.php';
38 | foreach ($map as $namespace => $path) {
39 | $loader->set($namespace, $path);
40 | }
41 |
42 | $map = require __DIR__ . '/autoload_psr4.php';
43 | foreach ($map as $namespace => $path) {
44 | $loader->setPsr4($namespace, $path);
45 | }
46 |
47 | $classMap = require __DIR__ . '/autoload_classmap.php';
48 | if ($classMap) {
49 | $loader->addClassMap($classMap);
50 | }
51 | }
52 |
53 | $loader->register(true);
54 |
55 | return $loader;
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/src/docx2jats/jats/Table.php:
--------------------------------------------------------------------------------
1 | getDataObject(); /* @var $dataObject \docx2jats\objectModel\body\Table */
29 |
30 | if ($dataObject->getId()) {
31 | $this->setAttribute('id', self::JATS_TABLE_ID_PREFIX . $dataObject->getId());
32 | }
33 |
34 | if ($dataObject->getLabel()) {
35 | $this->appendChild($this->ownerDocument->createElement('label', $dataObject->getLabel()));
36 | }
37 |
38 | if ($dataObject->getTitle()) {
39 | $captionNode = $this->ownerDocument->createElement('caption');
40 | $this->appendChild($captionNode);
41 | $title = $this->ownerDocument->createElement('title', $dataObject->getTitle());
42 | // append citation if exists
43 | if ($dataObject->hasReferences()) {
44 | $refIds = $dataObject->getRefIds();
45 | $lastKey = array_key_last($refIds);
46 | foreach ($refIds as $key => $id) {
47 | $refEl = $this->ownerDocument->createElement('xref', $id);
48 | $refEl->setAttribute('ref-type', 'bibr');
49 | $refEl->setAttribute('rid', Reference::JATS_REF_ID_PREFIX . $id);
50 | if ($key !== $lastKey) {
51 | $empty = $this->ownerDocument->createTextNode(' ');
52 | $title->appendChild($empty);
53 | }
54 | $title->appendChild($refEl);
55 | }
56 | }
57 |
58 | $captionNode->appendChild($title);
59 | }
60 |
61 | $tableNode = $this->ownerDocument->createElement('table');
62 | $this->appendChild($tableNode);
63 |
64 | foreach ($dataObject->getContent() as $content) {
65 | $row = new JatsRow($content);
66 | $tableNode->appendChild($row);
67 | $row->setContent();
68 | }
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/src/docx2jats/objectModel/body/Image.php:
--------------------------------------------------------------------------------
1 | link = $this->extractLink();
25 | $this->setCaptionLibre();
26 | }
27 |
28 | private function extractLink(): ?string {
29 | $link = null;
30 | $relationshipId = null;
31 |
32 | // Only pictures are supported
33 | $this->getXpath()->registerNamespace("a", "http://schemas.openxmlformats.org/drawingml/2006/main");
34 | $linkElement = $this->getFirstElementByXpath(".//a:blip", $this->getDomElement());
35 | if ($linkElement && $linkElement->hasAttribute("r:embed")) {
36 | $relationshipId = $linkElement->getAttribute("r:embed");
37 | }
38 |
39 | if ($relationshipId) {
40 | $link = Document::getRelationshipById($relationshipId);
41 | }
42 |
43 | return $link;
44 | }
45 |
46 | public function getLink(): ?string {
47 | return $this->link;
48 | }
49 |
50 | public function getFileName(): ?string {
51 | $name = basename($this->link);
52 | return $name;
53 | }
54 |
55 | /**
56 | * @brief LibreOffice Writer saves figure caption inside the drawing element;
57 | */
58 | private function setCaptionLibre(): void {
59 | $txbxContent = Document::$xpath->query('.//w:txbxContent', $this->getDomElement())[0];
60 | if (!$txbxContent) return;
61 |
62 | // Pick up the first paragraph that contains caption style
63 | foreach ($txbxContent->childNodes as $childEl) {
64 | if ($childEl->tagName === 'w:p' && $this->getOwnerDocument()->isCaption($childEl)) {
65 | $this->setCaption($childEl);
66 | return;
67 | }
68 | }
69 | }
70 |
71 | /**
72 | * @param int $currentFigureId
73 | */
74 | public function setFigureId(int $currentFigureId): void {
75 | $this->figureId = $currentFigureId;
76 | }
77 |
78 | /**
79 | * @return int
80 | */
81 | public function getId(): int {
82 | return $this->figureId;
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/src/docx2jats/jats/Figure.php:
--------------------------------------------------------------------------------
1 | figureObject = $dataObject;
25 | }
26 |
27 | function setContent() {
28 | $dataObject = $this->getDataObject(); /* @var $dataObject \docx2jats\objectModel\body\Image */
29 |
30 | if ($dataObject->getId()) {
31 | $this->setAttribute('id', self::JATS_FIGURE_ID_PREFIX . $dataObject->getId());
32 | }
33 |
34 | if ($dataObject->getLabel()) {
35 | $this->appendChild($this->ownerDocument->createElement('label', $dataObject->getLabel()));
36 | }
37 |
38 | if ($dataObject->getTitle()) {
39 | $captionNode = $this->ownerDocument->createElement('caption');
40 | $this->appendChild($captionNode);
41 | $title = $this->ownerDocument->createElement('title', $dataObject->getTitle());
42 | // append citation if exists
43 | if ($dataObject->hasReferences()) {
44 | $refIds = $dataObject->getRefIds();
45 | $lastKey = array_key_last($refIds->getRefIds());
46 | foreach ($refIds as $key => $id) {
47 | $refEl = $this->ownerDocument->createElement('xref', $id);
48 | $refEl->setAttribute('ref-type', 'bibr');
49 | $refEl->setAttribute('rid', Reference::JATS_REF_ID_PREFIX . $id);
50 | if ($key !== $lastKey) {
51 | $empty = $this->ownerDocument->createTextNode(' ');
52 | $title->appendChild($empty);
53 | }
54 | $title->appendChild($refEl);
55 | }
56 | }
57 | $captionNode->appendChild($title);
58 | }
59 |
60 | $figureNode = $this->ownerDocument->createElement('graphic');
61 | $this->appendChild($figureNode);
62 |
63 | $pathInfo = pathinfo($this->figureObject->getLink());
64 |
65 | $figureNode->setAttribute("mimetype", "image");
66 |
67 | switch ($pathInfo['extension']) {
68 | case "jpg":
69 | case "jpeg":
70 | $figureNode->setAttribute("mime-subtype", "jpeg");
71 | break;
72 | case "png":
73 | $figureNode->setAttribute("mime-subtype", "png");
74 | break;
75 | }
76 |
77 | $figureNode->setAttribute("xlink:href", $pathInfo['basename']);
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/src/docx2jats/jats/Par.php:
--------------------------------------------------------------------------------
1 | getDataObject()->getContent() as $content) {
25 | if (get_class($content) === 'docx2jats\objectModel\body\Field') {
26 | // Write links to references from Zotero and Mendeley plugin for MS Word
27 | if ($content->getType() === Field::DOCX_FIELD_CSL) {
28 | $lastKey = array_key_last($content->getRefIds());
29 | foreach ($content->getRefIds() as $key => $id) {
30 | $refEl = $this->ownerDocument->createElement('xref', $id);
31 | $refEl->setAttribute('ref-type', 'bibr');
32 | $refEl->setAttribute('rid', Reference::JATS_REF_ID_PREFIX . $id);
33 | $this->appendChild($refEl);
34 | if ($key !== $lastKey) {
35 | $refEl = $this->ownerDocument->createTextNode(' ');
36 | $this->appendChild($refEl);
37 | }
38 | }
39 | }
40 | // Write links to table and figures
41 | elseif ($content->getType() === Field::DOCX_FIELD_BOOKMARK_REF) {
42 | $refEl = $this->ownerDocument->createElement('xref');
43 | $this->appendChild($refEl);
44 | foreach ($content->getContent() as $text) { /* @var $text \docx2jats\objectModel\body\Text */
45 | JatsText::extractText($text, $refEl);
46 | }
47 | if ($tableIdRef = $content->tableIdRef) {
48 | $refEl->setAttribute('ref-type', 'table');
49 | $refEl->setAttribute('rid', Table::JATS_TABLE_ID_PREFIX . $tableIdRef);
50 | } elseif ($figureIdRef = $content->figureIdRef) {
51 | $refEl->setAttribute('ref-type', 'fig');
52 | $refEl->setAttribute('rid', Figure::JATS_FIGURE_ID_PREFIX . $figureIdRef);
53 | }
54 | }
55 | $prevTextRefs = []; // restart track of refs from Mendeley LW plugin
56 | } else {
57 | // Write links to references from Mendeley plugin for LibreOffice Writer
58 | /* @var $content \docx2jats\objectModel\body\Text */
59 | if ($content->hasCSLRefs) {
60 | $currentRefs = $content->refIds;
61 | foreach ($currentRefs as $currentRefId) {
62 | if (!in_array($currentRefId, $prevTextRefs)) {
63 | $refEl = $this->ownerDocument->createElement('xref', $currentRefId);
64 | $this->appendChild($refEl);
65 | $refEl->setAttribute('ref-type', 'bibr');
66 | $refEl->setAttribute('rid', Reference::JATS_REF_ID_PREFIX . $currentRefId);
67 | }
68 | }
69 | $prevTextRefs = $currentRefs;
70 | }
71 | // Write other text
72 | else {
73 | JatsText::extractText($content, $this);
74 | $prevTextRefs = []; // restart track of refs from Mendeley LW plugin
75 | }
76 | }
77 | }
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/docxtojats.php:
--------------------------------------------------------------------------------
1 | getJatsFile($outputDir . $filename . ".xml");
82 | $docxArchive->getMediaFiles($outputDir);
83 | } else {
84 | if (!is_dir($outputDir . $filename)) {
85 | mkdir($outputDir . $filename);
86 | }
87 | $jatsXML->getJatsFile($outputDir . $filename . DIRECTORY_SEPARATOR . $filename . ".xml");
88 | $docxArchive->getMediaFiles($outputDir . $filename . DIRECTORY_SEPARATOR);
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/src/docx2jats/jats/Text.php:
--------------------------------------------------------------------------------
1 | ownerDocument;
21 | // Dealing with simple text (without any properties)
22 | $nodeTypes = $jatsText->getType();
23 | if (empty($nodeTypes)) {
24 | $textNode = $domDocument->createTextNode($jatsText->getContent());
25 | $domElement->appendChild($textNode);
26 | unset($nodeTypes);
27 | }
28 | // Renaming text properties into standard HTML node element
29 | $typeArray = array();
30 | if (isset($nodeTypes)) {
31 | foreach ($nodeTypes as $nodeType) {
32 | switch ($nodeType) {
33 | case ObjectText::DOCX_TEXT_ITALIC:
34 | $typeArray[] = "italic";
35 | break;
36 | case ObjectText::DOCX_TEXT_BOLD:
37 | $typeArray[] = "bold";
38 | break;
39 | case ObjectText::DOCX_TEXT_SUPERSCRIPT:
40 | $typeArray[] = "sup";
41 | break;
42 | case ObjectText::DOCX_TEXT_SUBSCRIPT:
43 | $typeArray[] = "sub";
44 | break;
45 | case ObjectText::DOCX_TEXT_EXTLINK:
46 | $typeArray[] = "ext-link";
47 | break;
48 | }
49 | }
50 | }
51 | // Dealing with text that has only one property, e.g. italic, bold, link
52 | if (count($typeArray) === 1) {
53 | foreach ($typeArray as $typeKey => $type) {
54 | if (!is_array($type)) {
55 | $nodeElement = $domDocument->createElement($type);
56 | $nodeElement->nodeValue = htmlspecialchars($jatsText->getContent());
57 | $domElement->appendChild($nodeElement);
58 | if ($type == "ext-link") {
59 | $nodeElement->setAttribute("xlink:href", $jatsText->getLink());
60 | }
61 | } else {
62 | foreach ($type as $insideKey => $insideType) {
63 | $nodeElement = $domDocument->createElement($insideKey);
64 | $nodeElement->nodeValue = htmlspecialchars(trim($jatsText->getContent()));
65 | $domElement->appendChild($nodeElement);
66 | }
67 | }
68 | }
69 | // Dealing with complex cases -> text with several properties
70 | } else {
71 | /* @var $prevElement array of DOMElements */
72 | $prevElements = array();
73 | foreach ($typeArray as $key => $type) {
74 | if (!is_array($type)) {
75 | $nodeElement = $domDocument->createElement($type);
76 | }
77 |
78 | array_push($prevElements, $nodeElement);
79 |
80 | if ($key === 0) {
81 | $domElement->appendChild($prevElements[0]);
82 | } elseif (($key === (count($typeArray) - 1))) {
83 |
84 | $nodeElement->nodeValue = htmlspecialchars($jatsText->getContent());
85 | if ($type == "ext-link"){
86 | $nodeElement->setAttribute("xlink:href", $jatsText->getLink());
87 | }
88 |
89 | foreach ($prevElements as $prevKey => $prevElement) {
90 | if ($prevKey !== (count($prevElements) -1)) {
91 | $prevElement->appendChild(next($prevElements));
92 | }
93 | }
94 | }
95 | }
96 | }
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/src/docx2jats/objectModel/body/Cell.php:
--------------------------------------------------------------------------------
1 | cellNumber = $cellNumber;
36 | $this->isMerged = $this->defineMerged();
37 | $this->colspan = $this->extractColspanNumber();
38 | $this->extractRowspanNumber();
39 | $this->paragraphs = $this->setParagraphs();
40 | $this->properties = $this->setProperties('w:tcPr');
41 | }
42 |
43 | /**
44 | * @return bool
45 | */
46 | public function defineMerged(): bool {
47 | $mergeNodes = $this->getXpath()->query('w:tcPr/w:vMerge', $this->getDomElement());
48 |
49 | if ($mergeNodes->count() == 0) {
50 | return false;
51 | }
52 |
53 | return true;
54 | }
55 |
56 | /**
57 | * @return void
58 | */
59 | private function extractRowspanNumber(): void {
60 | $rowMergedNode = $this->getXpath()->query('w:tcPr/w:vMerge[@w:val=\'restart\']', $this->getDomElement());
61 | $this->rowspan = 1;
62 |
63 | if ($rowMergedNode->count() > 0) {
64 | $this->extractRowspanRecursion($this->getDomElement());
65 | }
66 | }
67 |
68 | /**
69 | * @param \DOMElement $node
70 | * @return void
71 | */
72 | private function extractRowspanRecursion(\DOMElement $node): void {
73 | $cellNodeListInNextRow = $this->getXpath()->query('parent::w:tr/following-sibling::w:tr[1]/w:tc', $node);
74 |
75 |
76 | $numberOfCells = 0; // counting number of cells in a row
77 | $mergedNode = null; // retrieving possibly merged cell node
78 |
79 | foreach ($cellNodeListInNextRow as $cellNodeInNextRow) {
80 |
81 | $colspanNode = $this->getXpath()->query('w:tcPr/w:gridSpan/@w:val', $cellNodeInNextRow);
82 | if ($colspanNode->count() == 0) {
83 | $numberOfCells ++;
84 | } else {
85 | $numberOfCells += intval($colspanNode[0]->nodeValue) - 1;
86 | }
87 |
88 | /*
89 | echo $this->getColspan();
90 | echo " : " . $numberOfCells . "-" . $this->cellNumber . "\n";
91 | */
92 | if ($numberOfCells == $this->cellNumber) {
93 | $mergedNode = $cellNodeInNextRow;
94 | break;
95 | }
96 | }
97 |
98 | // check if the node is actually merged
99 | if ($mergedNode) {
100 | $isActuallyMerged = $this->getXpath()->query('w:tcPr/w:vMerge', $mergedNode);
101 | if ($isActuallyMerged->count() > 0) {
102 | if ($isActuallyMerged[0]->getAttribute('w:val') !== 'restart') {
103 | $this->rowspan ++;
104 | $this->extractRowspanRecursion($mergedNode);
105 | }
106 | }
107 | }
108 | }
109 |
110 | /**
111 | * @return int
112 | */
113 | private function extractColspanNumber(): int {
114 | $colspan = 1;
115 |
116 | $colspanAttr = $this->getXpath()->query('w:tcPr/w:gridSpan/@w:val', $this->getDomElement());
117 | if ($this->isOnlyChildNode($colspanAttr)) {
118 | $colspan = $colspanAttr[0]->nodeValue;
119 | }
120 | return $colspan;
121 | }
122 |
123 | /**
124 | * @return array
125 | */
126 | public function getContent(): array {
127 | return $this->paragraphs;
128 | }
129 |
130 | /**
131 | * @return int
132 | */
133 | public function getColspan(): int {
134 | return $this->colspan;
135 | }
136 |
137 | /**
138 | * @return int
139 | */
140 | public function getRowspan(): int {
141 | return $this->rowspan;
142 | }
143 | }
144 |
--------------------------------------------------------------------------------
/src/docx2jats/objectModel/body/Text.php:
--------------------------------------------------------------------------------
1 | properties = $this->setProperties('w:rPr/child::node()');
35 | $this->text = $this->setText('w:t');
36 | $this->type = $this->setType();
37 | $this->setBookmarks();
38 | }
39 |
40 | /**
41 | * @return string
42 | */
43 |
44 | private function setText(string $xpathExpression) {
45 | $stringText = '';
46 | $contentNodes = $this->getXpath()->evaluate($xpathExpression, $this->getDomElement());
47 | /* @var $contentNode \DOMElement */
48 | foreach ($contentNodes as $contentNode) {
49 | $stringText = $stringText . $contentNode->nodeValue;
50 | }
51 |
52 | return $stringText;
53 | }
54 |
55 | /**
56 | * @return string
57 | */
58 | public function getContent(): string {
59 | return $this->text;
60 | }
61 |
62 | /**
63 | * @return array
64 | */
65 | public function getProperties(): array {
66 | return $this->properties;
67 | }
68 |
69 | /**
70 | * For a toggle property, (see ECMA-376 Part 1, 17.7.3), determine
71 | * its enabled state.
72 | *
73 | * @return bool
74 | */
75 | private function togglePropertyEnabled(\DOMElement $property): bool {
76 | if ($property->hasAttribute('w:val')) {
77 | $attrValue = $property->getAttribute('w:val');
78 | return ($attrValue == '1' || $attrValue == 'true');
79 | } else {
80 | return true; // No value means it's enabled
81 | }
82 | }
83 |
84 | /**
85 | * @return array
86 | */
87 | private function setType() {
88 | $type = array();
89 |
90 | $properties = $this->getXpath()->query('w:rPr/child::node()', $this->getDomElement());
91 | foreach ($properties as $property) {
92 | switch($property->nodeName) {
93 | case "w:b":
94 | if ($this->togglePropertyEnabled($property)) {
95 | $type[] = $this::DOCX_TEXT_BOLD;
96 | }
97 | break;
98 | case "w:i":
99 | if ($this->togglePropertyEnabled($property)) {
100 | $type[] = $this::DOCX_TEXT_ITALIC;
101 | }
102 | break;
103 | case "w:vertAlign":
104 | if ($property->hasAttribute('w:val')) {
105 | $attrValue = $property->getAttribute('w:val');
106 | if ($attrValue === "superscript") {
107 | $type[] = $this::DOCX_TEXT_SUPERSCRIPT;
108 | } elseif ($attrValue === "subscript") {
109 | $type[] = $this::DOCX_TEXT_SUBSCRIPT;
110 | }
111 | }
112 | break;
113 | case "w:strike":
114 | if ($this->togglePropertyEnabled($property)) {
115 | $type[] = $this::DOCX_TEXT_STRIKETHROUGH;
116 | }
117 | break;
118 | }
119 | }
120 |
121 | return $type;
122 | }
123 |
124 | public function addType(string $type): void {
125 | $this->type[] = $type;
126 | }
127 |
128 | /**
129 | * @return array
130 | */
131 | public function getType(): array {
132 | return $this->type;
133 | }
134 |
135 | function setLink(): void {
136 | $parent = $this->getDomElement()->parentNode;
137 | if ($parent->tagName == "w:hyperlink") {
138 | $ref = $parent->getAttribute("r:id");
139 | // TODO link by other attributes for identification, e.g. w:anchor
140 | if ($ref) {
141 | $this->link = Document::getRelationshipById($ref);
142 | }
143 | }
144 | }
145 |
146 | public function getLink(): ?string {
147 | return $this->link;
148 | }
149 | }
150 |
--------------------------------------------------------------------------------
/src/docx2jats/objectModel/body/Reference.php:
--------------------------------------------------------------------------------
1 | rawReference = $rawReference;
21 |
22 | if ($csl = json_decode($rawReference)) {
23 | $this->csl = $csl;
24 | $this->hasStructure = true;
25 | }
26 | }
27 |
28 | /**
29 | * @return int
30 | */
31 | public function getCslId(): string
32 | {
33 | return $this->cslId;
34 | }
35 |
36 | /**
37 | * @param string $instruction
38 | * @return array [instructions command, CSL as a string]
39 | */
40 | public static function extractRawCSL(string $instruction): array {
41 | $instruction = trim($instruction);
42 | $pos = strpos($instruction, '{');
43 | $instructionsRawPart = substr($instruction, 0, $pos);
44 | $rawCSL = substr($instruction, $pos);
45 | return array($instructionsRawPart, $rawCSL);
46 | }
47 |
48 | public static function findRefsCSL(string $rawCSL) : array {
49 | $citations = [];
50 | $json = json_decode($rawCSL);
51 | if (is_null($json)) return $citations;
52 | $items = $json->{'citationItems'};
53 | if (!$items) return $citations;
54 |
55 | foreach ($items as $item) {
56 | $reference = new Reference(json_encode($item, JSON_UNESCAPED_UNICODE));
57 | $reference->cslId = $item->{'id'};
58 | $citations[] = $reference;
59 | }
60 |
61 | return $citations;
62 | }
63 |
64 | public static function findPlainCit(string $rawCSL): ?string {
65 | $plainCit = null;
66 | $json = json_decode($rawCSL);
67 | if (is_null($json) || !$json->{'properties'}) return $plainCit;
68 |
69 | $props = null;
70 | if (property_exists($json, 'properties')) {
71 | $props = $json->{'properties'};
72 | }
73 |
74 | // Zotero
75 | if ($props && property_exists($props, 'plainCitation')) {
76 | return $props->{'plainCitation'};
77 | }
78 |
79 | if ($props && property_exists($props, 'formattedCitation')) {
80 | return $props->{'formattedCitation'};
81 | }
82 |
83 | // Mendeley
84 | if (property_exists($json, 'mendeley')) {
85 | $mendeley = $json->{'mendeley'};
86 | if ($props && property_exists($mendeley, 'formattedCitation')) {
87 | return $mendeley->{'formattedCitation'};
88 | }
89 |
90 | if (property_exists($mendeley, 'plainTextFormattedCitation')) {
91 | return $mendeley->{'plainTextFormattedCitation'};
92 | }
93 |
94 | if (property_exists($mendeley, 'previouslyFormattedCitation')) {
95 | return $mendeley->{'previouslyFormattedCitation'};
96 | }
97 | }
98 |
99 | return $plainCit;
100 | }
101 |
102 | /**
103 | * @param int $id csl ID
104 | * @param Document $document
105 | * @return Reference|null returns reference if csl id exists or null if doesn't
106 | */
107 | public static function cslExists(Reference $refToCompare, Document $document) : ?Reference {
108 |
109 | $refToCompareId = $refToCompare->getCslId();
110 | foreach ($document->getReferences() as $reference) {
111 | // Just compare by ID, it's enough for Zotero
112 | if ($reference->getCslId() == $refToCompareId && $refToCompare->isZoteroCSL) {
113 | return $reference;
114 | // Compare raw references for Mendeley
115 | } elseif (Reference::isCslMendeleySimilar($refToCompare, $reference)) {
116 | return $reference;
117 | }
118 | }
119 |
120 | return null;
121 | }
122 |
123 | public function setId(int $id) {
124 | $this->id = $id;
125 | }
126 |
127 | public function getId() : ?int {
128 | return $this->id;
129 | }
130 |
131 | public function getCSL() : ?\stdClass {
132 | return $this->csl;
133 | }
134 |
135 | public function hasStructure() : bool {
136 | return $this->hasStructure;
137 | }
138 |
139 | public function getRawReference() : string {
140 | return $this->rawReference;
141 | }
142 |
143 | static function isCslMendeleySimilar(Reference $referenceToCompare, Reference $reference) : bool {
144 | $ref = $reference->getCSL()->{'itemData'};
145 | $refToCompare = $referenceToCompare->getCSL()->{'itemData'};
146 |
147 | if (property_exists($refToCompare, 'id')) {
148 | unset($refToCompare->{'id'});
149 | }
150 |
151 | if (property_exists($ref , 'id')) {
152 | unset($ref->{'id'});
153 | }
154 |
155 | if (strcmp(json_encode($refToCompare, JSON_UNESCAPED_UNICODE), json_encode($ref, JSON_UNESCAPED_UNICODE)) === 0) {
156 | return true;
157 | }
158 |
159 | return false;
160 | }
161 | }
162 |
--------------------------------------------------------------------------------
/src/docx2jats/objectModel/DataObject.php:
--------------------------------------------------------------------------------
1 | domElement = $domElement;
35 | $this->ownerDocument = $ownerDocument;
36 | // assuming that Document is the container of this object and a direct parent
37 | if (is_null($parent)) {
38 | $this->parent = $ownerDocument;
39 | } else {
40 | $this->parent = $parent;
41 | }
42 |
43 | $this->xpath = Document::$xpath;
44 | }
45 |
46 | protected function getXpath(): \DOMXPath {
47 | return $this->xpath;
48 | }
49 |
50 | protected function setProperties(string $xpathExpression): array {
51 | $styleNodes = $this->getXpath()->evaluate($xpathExpression, $this->domElement);
52 | $properties = $this->extractPropertyRecursion($styleNodes);
53 |
54 | return $properties;
55 | }
56 |
57 | /**
58 | * @return \DOMElement
59 | */
60 | protected function getDomElement(): \DOMElement {
61 | return $this->domElement;
62 | }
63 |
64 | /**
65 | * @param \DOMNodeList $domNodeList
66 | * @return bool
67 | */
68 | protected function isOnlyChildNode(\DOMNodeList $domNodeList): bool {
69 | if ($domNodeList->count() === 1) {
70 | return true;
71 | }
72 | return false;
73 | }
74 |
75 | /**
76 | * @param $styleNodes
77 | * @return array
78 | */
79 | private function extractPropertyRecursion($styleNodes): array
80 | {
81 | $properties = array();
82 | foreach ($styleNodes as $styleNode) {
83 | if ($styleNode->hasAttributes()) {
84 | foreach ($styleNode->attributes as $attr) {
85 | $properties[$styleNode->nodeName][$attr->nodeName] = $attr->nodeValue;
86 | }
87 | } elseif ($styleNode->hasChildNodes()) {
88 | $children = $this->getXpath()->query('child::node()', $styleNode);
89 | $rPr = $this->extractPropertyRecursion($children);
90 | $properties[$styleNode->nodeName] = $rPr;
91 | }
92 | }
93 | return $properties;
94 | }
95 |
96 | /**
97 | * @return array
98 | */
99 | protected function setParagraphs(): array {
100 | $content = array();
101 |
102 | $parNodes = $this->getXpath()->query('w:p', $this->getDomElement());
103 | foreach ($parNodes as $parNode) {
104 | $par = new Par($parNode, $this->getOwnerDocument(), $this);
105 | $content[] = $par;
106 | }
107 |
108 | return $content;
109 | }
110 |
111 | /**
112 | * @param $flatSectionId
113 | */
114 | public function setFlatSectionId($flatSectionId): void {
115 | $this->flatSectionId = intval($flatSectionId);
116 | }
117 |
118 | /**
119 | * @return int
120 | */
121 | public function getFlatSectionId(): int {
122 | return $this->flatSectionId;
123 | }
124 |
125 | /**
126 | * @param array $dimensionalSectionId
127 | */
128 | public function setDimensionalSectionId(array $dimensionalSectionId): void {
129 | $this->dimensionalSectionId = array_filter($dimensionalSectionId);
130 | }
131 |
132 | /**
133 | * @return array
134 | */
135 | public function getDimensionalSectionId(): array {
136 | return $this->dimensionalSectionId;
137 | }
138 |
139 | /**
140 | * @param string $xpath
141 | * @param \DOMElement|null $parentElement
142 | * @return \DOMElement|null
143 | */
144 | public function getFirstElementByXpath(string $xpath, \DOMElement $parentElement = null): ?\DOMElement {
145 | $element = null;
146 |
147 | if ($parentElement) {
148 | $element = $this->getXpath()->query($xpath, $parentElement)[0];
149 | } else {
150 | $element = $this->getXpath()->query($xpath)[0];
151 | }
152 |
153 | return $element;
154 | }
155 |
156 | /**
157 | * @return Document;
158 | */
159 | public function getOwnerDocument(): ?Document
160 | {
161 | return $this->ownerDocument;
162 | }
163 |
164 | /**
165 | * @param Document $ownerDocument
166 | */
167 | public function setOwnerDocument(Document $ownerDocument): void
168 | {
169 | $this->ownerDocument = $ownerDocument;
170 | }
171 |
172 | /**
173 | * @return DataObject|Document|null
174 | * @brief retrieve the parent/container object that holds this one
175 | */
176 | public function getParent() {
177 | return $this->parent;
178 | }
179 | }
180 |
--------------------------------------------------------------------------------
/src/docx2jats/objectModel/body/InfoBlock.php:
--------------------------------------------------------------------------------
1 | parseReferences($el);
36 |
37 | // Identifying and parsing block element's label and title
38 | $runs = Document::$xpath->query('./w:r', $el);
39 | foreach ($runs as $key => $run) {
40 | $textNodes = Document::$xpath->query('./w:t', $run);
41 | if (!count($textNodes)) continue;
42 |
43 | // Just assuming that the first text run is a label, default for MS Word and Libreoffice Writer
44 | if ($key == 0) {
45 | $label .= $textNodes[0]->nodeValue;
46 | }
47 |
48 | // This detects if text run contains a bookmark
49 | $refCount = count($this->refIds);
50 | $this->setBookmarks($run);
51 | if (count($this->refIds) > $refCount) continue; // Don't parse text if a text run
52 |
53 | $title .= $textNodes[0]->nodeValue;
54 | }
55 |
56 | $labelNumber = Document::$xpath->query('./w:fldSimple//w:t', $el)[0];
57 | if (!is_null($labelNumber)) {
58 | $label .= $labelNumber->nodeValue;
59 | }
60 |
61 | if (!empty($label)) {
62 | $this->label = $label;
63 | }
64 |
65 | if (!empty($title)) {
66 | $this->title = trim($title);
67 | }
68 |
69 | // Caption may have bookmarks that are pointed from outside the table, retrieve their IDs;
70 | // TODO Check if other bookmark types may be inserted in captions
71 | $bookmarkStartEls = Document::$xpath->query('w:bookmarkStart', $el);
72 | foreach ($bookmarkStartEls as $bookmarkStartEl) {
73 | /* @var $bookmarkStartEl \DOMElement */
74 | if ($bookmarkStartEl->hasAttribute('w:name')) {
75 | $this->bookmarkIds[] = $bookmarkStartEl->getAttribute('w:name');
76 | }
77 | }
78 | }
79 |
80 | public function getLabel(): ?string
81 | {
82 | return $this->label;
83 | }
84 |
85 | public function getTitle(): ?string
86 | {
87 | return $this->title;
88 | }
89 |
90 | public function getBookmarkIds(): array
91 | {
92 | return $this->bookmarkIds;
93 | }
94 |
95 | public function hasReferences(): bool
96 | {
97 | return (!empty($this->refIds));
98 | }
99 |
100 | /**
101 | * @param \DOMElement $el
102 | * @return void
103 | * Identifies references in block element's textual data
104 | * Mendeley puts references in bookmarkStart element's name attribute, e.g.:
105 | * Zotero embraces references with fldChar elements (start - end), inside instructions, which start with CLS_CITATION, e.g.:
106 | * ADDIN ZOTERO_ITEM CSL_CITATION
107 | * TODO Refactor and remove artificial Field element
108 | */
109 | protected function parseReferences(\DOMElement $el): void
110 | {
111 | $contentNodes = $this->getXpath()->query('./w:r', $el);
112 |
113 | // Iterating through all text runs to find fields with CSL citations
114 | $field = null;
115 | foreach ($contentNodes as $contentNode) {
116 | if (!$field && Field::complexFieldStarts($contentNode)) {
117 | $field = new Field($contentNode, $this->getOwnerDocument(), $this);
118 | } elseif ($field && !Field::complexFieldLast($contentNode)) {
119 | $field->addContent($contentNode);
120 | } elseif ($field && Field::complexFieldLast($contentNode)) {
121 | $field->addContent($contentNode);
122 | // Field data is recorded, write a reference if exists
123 | if ($field->getType() === Field::DOCX_FIELD_CSL) {
124 | $this->addRefIds($field->getRefIds());
125 | }
126 | }
127 | }
128 |
129 | // Try to find Mendeley references
130 | if (empty($this->bookmarkIds)) return;
131 | }
132 |
133 | protected function addRefIds(array $ids) {
134 | $this->refIds = array_merge(
135 | $this->refIds,
136 | $ids
137 | );
138 | }
139 |
140 | abstract function getId(): int;
141 | }
142 |
--------------------------------------------------------------------------------
/src/docx2jats/objectModel/body/Field.php:
--------------------------------------------------------------------------------
1 | rawRuns[] = $domElement;
50 | }
51 |
52 | /**
53 | * @return mixed
54 | */
55 | public function getContent() {
56 | return $this->content;
57 | }
58 |
59 | static function complexFieldStarts(\DOMElement $domElement) {
60 | $fieldNode = Document::$xpath->query('w:fldChar', $domElement)[0];
61 | if ($fieldNode && $fieldNode->hasAttribute('w:fldCharType') && $fieldNode->getAttribute('w:fldCharType') === 'begin') {
62 | return true;
63 | }
64 | return false;
65 | }
66 |
67 | static function complexFieldLast(\DOMElement $domElement) {
68 | $fieldNode = Document::$xpath->query('w:fldChar', $domElement)[0];
69 | if ($fieldNode && $fieldNode->hasAttribute('w:fldCharType') && $fieldNode->getAttribute('w:fldCharType') === 'end') {
70 | return true;
71 | }
72 | return false;
73 | }
74 |
75 | public function addContent(\DOMElement $domElement) {
76 | $this->rawRuns[] = $domElement;
77 | if (self::complexFieldLast($domElement)) {
78 | $this->processRuns();
79 | }
80 | }
81 |
82 | /**
83 | * @brief retrieve instructions and text for the field
84 | */
85 | private function processRuns() {
86 | $resultText = false;
87 | foreach ($this->rawRuns as $run) {
88 | $fieldNode = Document::$xpath->query('w:fldChar', $run)[0];
89 | if ($fieldNode && $fieldNode->hasAttribute('w:fldCharType') && $fieldNode->getAttribute('w:fldCharType') === 'separate') {
90 | $resultText = true;
91 | }
92 |
93 | if (!$resultText) {
94 | $instructionNode = Document::$xpath->query('w:instrText', $run)[0];
95 | if ($instructionNode) {
96 | $instructionString = $instructionNode->nodeValue;
97 | $this->instructions[] = $instructionString;
98 | // Check if Zotero/Mendeley Citation
99 | if (strpos($instructionString, 'CSL_CITATION') !== false) {
100 | $this->type = self::DOCX_FIELD_CSL;
101 | $rawCSL = $this->extractRawCSL($instructionString);
102 | $references = Reference::findRefsCSL($rawCSL);
103 | $this->plainCit = Reference::findPlainCit($rawCSL);
104 | foreach ($references as $reference) {
105 | $reference->isZoteroCSL = $this->isZoteroCSL();
106 | if (!$ref = Reference::cslExists($reference, $this->getOwnerDocument())) {
107 | $this->getOwnerDocument()->addReference($reference);
108 | $this->refIds[] = $reference->getId();
109 | } else {
110 | $this->refIds[] = $ref->getId();
111 | }
112 | }
113 | }
114 | // Check if Link to the Bookmark (only Tables and Figures are supported)
115 | elseif (strpos($instructionString, 'REF') !== false) {
116 | $this->getParent()->hasBookmarks = true;
117 | $this->type = self::DOCX_FIELD_BOOKMARK_REF;
118 | $this->fldCharRefId = $this->extractRefID($instructionString);
119 | }
120 | }
121 | } else {
122 | $this->content[] = new Text($run, $this->getOwnerDocument());
123 | }
124 | }
125 | }
126 |
127 | /**
128 | * @return int
129 | */
130 | public function getType(): int
131 | {
132 | return $this->type;
133 | }
134 |
135 | /**
136 | * @param string $instruction
137 | * @return string containing raw CSL
138 | * @brief extract CSL as a string and determine its type (Zotero or Mendeley)
139 | */
140 | private function extractRawCSL(string $instruction): string {
141 | list($instructionsRawPart, $rawCSL) = Reference::extractRawCSL($instruction);
142 | if (strpos($instructionsRawPart, 'ZOTERO_ITEM') !== false) {
143 | $this->isZoteroCSL = true;
144 | }
145 | return $rawCSL;
146 | }
147 |
148 | private function extractRefID(string $instruction) {
149 | $exploded = explode(' ', trim($instruction));
150 | foreach ($exploded as $key => $word) {
151 | if ($word == 'REF') {
152 | if (array_key_exists($key+1, $exploded)) {
153 | return $exploded[$key + 1];
154 | }
155 | }
156 | }
157 | return null;
158 | }
159 |
160 | public function getPlainCit() {
161 | return $this->plainCit;
162 | }
163 |
164 | public function getRefIds() {
165 | return $this->refIds;
166 | }
167 |
168 | /**
169 | * @return bool
170 | */
171 | public function isZoteroCSL(): bool {
172 | return $this->isZoteroCSL;
173 | }
174 |
175 | /**
176 | * @return mixed
177 | */
178 | public function getFldCharRefId() {
179 | if ($this->type === self::DOCX_FIELD_BOOKMARK_REF) {
180 | return $this->fldCharRefId;
181 | }
182 |
183 | return null;
184 | }
185 | }
186 |
--------------------------------------------------------------------------------
/vendor/composer/InstalledVersions.php:
--------------------------------------------------------------------------------
1 |
27 | array (
28 | 'pretty_version' => 'dev-main',
29 | 'version' => 'dev-main',
30 | 'aliases' =>
31 | array (
32 | ),
33 | 'reference' => 'd5ab4b12220646b40524b31073d74cd66786ca8f',
34 | 'name' => 'doc/docx2jats',
35 | ),
36 | 'versions' =>
37 | array (
38 | 'doc/docx2jats' =>
39 | array (
40 | 'pretty_version' => 'dev-main',
41 | 'version' => 'dev-main',
42 | 'aliases' =>
43 | array (
44 | ),
45 | 'reference' => 'd5ab4b12220646b40524b31073d74cd66786ca8f',
46 | ),
47 | ),
48 | );
49 | private static $canGetVendors;
50 | private static $installedByVendor = array();
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 | public static function getInstalledPackages()
59 | {
60 | $packages = array();
61 | foreach (self::getInstalled() as $installed) {
62 | $packages[] = array_keys($installed['versions']);
63 | }
64 |
65 |
66 | if (1 === \count($packages)) {
67 | return $packages[0];
68 | }
69 |
70 | return array_keys(array_flip(\call_user_func_array('array_merge', $packages)));
71 | }
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 | public static function isInstalled($packageName)
82 | {
83 | foreach (self::getInstalled() as $installed) {
84 | if (isset($installed['versions'][$packageName])) {
85 | return true;
86 | }
87 | }
88 |
89 | return false;
90 | }
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 | public static function satisfies(VersionParser $parser, $packageName, $constraint)
106 | {
107 | $constraint = $parser->parseConstraints($constraint);
108 | $provided = $parser->parseConstraints(self::getVersionRanges($packageName));
109 |
110 | return $provided->matches($constraint);
111 | }
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 | public static function getVersionRanges($packageName)
123 | {
124 | foreach (self::getInstalled() as $installed) {
125 | if (!isset($installed['versions'][$packageName])) {
126 | continue;
127 | }
128 |
129 | $ranges = array();
130 | if (isset($installed['versions'][$packageName]['pretty_version'])) {
131 | $ranges[] = $installed['versions'][$packageName]['pretty_version'];
132 | }
133 | if (array_key_exists('aliases', $installed['versions'][$packageName])) {
134 | $ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']);
135 | }
136 | if (array_key_exists('replaced', $installed['versions'][$packageName])) {
137 | $ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']);
138 | }
139 | if (array_key_exists('provided', $installed['versions'][$packageName])) {
140 | $ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']);
141 | }
142 |
143 | return implode(' || ', $ranges);
144 | }
145 |
146 | throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
147 | }
148 |
149 |
150 |
151 |
152 |
153 | public static function getVersion($packageName)
154 | {
155 | foreach (self::getInstalled() as $installed) {
156 | if (!isset($installed['versions'][$packageName])) {
157 | continue;
158 | }
159 |
160 | if (!isset($installed['versions'][$packageName]['version'])) {
161 | return null;
162 | }
163 |
164 | return $installed['versions'][$packageName]['version'];
165 | }
166 |
167 | throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
168 | }
169 |
170 |
171 |
172 |
173 |
174 | public static function getPrettyVersion($packageName)
175 | {
176 | foreach (self::getInstalled() as $installed) {
177 | if (!isset($installed['versions'][$packageName])) {
178 | continue;
179 | }
180 |
181 | if (!isset($installed['versions'][$packageName]['pretty_version'])) {
182 | return null;
183 | }
184 |
185 | return $installed['versions'][$packageName]['pretty_version'];
186 | }
187 |
188 | throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
189 | }
190 |
191 |
192 |
193 |
194 |
195 | public static function getReference($packageName)
196 | {
197 | foreach (self::getInstalled() as $installed) {
198 | if (!isset($installed['versions'][$packageName])) {
199 | continue;
200 | }
201 |
202 | if (!isset($installed['versions'][$packageName]['reference'])) {
203 | return null;
204 | }
205 |
206 | return $installed['versions'][$packageName]['reference'];
207 | }
208 |
209 | throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
210 | }
211 |
212 |
213 |
214 |
215 |
216 | public static function getRootPackage()
217 | {
218 | $installed = self::getInstalled();
219 |
220 | return $installed[0]['root'];
221 | }
222 |
223 |
224 |
225 |
226 |
227 |
228 |
229 | public static function getRawData()
230 | {
231 | return self::$installed;
232 | }
233 |
234 |
235 |
236 |
237 |
238 |
239 |
240 |
241 |
242 |
243 |
244 |
245 |
246 |
247 |
248 |
249 |
250 |
251 |
252 | public static function reload($data)
253 | {
254 | self::$installed = $data;
255 | self::$installedByVendor = array();
256 | }
257 |
258 |
259 |
260 |
261 | private static function getInstalled()
262 | {
263 | if (null === self::$canGetVendors) {
264 | self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders');
265 | }
266 |
267 | $installed = array();
268 |
269 | if (self::$canGetVendors) {
270 | foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) {
271 | if (isset(self::$installedByVendor[$vendorDir])) {
272 | $installed[] = self::$installedByVendor[$vendorDir];
273 | } elseif (is_file($vendorDir.'/composer/installed.php')) {
274 | $installed[] = self::$installedByVendor[$vendorDir] = require $vendorDir.'/composer/installed.php';
275 | }
276 | }
277 | }
278 |
279 | $installed[] = self::$installed;
280 |
281 | return $installed;
282 | }
283 | }
284 |
--------------------------------------------------------------------------------
/src/docx2jats/objectModel/traits/Bookmarkable.php:
--------------------------------------------------------------------------------
1 | getDomElement();
42 | }
43 |
44 | $prevSibling = $rootElement->previousSibling;
45 | $bookMarks = array_fill_keys(['started', 'ended'], []);
46 | $bookMarks = $this->prevBookmarks($prevSibling, $bookMarks);
47 | $bookMarksActive = array_diff($bookMarks['started'], $bookMarks['ended']);
48 | if (empty($bookMarksActive)) return;
49 |
50 | $this->bookmarked = true;
51 | $allBookmarks = $this->getOwnerDocument()->bookMarks;
52 | foreach ($bookMarksActive as $bookMarkActive) {
53 | $name = $allBookmarks[$bookMarkActive];
54 | $this->bookmarkData[$bookMarkActive]['name'] = $name ;
55 | $content = $this->searchBookmarkContentByName($name);
56 | if (empty(trim($content)) || strpos($content, 'CSL_CITATION') === false) continue;
57 | $this->bookmarkData[$bookMarkActive]['content'] = $content;
58 | list($instructions, $rawCSL) = Reference::extractRawCSL($content);
59 | if (empty($rawCSL)) continue;
60 |
61 | $citations = Reference::findRefsCSL($rawCSL);
62 | if (empty($citations)) continue;
63 | $this->hasCSLRefs = true;
64 |
65 | foreach ($citations as $citation) {
66 | if (!$ref = Reference::cslExists($citation, $this->getOwnerDocument())) {
67 | $this->getOwnerDocument()->addReference($citation);
68 | $this->refIds[] = $citation->getId();
69 | } else {
70 | $this->refIds[] = $ref->getId();
71 | }
72 | }
73 | }
74 | $this->refIds = array_unique($this->refIds); // TODO explore why Mendeley LW plugin includes duplicates of refs into a single text run
75 | }
76 |
77 | /**
78 | * @param \DOMElement $prevSibling
79 | * @param array $bookMarks
80 | * @return array
81 | * @brief recursively find started and ended bookmarks
82 | */
83 | protected function prevBookmarks(?\DOMElement $prevSibling, array $bookMarks): array {
84 | if (is_null($prevSibling)) return $bookMarks; // reached end
85 | if ($prevSibling->nodeType !== XML_ELEMENT_NODE) return $this->prevBookmarks($prevSibling->previousSibling, $bookMarks);
86 |
87 | if ($prevSibling->tagName === 'w:bookmarkStart') {
88 | $bookMarks['started'][] = $prevSibling->getAttribute('w:id');
89 | }
90 |
91 | if ($prevSibling->tagName === 'w:bookmarkEnd') {
92 | $bookMarks['ended'][] = $prevSibling->getAttribute('w:id');
93 | }
94 |
95 | return $this->prevBookmarks($prevSibling->previousSibling, $bookMarks);
96 | }
97 |
98 | /**
99 | * @param int $id
100 | * @return string
101 | * @brief search for the bookmarks content in the docProps/custom.xml by bookmarkStart ID
102 | * particularly this is for searching of CSL Mendeley references
103 | * TODO search in other places
104 | */
105 | public function searchBookmarkContentByName(string $bookmarkName): ?string {
106 | $customProps = $this->getOwnerDocument()->docPropsCustom();
107 | if (!$customProps) return null; // custom.xml or analog doesn't exist
108 | $propertyEls = $customProps->getElementsByTagName('property');
109 | $contentEls = [];
110 | $nameLen = strlen($bookmarkName);
111 | foreach ($propertyEls as $propertyEl) { /* @var $propertyEl \DOMElement */
112 | if ($propertyEl->hasAttribute('name')) {
113 | $attrValue = $propertyEl->getAttribute('name');
114 | // attribute value consists of a name and unique ending
115 | if (substr($attrValue, 0, $nameLen) === $bookmarkName) {
116 | $contentEls[] = $propertyEl;
117 | }
118 | }
119 | }
120 |
121 | if (empty($contentEls)) return null;
122 |
123 | /**
124 | * Needs to be sorted as property elements can be present inside the parent in any order;
125 | * Consider 2 values of name attr: Mendeley_Bookmark_3XXM13m2wL_14 Mendeley_Bookmark_3XXM13m2wL_2,
126 | * Sorting is done by comparing trailing numbers that appear after last underscore
127 | */
128 | usort($contentEls, function ($a, $b) use ($nameLen) {
129 | $aInt = filter_var(substr($a->getAttribute('name'), $nameLen), FILTER_SANITIZE_NUMBER_INT);
130 | $bInt = filter_var(substr($b->getAttribute('name'), $nameLen), FILTER_SANITIZE_NUMBER_INT);
131 | if ($aInt === $bInt) return 0;
132 | return ($aInt < $bInt) ? -1 : 1;
133 | });
134 |
135 | $xpath = Document::$docPropsCustomXpath;
136 | if (!$xpath) return null;
137 | $resultString = '';
138 | foreach ($contentEls as $contentEl) {
139 | $lpwstr = $xpath->query('./vt:lpwstr[1]', $contentEl)[0];
140 | $resultString .= $lpwstr->nodeValue;
141 | }
142 |
143 | return $resultString;
144 | }
145 |
146 | public function getRefIds(): array
147 | {
148 | return $this->refIds;
149 | }
150 |
151 | function getBookmarkData(): array
152 | {
153 | return $this->bookmarkData;
154 | }
155 | }
156 |
--------------------------------------------------------------------------------
/src/docx2jats/DOCXArchive.php:
--------------------------------------------------------------------------------
1 | filePath = $filepath;
43 |
44 | if ($this->open($filepath)) {
45 | $this->contentType = $this->transformToXml(self::CONTENT_TYPES_PATH);
46 | self::$contentTypeXpath = new \DOMXPath($this->contentType);
47 |
48 | // Set the Main Document Part
49 | $ooxmlDocumentPath = $this->getRealFileDocumentPath('word/document.xml', self::CONTENT_TYPE_DOCUMENT_MAIN);
50 | $this->ooxmlDocument = $this->transformToXml($ooxmlDocumentPath);
51 |
52 | // Relationships of the Main Document Part
53 | $partRelationshipsPath = $this->getRealFileDocumentPath('word/_rels/document.xml.rels', self::CONTENT_TYPE_RELATIONSHIPS, $ooxmlDocumentPath);
54 | $partRelationships = $this->transformToXml($partRelationshipsPath);
55 |
56 | // Style names used in the document, styles should be checked recursively, see docx2jats\objectModel\Document::getBuiltinStyle
57 | $stylePath = $this->getRealFileDocumentPath('word/styles.xml', self::CONTENT_TYPE_STYLES);
58 | $styles = $this->transformToXml($stylePath);
59 |
60 | // Media files, e.g., images
61 | $this->mediaFiles = $this->extractMediaFiles();
62 |
63 | // Description of all numbered content, e.g., lists
64 | $numberingPath = $this->getRealFileDocumentPath('word/numbering.xml', self::CONTENT_TYPE_NUMBERING);
65 | $numbering = $this->transformToXml($numberingPath);
66 |
67 | // Custom Document properties, this is used by Mendeley plugin export from LibreOffice Writer
68 | $docPropsCustom = $this->getRealFileDocumentPath('docProps/custom.xml', self::CONTENT_TYPE_CUSTOM_PROP);
69 | $docPropsCustom = $this->transformToXml($docPropsCustom);
70 | $this->close();
71 |
72 | // construct as an array
73 | $params = array();
74 |
75 | $params["ooxmlDocument"] = $this->ooxmlDocument;
76 |
77 | if ($partRelationships) $params["partRelationships"] = $partRelationships;
78 | if ($styles) $params["styles"] = $styles;
79 | if ($numbering) $params["numbering"] = $numbering;
80 | if ($docPropsCustom) $params["docPropsCustom"] = $docPropsCustom;
81 |
82 | $document = new Document($params);
83 |
84 | $this->document = $document;
85 | }
86 | }
87 |
88 | public function getDocumentOoxml(): \DOMDocument {
89 | return $this->ooxmlDocument;
90 | }
91 |
92 | public function getDocument(): Document {
93 | return $this->document;
94 | }
95 |
96 | private function transformToXml(string $path): ?\DOMDocument {
97 | $index = $this->locateName($path);
98 | if ($index === false) return null;
99 | $data = $this->getFromIndex($index);
100 | $xml = new \DOMDocument();
101 | $xml->loadXML($data, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
102 | return $xml;
103 | }
104 |
105 | private function extractMediaFiles() {
106 | $paths = array();
107 | for ($i = 0; $i < $this->numFiles; $i++) {
108 | $filePath = $this->getNameIndex($i);
109 |
110 | if (!strpos($filePath, "media/")) continue;
111 |
112 | $paths[] = $filePath;
113 | }
114 |
115 | return $paths;
116 | }
117 |
118 | /**
119 | * @param string $path
120 | * @return string|null file extracted from DOCX archive
121 | */
122 |
123 | public function getFile(string $path): ?string {
124 | if ($this->open($this->filePath)) {
125 | $index = $this->locateName("word/" . $path);
126 | if (!$index) return null;
127 | $data = $this->getFromIndex($index);
128 | $this->close();
129 | return $data;
130 | }
131 |
132 | return null;
133 | }
134 |
135 | /**
136 | * @param $outputDir string, should include trailing slash
137 | * @brief writes media files to the specified dir; preserves original filename and extension
138 | */
139 | public function getMediaFiles(string $outputDir): void {
140 |
141 | if (empty($this->mediaFiles)) return;
142 |
143 | if ($this->open($this->filePath)) {
144 | foreach ($this->mediaFiles as $mediaFile) {
145 | $index = $this->locateName($mediaFile);
146 | $data = $this->getFromIndex($index);
147 | file_put_contents($outputDir . pathinfo($mediaFile)['basename'], $data);
148 | }
149 | $this->close();
150 | }
151 | }
152 |
153 | /**
154 | * @return array
155 | */
156 | public function getMediaFilesContent(): array {
157 | $filesContent = array();
158 |
159 | if (empty($this->mediaFiles)) return $filesContent;
160 |
161 | if ($this->open($this->filePath)) {
162 | foreach ($this->mediaFiles as $mediaFile) {
163 | $index = $this->locateName($mediaFile);
164 | $data = $this->getFromIndex($index);
165 | $filesContent[$mediaFile] = $data;
166 | }
167 | $this->close();
168 | }
169 |
170 | return $filesContent;
171 | }
172 |
173 | private function getRealFileDocumentPath(string $defaultPath, string $contentType = null, string $parentPath = null): string {
174 | $path = null;
175 | if (!is_null($contentType)) {
176 | foreach ($this->contentType->getElementsByTagName('Override') as $override) {
177 | if ($override->hasAttribute('PartName') &&
178 | $override->hasAttribute('ContentType') &&
179 | $override->getAttribute('ContentType') == $contentType) {
180 | if ($contentType !== self::CONTENT_TYPE_RELATIONSHIPS) {
181 | $path = $override->getAttribute('PartName');
182 | break;
183 | } else {
184 | // Find the file associated with relationships, compare by filename
185 | $partName = $override->getAttribute('PartName');
186 | if (strpos(pathinfo($partName)['basename'], pathinfo($parentPath)['basename']) !== false) {
187 | $path = $partName;
188 | break;
189 | }
190 | }
191 | }
192 | }
193 |
194 | // MS Word may not specify the path to the relationships files trying to guess based on the parent path
195 | if ($contentType === self::CONTENT_TYPE_RELATIONSHIPS && is_null($path)) {
196 | $path = 'word/_rels/' . pathinfo($parentPath)['basename'] . '.rels';
197 | }
198 | }
199 |
200 | if (is_null($path)) {
201 | $path = $defaultPath;
202 | }
203 |
204 | $path = ltrim($path, '/');
205 |
206 | try {
207 | $this->findDocumentByPath($path);
208 | } catch (\Exception $e) {
209 | if ($defaultPath === self::CONTENT_TYPE_DOCUMENT_MAIN) {
210 | trigger_error($e->getMessage(), E_USER_ERROR);
211 | } else {
212 | trigger_error($e->getMessage(), E_USER_NOTICE);
213 | }
214 | }
215 |
216 | return $path;
217 | }
218 |
219 | /**
220 | * @param string $path
221 | * @return \DOMDocument
222 | * @throws \Exception if the document inside the archive isn't found
223 | */
224 | private function findDocumentByPath(string $path): void {
225 | $domDocument = $this->transformToXml($path);
226 | if (!$domDocument) {
227 | throw new \Exception('Cannot find document inside the archive by the path ' . $path);
228 | }
229 | }
230 | }
231 |
--------------------------------------------------------------------------------
/src/docx2jats/jats/Reference.php:
--------------------------------------------------------------------------------
1 | 'journal',
21 | 'book' => 'book',
22 | 'chapter' => 'chapter',
23 | 'paper-conference' => 'confproc',
24 | 'dataset' => 'data',
25 | 'article-magazine' => 'periodical',
26 | 'article-newspaper' => 'periodical',
27 | 'manuscript' => 'preprint',
28 | 'report' => 'report',
29 | 'patent' => 'patent',
30 | 'webpage' => 'website',
31 | 'post-weblog' => 'website',
32 | 'post' => 'website',
33 | 'thesis' => 'thesis',
34 | ];
35 |
36 | public function __construct() {
37 | parent::__construct('ref');
38 | }
39 |
40 | public function setContent(ObjReference $reference) {
41 | $this->setAttribute('id', self::JATS_REF_ID_PREFIX . $reference->getId());
42 | if (!$reference->hasStructure()) {
43 | $mixedCitationEl = $this->ownerDocument->createElement('mixed-citation');
44 | $textContent = $this->ownerDocument->createTextNode($reference->getRawReference());
45 | $mixedCitationEl->appendChild($textContent);
46 | $this->appendChild($mixedCitationEl);
47 | }
48 |
49 | else {
50 | $this->setStructure($reference);
51 | }
52 | }
53 |
54 | private function setStructure(ObjReference $reference) {
55 | if ($reference->getCSL()) {
56 | $this->setStructureFromCSL($reference->getCSL());
57 | }
58 | }
59 |
60 | private function setStructureFromCSL(\stdClass $csl) {
61 | $data = $csl->{'itemData'};
62 | $cslPubType = $this->getStdClassPropertyValue($data, 'type');
63 | if (array_key_exists($cslPubType, self::$refTypeCSLMap)) {
64 | $jatsPubType = self::$refTypeCSLMap[$cslPubType];
65 | } else {
66 | $jatsPubType = current(self::$refTypeCSLMap);
67 | }
68 | $elementCitationEl = $this->createAndAppendElement($this, 'element-citation', null, ['publication-type' => $jatsPubType]);
69 |
70 | // Authors and editors
71 | $authors = $this->getStdClassPropertyValue($data, 'author');
72 | if ($authors) {
73 | $this->extractCSLNames($elementCitationEl, $authors, 'author');
74 | }
75 |
76 | $containerAuthors = $this->getStdClassPropertyValue($data, 'container-author');
77 | if ($containerAuthors) {
78 | $this->extractCSLNames($elementCitationEl, $containerAuthors, 'editor');
79 | }
80 |
81 | $editor = $this->getStdClassPropertyValue($data, 'editor');
82 | if ($editor && !$containerAuthors) {
83 | $this->extractCSLNames($elementCitationEl, $editor, 'editor');
84 | }
85 |
86 | // Title
87 | $title = $this->getStdClassPropertyValue($data, 'title');
88 | if ($title) {
89 | if ($jatsPubType === 'chapter') {
90 | $this->createAndAppendElement($elementCitationEl, 'chapter-title', $title);
91 | } elseif ($jatsPubType === 'book') {
92 | $this->createAndAppendElement($elementCitationEl, 'source', $title);
93 | } else {
94 | $this->createAndAppendElement($elementCitationEl, 'article-title', $title);
95 | }
96 | }
97 |
98 | // Source
99 | $containerTitle = $this->getStdClassPropertyValue($data, 'container-title');
100 | if ($containerTitle && $jatsPubType !== 'book') {
101 | $sourceEl = $this->createAndAppendElement($elementCitationEl, 'source', $containerTitle);
102 | }
103 |
104 | $publisher = $this->getStdClassPropertyValue($data, 'publisher');
105 | if ($publisher) {
106 | $publisherEl = $this->createAndAppendElement($elementCitationEl, 'publisher-name', $publisher);
107 | }
108 |
109 | $publisherPlace = $this->getStdClassPropertyValue($data, 'publisher-place');
110 | if ($publisherPlace) {
111 | $publisherLocEl = $this->createAndAppendElement($elementCitationEl, 'publisher-loc', $publisherPlace);
112 | }
113 |
114 | $volume = $this->getStdClassPropertyValue($data, 'volume');
115 | if ($volume) {
116 | $volumeEl = $this->createAndAppendElement($elementCitationEl, 'volume', $volume);
117 | }
118 |
119 | $issue = $this->getStdClassPropertyValue($data, 'issue');
120 | if ($issue) {
121 | $issueEl = $this->createAndAppendElement($elementCitationEl, 'issue', $issue);
122 | }
123 |
124 | $event = $this->getStdClassPropertyValue($data, 'event');
125 | if ($event) {
126 | $confTitleEl = $this->createAndAppendElement($elementCitationEl, 'conf-name', $event);
127 | }
128 |
129 | $event = $this->getStdClassPropertyValue($data, 'event-place');
130 | if ($event && $jatsPubType === 'conference') { // Zotero adds event-place to books and chapters
131 | $confLocEl = $this->createAndAppendElement($elementCitationEl, 'conf-loc', $event);
132 | }
133 |
134 | // pages
135 | $page = $this->getStdClassPropertyValue($data, 'page');
136 | if ($page) {
137 | $pageRangeEl = $this->createAndAppendElement($elementCitationEl, 'page-range', $page);
138 | }
139 |
140 | $pageFirst = $this->getStdClassPropertyValue($data, 'page-first');
141 | if ($pageFirst) {
142 | $pageFirstEl = $this->createAndAppendElement($elementCitationEl, 'fpage', $pageFirst);
143 | }
144 |
145 | // Identificators
146 | $doi = $this->getStdClassPropertyValue($data, 'DOI');
147 | if ($doi) {
148 | $doiEl = $this->createAndAppendElement($elementCitationEl, 'pub-id', $doi, ['pub-id-type' => 'doi']);
149 | }
150 |
151 | $pmid = $this->getStdClassPropertyValue($data, 'PMID');
152 | if ($pmid) {
153 | $pmidEl = $this->createAndAppendElement($elementCitationEl, 'pub-id', $doi, ['pub-id-type' => 'pmid']);
154 | }
155 |
156 | $url = $this->getStdClassPropertyValue($data, 'URL');
157 | if ($url) {
158 | $urlEl = $this->createAndAppendElement($elementCitationEl, 'ext-link', $url);
159 | }
160 |
161 | $issn = $this->getStdClassPropertyValue($data, 'ISSN');
162 | if ($issn) {
163 | $issnEl = $this->createAndAppendElement($elementCitationEl, 'issn', $issn);
164 | }
165 |
166 | // Date
167 | $issued = $this->getStdClassPropertyValue($data, 'issued');
168 | if ($issued) {
169 | $dateParts = $this->getStdClassPropertyValue($issued, 'date-parts');
170 | if ($dateParts) {
171 | if (array_key_exists(0, $dateParts[0])) {
172 | $yearEl = $this->createAndAppendElement($elementCitationEl, 'year', $dateParts[0][0]);
173 | }
174 |
175 | if (array_key_exists(1, $dateParts[0])) {
176 | $monthEl = $this->createAndAppendElement($elementCitationEl, 'month', $dateParts[0][1]);
177 | }
178 |
179 | if (array_key_exists(2, $dateParts[0])) {
180 | $dayEl = $this->createAndAppendElement($elementCitationEl, 'day', $dateParts[0][2]);
181 | }
182 | } else {
183 | $rawDate = $this->getStdClassPropertyValue($issued, 'raw');
184 | if ($rawDate) {
185 | if ($formattedDate = strtotime($rawDate)) {
186 | if ($year = date('Y', $formattedDate)) {
187 | $yearEl = $this->createAndAppendElement($elementCitationEl, 'year', $year);
188 | }
189 |
190 | if ($month = date('m', $formattedDate)) {
191 | $monthEl = $this->createAndAppendElement($elementCitationEl, 'month', $month);
192 | }
193 |
194 | if ($day = date('d', $formattedDate)) {
195 | $dayEl = $this->createAndAppendElement($elementCitationEl, 'day', $day);
196 | }
197 | }
198 | }
199 | }
200 | }
201 |
202 |
203 | }
204 |
205 | private function createAndAppendElement(\DOMElement $parentEl, string $elName, string $text = null, array $attrNameValue = null) : \DOMElement {
206 | $ownerDocument = $this->ownerDocument;
207 | $el = $ownerDocument->createElement($elName);
208 | $parentEl->appendChild($el);
209 | if ($text) {
210 | $el->appendChild($ownerDocument->createTextNode($text));
211 | }
212 |
213 | if (!empty($attrNameValue)) {
214 | foreach ($attrNameValue as $name => $value) {
215 | $el->setAttribute($name, $value);
216 | }
217 | }
218 |
219 | return $el;
220 | }
221 |
222 | /**
223 | * @return mixed
224 | */
225 | private function getStdClassPropertyValue($class, string $property) {
226 | if (property_exists($class, $property)) {
227 | return $class->{$property};
228 | }
229 |
230 | return null;
231 | }
232 |
233 | /**
234 | * @param \DOMElement $elementCitationEl
235 | * @param mixed $stdProperty
236 | * @param string $personGroupType
237 | * @brief extracts and adds to JATS XML authors and editors
238 | */
239 | private function extractCSLNames(\DOMElement $elementCitationEl, $stdProperty, string $personGroupType) {
240 | $personGroupEl = $this->createAndAppendElement($elementCitationEl, 'person-group', null, ['person-group-type' => $personGroupType]);
241 | foreach ($stdProperty as $author) {
242 | $nameEl = $this->createAndAppendElement($personGroupEl, 'name');
243 | $family = $this->getStdClassPropertyValue($author, 'family');
244 | if ($family) {
245 | $surnameEl = $this->createAndAppendElement($nameEl, 'surname', $family);
246 | }
247 | $given = $this->getStdClassPropertyValue($author, 'given');
248 | if ($given) {
249 | $givenEl = $this->createAndAppendElement($nameEl, 'given-names', $given);
250 | }
251 | }
252 | }
253 | }
254 |
--------------------------------------------------------------------------------
/src/docx2jats/jats/Document.php:
--------------------------------------------------------------------------------
1 | unique list ID, corresponds to ID in numbering.xml */
44 | var $lists = array();
45 |
46 | public function __construct(DOCXArchive $docxArchive) {
47 | parent::__construct('1.0', 'utf-8');
48 | $this->docxArchive = $docxArchive;
49 | $this->preserveWhiteSpace = false;
50 | $this->formatOutput = true;
51 |
52 | // Doctype
53 | $impl = new \DOMImplementation();
54 | $this->appendChild($impl->createDocumentType("article", "-//NLM//DTD JATS (Z39.96) Journal Publishing DTD v1.2 20190208//EN", "https://jats.nlm.nih.gov/publishing/1.2/JATS-journalpublishing1.dtd"));
55 |
56 | $this->setBasicStructure();
57 | $this->extractContent();
58 | $this->cleanContent();
59 | $this->extractMetadata();
60 | $this->extractReferences();
61 | }
62 |
63 | public function getJatsFile(string $pathToFile) {
64 | $this->save($pathToFile);
65 | }
66 |
67 | private function setBasicStructure() {
68 | $this->article = $this->createElement('article');
69 | $this->article->setAttributeNS(
70 | "http://www.w3.org/2000/xmlns/",
71 | "xmlns:xlink",
72 | "http://www.w3.org/1999/xlink"
73 | );
74 |
75 | $this->appendChild($this->article);
76 |
77 | $this->front = $this->createElement('front');
78 | $this->article->appendChild($this->front);
79 |
80 | $this->body = $this->createElement('body');
81 | $this->article->appendChild($this->body);
82 |
83 | $this->back = $this->createElement('back');
84 | $this->article->appendChild($this->back);
85 | }
86 |
87 | private function extractContent() {
88 | $document = $this->docxArchive->getDocument();
89 | if (!empty($document->getContent())) {
90 |
91 | $latestSectionId = array();
92 | $latestSections = array();
93 |
94 | $subList = array(); // temporary container for sublists
95 | $listItem = null; // temporary container for previous list item
96 | $listCounter = -1; // temporary container for current list ID
97 | foreach ($document->getContent() as $key => $content) {
98 | $contentId = 'sec-' . implode('_', $content->getDimensionalSectionId());
99 |
100 | // Appending section, must correspond section nested level; TODO optimize with recursion
101 | if ($content->getDimensionalSectionId() !== $latestSectionId) {
102 | $sectionNode = $this->createElement("sec");
103 | $sectionNode->setAttribute('id', $contentId);
104 | $this->sections[$contentId] = $sectionNode;
105 | if (count($content->getDimensionalSectionId()) === 1) {
106 | $this->body->appendChild($sectionNode);
107 | $latestSections[0] = $sectionNode;
108 | } elseif (count($content->getDimensionalSectionId()) === 2) {
109 | $latestSections[0]->appendChild($sectionNode);
110 | $latestSections[1] = $sectionNode;
111 | } elseif (count($content->getDimensionalSectionId()) === 3) {
112 | $latestSections[1]->appendChild($sectionNode);
113 | $latestSections[2] = $sectionNode;
114 | } elseif (count($content->getDimensionalSectionId()) === 4) {
115 | $latestSections[2]->appendChild($sectionNode);
116 | $latestSections[3] = $sectionNode;
117 | } elseif (count($content->getDimensionalSectionId()) === 5) {
118 | $latestSections[3]->appendChild($sectionNode);
119 | }
120 |
121 | $latestSectionId = $content->getDimensionalSectionId();
122 | }
123 |
124 | // If there aren't any sections, append content to the body
125 | if (empty($this->sections)) {
126 | $sectionsOrBody = array($this->body);
127 | } else {
128 | $sectionsOrBody = $this->sections;
129 | }
130 |
131 | switch (get_class($content)) {
132 |
133 | case "docx2jats\objectModel\body\Par":
134 | /* @var $content Par */
135 | $jatsPar = new JatsPar($content);
136 |
137 | foreach ($sectionsOrBody as $section) {
138 | if ($contentId === $section->getAttribute('id') || $section->nodeName === "body") {
139 | if (!in_array(Par::DOCX_PAR_LIST, $content->getType())) {
140 | $section->appendChild($jatsPar);
141 | $jatsPar->setContent();
142 | } elseif (!in_array(Par::DOCX_PAR_HEADING, $content->getType())) {
143 | $itemId = $content->getNumberingItemProp()[Par::DOCX_LIST_ITEM_ID];
144 | $hasSublist = $content->getNumberingItemProp()[Par::DOCX_LIST_HAS_SUBLIST];
145 |
146 | // Creating and appending new list
147 | // !array_key_exists... is necessary as there can be several lists with the same id, usually it's malformed doc
148 | // TODO find a way to properly deal with numberings with the same id interrupted by simple regular paragraphs
149 | if ($listCounter !== $content->getNumberingId()) {
150 | $newList = $this->createElement('list');
151 | if ($content->getNumberingType() == Par::DOCX_LIST_TYPE_ORDERED) {
152 | $newList->setAttribute("list-type", "order");
153 | } else {
154 | $newList->setAttribute("list-type", "bullet");
155 | }
156 | $this->lists[$content->getNumberingId()] = $newList;
157 | }
158 |
159 | $section->appendChild($this->lists[$content->getNumberingId()]);
160 |
161 | // appends nested lists and list items based on their level
162 | if (count($itemId) === $content->getNumberingLevel()+1) {
163 | $listItem = $this->createElement('list-item');
164 | $listItem->appendChild($jatsPar);
165 | $jatsPar->setContent();
166 |
167 | if ($content->getNumberingLevel() === 0) {
168 | $this->lists[$content->getNumberingId()]->appendChild($listItem);
169 | } elseif (array_key_exists($content->getNumberingLevel()-1, $subList)) {
170 | $subList[$content->getNumberingLevel()-1]->appendChild($listItem);
171 | // Append to first list level if user has set unrealistic level for nested items
172 | } else {
173 | $this->lists[$content->getNumberingId()]->appendChild($listItem);
174 | }
175 |
176 | if ($hasSublist) {
177 | $subList[$content->getNumberingLevel()] = $this->createElement('list');
178 | if ($content->getSubNumberingType() == Par::DOCX_LIST_TYPE_ORDERED) {
179 | $subList[$content->getNumberingLevel()]->setAttribute("list-type", "order");
180 | } else {
181 | $subList[$content->getNumberingLevel()]->setAttribute("list-type", "bullet");
182 | }
183 | $listItem->appendChild($subList[$content->getNumberingLevel()]);
184 | }
185 | }
186 |
187 | // Refreshing list-item ID number
188 | $listCounter = $content->getNumberingId();
189 | }
190 | }
191 | }
192 | break;
193 | case "docx2jats\objectModel\body\Table":
194 | foreach ($sectionsOrBody as $section) {
195 | if ($contentId === $section->getAttribute('id') || $section->nodeName === "body") {
196 | $table = new JatsTable($content);
197 | $section->appendChild($table);
198 | $table->setContent();
199 |
200 | }
201 | }
202 | break;
203 | case "docx2jats\objectModel\body\Image":
204 | foreach ($sectionsOrBody as $section) {
205 | if ($contentId === $section->getAttribute('id') || $section->nodeName === "body") {
206 | $figure = new JatsFigure($content);
207 | $section->appendChild($figure);
208 | $figure->setContent();
209 | }
210 | }
211 | }
212 | }
213 | }
214 | }
215 |
216 | /*
217 | * @brief MS Word output leaves empty nodes, normalize the final document
218 | * elements with attribute and empty table cells should be left; empty table rows can be deleted as do not have semantic meaning
219 | */
220 |
221 | private function cleanContent(): void {
222 | $xpath = new \DOMXPath($this);
223 | $nodesToRemove = $xpath->query("//body//*[not(normalize-space()) and not(.//@*) and not(self::td)]");
224 | foreach ($nodesToRemove as $nodeToRemove) {
225 | $nodeToRemove->parentNode->removeChild($nodeToRemove);
226 | }
227 | }
228 |
229 | private function extractMetadata() {
230 | //TODO find and extract OOXML metadata
231 |
232 | // Needed to make JATS XML document valid
233 | $journalMetaNode = $this->createElement("journal-meta");
234 | $this->front->appendChild($journalMetaNode);
235 | $journalIdNode = $this->createElement("journal-id");
236 | $journalMetaNode->appendChild($journalIdNode);
237 | $issnNode = $this->createElement("issn");
238 | $journalMetaNode->appendChild($issnNode);
239 |
240 | $articleMetaNode = $this->createElement("article-meta");
241 | $this->front->appendChild($articleMetaNode);
242 | $titleGroupNode = $this->createElement("title-group");
243 | $articleMetaNode->appendChild($titleGroupNode);
244 | $articleTitleNode = $this->createElement("article-title");
245 | $titleGroupNode->appendChild($articleTitleNode);
246 | }
247 |
248 | private function extractReferences() : void {
249 | $document = $this->docxArchive->getDocument();
250 | $references = $document->getReferences();
251 | if (empty($references)) return;
252 |
253 | $refList = $this->createElement('ref-list');
254 | $this->back->appendChild($refList);
255 | foreach ($references as $reference) {
256 | $referenceEl = new Reference();
257 | $refList->appendChild($referenceEl);
258 | $referenceEl->setContent($reference);
259 | }
260 | }
261 | }
262 |
--------------------------------------------------------------------------------
/src/docx2jats/objectModel/body/Par.php:
--------------------------------------------------------------------------------
1 | defineType();
63 | $this->properties = $this->setProperties('w:pPr/child::node()');
64 | $this->text = $this->setContent('w:r|w:hyperlink');
65 | $this->type = $this->defineType();
66 | $this->headingLevel = $this->setHeadingLevel();
67 | $this->numberingLevel = $this->setNumberingLevel();
68 | $this->numberingId = $this->setNumberingId();
69 | $this->numberingItemProp = $this->setNumberingItemProp();
70 | $this->numberingType = $this->extractNumberingType();
71 | }
72 |
73 | /**
74 | * @return array
75 | */
76 | public function getProperties(): array {
77 | return $this->properties;
78 | }
79 |
80 |
81 | /**
82 | * @return array
83 | */
84 | public function getContent(): array {
85 | return $this->text;
86 | }
87 |
88 | /**
89 | * @return array
90 | */
91 | public function getType() {
92 | return $this->type;
93 | }
94 |
95 | /**
96 | * @param string $xpathExpression
97 | * @return array
98 | * @brief Sets a content for the paragraph: text runs, links and complex fields
99 | */
100 | protected function setContent(string $xpathExpression) {
101 | $content = array();
102 | $contentNodes = $this->getXpath()->query($xpathExpression, $this->getDomElement());
103 | $field = null;
104 | foreach ($contentNodes as $contentNode) {
105 | if ($contentNode->nodeName === "w:r") {
106 | // complex field or text run; complex field spans on several text runs
107 | if (!$field && Field::complexFieldStarts($contentNode)) {
108 | $field = new Field($contentNode, $this->getOwnerDocument(), $this);
109 | $content[] = $field;
110 | } elseif ($field && !Field::complexFieldLast($contentNode)) {
111 | $field->addContent($contentNode);
112 | } elseif ($field && Field::complexFieldLast($contentNode)) {
113 | $field->addContent($contentNode);
114 |
115 | // record a position of field with a bookmark in an array
116 | if ($field->getFldCharRefId()) $this->fldCharRefPos[] = count($content)-1;
117 | $field = null;
118 | } else {
119 | $text = new Text($contentNode, $this->getOwnerDocument());
120 | $content[] = $text;
121 | }
122 | } elseif ($contentNode->nodeName === "w:hyperlink") {
123 | $children = $this->getXpath()->query('child::node()', $contentNode);
124 | foreach ($children as $child) {
125 | $href = new Text($child, $this->getOwnerDocument());
126 | $href->addType($href::DOCX_TEXT_EXTLINK);
127 | $href->setLink();
128 | $content[] = $href;
129 | }
130 | }
131 | }
132 |
133 | return $content;
134 | }
135 |
136 | /**
137 | * @return array
138 | */
139 | private function defineType() {
140 | $type = array();
141 | $styles = $this->getXpath()->query('w:pPr/w:pStyle/@w:val', $this->getDomElement());
142 |
143 | if ($this->isOnlyChildNode($styles) &&
144 | Document::getBuiltinStyle(Document::DOCX_STYLES_PARAGRAPH, $styles[0]->nodeValue, self::$bibliography)) {
145 |
146 | $type[] = self::DOCX_PAR_REF;
147 | return $type; // stop if reference
148 | }
149 |
150 | if ($this->isOnlyChildNode($styles) &&
151 | Document::getBuiltinStyle(Document::DOCX_STYLES_PARAGRAPH, $styles[0]->nodeValue, self::$headings)) {
152 |
153 | $type[] = self::DOCX_PAR_HEADING;
154 | }
155 |
156 | //w:numPr node can appear in lists, heading (heading level), text corrections -> with a child ins with the name of the editor, etc...
157 | $numberingNode = $this->getXpath()->query('w:pPr/w:numPr', $this->getDomElement());
158 | if ($this->isOnlyChildNode($numberingNode) && !in_array(self::DOCX_PAR_HEADING, $type)) { // do not include headings to lists
159 |
160 | // if w:ilvl is a child, in more other cases it would be a list
161 | // TODO should other algorithms for list detection be considered?
162 | $levelNode = $this->getXpath()->query('w:ilvl', $numberingNode[0]);
163 | if ($this->isOnlyChildNode($levelNode)) {
164 | $type[] = self::DOCX_PAR_LIST;
165 | }
166 | }
167 |
168 | if (empty($type)) {
169 | $type[] = self::DOCX_PAR_REGULAR;
170 | }
171 |
172 | return $type;
173 | }
174 |
175 | /**
176 | * @return int $level
177 | */
178 | private function setHeadingLevel() {
179 | $level = 0;
180 | $styleString = '';
181 | if (in_array(self::DOCX_PAR_HEADING, $this->type )) {
182 | $styles = $this->getXpath()->query('w:pPr/w:pStyle/@w:val', $this->getDomElement());
183 | $styleString = Document::getBuiltinStyle(Document::DOCX_STYLES_PARAGRAPH, $styles[0]->nodeValue, self::$headings);
184 | }
185 |
186 | // Not a heading if empty
187 | if (empty($styleString)) return $level;
188 |
189 | preg_match_all('/\d+/', $styleString, $matches);
190 |
191 | // Treat headings without a number as the 1st level headings
192 | if (empty($matches[0])) return $level+1;
193 |
194 | $level = intval(implode('', $matches[0]));
195 |
196 | return $level;
197 | }
198 |
199 | /**
200 | * @return int
201 | */
202 | public function getHeadingLevel(): int {
203 | return $this->headingLevel;
204 | }
205 |
206 | /**
207 | * @return int
208 | */
209 | private function setNumberingLevel(): int {
210 | $numberingLevel = 0;
211 | $numberString = '';
212 | if (in_array(self::DOCX_PAR_LIST, $this->type)) {
213 | $numberNode = $this->getXpath()->query('w:pPr/w:numPr/w:ilvl/@w:val', $this->getDomElement());
214 | if ($this->isOnlyChildNode($numberNode)) {
215 | $numberString = $numberNode[0]->nodeValue;
216 | }
217 | }
218 |
219 | if (empty($numberString)) return $numberingLevel;
220 |
221 | $numberingLevel = intval($numberString);
222 |
223 | return $numberingLevel;
224 | }
225 |
226 | /**
227 | * @return int
228 | */
229 | public function getNumberingLevel(): int {
230 | return $this->numberingLevel;
231 | }
232 |
233 | /**
234 | * @return int
235 | */
236 | private function setNumberingId(): int {
237 | $numberingId = 0;
238 | $numberString = '';
239 | if (in_array(self::DOCX_PAR_LIST, $this->type)) {
240 | $numberNode = $this->getXpath()->query('w:pPr/w:numPr/w:numId/@w:val', $this->getDomElement());
241 | if ($this->isOnlyChildNode($numberNode)) {
242 | $numberString = $numberNode[0]->nodeValue;
243 | }
244 | }
245 |
246 | if (empty($numberString)) return $numberingId;
247 |
248 | $numberingId = intval($numberString);
249 |
250 | return $numberingId;
251 | }
252 |
253 |
254 | /**
255 | * @return int
256 | */
257 | public function getNumberingId(): int {
258 | return $this->numberingId;
259 | }
260 |
261 | /**
262 | * @return array
263 | */
264 | private function setNumberingItemProp(): array {
265 |
266 | $propArray = array();
267 | $itemDimensionalId = array_fill(0, $this->getNumberingLevel()+1, 0);
268 |
269 | if (!in_array(self::DOCX_PAR_LIST, $this->getType())) return $propArray;
270 |
271 | $propArray = array(self::DOCX_LIST_START => false, self::DOCX_LIST_END => false, self::DOCX_LIST_HAS_SUBLIST => false, self::DOCX_LIST_ITEM_ID => $itemDimensionalId);
272 |
273 | $numberNode = $this->getXpath()->query('w:pPr/w:numPr/w:ilvl/@w:val', $this->getDomElement())[0];
274 | $number = intval($numberNode->nodeValue);
275 |
276 | // Properties based on the previous node's level
277 | $prevNumberNode = $this->getXpath()->query('preceding-sibling::w:p[1]/w:pPr/w:numPr/w:ilvl/@w:val', $this->getDomElement());
278 | if ($this->isOnlyChildNode($prevNumberNode)) {
279 | $prevNumber = intval($prevNumberNode[0]->nodeValue);
280 | if ($prevNumber < $number) $propArray[self::DOCX_LIST_START] = true;
281 | } else {
282 | $propArray[self::DOCX_LIST_START] = true;
283 | }
284 |
285 | // Properties based on the following node's level
286 | $nextNumberNode = $this->getXpath()->query('following-sibling::w:p[1]/w:pPr/w:numPr/w:ilvl/@w:val', $this->getDomElement());
287 | if ($this->isOnlyChildNode($nextNumberNode)) {
288 | $nextNumber = intval($nextNumberNode[0]->nodeValue);
289 | if ($nextNumber < $number) $propArray[self::DOCX_LIST_END] = true;
290 | if ($nextNumber > $number) {
291 | $propArray[self::DOCX_LIST_HAS_SUBLIST] = true;
292 | $this->subNumberingType = $this->extractNumberingType($nextNumberNode[0]);
293 | }
294 | } else {
295 | $propArray[self::DOCX_LIST_END] = true;
296 | }
297 |
298 | // Determining dimensional ID based on Node's level and the number of preceding nodes on the same level and levels above
299 |
300 | $numberingLevel = $this->getNumberingLevel();
301 | while (!($numberingLevel < 0)) {
302 | $previousSiblingSameList = $this->getXpath()->query('preceding-sibling::w:p/w:pPr/w:numPr/w:numId[@w:val="' . $this->getNumberingId() . '"]', $this->getDomElement());
303 | $countSameLevel = 0;
304 | if (count($previousSiblingSameList) > 0) {
305 | foreach ($previousSiblingSameList as $sameListItem) {
306 | $previousSiblingSameId = $this->getXpath()->query('parent::w:numPr/w:ilvl[@w:val="' . $numberingLevel . '"]', $sameListItem);
307 | if ($this->isOnlyChildNode($previousSiblingSameId)) $countSameLevel++;
308 | }
309 | }
310 |
311 | $itemDimensionalId[$numberingLevel] = $countSameLevel;
312 | $numberingLevel--;
313 | }
314 |
315 | $propArray[self::DOCX_LIST_ITEM_ID] = $itemDimensionalId;
316 |
317 | return $propArray;
318 | }
319 |
320 | public function getNumberingItemProp() {
321 | return $this->numberingItemProp;
322 | }
323 |
324 | private function extractNumberingType($domElement = null): int {
325 | $numberingType = self::DOCX_LIST_TYPE_UNORDERED;
326 | $numberingPrNode = null;
327 | if ($domElement === null) $domElement = $this->getDomElement();
328 | if (in_array(self::DOCX_PAR_LIST, $this->type)) {
329 | $numberingPrNode = $this->getXpath()->query("w:pPr/w:numPr", $domElement);
330 | } else {
331 | // shouldn't be true; keeping if other algorithm for numbering detection would be used
332 | return $numberingType;
333 | }
334 |
335 | if ($numberingPrNode->count() == 0) return $numberingType;
336 |
337 | $lvl = $this->getXpath()->query("w:ilvl/@w:val", $numberingPrNode[0]);
338 |
339 | if ($lvl->count() == 0) return $numberingType;
340 |
341 | $id = $this->getXpath()->query("w:numId/@w:val", $numberingPrNode[0]);
342 |
343 | if ($id->count() == 0) return $numberingType;
344 |
345 | $type = Document::getNumberingTypeById($id[0]->nodeValue, $lvl[0]->nodeValue);
346 |
347 | if (!in_array($type, self::$numberingUnorderedMarkers)) $numberingType = self::DOCX_LIST_TYPE_ORDERED;
348 |
349 | return $numberingType;
350 | }
351 |
352 | /**
353 | * @return int
354 | */
355 | public function getNumberingType(): int {
356 | return $this->numberingType;
357 | }
358 |
359 | public function toString(): string {
360 | $text = '';
361 | foreach ($this->getContent() as $content) {
362 | if (get_class($content) !== 'docx2jats\objectModel\body\Text') continue;
363 | $text .= $content->getContent();
364 | }
365 | return $text;
366 | }
367 |
368 | public function getSubNumberingType() {
369 | return $this->subNumberingType;
370 | }
371 | }
372 |
--------------------------------------------------------------------------------
/src/docx2jats/objectModel/Document.php:
--------------------------------------------------------------------------------
1 | name
69 | */
70 | public $bookMarks = array();
71 |
72 | public function __construct(array $params) {
73 | if (array_key_exists("partRelationships", $params)) {
74 | $this->relationships = $params["partRelationships"];
75 | self::$relationshipsXpath = new \DOMXPath($this->relationships);
76 | }
77 |
78 | if (array_key_exists("styles", $params)) {
79 | $this->styles = $params["styles"];
80 | self::$stylesXpath = new \DOMXPath($this->styles);
81 | }
82 |
83 | if (array_key_exists("numbering", $params)) {
84 | $this->numbering = $params["numbering"];
85 | self::$numberingXpath = new \DOMXPath($this->numbering);
86 | }
87 |
88 | if (array_key_exists("docPropsCustom", $params)) {
89 | $this->docPropsCustom = $params["docPropsCustom"];
90 | self::$docPropsCustomXpath = new \DOMXPath($this->docPropsCustom);
91 | }
92 |
93 | self::$xpath = new \DOMXPath($params["ooxmlDocument"]);
94 | $this->findBookmarks();
95 |
96 | $childNodes = self::$xpath->query("//w:body/child::node()");
97 |
98 | $content = array();
99 | $unUsedCaption = null;
100 | foreach ($childNodes as $key => $childNode) {
101 | // Assign block elements, i.e., Figures, Tables, Paragraphs, depending on the context
102 | switch ($childNode->nodeName) {
103 | case "w:p":
104 | /**
105 | * TODO add support for other drawings type, e.g., c:chart
106 | * Figures are contained inside paragraphs, particularly - in text runs;
107 | * there may be several images each inside own text run.
108 | * In addition, LibreOffice Writer's DOCX export includes 2 duplicates of drawings for compatibility reasons
109 | */
110 | if ($this->isDrawing($childNode)) {
111 | $drawingEls = null;
112 | $textRuns = self::$xpath->query('w:r', $childNode);
113 | foreach ($textRuns as $textRun) {
114 | // Retrieve only first one (LibreOffice Writer duplicates with a fallback option
115 | $checkDrawingEl = self::$xpath->query('.//w:drawing[1]', $textRun)[0];
116 | if ($checkDrawingEl) $drawingEls[] = $checkDrawingEl;
117 | }
118 | if (empty($drawingEls)) break;
119 |
120 | foreach ($drawingEls as $drawingEl) {
121 | // check if contains image, charts aren't supported
122 | self::$xpath->registerNamespace("pic", "http://schemas.openxmlformats.org/drawingml/2006/picture");
123 | $imageNodes = self::$xpath->query(".//pic:pic", $drawingEl);
124 | if ($imageNodes->length === 0) break;
125 |
126 | $figure = new Image($drawingEl, $this);
127 | $content[] = $figure;
128 |
129 | // Get coordinates for this figure
130 | $this->elsAreFigures[] = count($content) - 1;
131 |
132 | // Set unique ID
133 | $figure->setFigureId($this->currentFigureId++);
134 |
135 | // Set caption if exists
136 | if ($unUsedCaption) {
137 | $figure->setCaption($unUsedCaption);
138 | $unUsedCaption = null;
139 | }
140 | }
141 |
142 | } elseif ($this->isCaption($childNode)) {
143 | // Check if previous node is drawing or table
144 | if (!empty($content)) { // may be empty if caption is the first element
145 | $prevObject =& $content[array_key_last($content)];
146 | }
147 |
148 | if (isset($prevObject) && (get_class($prevObject) === 'docx2jats\objectModel\body\Table' || get_class($prevObject) === 'docx2jats\objectModel\body\Image')) {
149 | $prevObject->setCaption($childNode);
150 | } else {
151 | $unUsedCaption = $childNode;
152 | }
153 | } else {
154 | $par = new Par($childNode, $this);
155 | if (in_array(Par::DOCX_PAR_REF, $par->getType())) {
156 | if (!empty(trim($par->toString()))) {
157 | $reference = new Reference($par->toString());
158 | $this->addReference($reference);
159 | }
160 | } else {
161 | $content[] = $par;
162 | }
163 |
164 | if ($par->hasBookmarks) {
165 | $this->elsHavefldCharRefs[] = count($content)-1;
166 | }
167 | }
168 | break;
169 | case "w:tbl":
170 | $table = new Table($childNode, $this);
171 | $content[] = $table;
172 | $this->elsAreTables[] = count($content)-1;
173 |
174 | // Set unique ID
175 | $table->setTableId($this->currentTableId++);
176 | // Set caption if exists
177 | if ($unUsedCaption) {
178 | $table->setCaption($unUsedCaption);
179 | $unUsedCaption = null;
180 | }
181 | break;
182 | }
183 | }
184 |
185 | $this->content = $this->addSectionMarks($content);
186 | self::$minimalHeadingLevel = $this->minimalHeadingLevel();
187 | $this->setInternalRefs();
188 | }
189 |
190 | /**
191 | * @return array
192 | */
193 | public function getContent(): array {
194 | return $this->content;
195 | }
196 |
197 | private function minimalHeadingLevel(): int {
198 | $minimalNumber = 7;
199 | foreach ($this->content as $dataObject) {
200 | if (get_class($dataObject) === "docx2jats\objectModel\body\Par" && in_array(Par::DOCX_PAR_LIST, $dataObject->getType())) {
201 | $number = $dataObject->getHeadingLevel();
202 | if ($number && $number < $minimalNumber) {
203 | $minimalNumber = $number;
204 | }
205 | }
206 | }
207 |
208 | return $minimalNumber;
209 | }
210 |
211 | /**
212 | * @return int
213 | */
214 | public static function getMinimalHeadingLevel(): int {
215 | return self::$minimalHeadingLevel;
216 | }
217 |
218 | /**
219 | * @param array $content
220 | * @return array
221 | * @brief set marks for the section, number in order and specific ID for nested sections
222 | */
223 | private function addSectionMarks(array $content): array {
224 |
225 | $flatSectionId = 0; // simple section id
226 | $dimensions = array_fill(0, self::SECT_NESTED_LEVEL_LIMIT, 0); // contains dimensional section id
227 | foreach ($content as $key => $object) {
228 | if (get_class($object) === "docx2jats\objectModel\body\Par" && $object->getType() && $object->getHeadingLevel()) {
229 | $flatSectionId++;
230 | $dimensions = $this->extractSectionDimension($object, $dimensions);
231 | }
232 |
233 | $object->setDimensionalSectionId($dimensions);
234 | $object->setFlatSectionId($flatSectionId);
235 | }
236 |
237 | return $content;
238 | }
239 |
240 | /**
241 | * @param $object Par
242 | * @param array $dimensions
243 | * @param int $n
244 | * @return array
245 | * @brief for internal use, defines dimensional section id for a given Par heading
246 | */
247 | private function extractSectionDimension(Par $object, array $dimensions): array
248 | {
249 | $number = $object->getHeadingLevel() - 1;
250 | $dimensions[$number]++;
251 | while ($number < self::SECT_NESTED_LEVEL_LIMIT) {
252 | $number++;
253 | $dimensions[$number] = 0;
254 | }
255 | return $dimensions;
256 | }
257 |
258 | static function getRelationshipById(string $id): string {
259 | $element = self::$relationshipsXpath->query("//*[@Id='" . $id ."']");
260 | $target = $element[0]->getAttribute("Target");
261 | return $target;
262 | }
263 |
264 | static function getElementStyling(string $constStyleType, string $id): ?string {
265 | /* @var $element \DOMElement */
266 | /* @var $name \DOMElement */
267 | if (self::$stylesXpath) {
268 | $element = self::$stylesXpath->query("/w:styles/w:style[@w:type='" . $constStyleType . "'][@w:styleId='" . $id . "']")[0];
269 | $name = self::$stylesXpath->query("w:name", $element)[0];
270 | return $name->getAttribute("w:val");
271 | } else {
272 | return null;
273 | }
274 | }
275 |
276 | static function getBuiltinStyle(string $constStyleType, string $id, array $builtinStyles): ?string {
277 | // Traverse the chain of styles to see if the named id style
278 | // inherits from one of the sought-for built-in styles and
279 | // return the one that matches.
280 | if (self::$stylesXpath) {
281 | do {
282 | $element = self::$stylesXpath->query("/w:styles/w:style[@w:type='" . $constStyleType . "'][@w:styleId='" . $id . "']")[0];
283 |
284 | $basedOn = self::$stylesXpath->query("w:basedOn", $element)[0];
285 | $id = $basedOn ? $basedOn->getAttribute("w:val") : null;
286 |
287 | $name = self::$stylesXpath->query("w:name", $element)[0];
288 | if (!$name) return null;
289 | $styleName = $name->getAttribute("w:val");
290 |
291 | if (in_array(strtolower($styleName), $builtinStyles)) return $styleName;
292 | } while($id);
293 |
294 | return null;
295 | } else {
296 |
297 | // Fall back on using the original id as if it were the name
298 | if (in_array($id, $builtinStyles)) return $id;
299 | else return null;
300 | }
301 | }
302 |
303 |
304 | private function isDrawing($childNode): bool {
305 | $element = Document::$xpath->query("w:r//w:drawing", $childNode)[0];
306 | if ($element) return true;
307 | return false;
308 | }
309 |
310 | /**
311 | * @param $childNode
312 | * @return bool
313 | * @brief determines if an element is caption
314 | */
315 | function isCaption($childNode): bool {
316 | $elementStyle = Document::$xpath->query("w:pPr/w:pStyle/@w:val", $childNode)[0];
317 | if (is_null($elementStyle)) return false;
318 |
319 | if (Document::getBuiltinStyle(Document::DOCX_STYLES_PARAGRAPH, $elementStyle->nodeValue, Table::$caption)) {
320 | return true;
321 | }
322 |
323 | return false;
324 | }
325 |
326 | /**
327 | * @param string $id
328 | * @param string $lvl
329 | * @return string|null
330 | * @brief Find w:num element by value of m:val attribute; retrieve w:abstractNumId element's m:val value;
331 | * Find w:abstractNum by a value of w:abstractNumId; retrieve the type of the list by the value of w:numFmt element under
332 | * w:lvl element with a correspondent value (see $lvl parameter)
333 | */
334 | static function getNumberingTypeById(string $id, string $lvl): ?string {
335 | if (!self::$numberingXpath) return null; // the numbering styles are missing.
336 |
337 | $abstractNumIdEl = self::$numberingXpath->query("//w:num[@w:numId='" . $id . "']/w:abstractNumId");
338 | if ($abstractNumIdEl->count() == 0) return null;
339 |
340 | $abstractNumId = $abstractNumIdEl[0]->getAttribute("w:val");
341 |
342 | $element = self::$numberingXpath->query("//*[@w:abstractNumId='" . $abstractNumId . "']");
343 | if ($element->count() == 0) return null;
344 |
345 | $level = self::$numberingXpath->query("w:lvl[@w:ilvl='" . $lvl . "']", $element[0]);
346 | if ($level->count() == 0) return null;
347 |
348 | $type = self::$numberingXpath->query("w:numFmt/@w:val", $level[0]);
349 | if ($type->count() == 0) return null;
350 |
351 | return $type[0]->nodeValue;
352 | }
353 |
354 | public function addReference(Reference $reference) {
355 | $this->refCount++;
356 | $reference->setId($this->refCount);
357 | $this->references[$this->refCount] = $reference;
358 | }
359 |
360 | public function getReferences() : array {
361 | return $this->references;
362 | }
363 |
364 | public function getLastReference() : ?Reference {
365 | $lastId = array_key_last($this->references);
366 | return $this->references[$lastId];
367 | }
368 |
369 | /**
370 | * @brief iterate through the content and establish internal links between element
371 | * elsHaveBookmarks holds position in an array of each paragraph that includes a bookmark
372 | * it's slightly faster than looping over the whole content
373 | */
374 | private function setInternalRefs(): void {
375 | if (empty($this->elsHavefldCharRefs)) return;
376 |
377 | // Find and map tables' and figures' bookmarks
378 | $refTableMap = $this->getBookmarkCaptionMapping($this->elsAreTables);
379 | $refFigureMap = $this->getBookmarkCaptionMapping($this->elsAreFigures);
380 |
381 | // Find bookmark refs
382 | foreach ($this->elsHavefldCharRefs as $parKeyWithBookmark) {
383 | $par = $this->getContent()[$parKeyWithBookmark]; /* @var $par Par */
384 | foreach ($par->fldCharRefPos as $fieldKeyWithBookmark) {
385 | $field = $par->getContent()[$fieldKeyWithBookmark]; /* @var $field \docx2jats\objectModel\body\Field */
386 |
387 | // Set links to tables
388 | foreach ($refTableMap as $tableId => $tableRefs) {
389 | if (in_array($field->getFldCharRefId(), $tableRefs)) {
390 | $field->tableIdRef = $tableId;
391 | }
392 | }
393 |
394 | // Set links to Figures
395 | foreach ($refFigureMap as $figureId => $figureRefs) {
396 | if (in_array($field->getFldCharRefId(), $figureRefs)) {
397 | $field->figureIdRef = $figureId;
398 | }
399 | }
400 | }
401 | }
402 | }
403 |
404 | /**
405 | * @return array
406 | * @brief (or not so brief) Map OOXML bookmark refs inside tables and figures with correspondent table/figure IDs.
407 | * In OOXML those bookmarks are stored inside captions
408 | * This is used to set right link to these objects from the text
409 | * Keep in mind that bookmarks also may be stored in an external file, e.g., Mendeley plugin for LibreOffice Writer
410 | * stores links to references this way
411 | */
412 | function getBookmarkCaptionMapping(array $keysInContent): array {
413 | $refMap = [];
414 | foreach ($keysInContent as $tableKey) {
415 | $table = $this->content[$tableKey]; /* @var $table Table|Image */
416 | if (empty($table->getBookmarkIds())) continue;
417 | $refMap[$table->getId()] = $table->getBookmarkIds();
418 | }
419 |
420 | return $refMap;
421 | }
422 |
423 | /**
424 | * Find and retrieve id and name from all bookmarks in the main document part
425 | */
426 | private function findBookmarks(): void {
427 | $bookmarkEls = self::$xpath->query('//w:bookmarkStart');
428 | foreach ($bookmarkEls as $bookmarkEl) {
429 | $this->bookMarks[$bookmarkEl->getAttribute('w:id')] = $bookmarkEl->getAttribute('w:name');
430 | }
431 | }
432 |
433 | public function docPropsCustom() {
434 | return $this->docPropsCustom;
435 | }
436 | }
437 |
--------------------------------------------------------------------------------
/vendor/composer/ClassLoader.php:
--------------------------------------------------------------------------------
1 |
7 | * Jordi Boggiano
8 | *
9 | * For the full copyright and license information, please view the LICENSE
10 | * file that was distributed with this source code.
11 | */
12 |
13 | namespace Composer\Autoload;
14 |
15 | /**
16 | * ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
17 | *
18 | * $loader = new \Composer\Autoload\ClassLoader();
19 | *
20 | * // register classes with namespaces
21 | * $loader->add('Symfony\Component', __DIR__.'/component');
22 | * $loader->add('Symfony', __DIR__.'/framework');
23 | *
24 | * // activate the autoloader
25 | * $loader->register();
26 | *
27 | * // to enable searching the include path (eg. for PEAR packages)
28 | * $loader->setUseIncludePath(true);
29 | *
30 | * In this example, if you try to use a class in the Symfony\Component
31 | * namespace or one of its children (Symfony\Component\Console for instance),
32 | * the autoloader will first look for the class under the component/
33 | * directory, and it will then fallback to the framework/ directory if not
34 | * found before giving up.
35 | *
36 | * This class is loosely based on the Symfony UniversalClassLoader.
37 | *
38 | * @author Fabien Potencier
39 | * @author Jordi Boggiano
40 | * @see https://www.php-fig.org/psr/psr-0/
41 | * @see https://www.php-fig.org/psr/psr-4/
42 | */
43 | class ClassLoader
44 | {
45 | private $vendorDir;
46 |
47 | // PSR-4
48 | private $prefixLengthsPsr4 = array();
49 | private $prefixDirsPsr4 = array();
50 | private $fallbackDirsPsr4 = array();
51 |
52 | // PSR-0
53 | private $prefixesPsr0 = array();
54 | private $fallbackDirsPsr0 = array();
55 |
56 | private $useIncludePath = false;
57 | private $classMap = array();
58 | private $classMapAuthoritative = false;
59 | private $missingClasses = array();
60 | private $apcuPrefix;
61 |
62 | private static $registeredLoaders = array();
63 |
64 | public function __construct($vendorDir = null)
65 | {
66 | $this->vendorDir = $vendorDir;
67 | }
68 |
69 | public function getPrefixes()
70 | {
71 | if (!empty($this->prefixesPsr0)) {
72 | return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
73 | }
74 |
75 | return array();
76 | }
77 |
78 | public function getPrefixesPsr4()
79 | {
80 | return $this->prefixDirsPsr4;
81 | }
82 |
83 | public function getFallbackDirs()
84 | {
85 | return $this->fallbackDirsPsr0;
86 | }
87 |
88 | public function getFallbackDirsPsr4()
89 | {
90 | return $this->fallbackDirsPsr4;
91 | }
92 |
93 | public function getClassMap()
94 | {
95 | return $this->classMap;
96 | }
97 |
98 | /**
99 | * @param array $classMap Class to filename map
100 | */
101 | public function addClassMap(array $classMap)
102 | {
103 | if ($this->classMap) {
104 | $this->classMap = array_merge($this->classMap, $classMap);
105 | } else {
106 | $this->classMap = $classMap;
107 | }
108 | }
109 |
110 | /**
111 | * Registers a set of PSR-0 directories for a given prefix, either
112 | * appending or prepending to the ones previously set for this prefix.
113 | *
114 | * @param string $prefix The prefix
115 | * @param array|string $paths The PSR-0 root directories
116 | * @param bool $prepend Whether to prepend the directories
117 | */
118 | public function add($prefix, $paths, $prepend = false)
119 | {
120 | if (!$prefix) {
121 | if ($prepend) {
122 | $this->fallbackDirsPsr0 = array_merge(
123 | (array) $paths,
124 | $this->fallbackDirsPsr0
125 | );
126 | } else {
127 | $this->fallbackDirsPsr0 = array_merge(
128 | $this->fallbackDirsPsr0,
129 | (array) $paths
130 | );
131 | }
132 |
133 | return;
134 | }
135 |
136 | $first = $prefix[0];
137 | if (!isset($this->prefixesPsr0[$first][$prefix])) {
138 | $this->prefixesPsr0[$first][$prefix] = (array) $paths;
139 |
140 | return;
141 | }
142 | if ($prepend) {
143 | $this->prefixesPsr0[$first][$prefix] = array_merge(
144 | (array) $paths,
145 | $this->prefixesPsr0[$first][$prefix]
146 | );
147 | } else {
148 | $this->prefixesPsr0[$first][$prefix] = array_merge(
149 | $this->prefixesPsr0[$first][$prefix],
150 | (array) $paths
151 | );
152 | }
153 | }
154 |
155 | /**
156 | * Registers a set of PSR-4 directories for a given namespace, either
157 | * appending or prepending to the ones previously set for this namespace.
158 | *
159 | * @param string $prefix The prefix/namespace, with trailing '\\'
160 | * @param array|string $paths The PSR-4 base directories
161 | * @param bool $prepend Whether to prepend the directories
162 | *
163 | * @throws \InvalidArgumentException
164 | */
165 | public function addPsr4($prefix, $paths, $prepend = false)
166 | {
167 | if (!$prefix) {
168 | // Register directories for the root namespace.
169 | if ($prepend) {
170 | $this->fallbackDirsPsr4 = array_merge(
171 | (array) $paths,
172 | $this->fallbackDirsPsr4
173 | );
174 | } else {
175 | $this->fallbackDirsPsr4 = array_merge(
176 | $this->fallbackDirsPsr4,
177 | (array) $paths
178 | );
179 | }
180 | } elseif (!isset($this->prefixDirsPsr4[$prefix])) {
181 | // Register directories for a new namespace.
182 | $length = strlen($prefix);
183 | if ('\\' !== $prefix[$length - 1]) {
184 | throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
185 | }
186 | $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
187 | $this->prefixDirsPsr4[$prefix] = (array) $paths;
188 | } elseif ($prepend) {
189 | // Prepend directories for an already registered namespace.
190 | $this->prefixDirsPsr4[$prefix] = array_merge(
191 | (array) $paths,
192 | $this->prefixDirsPsr4[$prefix]
193 | );
194 | } else {
195 | // Append directories for an already registered namespace.
196 | $this->prefixDirsPsr4[$prefix] = array_merge(
197 | $this->prefixDirsPsr4[$prefix],
198 | (array) $paths
199 | );
200 | }
201 | }
202 |
203 | /**
204 | * Registers a set of PSR-0 directories for a given prefix,
205 | * replacing any others previously set for this prefix.
206 | *
207 | * @param string $prefix The prefix
208 | * @param array|string $paths The PSR-0 base directories
209 | */
210 | public function set($prefix, $paths)
211 | {
212 | if (!$prefix) {
213 | $this->fallbackDirsPsr0 = (array) $paths;
214 | } else {
215 | $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
216 | }
217 | }
218 |
219 | /**
220 | * Registers a set of PSR-4 directories for a given namespace,
221 | * replacing any others previously set for this namespace.
222 | *
223 | * @param string $prefix The prefix/namespace, with trailing '\\'
224 | * @param array|string $paths The PSR-4 base directories
225 | *
226 | * @throws \InvalidArgumentException
227 | */
228 | public function setPsr4($prefix, $paths)
229 | {
230 | if (!$prefix) {
231 | $this->fallbackDirsPsr4 = (array) $paths;
232 | } else {
233 | $length = strlen($prefix);
234 | if ('\\' !== $prefix[$length - 1]) {
235 | throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
236 | }
237 | $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
238 | $this->prefixDirsPsr4[$prefix] = (array) $paths;
239 | }
240 | }
241 |
242 | /**
243 | * Turns on searching the include path for class files.
244 | *
245 | * @param bool $useIncludePath
246 | */
247 | public function setUseIncludePath($useIncludePath)
248 | {
249 | $this->useIncludePath = $useIncludePath;
250 | }
251 |
252 | /**
253 | * Can be used to check if the autoloader uses the include path to check
254 | * for classes.
255 | *
256 | * @return bool
257 | */
258 | public function getUseIncludePath()
259 | {
260 | return $this->useIncludePath;
261 | }
262 |
263 | /**
264 | * Turns off searching the prefix and fallback directories for classes
265 | * that have not been registered with the class map.
266 | *
267 | * @param bool $classMapAuthoritative
268 | */
269 | public function setClassMapAuthoritative($classMapAuthoritative)
270 | {
271 | $this->classMapAuthoritative = $classMapAuthoritative;
272 | }
273 |
274 | /**
275 | * Should class lookup fail if not found in the current class map?
276 | *
277 | * @return bool
278 | */
279 | public function isClassMapAuthoritative()
280 | {
281 | return $this->classMapAuthoritative;
282 | }
283 |
284 | /**
285 | * APCu prefix to use to cache found/not-found classes, if the extension is enabled.
286 | *
287 | * @param string|null $apcuPrefix
288 | */
289 | public function setApcuPrefix($apcuPrefix)
290 | {
291 | $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
292 | }
293 |
294 | /**
295 | * The APCu prefix in use, or null if APCu caching is not enabled.
296 | *
297 | * @return string|null
298 | */
299 | public function getApcuPrefix()
300 | {
301 | return $this->apcuPrefix;
302 | }
303 |
304 | /**
305 | * Registers this instance as an autoloader.
306 | *
307 | * @param bool $prepend Whether to prepend the autoloader or not
308 | */
309 | public function register($prepend = false)
310 | {
311 | spl_autoload_register(array($this, 'loadClass'), true, $prepend);
312 |
313 | if (null === $this->vendorDir) {
314 | return;
315 | }
316 |
317 | if ($prepend) {
318 | self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders;
319 | } else {
320 | unset(self::$registeredLoaders[$this->vendorDir]);
321 | self::$registeredLoaders[$this->vendorDir] = $this;
322 | }
323 | }
324 |
325 | /**
326 | * Unregisters this instance as an autoloader.
327 | */
328 | public function unregister()
329 | {
330 | spl_autoload_unregister(array($this, 'loadClass'));
331 |
332 | if (null !== $this->vendorDir) {
333 | unset(self::$registeredLoaders[$this->vendorDir]);
334 | }
335 | }
336 |
337 | /**
338 | * Loads the given class or interface.
339 | *
340 | * @param string $class The name of the class
341 | * @return bool|null True if loaded, null otherwise
342 | */
343 | public function loadClass($class)
344 | {
345 | if ($file = $this->findFile($class)) {
346 | includeFile($file);
347 |
348 | return true;
349 | }
350 | }
351 |
352 | /**
353 | * Finds the path to the file where the class is defined.
354 | *
355 | * @param string $class The name of the class
356 | *
357 | * @return string|false The path if found, false otherwise
358 | */
359 | public function findFile($class)
360 | {
361 | // class map lookup
362 | if (isset($this->classMap[$class])) {
363 | return $this->classMap[$class];
364 | }
365 | if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
366 | return false;
367 | }
368 | if (null !== $this->apcuPrefix) {
369 | $file = apcu_fetch($this->apcuPrefix.$class, $hit);
370 | if ($hit) {
371 | return $file;
372 | }
373 | }
374 |
375 | $file = $this->findFileWithExtension($class, '.php');
376 |
377 | // Search for Hack files if we are running on HHVM
378 | if (false === $file && defined('HHVM_VERSION')) {
379 | $file = $this->findFileWithExtension($class, '.hh');
380 | }
381 |
382 | if (null !== $this->apcuPrefix) {
383 | apcu_add($this->apcuPrefix.$class, $file);
384 | }
385 |
386 | if (false === $file) {
387 | // Remember that this class does not exist.
388 | $this->missingClasses[$class] = true;
389 | }
390 |
391 | return $file;
392 | }
393 |
394 | /**
395 | * Returns the currently registered loaders indexed by their corresponding vendor directories.
396 | *
397 | * @return self[]
398 | */
399 | public static function getRegisteredLoaders()
400 | {
401 | return self::$registeredLoaders;
402 | }
403 |
404 | private function findFileWithExtension($class, $ext)
405 | {
406 | // PSR-4 lookup
407 | $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
408 |
409 | $first = $class[0];
410 | if (isset($this->prefixLengthsPsr4[$first])) {
411 | $subPath = $class;
412 | while (false !== $lastPos = strrpos($subPath, '\\')) {
413 | $subPath = substr($subPath, 0, $lastPos);
414 | $search = $subPath . '\\';
415 | if (isset($this->prefixDirsPsr4[$search])) {
416 | $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
417 | foreach ($this->prefixDirsPsr4[$search] as $dir) {
418 | if (file_exists($file = $dir . $pathEnd)) {
419 | return $file;
420 | }
421 | }
422 | }
423 | }
424 | }
425 |
426 | // PSR-4 fallback dirs
427 | foreach ($this->fallbackDirsPsr4 as $dir) {
428 | if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
429 | return $file;
430 | }
431 | }
432 |
433 | // PSR-0 lookup
434 | if (false !== $pos = strrpos($class, '\\')) {
435 | // namespaced class name
436 | $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
437 | . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
438 | } else {
439 | // PEAR-like class name
440 | $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
441 | }
442 |
443 | if (isset($this->prefixesPsr0[$first])) {
444 | foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
445 | if (0 === strpos($class, $prefix)) {
446 | foreach ($dirs as $dir) {
447 | if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
448 | return $file;
449 | }
450 | }
451 | }
452 | }
453 | }
454 |
455 | // PSR-0 fallback dirs
456 | foreach ($this->fallbackDirsPsr0 as $dir) {
457 | if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
458 | return $file;
459 | }
460 | }
461 |
462 | // PSR-0 include paths.
463 | if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
464 | return $file;
465 | }
466 |
467 | return false;
468 | }
469 | }
470 |
471 | /**
472 | * Scope isolated include.
473 | *
474 | * Prevents access to $this/self from included files.
475 | */
476 | function includeFile($file)
477 | {
478 | include $file;
479 | }
480 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------