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