Bug 18143: Silence XML MARC Framework export flood
[koha.git] / C4 / ImportExportFramework.pm
1 package C4::ImportExportFramework;
2
3 # Copyright 2010-2011 MASmedios.com y Ministerio de Cultura
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use strict;
21 use warnings;
22 use XML::LibXML;
23 use XML::LibXML::XPathContext;
24 use Digest::MD5 qw();
25 use POSIX qw(strftime);
26
27 use C4::Context;
28 use C4::Debug;
29
30
31 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
32
33 BEGIN {
34     require Exporter;
35     @ISA    = qw(Exporter);
36     @EXPORT = qw(
37         &ExportFramework
38         &ImportFramework
39         &createODS
40     );
41 }
42
43
44 use constant XMLSTR => '<?xml version="1.0" encoding="UTF-8"?>
45 <?mso-application progid="Excel.Sheet"?>
46 <Workbook
47   xmlns:x="urn:schemas-microsoft-com:office:excel"
48   xmlns="urn:schemas-microsoft-com:office:spreadsheet"
49   xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
50
51 <Styles>
52  <Style ss:ID="Default" ss:Name="Normal">
53   <Alignment ss:Vertical="Bottom"/>
54   <Borders/>
55   <Font/>
56   <Interior/>
57   <NumberFormat/>
58   <Protection/>
59  </Style>
60  <Style ss:ID="s27">
61   <Font x:Family="Swiss" ss:Color="#0000FF" ss:Bold="1"/>
62  </Style>
63  <Style ss:ID="s21">
64   <NumberFormat ss:Format="yyyy\-mm\-dd"/>
65  </Style>
66  <Style ss:ID="s22">
67   <NumberFormat ss:Format="yyyy\-mm\-dd\ hh:mm:ss"/>
68  </Style>
69  <Style ss:ID="s23">
70   <NumberFormat ss:Format="hh:mm:ss"/>
71  </Style>
72 </Styles>
73
74 </Workbook>
75 ';
76
77
78 use constant ODSSTR => '<?xml version="1.0" encoding="UTF-8"?>
79 <office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" xmlns:math="http://www.w3.org/1998/Math/MathML" xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" xmlns:ooo="http://openoffice.org/2004/office" xmlns:ooow="http://openoffice.org/2004/writer" xmlns:oooc="http://openoffice.org/2004/calc" xmlns:dom="http://www.w3.org/2001/xml-events" xmlns:xforms="http://www.w3.org/2002/xforms" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" office:version="1.0">
80 <office:scripts/>
81 <office:font-face-decls/>
82 <office:automatic-styles/>
83 </office:document-content>';
84
85
86 use constant ODS_STYLES_STR => '<?xml version="1.0" encoding="UTF-8"?>
87 <office:document-styles xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" xmlns:math="http://www.w3.org/1998/Math/MathML" xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" xmlns:ooo="http://openoffice.org/2004/office" xmlns:ooow="http://openoffice.org/2004/writer" xmlns:oooc="http://openoffice.org/2004/calc" xmlns:dom="http://www.w3.org/2001/xml-events" office:version="1.0">
88 <office:font-face-decls></office:font-face-decls>
89 <office:styles></office:styles>
90 <office:automatic-styles></office:automatic-styles>
91 <office:master-styles></office:master-styles>
92 </office:document-styles>';
93
94
95 use constant ODS_SETTINGS_STR => '<?xml version="1.0" encoding="UTF-8"?>
96 <office:document-settings xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:config="urn:oasis:names:tc:opendocument:xmlns:config:1.0" xmlns:ooo="http://openoffice.org/2004/office" office:version="1.0"><office:settings>
97 <config:config-item-set config:name="ooo:view-settings">
98 <config:config-item config:name="VisibleAreaTop" config:type="int">0</config:config-item>
99 <config:config-item config:name="VisibleAreaLeft" config:type="int">0</config:config-item>
100 <config:config-item config:name="VisibleAreaWidth" config:type="int">2000</config:config-item>
101 <config:config-item config:name="VisibleAreaHeight" config:type="int">900</config:config-item>
102 <config:config-item-map-indexed config:name="Views"><config:config-item-map-entry>
103 <config:config-item config:name="ViewId" config:type="string">View1</config:config-item>
104 <config:config-item-map-named config:name="Tables">
105 <config:config-item-map-entry config:name="Sheet1"><config:config-item config:name="CursorPositionX" config:type="int">0</config:config-item><config:config-item config:name="CursorPositionY" config:type="int">1</config:config-item><config:config-item config:name="HorizontalSplitMode" config:type="short">0</config:config-item><config:config-item config:name="VerticalSplitMode" config:type="short">0</config:config-item><config:config-item config:name="HorizontalSplitPosition" config:type="int">0</config:config-item><config:config-item config:name="VerticalSplitPosition" config:type="int">0</config:config-item><config:config-item config:name="ActiveSplitRange" config:type="short">2</config:config-item><config:config-item config:name="PositionLeft" config:type="int">0</config:config-item><config:config-item config:name="PositionRight" config:type="int">0</config:config-item><config:config-item config:name="PositionTop" config:type="int">0</config:config-item><config:config-item config:name="PositionBottom" config:type="int">0</config:config-item>
106 </config:config-item-map-entry>
107 </config:config-item-map-named>
108 <config:config-item config:name="ActiveTable" config:type="string">Sheet1</config:config-item>
109 <config:config-item config:name="HorizontalScrollbarWidth" config:type="int">270</config:config-item>
110 <config:config-item config:name="ZoomType" config:type="short">0</config:config-item>
111 <config:config-item config:name="ZoomValue" config:type="int">100</config:config-item>
112 <config:config-item config:name="PageViewZoomValue" config:type="int">50</config:config-item>
113 <config:config-item config:name="ShowPageBreakPreview" config:type="boolean">false</config:config-item>
114 <config:config-item config:name="ShowZeroValues" config:type="boolean">true</config:config-item>
115 <config:config-item config:name="ShowNotes" config:type="boolean">true</config:config-item>
116 <config:config-item config:name="ShowGrid" config:type="boolean">true</config:config-item>
117 <config:config-item config:name="GridColor" config:type="long">12632256</config:config-item>
118 <config:config-item config:name="ShowPageBreaks" config:type="boolean">true</config:config-item>
119 <config:config-item config:name="HasColumnRowHeaders" config:type="boolean">true</config:config-item>
120 <config:config-item config:name="HasSheetTabs" config:type="boolean">true</config:config-item>
121 <config:config-item config:name="IsOutlineSymbolsSet" config:type="boolean">true</config:config-item>
122 <config:config-item config:name="IsSnapToRaster" config:type="boolean">false</config:config-item>
123 <config:config-item config:name="RasterIsVisible" config:type="boolean">false</config:config-item>
124 <config:config-item config:name="IsRasterAxisSynchronized" config:type="boolean">true</config:config-item></config:config-item-map-entry></config:config-item-map-indexed>
125 </config:config-item-set>
126 <config:config-item-set config:name="ooo:configuration-settings">
127 <config:config-item config:name="ShowZeroValues" config:type="boolean">true</config:config-item>
128 <config:config-item config:name="ShowNotes" config:type="boolean">true</config:config-item>
129 <config:config-item config:name="ShowGrid" config:type="boolean">true</config:config-item>
130 <config:config-item config:name="GridColor" config:type="long">12632256</config:config-item>
131 <config:config-item config:name="ShowPageBreaks" config:type="boolean">true</config:config-item>
132 <config:config-item config:name="LinkUpdateMode" config:type="short">3</config:config-item>
133 <config:config-item config:name="HasColumnRowHeaders" config:type="boolean">true</config:config-item>
134 <config:config-item config:name="HasSheetTabs" config:type="boolean">true</config:config-item>
135 <config:config-item config:name="IsOutlineSymbolsSet" config:type="boolean">true</config:config-item>
136 <config:config-item config:name="IsSnapToRaster" config:type="boolean">false</config:config-item>
137 <config:config-item config:name="RasterIsVisible" config:type="boolean">false</config:config-item>
138 <config:config-item config:name="IsRasterAxisSynchronized" config:type="boolean">true</config:config-item>
139 <config:config-item config:name="AutoCalculate" config:type="boolean">true</config:config-item>
140 <config:config-item config:name="PrinterName" config:type="string">Generic Printer</config:config-item>
141 <config:config-item config:name="ApplyUserData" config:type="boolean">true</config:config-item>
142 <config:config-item config:name="CharacterCompressionType" config:type="short">0</config:config-item>
143 <config:config-item config:name="SaveVersionOnClose" config:type="boolean">false</config:config-item>
144 <config:config-item config:name="UpdateFromTemplate" config:type="boolean">false</config:config-item>
145 <config:config-item config:name="AllowPrintJobCancel" config:type="boolean">true</config:config-item>
146 <config:config-item config:name="LoadReadonly" config:type="boolean">false</config:config-item>
147 </config:config-item-set>
148 </office:settings></office:document-settings>';
149
150
151 use constant ODS_MANIFEST_STR => '<?xml version="1.0" encoding="UTF-8"?>
152 <manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0">
153  <manifest:file-entry manifest:media-type="application/vnd.oasis.opendocument.spreadsheet" manifest:full-path="/"/>
154  <manifest:file-entry manifest:media-type="" manifest:full-path="Configurations2/statusbar/"/>
155  <manifest:file-entry manifest:media-type="" manifest:full-path="Configurations2/accelerator/"/>
156  <manifest:file-entry manifest:media-type="" manifest:full-path="Configurations2/floater/"/>
157  <manifest:file-entry manifest:media-type="" manifest:full-path="Configurations2/popupmenu/"/>
158  <manifest:file-entry manifest:media-type="" manifest:full-path="Configurations2/progressbar/"/>
159  <manifest:file-entry manifest:media-type="" manifest:full-path="Configurations2/menubar/"/>
160  <manifest:file-entry manifest:media-type="" manifest:full-path="Configurations2/toolbar/"/>
161  <manifest:file-entry manifest:media-type="" manifest:full-path="Configurations2/images/Bitmaps/"/>
162  <manifest:file-entry manifest:media-type="" manifest:full-path="Configurations2/images/"/>
163  <manifest:file-entry manifest:media-type="application/vnd.sun.xml.ui.configuration" manifest:full-path="Configurations2/"/>
164  <manifest:file-entry manifest:media-type="text/xml" manifest:full-path="content.xml"/>
165  <manifest:file-entry manifest:media-type="text/xml" manifest:full-path="styles.xml"/>
166  <manifest:file-entry manifest:media-type="text/xml" manifest:full-path="meta.xml"/>
167  <manifest:file-entry manifest:media-type="" manifest:full-path="Thumbnails/"/>
168  <manifest:file-entry manifest:media-type="text/xml" manifest:full-path="settings.xml"/>
169 </manifest:manifest>';
170
171
172 =head1 NAME
173
174 C4::ImportExportFramework - Import/Export Framework to Excel-xml/ODS Module Functions
175
176 =head1 SYNOPSIS
177
178   use C4::ImportExportFramework;
179
180 =head1 DESCRIPTION
181
182 Module to Import/Export Framework to Excel-xml/ODS on intranet administration - MARC Frameworks section
183
184 Module to Import/Export Framework to Excel-xml/ODS on intranet administration - MARC Frameworks section
185 exporting the tables marc_tag_structure, marc_subfield_structure to excel-xml/ods or viceversa
186
187 Functions for handling import/export.
188
189
190 =head1 SUBROUTINES
191
192
193
194 =head2 ExportFramework
195
196 Export all the information of a Framework to an excel "xml" file or OpenDocument SpreadSheet "ods" file.
197
198 return :
199 succes
200
201 =cut
202
203 sub ExportFramework
204 {
205     my ($frameworkcode, $xmlStrRef, $mode) = @_;
206
207     my $dbh = C4::Context->dbh;
208     if ($dbh) {
209         my $dom;
210         my $root;
211         my $elementSS;
212         if ($mode eq 'ods' || $mode eq 'excel') {
213             eval {
214                 my $parser = XML::LibXML->new();
215                 $dom = $parser->parse_string(($mode && $mode eq 'ods')?ODSSTR:XMLSTR);
216                 if ($dom) {
217                     $root = $dom->documentElement();
218                     if ($mode && $mode eq 'ods') {
219                         my $elementBody = $dom->createElement('office:body');
220                         $root->appendChild($elementBody);
221                         $elementSS = $dom->createElement('office:spreadsheet');
222                         $elementBody->appendChild($elementSS);
223                     }
224                 }
225             };
226             if ($@) {
227                 $debug and warn "Error ExportFramework $@\n";
228                 return 0;
229             }
230         }
231
232         if (_export_table('marc_tag_structure', $dbh, ($mode eq 'csv')?$xmlStrRef:$dom, ($mode eq 'ods')?$elementSS:$root, $frameworkcode, $mode)) {
233             if (_export_table('marc_subfield_structure', $dbh, ($mode eq 'csv')?$xmlStrRef:$dom, ($mode eq 'ods')?$elementSS:$root, $frameworkcode, $mode)) {
234                 $$xmlStrRef = $dom->toString(1) if ($mode eq 'ods' || $mode eq 'excel');
235                 return 1;
236             }
237         }
238     }
239     return 0;
240 }#ExportFramework
241
242
243
244
245 # Export all the data from a mysql table to an spreadsheet.
246 sub _export_table
247 {
248     my ($table, $dbh, $dom, $root, $frameworkcode, $mode) = @_;
249     if ($mode eq 'csv') {
250         _export_table_csv($table, $dbh, $dom, $root, $frameworkcode);
251     } elsif ($mode eq 'ods') {
252         _export_table_ods($table, $dbh, $dom, $root, $frameworkcode);
253     } else {
254         _export_table_excel($table, $dbh, $dom, $root, $frameworkcode);
255     }
256 }
257
258 # Export the mysql table to an csv file
259 sub _export_table_csv
260 {
261     my ($table, $dbh, $strCSV, $root, $frameworkcode) = @_;
262
263     eval {
264         # First row with the name of the columns
265         my $query = 'SHOW COLUMNS FROM ' . $table;
266         my $sth = $dbh->prepare($query);
267         $sth->execute();
268         my @fields = ();
269         while (my $hashRef = $sth->fetchrow_hashref) {
270             $$strCSV .= '"' . $hashRef->{Field} . '",';
271             push @fields, $hashRef->{Field};
272         }
273         chop $$strCSV;
274         $$strCSV .= chr(10);
275         # Populate rows with the data from mysql
276         $query = 'SELECT * FROM ' . $table . ' WHERE frameworkcode=?';
277         $sth = $dbh->prepare($query);
278         $sth->execute($frameworkcode);
279         my $data;
280         while (my $hashRef = $sth->fetchrow_hashref) {
281             for my $field (@fields) {
282                 my $value = $hashRef->{$field} // q||;
283                 $value =~ s/[\r\n]//g;
284                 $$strCSV .= '"' . $value . '",';
285             }
286             chop $$strCSV;
287             $$strCSV .= chr(10);
288         }
289         $$strCSV .= chr(10);
290         for (@fields) {
291             # Separator for change of table
292             $$strCSV .= '"#-#",';
293         }
294         chop $$strCSV;
295         $$strCSV .= chr(10);
296         $$strCSV .= chr(10);
297     };
298     if ($@) {
299         $debug and warn "Error _export_table_csv $@\n";
300         return 0;
301     }
302     return 1;
303 }#_export_table_csv
304
305
306 # Export the mysql table to an ods file
307 sub _export_table_ods
308 {
309     my ($table, $dbh, $dom, $root, $frameworkcode) = @_;
310
311     eval {
312         my $elementTable = $dom->createElement('table:table');
313         $elementTable->setAttribute('table:name', $table);
314         $elementTable->setAttribute('table:print', 'false');
315         $root->appendChild($elementTable);
316         my $elementRow = $dom->createElement('table:table-row');
317         $elementTable->appendChild($elementRow);
318
319         my $elementCell;
320         my $elementData;
321         # First row with the name of the columns
322         my $query = 'SHOW COLUMNS FROM ' . $table;
323         my $sth = $dbh->prepare($query);
324         $sth->execute();
325         my @fields = ();
326         while (my $hashRef = $sth->fetchrow_hashref) {
327             $elementCell = $dom->createElement('table:table-cell');
328             $elementCell->setAttribute('office:value-type', 'string');
329             $elementCell->setAttribute('office:value', $hashRef->{Field});
330             $elementRow->appendChild($elementCell);
331             $elementData = $dom->createElement('text:p');
332             $elementCell->appendChild($elementData);
333             $elementData->appendTextNode($hashRef->{Field});
334             push @fields, {name => $hashRef->{Field}, type => ($hashRef->{Type} =~ /int/i)?'float':'string'};
335         }
336         # Populate rows with the data from mysql
337         $query = 'SELECT * FROM ' . $table . ' WHERE frameworkcode=?';
338         $sth = $dbh->prepare($query);
339         $sth->execute($frameworkcode);
340         my $data;
341         while (my $hashRef = $sth->fetchrow_hashref) {
342             $elementRow = $dom->createElement('table:table-row');
343             $elementTable->appendChild($elementRow);
344             for (@fields) {
345                 $data = $hashRef->{$_->{name}};
346                 if ($_->{type} eq 'float' && !defined($data)) {
347                     $data = '0';
348                 } elsif ($_->{type} eq 'string' && (!$data && $data ne '0')) {
349                     $data = '#';
350                 }
351                 $data = _parseContent2Xml($data) if ($_->{type} eq 'string');
352                 $elementCell = $dom->createElement('table:table-cell');
353                 $elementCell->setAttribute('office:value-type', $_->{type});
354                 $elementCell->setAttribute('office:value', $data);
355                 $elementRow->appendChild($elementCell);
356                 $elementData = $dom->createElement('text:p');
357                 $elementCell->appendChild($elementData);
358                 $elementData->appendTextNode($data);
359             }
360         }
361     };
362     if ($@) {
363         $debug and warn "Error _export_table_ods $@\n";
364         return 0;
365     }
366     return 1;
367 }#_export_table_ods
368
369
370 # Export the mysql table to an excel-xml (openoffice/libreoffice compatible) file
371 sub _export_table_excel
372 {
373     my ($table, $dbh, $dom, $root, $frameworkcode) = @_;
374
375     eval {
376         my $elementWS = $dom->createElement('Worksheet');
377         $elementWS->setAttribute('ss:Name', $table);
378         $root->appendChild($elementWS);
379         my $elementTable = $dom->createElement('ss:Table');
380         $elementWS->appendChild($elementTable);
381         my $elementRow = $dom->createElement('ss:Row');
382         $elementTable->appendChild($elementRow);
383
384         # First row with the name of the columns
385         my $elementCell;
386         my $elementData;
387         my $query = 'SHOW COLUMNS FROM ' . $table;
388         my $sth = $dbh->prepare($query);
389         $sth->execute();
390         my @fields = ();
391         while (my $hashRef = $sth->fetchrow_hashref) {
392             $elementCell = $dom->createElement('ss:Cell');
393             $elementCell->setAttribute('ss:StyleID', 's27');
394             $elementRow->appendChild($elementCell);
395             $elementData = $dom->createElement('ss:Data');
396             $elementData->setAttribute('ss:Type', 'String');
397             $elementCell->appendChild($elementData);
398             $elementData->appendTextNode($hashRef->{Field});
399             push @fields, {name => $hashRef->{Field}, type => ($hashRef->{Type} =~ /int/i)?'Number':'String'};
400         }
401         # Populate rows with the data from mysql
402         $query = 'SELECT * FROM ' . $table . ' WHERE frameworkcode=?';
403         $sth = $dbh->prepare($query);
404         $sth->execute($frameworkcode);
405         my $data;
406         while (my $hashRef = $sth->fetchrow_hashref) {
407             $elementRow = $dom->createElement('ss:Row');
408             $elementTable->appendChild($elementRow);
409             for (@fields) {
410                 $elementCell = $dom->createElement('ss:Cell');
411                 $elementRow->appendChild($elementCell);
412                 $elementData = $dom->createElement('ss:Data');
413                 $elementData->setAttribute('ss:Type', $_->{type});
414                 $elementCell->appendChild($elementData);
415                 $data = $hashRef->{$_->{name}};
416                 if ($_->{type} eq 'Number' && !defined($data)) {
417                     $data = '0';
418                 } elsif ($_->{type} eq 'String' && !defined($data)) {
419                     $data = q{};
420                 } elsif ($_->{type} eq 'String' && (!$data && $data ne '0')) {
421                     $data = '#';
422                 }
423                 $elementData->appendTextNode(($_->{type} eq 'String')?_parseContent2Xml($data):$data);
424             }
425         }
426     };
427     if ($@) {
428         $debug and warn "Error _export_table_excel $@\n";
429         return 0;
430     }
431     return 1;
432 }#_export_table_excel
433
434
435
436
437
438
439
440 # Format chars problematics to a correct format for xml.
441 sub _parseContent2Xml
442 {
443     my $content = shift;
444
445     $content =~ s/\&(?![a-zA-Z#0-9]{1,4};)/&amp;/g;
446     $content =~ s/</&lt;/g;
447     $content =~ s/>/&gt;/g;
448     return $content;
449 }#_parseContent2Xml
450
451
452 # Get the tmp directory on the system
453 sub _getTmp
454 {
455     my $tmp = '/tmp';
456     if ($ENV{'TMP'} && -d $ENV{'TMP'}) {
457         $tmp = $ENV{'TMP'};
458     } elsif ($ENV{'TMPDIR'} && -d $ENV{'TMPDIR'}) {
459         $tmp = $ENV{'TMPDIR'};
460     } elsif ($ENV{'TEMP'} && -d $ENV{'TEMP'}) {
461         $tmp = $ENV{'TEMP'};
462     }
463     return $tmp;
464 }#_getTmp
465
466
467 # Create our tempdir directory for the ods process
468 sub _createTmpDir
469 {
470     my $tmp = shift;
471
472     my $tempdir = (-d $tmp)?$tmp . '/':'./';
473     $tempdir .= 'tmp_ods_' . Digest::MD5::md5_hex(Digest::MD5::md5_hex(time().{}.rand().{}.$$));
474     eval {
475         mkdir $tempdir;
476     };
477     if ($@) {
478         return;
479     } else {
480         return $tempdir;
481     }
482 }#_createTmpDir
483
484 =head2 createODS
485
486 Creates a temporary directory to create the ods file and read it to store its content in a string.
487
488 return :
489 success
490
491 =cut
492
493 sub createODS
494 {
495     my ($strContent, $lang, $strODSRef) = @_;
496
497     my $tmp = _getTmp();
498     my $tempModule = 1;
499     my $tempdir;
500     eval {
501         require File::Temp;
502         import File::Temp qw/ tempfile tempdir /;
503         $tempdir = tempdir ( 'tmp_ods_' . $$ . '_XXXXXXXX', DIR => (-d $tmp)?$tmp:'.', CLEANUP => 1);
504     };
505     if ($@) {
506         $tempModule = 0;
507         $tempdir = _createTmpDir($tmp);
508     }
509     if ($tempdir) {
510         my $fh;
511         # populate tempdir directory with the ods elements
512         eval {
513             if (open($fh, '>',  "$tempdir/content.xml")) {
514                 print {$fh} $strContent;
515                 close($fh);
516             }
517             if (open($fh, '>', "$tempdir/mimetype")) {
518                 print {$fh} 'application/vnd.oasis.opendocument.spreadsheet';
519                 close($fh);
520             }
521             if (open($fh, '>', "$tempdir/meta.xml")) {
522                 print {$fh} _getMeta($lang);
523                 close($fh);
524             }
525             if (open($fh, '>', "$tempdir/styles.xml")) {
526                 print {$fh} ODS_STYLES_STR;
527                 close($fh);
528             }
529             if (open($fh, '>', "$tempdir/settings.xml")) {
530                 print {$fh} ODS_SETTINGS_STR;
531                 close($fh);
532             }
533             mkdir($tempdir.'/META-INF/');
534             mkdir($tempdir.'/Configurations2/');
535             mkdir($tempdir.'/Configurations2/acceleator/');
536             mkdir($tempdir.'/Configurations2/images/');
537             mkdir($tempdir.'/Configurations2/popupmenu/');
538             mkdir($tempdir.'/Configurations2/statusbar/');
539             mkdir($tempdir.'/Configurations2/floater/');
540             mkdir($tempdir.'/Configurations2/menubar/');
541             mkdir($tempdir.'/Configurations2/progressbar/');
542             mkdir($tempdir.'/Configurations2/toolbar/');
543
544             if (open($fh, '>', "$tempdir/META-INF/manifest.xml")) {
545                 print {$fh} ODS_MANIFEST_STR;
546                 close($fh);
547             }
548         };
549         if ($@) {
550             $debug and warn "Error createODS $@\n";
551         } else {
552             # create ods file from tempdir directory
553             eval {
554                 require Archive::Zip;
555                 import Archive::Zip qw( :ERROR_CODES :CONSTANTS );
556                 my $zip = Archive::Zip->new();
557                 $zip->addTree( $tempdir, '' );
558                 $zip->writeToFileNamed($tempdir . '/new.ods');
559             };
560             if ($@) {
561                 my $cmd = qx(which zip 2>/dev/null || whereis zip);
562                 chomp $cmd;
563                 $cmd = 'zip' if (!$cmd || !-x $cmd);
564                 system("cd $tempdir && $cmd -r new.ods ./");
565             }
566             my $ok = 0;
567             # read ods file and return as a string
568             if (-f "$tempdir/new.ods") {
569                 if (open ($fh, '<', "$tempdir/new.ods")) {
570                     binmode $fh;
571                     my $buffer;
572                     while (read ($fh, $buffer, 65536)) {
573                         $$strODSRef .= $buffer;
574                     }
575                     close($fh);
576                     $ok = 1;
577                 }
578             }
579             # delete tempdir directory
580             if (!$tempModule && $tempdir) {
581                 eval {
582                     require File::Path;
583                     import File::Temp qw/ rmtree /;
584                     rmtree($tempdir);
585                 };
586                 if ($@) {
587                     system("rm -rf $tempdir");
588                 }
589             }
590             return 1 if ($ok);
591         }
592     }
593     return 0;
594 }#createODS
595
596
597 # return Meta content for ods file
598 sub _getMeta
599 {
600     my $lang = shift;
601
602     my $myDate = strftime ("%Y-%m-%dT%H:%M:%S", localtime(time()));
603     my $meta = '<?xml version="1.0" encoding="UTF-8"?>
604     <office:document-meta xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:ooo="http://openoffice.org/2004/office" office:version="1.0">
605         <office:meta>
606             <meta:generator>ods-php</meta:generator>
607             <meta:creation-date>' . $myDate . '</meta:creation-date>
608             <dc:date>' . $myDate . '</dc:date>
609             <dc:language>' . $lang . '</dc:language>
610             <meta:editing-cycles>2</meta:editing-cycles>
611             <meta:editing-duration>PT15S</meta:editing-duration>
612             <meta:user-defined meta:name="Info 1"/>
613             <meta:user-defined meta:name="Info 2"/>
614             <meta:user-defined meta:name="Info 3"/>
615             <meta:user-defined meta:name="Info 4"/>
616         </office:meta>
617     </office:document-meta>';
618     return $meta;
619 }#_getMeta
620
621
622 =head2 ImportFramework
623
624 Import all the information of a Framework from a excel-xml/ods file.
625
626 return :
627 success
628
629 =cut
630
631 sub ImportFramework
632 {
633     my ($filename, $frameworkcode, $deleteFilename) = @_;
634
635     my $tempdir;
636     my $ok = -1;
637     my $dbh = C4::Context->dbh;
638     if (-r $filename && $dbh) {
639         my $extension = '';
640         if ($filename =~ /\.(csv|ods|xml)$/i) {
641             $extension = lc($1);
642         } else {
643             unlink ($filename) if ($deleteFilename); # remove temporary file
644             return -1;
645         }
646         if ($extension eq 'ods') {
647             ($tempdir, $filename) = _openODS($filename, $deleteFilename);
648         }
649         if ($filename) {
650             my $dom;
651             eval {
652                 if ($extension eq 'ods' || $extension eq 'xml') {
653                     # They have xml structure, so read it on a dom object
654                     my $parser = XML::LibXML->new();
655                     $dom = $parser->parse_file($filename);
656                     if ($dom) {
657                         my $root = $dom->documentElement();
658                     }
659                 } else {
660                     # They are text files, so open it to read
661                     open($dom, '<', $filename);
662                 }
663                 if ($dom) {
664                     # Process both tables
665                     my $numDeleted = 0;
666                     my $numDeletedAux = 0;
667                     if (($numDeletedAux = _import_table($dbh, 'marc_tag_structure', $frameworkcode, $dom, ['frameworkcode', 'tagfield'], $extension)) >= 0) {
668                         $numDeleted += $numDeletedAux if ($numDeletedAux > 0);
669                         if (($numDeletedAux = _import_table($dbh, 'marc_subfield_structure', $frameworkcode, $dom, ['frameworkcode', 'tagfield', 'tagsubfield'], $extension)) >= 0) {
670                             $numDeleted += $numDeletedAux if ($numDeletedAux > 0);
671                             $ok = ($numDeleted > 0)?$numDeleted:0;
672                         }
673                     }
674                 } else {
675                     $debug and warn "Error ImportFramework couldn't create dom\n";
676                 }
677             };
678             if ($@) {
679                 $debug and warn "Error ImportFramework $@\n";
680             } else {
681                 if ($extension eq 'csv') {
682                     close($dom) if ($dom);
683                 }
684             }
685         }
686         unlink ($filename) if ($deleteFilename); # remove temporary file
687     } else {
688         $debug and warn "Error ImportFramework no conex to database or not readeable $filename\n";
689     }
690     if ($deleteFilename && $tempdir && -d $tempdir && -w $tempdir) {
691         eval {
692             require File::Path;
693             import File::Temp qw/ rmtree /;
694             rmtree($tempdir);
695         };
696         if ($@) {
697             system("rm -rf $tempdir");
698         }
699     }
700     return $ok;
701 }#ImportFramework
702
703 # Open (uncompress) ods file and return the content.xml file
704 sub _openODS
705 {
706     my ($filename, $deleteFilename) = @_;
707
708     my $tmp = _getTmp();
709     my $tempModule = 1;
710     my $tempdir;
711     eval {
712         require File::Temp;
713         import File::Temp qw/ tempfile tempdir /;
714         $tempdir = tempdir ( 'tmp_ods_' . $$ . '_XXXXXXXX', DIR => (-d $tmp)?$tmp:'.', CLEANUP => 1);
715     };
716     if ($@) {
717         $tempModule = 0;
718         $tempdir = _createTmpDir($tmp);
719     }
720     if ($tempdir) {
721         eval {
722             require Archive::Zip;
723             import Archive::Zip qw( :ERROR_CODES :CONSTANTS );
724             my $zip = Archive::Zip->new($filename);
725             foreach my $file ($zip->members) {
726                 next if ($file->isDirectory);
727                 (my $extractName = $file->fileName) =~ s{.*/}{};
728                 next unless ($extractName eq 'content.xml');
729                 $file->extractToFileNamed("$tempdir/$extractName");
730             }
731         };
732         if ($@) {
733             my $cmd = qx(which unzip 2>/dev/null || whereis unzip);
734             chomp $cmd;
735             $cmd = 'unzip' if (!$cmd || !-x $cmd);
736             system("$cmd $filename -d $tempdir");
737         }
738         if (-f "$tempdir/content.xml") {
739             unlink ($filename) if ($deleteFilename);
740             return ($tempdir, "$tempdir/content.xml");
741         }
742     }
743     unlink ($filename) if ($deleteFilename);
744     return ($tempdir, undef);
745 }#_openODS
746
747
748
749 # Check the table and columns corresponds with worksheet
750 sub _check_validity_worksheet
751 {
752     my ($dbh, $table, $nodeFields, $fieldsA, $format) = @_;
753
754     my $ret = 0;
755     eval {
756         my $query = 'DESCRIBE ' . $table;
757         my $sth = $dbh->prepare($query);
758         $sth->execute();
759         $sth->finish;
760         $query = 'SHOW COLUMNS FROM ' . $table;
761         $sth = $dbh->prepare($query);
762         $sth->execute();
763         my $fields = {};
764         while (my $hashRef = $sth->fetchrow_hashref) {
765             $fields->{$hashRef->{Field}} = $hashRef->{Field};
766         }
767         my @fields;
768         my $fieldsR;
769         if ($fieldsA) {
770             $fieldsR = $fieldsA;
771         } else {
772             $fieldsR = \@fields;
773             _getFields($nodeFields, $fieldsR, $format);
774         }
775         $ret = 1;
776         for (@$fieldsR) {
777             unless (exists($fields->{$_})) {
778                 $ret = 0;
779                 last;
780             }
781         }
782     };
783     return $ret;
784 }#_check_validity_worksheet
785
786
787 # Import the data from an excel-xml/ods to mysql tables.
788 sub _import_table
789 {
790     my ($dbh, $table, $frameworkcode, $dom, $PKArray, $format) = @_;
791     my %fields2Delete;
792     my $query;
793     my @fields;
794     # Create hash with all elements defined by primary key to know which ones to delete after parsing the spreadsheet
795     eval {
796         @fields = @$PKArray;
797         shift @fields;
798         $query = 'SELECT ' . join(',', @fields) . ' FROM ' . $table . ' WHERE frameworkcode=?';
799         my $sth = $dbh->prepare($query);
800         $sth->execute($frameworkcode);
801         my $field;
802         while (my $hashRef = $sth->fetchrow_hashref) {
803             $field = '';
804             map { $field .= $hashRef->{$_} . '_'; } @fields;
805             chop $field;
806             $fields2Delete{$field} = 1;
807         }
808         $sth->finish;
809     };
810     my $ok = 0;
811     if ($format eq 'csv') {
812         my @fieldsName = ();
813         eval {
814             my $query = 'SHOW COLUMNS FROM ' . $table;
815             my $sth = $dbh->prepare($query);
816             $sth->execute();
817             while (my $hashRef = $sth->fetchrow_hashref) {
818                 push @fieldsName, $hashRef->{Field};
819             }
820         };
821         $ok = _import_table_csv($dbh, $table, $frameworkcode, $dom, $PKArray, \%fields2Delete, \@fieldsName);
822     } elsif ($format eq 'ods') {
823         $ok = _import_table_ods($dbh, $table, $frameworkcode, $dom, $PKArray, \%fields2Delete);
824     } else {
825         $ok = _import_table_excel($dbh, $table, $frameworkcode, $dom, $PKArray, \%fields2Delete);
826     }
827     if ($ok) {
828         if (($ok = scalar(keys %fields2Delete)) > 0) {
829             $query = 'DELETE FROM ' . $table . ' WHERE ';
830             map {$query .= $_ . '=? AND ';} @$PKArray;
831             $query = substr($query, 0, -4);
832             my $sth = $dbh->prepare($query);
833             for (keys %fields2Delete) {
834                 eval {
835                     $sth->execute(($frameworkcode, split('_', $_)));
836                 };
837             }
838         }
839     } else {
840         $ok = -1;
841     }
842     return $ok;
843 }#_import_table
844
845
846 # Insert/Update the row from the spreadsheet in the database
847 sub _processRow_DB
848 {
849     my ($dbh, $db_scheme, $table, $fields, $dataStr, $updateStr, $dataFields, $dataFieldsHash, $PKArray, $fieldsPK, $fields2Delete) = @_;
850
851     my $ok = 0;
852     my $query;
853     if ($db_scheme eq 'mysql') {
854         $query = 'INSERT INTO ' . $table . ' (' . $fields . ') VALUES (' . $dataStr . ') ON DUPLICATE KEY UPDATE ' . $updateStr;
855     } else {
856         $query = 'INSERT INTO ' . $table . ' (' . $fields . ') VALUES (' . $dataStr . ')';
857     }
858     eval {
859         my $sth = $dbh->prepare($query);
860         if ($db_scheme eq 'mysql') {
861             $sth->execute((@$dataFields, @$dataFields));
862         } else {
863             $sth->execute(@$dataFields);
864         }
865     };
866     if ($@) {
867         unless ($db_scheme eq 'mysql') {
868             $query = 'UPDATE ' . $table . ' SET ' . $updateStr . ' WHERE ';
869             map {$query .= $_ . '=? AND ';} @$PKArray;
870             $query = substr($query, 0, -4);
871             eval {
872                 my $sth2 = $dbh->prepare($query);
873                 my @dataPK = ();
874                 map {push @dataPK, $dataFieldsHash->{$_};} @$PKArray;
875                 $sth2->execute((@$dataFields, @dataPK));
876             };
877             $ok = 1 unless ($@);
878         }
879         $debug and warn "Error _processRows_Table $@\n";
880     } else {
881         $ok = 1;
882     }
883     if ($ok) {
884         my $field = '';
885         map { $field .= $dataFieldsHash->{$_} . '_'; } @$fieldsPK;
886         chop $field;
887         delete $fields2Delete->{$field} if (exists($fields2Delete->{$field}));
888     }
889     return $ok;
890 }#_processRow_DB
891
892
893 # Process the rows of a worksheet and insert/update them in a mysql table.
894 sub _processRows_Table
895 {
896     my ($dbh, $frameworkcode, $nodeR, $table, $PKArray, $format, $fields2Delete) = @_;
897
898     my $query;
899     my @fields = ();
900     my $fields = '';
901     my $dataStr = '';
902     my $updateStr = '';
903     my $j = 0;
904     my $db_scheme = C4::Context->config("db_scheme");
905     my $ok = 0;
906     my @fieldsPK = @$PKArray;
907     shift @fieldsPK;
908     while ($nodeR) {
909         if ($nodeR->nodeType == 1 && (($format && $format eq 'ods' && $nodeR->nodeName =~ /(?:table:)?table-row/) || ($nodeR->nodeName =~ /(?:ss:)?Row/)) && $nodeR->hasChildNodes()) {
910             if ($j == 0) {
911                 # Get name columns
912                 _getFields($nodeR, \@fields, $format);
913                 return 0 unless _check_validity_worksheet($dbh, $table, $nodeR, \@fields, $format);
914                 $fields = join(',', @fields);
915                 $dataStr = '';
916                 map { $dataStr .= '?,';} @fields;
917                 chop($dataStr) if ($dataStr);
918                 $updateStr = '';
919                 map { $updateStr .= $_ . '=?,';} @fields;
920                 chop($updateStr) if ($updateStr);
921             } else {
922                 # Get data from row
923                 my ($dataFields, $dataFieldsR) = _getDataFields($frameworkcode, $nodeR, \@fields, $format);
924                 if (scalar(@fields) == scalar(@$dataFieldsR)) {
925                     $ok = _processRow_DB($dbh, $db_scheme, $table, $fields, $dataStr, $updateStr, $dataFieldsR, $dataFields, $PKArray, \@fieldsPK, $fields2Delete);
926                 }
927             }
928             $j++;
929         }
930         $nodeR = $nodeR->nextSibling;
931     }
932     return 1;
933 }#_processRows_Table
934
935
936
937
938 # Import worksheet from the csv file to the mysql table
939 sub _import_table_csv
940 {
941     my ($dbh, $table, $frameworkcode, $dom, $PKArray, $fields2Delete, $fields) = @_;
942
943     my $row = '';
944     my $partialRow = '';
945     my $numFields = @$fields;
946     my $fieldsNameRead = 0;
947     my @arrData;
948     my ($fieldsStr, $dataStr, $updateStr);
949     my $db_scheme = C4::Context->config("db_scheme");
950     my @fieldsPK = @$PKArray;
951     shift @fieldsPK;
952     my $ok = 0;
953     my $numRow = 0;
954     my $pos = 0;
955     while (<$dom>) {
956         $row = $_;
957         # Check whether the line has an unfinished field, i.e., a field with CR/LF in its data
958         if ($row =~ /,"[^"]*[\r\n]+$/ || $row =~ /^[^"]+[\r\n]+$/) {
959             $row =~ s/[\r\n]+$//;
960             $partialRow .= $row;
961             next;
962         }
963         if ($partialRow) {
964             $row = $partialRow . $row;
965             $partialRow = '';
966         }
967         # Line OK, process it
968         if ($row =~ /(?:".*?",?)+/) {
969             @arrData = split('","', $row);
970             $arrData[0] = substr($arrData[0], 1) if ($arrData[0] =~ /^"/);
971             $arrData[$#arrData] =~ s/[\r\n]+$//;
972             chop $arrData[$#arrData] if ($arrData[$#arrData] =~ /"$/);
973             if (@arrData) {
974                 if ($arrData[0] eq '#-#' && $arrData[$#arrData] eq '#-#') {
975                     # Change of table with separators #-#
976                     return 1;
977                 } elsif ($fieldsNameRead && $arrData[0] eq 'tagfield') {
978                     # Change of table because we begin with field name with former field names read
979                     seek($dom, $pos, 0);
980                     return 1;
981                 }
982                 if (!$fieldsNameRead) {
983                     # New table, we read the field names
984                     $fieldsNameRead = 1;
985                     $fields = [@arrData];
986                     $fieldsStr = join(',', @$fields);
987                     $dataStr = '';
988                     map { $dataStr .= '?,';} @$fields;
989                     chop($dataStr) if ($dataStr);
990                     $updateStr = '';
991                     map { $updateStr .= $_ . '=?,';} @$fields;
992                     chop($updateStr) if ($updateStr);
993                 } else {
994                     # Read data
995                     my $j = 0;
996                     my %dataFields = ();
997                     for (@arrData) {
998                         if ($fields->[$j] eq 'frameworkcode' && $_ ne $frameworkcode) {
999                             $dataFields{$fields->[$j]} = $frameworkcode;
1000                             $arrData[$j] = $frameworkcode;
1001                         } else {
1002                             $dataFields{$fields->[$j]} = $_;
1003                         }
1004                         $j++
1005                     }
1006                     $ok = _processRow_DB($dbh, $db_scheme, $table, $fieldsStr, $dataStr, $updateStr, \@arrData, \%dataFields, $PKArray, \@fieldsPK, $fields2Delete);
1007                 }
1008                 $pos = tell($dom);
1009             }
1010             @arrData = ();
1011         }
1012         $numRow++;
1013     }
1014     return $ok;
1015 }#_import_table_csv
1016
1017
1018 # Import worksheet from the ods content.xml file to the mysql table
1019 sub _import_table_ods
1020 {
1021     my ($dbh, $table, $frameworkcode, $dom, $PKArray, $fields2Delete) = @_;
1022
1023     my $xc = XML::LibXML::XPathContext->new($dom);
1024     $xc->registerNs('xmlns:office','urn:oasis:names:tc:opendocument:xmlns:office:1.0');
1025     $xc->registerNs('xmlns:table','urn:oasis:names:tc:opendocument:xmlns:table:1.0');
1026     $xc->registerNs('xmlns:text','urn:oasis:names:tc:opendocument:xmlns:text:1.0');
1027     my @nodes;
1028     @nodes = $xc->findnodes('//table:table[@table:name="' . $table . '"]');
1029     if (@nodes == 1 && $nodes[0]->hasChildNodes()) {
1030         my $nodeR = $nodes[0]->firstChild;
1031         return _processRows_Table($dbh, $frameworkcode, $nodeR, $table, $PKArray, 'ods', $fields2Delete);
1032     } else {
1033         $debug and warn "Error _import_table_ods there's not worksheet for $table\n";
1034     }
1035     return 0;
1036 }#_import_table_ods
1037
1038
1039 # Import worksheet from the excel-xml file to the mysql table
1040 sub _import_table_excel
1041 {
1042     my ($dbh, $table, $frameworkcode, $dom, $PKArray, $fields2Delete) = @_;
1043
1044     my $xc = XML::LibXML::XPathContext->new($dom);
1045     $xc->registerNs('xmlns','urn:schemas-microsoft-com:office:spreadsheet');
1046     $xc->registerNs('xmlns:ss','urn:schemas-microsoft-com:office:spreadsheet');
1047     $xc->registerNs('xmlns:x','urn:schemas-microsoft-com:office:excel');
1048     my @nodes;
1049     @nodes = $xc->findnodes('//ss:Worksheet[@ss:Name="' . $table . '"]');
1050     if (@nodes > 0) {
1051         for (my $i=0; $i < @nodes; $i++) {
1052             my @nodesT = $nodes[$i]->getElementsByTagNameNS('urn:schemas-microsoft-com:office:spreadsheet', 'Table');
1053             if (@nodesT == 1 && $nodesT[0]->hasChildNodes()) {
1054                 my $nodeR = $nodesT[0]->firstChild;
1055                 return _processRows_Table($dbh, $frameworkcode, $nodeR, $table, $PKArray, undef, $fields2Delete);
1056             }
1057         }
1058     } else {
1059         $debug and warn "Error _import_table_excel there's not worksheet for $table\n";
1060     }
1061     return 0;
1062 }#_import_table_excel
1063
1064
1065 # Get the data from a cell on a ods file through the value attribute or the text node
1066 sub _getDataNodeODS
1067 {
1068     my $node = shift;
1069
1070     my $data;
1071     my $repeated = 0;
1072     if ($node->nodeType == 1 && $node->nodeName =~ /(?:table:)?table-cell/) {
1073         if ($node->hasAttributeNS('urn:oasis:names:tc:opendocument:xmlns:office:1.0', 'value')) {
1074             $data = $node->getAttributeNS('urn:oasis:names:tc:opendocument:xmlns:office:1.0', 'value');
1075         } elsif ($node->hasChildNodes()) {
1076             my @nodes2 = $node->getElementsByTagNameNS('urn:oasis:names:tc:opendocument:xmlns:text:1.0', 'p');
1077             if (@nodes2 == 1 && $nodes2[0]->hasChildNodes()) {
1078                 $data = $nodes2[0]->firstChild->nodeValue;
1079             }
1080         }
1081         if ($node->hasAttributeNS('urn:oasis:names:tc:opendocument:xmlns:table:1.0', 'number-columns-repeated')) {
1082             $repeated = $node->getAttributeNS('urn:oasis:names:tc:opendocument:xmlns:table:1.0', 'number-columns-repeated');
1083         }
1084     }
1085     return ($data, $repeated);
1086 }#_getDataNodeODS
1087
1088
1089 # Get the data from a row of a spreadsheet
1090 sub _getDataFields
1091 {
1092     my ($frameworkcode, $node, $fields, $format) = @_;
1093
1094     my $dataFields = {};
1095     my @dataFieldsA = ();
1096     if ($node && $node->hasChildNodes()) {
1097         my $node2 = $node->firstChild;
1098         my ($data, $repeated);
1099         my $i = 0;
1100         my $ok = 0;
1101         $repeated = 0;
1102         while ($node2) {
1103             if ($format && $format eq 'ods') {
1104                 ($data, $repeated) = _getDataNodeODS($node2) if ($repeated <= 0);
1105                 $repeated--;
1106                 $ok = 1 if (defined($data));
1107             } else {
1108                 if ($node2->nodeType == 1 && $node2->nodeName  =~ /(?:ss:)?Cell/) {
1109                     my @nodes3 = $node2->getElementsByTagNameNS('urn:schemas-microsoft-com:office:spreadsheet', 'Data');
1110                     if (@nodes3 == 1 && $nodes3[0]->hasChildNodes()) {
1111                         $data = $nodes3[0]->firstChild->nodeValue;
1112                         $ok = 1;
1113                     }
1114                 }
1115             }
1116             if ($ok) {
1117                 $data = '' if ($data eq '#');
1118                 $data = $frameworkcode if ($fields->[$i] eq 'frameworkcode');
1119                 $dataFields->{$fields->[$i]} = $data;
1120                 push @dataFieldsA, $data;
1121                 $i++;
1122             }
1123             $ok = 0;
1124             $node2 = $node2->nextSibling if ($repeated <= 0);
1125         }
1126     }
1127     return ($dataFields, \@dataFieldsA);
1128 }#_getDataFields
1129
1130
1131 # Get the data from the first row to know the column names
1132 sub _getFields
1133 {
1134     my ($node, $fields, $format) = @_;
1135
1136     if ($node && $node->hasChildNodes()) {
1137         my $node2 = $node->firstChild;
1138         my ($data, $repeated);
1139         while ($node2) {
1140             if ($format && $format eq 'ods') {
1141                 ($data, $repeated) = _getDataNodeODS($node2);
1142                 push @$fields, $data if (defined($data));
1143             } else {
1144                 if ($node2->nodeType == 1 && $node2->nodeName =~ /(?:ss:)?Cell/) {
1145                     my @nodes3 = $node2->getElementsByTagNameNS('urn:schemas-microsoft-com:office:spreadsheet', 'Data');
1146                     if (@nodes3 == 1 && $nodes3[0]->hasChildNodes()) {
1147                         $data = $nodes3[0]->firstChild->nodeValue;
1148                         push @$fields, $data;
1149                     }
1150                 }
1151             }
1152             $node2 = $node2->nextSibling;
1153         }
1154     }
1155 }#_getFields
1156
1157
1158
1159
1160 1;
1161 __END__
1162
1163 =head1 AUTHOR
1164
1165 Koha Development Team <http://koha-community.org/>
1166
1167 =cut
1168
1169