1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2011, 2012, 2013, 2016 Free Software Foundation, Inc.
3 
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8 
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13 
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16 
17 #include <config.h>
18 
19 #include "ods-reader.h"
20 #include "spreadsheet-reader.h"
21 
22 #include <assert.h>
23 #include <stdbool.h>
24 #include <errno.h>
25 #include <libxml/xmlreader.h>
26 #include <zlib.h>
27 
28 #include "data/case.h"
29 #include "data/casereader-provider.h"
30 #include "data/data-in.h"
31 #include "data/dictionary.h"
32 #include "data/format.h"
33 #include "data/identifier.h"
34 #include "data/value.h"
35 #include "data/variable.h"
36 #include "libpspp/assertion.h"
37 #include "libpspp/i18n.h"
38 #include "libpspp/message.h"
39 #include "libpspp/misc.h"
40 #include "libpspp/str.h"
41 #include "libpspp/zip-reader.h"
42 
43 #include "gl/c-strtod.h"
44 #include "gl/minmax.h"
45 #include "gl/xalloc.h"
46 
47 #include "gettext.h"
48 #define _(msgid) gettext (msgid)
49 #define N_(msgid) (msgid)
50 
51 static void ods_file_casereader_destroy (struct casereader *, void *);
52 static struct ccase *ods_file_casereader_read (struct casereader *, void *);
53 
54 
55 static const struct casereader_class ods_file_casereader_class =
56   {
57     ods_file_casereader_read,
58     ods_file_casereader_destroy,
59     NULL,
60     NULL,
61   };
62 
63 struct sheet_detail
64 {
65   /* The name of the sheet (utf8 encoding) */
66   char *name;
67 
68   int start_col;
69   int stop_col;
70   int start_row;
71   int stop_row;
72 };
73 
74 
75 enum reader_state
76   {
77     STATE_INIT = 0,        /* Initial state */
78     STATE_SPREADSHEET,     /* Found the start of the spreadsheet doc */
79     STATE_TABLE,           /* Found the sheet that we actually want */
80     STATE_ROW,             /* Found the start of the cell array */
81     STATE_CELL,            /* Found a cell */
82     STATE_CELL_CONTENT     /* Found a the text within a cell */
83   };
84 
85 struct state_data
86 {
87   xmlTextReaderPtr xtr;
88   struct zip_member *zm;
89   int node_type;
90   enum reader_state state;
91   int row;
92   int col;
93   int current_sheet;
94   xmlChar *current_sheet_name;
95 
96   int col_span;
97 };
98 
99 static void
state_data_destroy(struct state_data * sd)100 state_data_destroy (struct state_data *sd)
101 {
102   xmlFree (sd->current_sheet_name);
103   sd->current_sheet_name = NULL;
104 
105   xmlFreeTextReader (sd->xtr);
106   sd->xtr = NULL;
107 
108   zip_member_finish (sd->zm);
109   sd->zm = NULL;
110 }
111 
112 struct ods_reader
113 {
114   struct spreadsheet spreadsheet;
115   struct zip_reader *zreader;
116 
117   int target_sheet_index;
118   xmlChar *target_sheet_name;
119 
120   /* State data for the meta data */
121   struct state_data msd;
122 
123   /* State data for the reader */
124   struct state_data rsd;
125 
126   int start_row;
127   int start_col;
128   int stop_row;
129   int stop_col;
130 
131   struct sheet_detail *sheets;
132   int n_allocated_sheets;
133 
134   struct caseproto *proto;
135   struct dictionary *dict;
136   struct ccase *first_case;
137   bool used_first_case;
138   bool read_names;
139 
140   struct string ods_errs;
141 
142   struct string zip_errs;
143 };
144 
145 void
ods_unref(struct spreadsheet * s)146 ods_unref (struct spreadsheet *s)
147 {
148   struct ods_reader *r = (struct ods_reader *) s;
149 
150   if (--s->ref_cnt == 0)
151     {
152       int i;
153 
154       state_data_destroy (&r->msd);
155       for (i = 0; i < r->n_allocated_sheets; ++i)
156 	{
157 	  xmlFree (r->sheets[i].name);
158 	}
159 
160       dict_unref (r->dict);
161 
162       zip_reader_destroy (r->zreader);
163       free (r->sheets);
164       free (s->file_name);
165       free (r);
166     }
167 }
168 
169 
170 
171 static bool
reading_target_sheet(const struct ods_reader * r,const struct state_data * msd)172 reading_target_sheet (const struct ods_reader *r, const struct state_data *msd)
173 {
174   if (r->target_sheet_name != NULL)
175     {
176       if (0 == xmlStrcmp (r->target_sheet_name, msd->current_sheet_name))
177 	return true;
178     }
179 
180   if (r->target_sheet_index == msd->current_sheet + 1)
181     return true;
182 
183   return false;
184 }
185 
186 
187 static void process_node (struct ods_reader *or, struct state_data *r);
188 
189 
190 const char *
ods_get_sheet_name(struct spreadsheet * s,int n)191 ods_get_sheet_name (struct spreadsheet *s, int n)
192 {
193   struct ods_reader *r = (struct ods_reader *) s;
194   struct state_data *or = &r->msd;
195 
196   assert (n < s->n_sheets);
197 
198   while (
199 	  (r->n_allocated_sheets <= n)
200 	  || or->state != STATE_SPREADSHEET
201 	)
202     {
203       int ret = xmlTextReaderRead (or->xtr);
204       if (ret != 1)
205 	break;
206 
207       process_node (r, or);
208     }
209 
210   return r->sheets[n].name;
211 }
212 
213 char *
ods_get_sheet_range(struct spreadsheet * s,int n)214 ods_get_sheet_range (struct spreadsheet *s, int n)
215 {
216   struct ods_reader *r = (struct ods_reader *) s;
217   struct state_data *or = &r->msd;
218 
219   assert (n < s->n_sheets);
220 
221   while (
222 	  (r->n_allocated_sheets <= n)
223 	  || (r->sheets[n].stop_row == -1)
224 	  || or->state != STATE_SPREADSHEET
225 	)
226     {
227       int ret = xmlTextReaderRead (or->xtr);
228       if (ret != 1)
229 	break;
230 
231       process_node (r, or);
232     }
233 
234   return create_cell_range (
235 			  r->sheets[n].start_col,
236 			  r->sheets[n].start_row,
237 			  r->sheets[n].stop_col,
238 			  r->sheets[n].stop_row);
239 }
240 
241 
242 static void
ods_file_casereader_destroy(struct casereader * reader UNUSED,void * r_)243 ods_file_casereader_destroy (struct casereader *reader UNUSED, void *r_)
244 {
245   struct ods_reader *r = r_;
246   if (r == NULL)
247     return ;
248 
249   state_data_destroy (&r->rsd);
250 
251   if (! ds_is_empty (&r->ods_errs))
252     msg (ME, "%s", ds_cstr (&r->ods_errs));
253 
254   ds_destroy (&r->ods_errs);
255 
256   if (r->first_case && ! r->used_first_case)
257     case_unref (r->first_case);
258 
259 
260   caseproto_unref (r->proto);
261   r->proto = NULL;
262 
263   xmlFree (r->target_sheet_name);
264   r->target_sheet_name = NULL;
265 
266 
267   ods_unref (&r->spreadsheet);
268 }
269 
270 
271 
272 
273 
274 static void
process_node(struct ods_reader * or,struct state_data * r)275 process_node (struct ods_reader *or, struct state_data *r)
276 {
277   xmlChar *name = xmlTextReaderName (r->xtr);
278   if (name == NULL)
279     name = xmlStrdup (_xml ("--"));
280 
281 
282   r->node_type = xmlTextReaderNodeType (r->xtr);
283 
284   switch (r->state)
285     {
286     case STATE_INIT:
287       if (0 == xmlStrcasecmp (name, _xml("office:spreadsheet")) &&
288 	  XML_READER_TYPE_ELEMENT  == r->node_type)
289 	{
290 	  r->state = STATE_SPREADSHEET;
291 	  r->current_sheet = -1;
292 	  r->current_sheet_name = NULL;
293 	}
294       break;
295     case STATE_SPREADSHEET:
296       if (0 == xmlStrcasecmp (name, _xml("table:table"))
297 	  &&
298 	  (XML_READER_TYPE_ELEMENT == r->node_type))
299 	{
300 	  xmlFree (r->current_sheet_name);
301 	  r->current_sheet_name = xmlTextReaderGetAttribute (r->xtr, _xml ("table:name"));
302 
303 	  ++r->current_sheet;
304 
305 	  if (r->current_sheet >= or->n_allocated_sheets)
306 	    {
307 	      assert (r->current_sheet == or->n_allocated_sheets);
308 	      or->sheets = xrealloc (or->sheets, sizeof (*or->sheets) * ++or->n_allocated_sheets);
309 	      or->sheets[or->n_allocated_sheets - 1].start_col = -1;
310 	      or->sheets[or->n_allocated_sheets - 1].stop_col = -1;
311 	      or->sheets[or->n_allocated_sheets - 1].start_row = -1;
312 	      or->sheets[or->n_allocated_sheets - 1].stop_row = -1;
313 	      or->sheets[or->n_allocated_sheets - 1].name = CHAR_CAST (char *, xmlStrdup (r->current_sheet_name));
314 	    }
315 
316 	  r->col = 0;
317 	  r->row = 0;
318 
319 	  r->state = STATE_TABLE;
320 	}
321       else if (0 == xmlStrcasecmp (name, _xml("office:spreadsheet")) &&
322 	       XML_READER_TYPE_ELEMENT  == r->node_type)
323 	{
324 	  r->state = STATE_INIT;
325 	}
326       break;
327     case STATE_TABLE:
328       if (0 == xmlStrcasecmp (name, _xml("table:table-row")) &&
329 	  (XML_READER_TYPE_ELEMENT  == r->node_type))
330 	{
331 	  xmlChar *value =
332 	    xmlTextReaderGetAttribute (r->xtr,
333 				       _xml ("table:number-rows-repeated"));
334 
335 	  int row_span = value ? _xmlchar_to_int (value) : 1;
336 
337 	  r->row += row_span;
338 	  r->col = 0;
339 
340 	  if (! xmlTextReaderIsEmptyElement (r->xtr))
341 	    r->state = STATE_ROW;
342 
343 	  xmlFree (value);
344 	}
345       else if (0 == xmlStrcasecmp (name, _xml("table:table")) &&
346 	       (XML_READER_TYPE_END_ELEMENT  == r->node_type))
347 	{
348 	  r->state = STATE_SPREADSHEET;
349 	}
350       break;
351     case STATE_ROW:
352       if ((0 == xmlStrcasecmp (name, _xml ("table:table-cell")))
353 	   &&
354 	   (XML_READER_TYPE_ELEMENT  == r->node_type))
355 	{
356 	  xmlChar *value =
357 	    xmlTextReaderGetAttribute (r->xtr,
358 				       _xml ("table:number-columns-repeated"));
359 
360 	  r->col_span = value ? _xmlchar_to_int (value) : 1;
361 	  r->col += r->col_span;
362 
363 	  if (! xmlTextReaderIsEmptyElement (r->xtr))
364 	    r->state = STATE_CELL;
365 
366 	  xmlFree (value);
367 	}
368       else if ((0 == xmlStrcasecmp (name, _xml ("table:table-row")))
369 		&&
370 		(XML_READER_TYPE_END_ELEMENT  == r->node_type))
371 	{
372 	  r->state = STATE_TABLE;
373 	}
374       break;
375     case STATE_CELL:
376       if ((0 == xmlStrcasecmp (name, _xml("text:p")))
377 	    &&
378 	   (XML_READER_TYPE_ELEMENT  == r->node_type))
379 	{
380 	  if (! xmlTextReaderIsEmptyElement (r->xtr))
381 	    r->state = STATE_CELL_CONTENT;
382 	}
383       else if
384 	((0 == xmlStrcasecmp (name, _xml("table:table-cell")))
385 	  &&
386 	  (XML_READER_TYPE_END_ELEMENT  == r->node_type)
387 	)
388 	{
389 	  r->state = STATE_ROW;
390 	}
391       break;
392     case STATE_CELL_CONTENT:
393       assert (r->current_sheet >= 0);
394       assert (r->current_sheet < or->n_allocated_sheets);
395 
396       if (or->sheets[r->current_sheet].start_row == -1)
397 	or->sheets[r->current_sheet].start_row = r->row - 1;
398 
399       if (
400 	  (or->sheets[r->current_sheet].start_col == -1)
401 	  ||
402 	  (or->sheets[r->current_sheet].start_col >= r->col - 1)
403 	)
404 	or->sheets[r->current_sheet].start_col = r->col - 1;
405 
406       or->sheets[r->current_sheet].stop_row = r->row - 1;
407 
408       if (or->sheets[r->current_sheet].stop_col < r->col - 1)
409 	or->sheets[r->current_sheet].stop_col = r->col - 1;
410 
411       if (XML_READER_TYPE_END_ELEMENT  == r->node_type)
412 	r->state = STATE_CELL;
413       break;
414     default:
415       NOT_REACHED ();
416       break;
417     };
418 
419   xmlFree (name);
420 }
421 
422 /*
423    A struct containing the parameters of a cell's value
424    parsed from the xml
425 */
426 struct xml_value
427 {
428   xmlChar *type;
429   xmlChar *value;
430   xmlChar *text;
431 };
432 
433 struct var_spec
434 {
435   char *name;
436   struct xml_value firstval;
437 };
438 
439 
440 /* Determine the width that a xmv should probably have */
441 static int
xmv_to_width(const struct xml_value * xmv,int fallback)442 xmv_to_width (const struct xml_value *xmv, int fallback)
443 {
444   int width = SPREADSHEET_DEFAULT_WIDTH;
445 
446   /* Non-strings always have zero width */
447   if (xmv->type != NULL && 0 != xmlStrcmp (xmv->type, _xml("string")))
448     return 0;
449 
450   if (fallback != -1)
451     return fallback;
452 
453   if (xmv->value)
454     width = ROUND_UP (xmlStrlen (xmv->value),
455 		      SPREADSHEET_DEFAULT_WIDTH);
456   else if (xmv->text)
457     width = ROUND_UP (xmlStrlen (xmv->text),
458 		      SPREADSHEET_DEFAULT_WIDTH);
459 
460   return width;
461 }
462 
463 /*
464    Sets the VAR of case C, to the value corresponding to the xml data
465  */
466 static void
convert_xml_to_value(struct ccase * c,const struct variable * var,const struct xml_value * xmv,int col,int row)467 convert_xml_to_value (struct ccase *c, const struct variable *var,
468 		      const struct xml_value *xmv, int col, int row)
469 {
470   union value *v = case_data_rw (c, var);
471 
472   if (xmv->value == NULL && xmv->text == NULL)
473     value_set_missing (v, var_get_width (var));
474   else if (var_is_alpha (var))
475     /* Use the text field, because it seems that there is no
476        value field for strings */
477     value_copy_str_rpad (v, var_get_width (var), xmv->text, ' ');
478   else
479     {
480       const struct fmt_spec *fmt = var_get_write_format (var);
481       enum fmt_category fc  = fmt_get_category (fmt->type);
482 
483       assert (fc != FMT_CAT_STRING);
484 
485       if (0 == xmlStrcmp (xmv->type, _xml("float")))
486 	{
487 	  v->f = c_strtod (CHAR_CAST (const char *, xmv->value), NULL);
488 	}
489       else
490 	{
491 	  const char *text = xmv->value ?
492 	    CHAR_CAST (const char *, xmv->value) : CHAR_CAST (const char *, xmv->text);
493 
494 	  char *m = data_in (ss_cstr (text), "UTF-8",
495 			 fmt->type,
496 			 v,
497 			 var_get_width (var),
498 			 "UTF-8");
499 
500 	  if (m)
501 	    {
502 	      char buf [FMT_STRING_LEN_MAX + 1];
503 	      char *cell = create_cell_ref (col, row);
504 
505 	      msg (MW, _("Cannot convert the value in the spreadsheet cell %s to format (%s): %s"),
506 		   cell, fmt_to_string (fmt, buf), m);
507 	      free (cell);
508 	    }
509 	  free (m);
510 	}
511     }
512 }
513 
514 static int
xml_reader_for_zip_member(void * zm_,char * buffer,int len)515 xml_reader_for_zip_member (void *zm_, char *buffer, int len)
516 {
517   struct zip_member *zm = zm_;
518   return zip_member_read (zm, buffer, len);
519 }
520 
521 /* Try to find out how many sheets there are in the "workbook" */
522 static int
get_sheet_count(struct zip_reader * zreader)523 get_sheet_count (struct zip_reader *zreader)
524 {
525   xmlTextReaderPtr mxtr;
526   struct zip_member *meta = NULL;
527   meta = zip_member_open (zreader, "meta.xml");
528 
529   if (meta == NULL)
530     return -1;
531 
532   mxtr = xmlReaderForIO (xml_reader_for_zip_member, NULL, meta, NULL, NULL, 0);
533 
534   while (1 == xmlTextReaderRead (mxtr))
535     {
536       xmlChar *name = xmlTextReaderName (mxtr);
537       if (0 == xmlStrcmp (name, _xml("meta:document-statistic")))
538 	{
539 	  xmlChar *attr = xmlTextReaderGetAttribute (mxtr, _xml ("meta:table-count"));
540 
541 	  if (attr != NULL)
542 	    {
543 	      int s = _xmlchar_to_int (attr);
544 	      xmlFreeTextReader (mxtr);
545               zip_member_finish (meta);
546 	      xmlFree (name);
547 	      xmlFree (attr);
548 	      return s;
549 	    }
550 	  xmlFree (attr);
551 	}
552       xmlFree (name);
553     }
554 
555   xmlFreeTextReader (mxtr);
556   zip_member_finish (meta);
557   return -1;
558 }
559 
560 static void
ods_error_handler(void * ctx,const char * mesg,xmlParserSeverities sev UNUSED,xmlTextReaderLocatorPtr loc)561 ods_error_handler (void *ctx, const char *mesg,
562 		   xmlParserSeverities sev UNUSED,
563 		   xmlTextReaderLocatorPtr loc)
564 {
565   struct ods_reader *r = ctx;
566 
567   msg (MW, _("There was a problem whilst reading the %s file `%s' (near line %d): `%s'"),
568        "ODF",
569        r->spreadsheet.file_name,
570        xmlTextReaderLocatorLineNumber (loc),
571        mesg);
572 }
573 
574 
575 static bool
init_reader(struct ods_reader * r,bool report_errors,struct state_data * state)576 init_reader (struct ods_reader *r, bool report_errors,
577              struct state_data *state)
578 {
579   struct zip_member *content = zip_member_open (r->zreader, "content.xml");
580   xmlTextReaderPtr xtr;
581 
582   if (content == NULL)
583     return NULL;
584 
585   xtr = xmlReaderForIO (xml_reader_for_zip_member, NULL, content, NULL, NULL,
586 			report_errors ? 0 : (XML_PARSE_NOERROR | XML_PARSE_NOWARNING));
587 
588   if (xtr == NULL)
589       return false;
590 
591   *state = (struct state_data) { .xtr = xtr,
592                                  .zm = content,
593                                  .state = STATE_INIT };
594 
595   r->spreadsheet.type = SPREADSHEET_ODS;
596 
597   if (report_errors)
598     xmlTextReaderSetErrorHandler (xtr, ods_error_handler, r);
599 
600   return true;
601 }
602 
603 
604 
605 struct spreadsheet *
ods_probe(const char * filename,bool report_errors)606 ods_probe (const char *filename, bool report_errors)
607 {
608   int sheet_count;
609   struct ods_reader *r = xzalloc (sizeof *r);
610   struct zip_reader *zr;
611 
612   ds_init_empty (&r->zip_errs);
613 
614   zr = zip_reader_create (filename, &r->zip_errs);
615 
616   if (zr == NULL)
617     {
618       if (report_errors)
619 	{
620 	  msg (ME, _("Cannot open %s as a OpenDocument file: %s"),
621 	       filename, ds_cstr (&r->zip_errs));
622 	}
623       ds_destroy (&r->zip_errs);
624       free (r);
625       return NULL;
626     }
627 
628   sheet_count = get_sheet_count (zr);
629 
630   r->zreader = zr;
631   r->spreadsheet.ref_cnt = 1;
632 
633   if (!init_reader (r, report_errors, &r->msd))
634     goto error;
635 
636   r->spreadsheet.n_sheets = sheet_count;
637   r->n_allocated_sheets = 0;
638   r->sheets = NULL;
639 
640   r->spreadsheet.file_name = strdup (filename);
641   return &r->spreadsheet;
642 
643  error:
644   ds_destroy (&r->zip_errs);
645   zip_reader_destroy (r->zreader);
646   free (r);
647   return NULL;
648 }
649 
650 struct casereader *
ods_make_reader(struct spreadsheet * spreadsheet,const struct spreadsheet_read_options * opts)651 ods_make_reader (struct spreadsheet *spreadsheet,
652 		 const struct spreadsheet_read_options *opts)
653 {
654   intf ret = 0;
655   xmlChar *type = NULL;
656   unsigned long int vstart = 0;
657   casenumber n_cases = CASENUMBER_MAX;
658   int i;
659   struct var_spec *var_spec = NULL;
660   int n_var_specs = 0;
661 
662   struct ods_reader *r = (struct ods_reader *) spreadsheet;
663   xmlChar *val_string = NULL;
664 
665   assert (r);
666   r->read_names = opts->read_names;
667   ds_init_empty (&r->ods_errs);
668   ++r->spreadsheet.ref_cnt;
669 
670   if (!init_reader (r, true, &r->rsd))
671     goto error;
672 
673   r->used_first_case = false;
674   r->first_case = NULL;
675 
676   if (opts->cell_range)
677     {
678       if (! convert_cell_ref (opts->cell_range,
679 			       &r->start_col, &r->start_row,
680 			       &r->stop_col, &r->stop_row))
681 	{
682 	  msg (SE, _("Invalid cell range `%s'"),
683 	       opts->cell_range);
684 	  goto error;
685 	}
686     }
687   else
688     {
689       r->start_col = 0;
690       r->start_row = 0;
691       r->stop_col = -1;
692       r->stop_row = -1;
693     }
694 
695   r->target_sheet_name = xmlStrdup (BAD_CAST opts->sheet_name);
696   r->target_sheet_index = opts->sheet_index;
697 
698   /* Advance to the start of the cells for the target sheet */
699   while (! reading_target_sheet (r, &r->rsd)
700 	  || r->rsd.state != STATE_ROW || r->rsd.row <= r->start_row)
701     {
702       if (1 != (ret = xmlTextReaderRead (r->rsd.xtr)))
703 	   break;
704 
705       process_node (r, &r->rsd);
706     }
707 
708   if (ret < 1)
709     {
710       msg (MW, _("Selected sheet or range of spreadsheet `%s' is empty."),
711            spreadsheet->file_name);
712       goto error;
713     }
714 
715   if (opts->read_names)
716     {
717       while (1 == xmlTextReaderRead (r->rsd.xtr))
718 	{
719 	  process_node (r, &r->rsd);
720 
721 	  /* If the row is finished then stop for now */
722 	  if (r->rsd.state == STATE_TABLE && r->rsd.row > r->start_row)
723 	    break;
724 
725 	  int idx = r->rsd.col - r->start_col - 1;
726 
727 	  if (idx < 0)
728 	    continue;
729 
730 	  if (r->stop_col != -1 && idx > r->stop_col - r->start_col)
731 	    continue;
732 
733 	  if (r->rsd.state == STATE_CELL_CONTENT
734 	      &&
735 	      XML_READER_TYPE_TEXT  == r->rsd.node_type)
736 	    {
737 	      xmlChar *value = xmlTextReaderValue (r->rsd.xtr);
738 	      if (idx >= n_var_specs)
739 		{
740 		  var_spec = xrealloc (var_spec, sizeof (*var_spec) * (idx + 1));
741 
742 		  /* xrealloc (unlike realloc) doesn't initialise its memory to 0 */
743 		  memset (var_spec + n_var_specs,
744 			  0,
745 			  (idx - n_var_specs + 1) * sizeof (*var_spec));
746 		  n_var_specs = idx + 1;
747 		}
748 	      for (int i = 0; i < r->rsd.col_span; ++i)
749 		{
750 		  var_spec[idx - i].firstval.text = 0;
751 		  var_spec[idx - i].firstval.value = 0;
752 		  var_spec[idx - i].firstval.type = 0;
753 		  var_spec[idx - i].name =
754 		    strdup (CHAR_CAST (const char *, value));
755 		}
756 
757 	      xmlFree (value);
758 	    }
759 	}
760     }
761 
762   /* Read in the first row of data */
763   while (1 == xmlTextReaderRead (r->rsd.xtr))
764     {
765       int idx;
766       process_node (r, &r->rsd);
767 
768       if (! reading_target_sheet (r, &r->rsd))
769 	break;
770 
771       /* If the row is finished then stop for now */
772       if (r->rsd.state == STATE_TABLE &&
773 	  r->rsd.row > r->start_row + (opts->read_names ? 1 : 0))
774 	break;
775 
776       idx = r->rsd.col - r->start_col - 1;
777       if (idx < 0)
778 	continue;
779 
780       if (r->stop_col != -1 && idx > r->stop_col - r->start_col)
781 	continue;
782 
783       if (r->rsd.state == STATE_CELL &&
784 	   XML_READER_TYPE_ELEMENT  == r->rsd.node_type)
785 	{
786 	  type = xmlTextReaderGetAttribute (r->rsd.xtr, _xml ("office:value-type"));
787 	  val_string = xmlTextReaderGetAttribute (r->rsd.xtr, _xml ("office:value"));
788 	}
789 
790       if (r->rsd.state == STATE_CELL_CONTENT &&
791 	   XML_READER_TYPE_TEXT  == r->rsd.node_type)
792 	{
793 	  if (idx >= n_var_specs)
794 	    {
795 	      var_spec = xrealloc (var_spec, sizeof (*var_spec) * (idx + 1));
796 	      memset (var_spec + n_var_specs,
797 		      0,
798 		      (idx - n_var_specs + 1) * sizeof (*var_spec));
799 
800 	      var_spec [idx].name = NULL;
801 	      n_var_specs = idx + 1;
802 	    }
803 
804 	  var_spec [idx].firstval.type = type;
805 	  var_spec [idx].firstval.text = xmlTextReaderValue (r->rsd.xtr);
806 	  var_spec [idx].firstval.value = val_string;
807 
808 	  val_string = NULL;
809 	  type = NULL;
810 	}
811     }
812 
813 
814   /* Create the dictionary and populate it */
815   r->spreadsheet.dict = r->dict = dict_create (
816     CHAR_CAST (const char *, xmlTextReaderConstEncoding (r->rsd.xtr)));
817 
818   for (i = 0; i < n_var_specs ; ++i)
819     {
820       struct fmt_spec fmt;
821       struct variable *var = NULL;
822       char *name = dict_make_unique_var_name (r->dict, var_spec[i].name, &vstart);
823       int width  = xmv_to_width (&var_spec[i].firstval, opts->asw);
824       dict_create_var (r->dict, name, width);
825       free (name);
826 
827       var = dict_get_var (r->dict, i);
828 
829       if (0 == xmlStrcmp (var_spec[i].firstval.type, _xml("date")))
830 	{
831 	  fmt.type = FMT_DATE;
832 	  fmt.d = 0;
833 	  fmt.w = 20;
834 	}
835       else
836 	fmt = fmt_default_for_width (width);
837 
838       var_set_both_formats (var, &fmt);
839     }
840 
841   if (n_var_specs ==  0)
842     {
843       msg (MW, _("Selected sheet or range of spreadsheet `%s' is empty."),
844            spreadsheet->file_name);
845       goto error;
846     }
847 
848   /* Create the first case, and cache it */
849   r->proto = caseproto_ref (dict_get_proto (r->dict));
850   r->first_case = case_create (r->proto);
851   case_set_missing (r->first_case);
852 
853   for (i = 0 ; i < n_var_specs; ++i)
854     {
855       const struct variable *var = dict_get_var (r->dict, i);
856 
857       convert_xml_to_value (r->first_case, var,  &var_spec[i].firstval,
858 			    r->rsd.col - n_var_specs + i,
859 			    r->rsd.row - 1);
860     }
861 
862   /* Read in the first row of data */
863   while (1 == xmlTextReaderRead (r->rsd.xtr))
864     {
865       process_node (r, &r->rsd);
866 
867       if (r->rsd.state == STATE_ROW)
868 	break;
869     }
870 
871 
872   for (i = 0 ; i < n_var_specs ; ++i)
873     {
874       free (var_spec[i].firstval.type);
875       free (var_spec[i].firstval.value);
876       free (var_spec[i].firstval.text);
877       free (var_spec[i].name);
878     }
879 
880   free (var_spec);
881 
882 
883   return casereader_create_sequential
884     (NULL,
885      r->proto,
886      n_cases,
887      &ods_file_casereader_class, r);
888 
889  error:
890 
891   for (i = 0 ; i < n_var_specs ; ++i)
892     {
893       free (var_spec[i].firstval.type);
894       free (var_spec[i].firstval.value);
895       free (var_spec[i].firstval.text);
896       free (var_spec[i].name);
897     }
898 
899   free (var_spec);
900 
901   ods_file_casereader_destroy (NULL, r);
902 
903   return NULL;
904 }
905 
906 
907 /* Reads and returns one case from READER's file.  Returns a null
908    pointer on failure. */
909 static struct ccase *
ods_file_casereader_read(struct casereader * reader UNUSED,void * r_)910 ods_file_casereader_read (struct casereader *reader UNUSED, void *r_)
911 {
912   struct ccase *c = NULL;
913   struct ods_reader *r = r_;
914 
915   xmlChar *val_string = NULL;
916   xmlChar *type = NULL;
917 
918   if (!r->used_first_case)
919     {
920       r->used_first_case = true;
921       return r->first_case;
922     }
923 
924 
925   /* Advance to the start of a row. (If there is one) */
926   while (r->rsd.state != STATE_ROW
927 	 && 1 == xmlTextReaderRead (r->rsd.xtr)
928 	)
929     {
930       process_node (r, &r->rsd);
931     }
932 
933 
934   if (! reading_target_sheet (r, &r->rsd)
935        ||  r->rsd.state < STATE_TABLE
936        ||  (r->stop_row != -1 && r->rsd.row > r->stop_row + 1)
937 )
938     {
939       return NULL;
940     }
941 
942   c = case_create (r->proto);
943   case_set_missing (c);
944 
945   while (1 == xmlTextReaderRead (r->rsd.xtr))
946     {
947       process_node (r, &r->rsd);
948 
949       if (r->stop_row != -1 && r->rsd.row > r->stop_row + 1)
950 	break;
951 
952       if (r->rsd.state == STATE_CELL &&
953 	   r->rsd.node_type == XML_READER_TYPE_ELEMENT)
954 	{
955 	  type = xmlTextReaderGetAttribute (r->rsd.xtr, _xml ("office:value-type"));
956 	  val_string = xmlTextReaderGetAttribute (r->rsd.xtr, _xml ("office:value"));
957 	}
958 
959       if (r->rsd.state == STATE_CELL_CONTENT &&
960 	   r->rsd.node_type == XML_READER_TYPE_TEXT)
961 	{
962 	  int col;
963 	  struct xml_value *xmv = xzalloc (sizeof *xmv);
964 	  xmv->text = xmlTextReaderValue (r->rsd.xtr);
965 	  xmv->value = val_string;
966 	  val_string = NULL;
967 	  xmv->type = type;
968 	  type = NULL;
969 
970 	  for (col = 0; col < r->rsd.col_span; ++col)
971 	    {
972 	      const struct variable *var;
973 	      const int idx = r->rsd.col - col - r->start_col - 1;
974 	      if (idx < 0)
975 		continue;
976 	      if (r->stop_col != -1 && idx > r->stop_col - r->start_col)
977 		break;
978 	      if (idx >= dict_get_var_cnt (r->dict))
979 		break;
980 
981               var = dict_get_var (r->dict, idx);
982 	      convert_xml_to_value (c, var, xmv, idx + r->start_col, r->rsd.row - 1);
983 	    }
984 
985 	  xmlFree (xmv->text);
986 	  xmlFree (xmv->value);
987 	  xmlFree (xmv->type);
988 	  free (xmv);
989 	}
990       if (r->rsd.state <= STATE_TABLE)
991 	break;
992     }
993 
994   xmlFree (type);
995   xmlFree (val_string);
996 
997   return c;
998 }
999