source: extensions/GrumPluginClasses/classes/GPCExport.class.inc.php @ 17757

Last change on this file since 17757 was 17757, checked in by grum, 12 years ago

version 3.5.4
GPCExport

. Improve ODS formatting
. Fix bug in SQLite export options

FilterBox

. add 'not between' filter

  • Property svn:executable set to *
File size: 16.1 KB
Line 
1<?php
2/* -----------------------------------------------------------------------------
3  class name     : GPCExport
4  class version  : 1.0.0
5  plugin version : 3.5.4
6  date           : 2012-09-03
7  ------------------------------------------------------------------------------
8  author: grum at piwigo.org
9  << May the Little SpaceFrog be with you >>
10  ------------------------------------------------------------------------------
11
12  :: HISTORY
13
14| release | date       |
15| 1.0.0   | 2012/09/03 | * New class
16|         |            |
17|         |            |
18|         |            |
19|         |            |
20
21  ------------------------------------------------------------------------------
22
23Provided classes are:
24 - GPCGenericExport: generic class, ancestor for all other class. Not to be used directly
25 - GPCCSVExport: class for separated text (.csv) export
26 - GPCODSExport: class for OpenDocument Spreadsheet (.ods) export
27 - GPCSQLiteExport: class for SQLite (.db) export
28
29GPCGenericExport methods:
30  - public function __construct()
31  - public function __destruct()
32  - public function write()
33  - public function setDefaultFormat()
34  - public function setDefaultType
35  - public function setColumnsDef()
36  - public function getColumnsDef()
37  - public function setOptions()
38  - public function getOptions()
39  - public function setFileName()
40  - public function getFileName()
41  - public function setFileDir()
42  - public function getFileDir()
43  - public function setFileMode()
44  - public function getFileMode()
45
46   ---------------------------------------------------------------------- */
47
48include_once('GPCCore.class.inc.php');
49include_once('External/odsPhpGenerator/ods.php');
50
51/**
52 * Generic class, provide generic functions for derivated classes
53 */
54class GPCGenericExport {
55  protected $defaultFormat=array(
56                'INTEGER' => '%d',
57                'TEXT'    => '%s',
58                'REAL'   => '%f'
59              );
60  protected $defaultType='TEXT';
61  protected $fileName='';
62  protected $fileDir='';
63  protected $fileMode='w';
64  protected $columnsDef=array();
65  protected $options=array();
66
67  public function __construct($file='')
68  {
69    if($file!='')
70      $this->setFileName($file);
71  }
72
73  public function __destruct()
74  {
75  }
76
77  /**
78   * this methods have to be overrided to write the destination file
79   *
80   * @param Array $data: data to write
81   * @return Boolean: true if file is written, otherwise false
82   */
83  public function write($data)
84  {
85  } //write
86
87  /**
88   * set the default format for the given type
89   *
90   * @param String $type: 'INTEGER', 'REAL', 'TEXT'
91   * @param String $format: format to be applied (sprintf format)
92   * @return Boolean: true if ok otherwise false
93   */
94  public function setDefaultFormat($type, $format)
95  {
96    $type=strtoupper($type);
97
98    if($type=='INTEGER' or $type=='REAL' or $type=='TEXT')
99    {
100      $this->defaultFormat[$type]=$format;
101      return(true);
102    }
103    return(false);
104  } // setDefaultFormat
105
106  /**
107   * set the default type for file data
108   *
109   * @param String $type: 'INTEGER', 'REAL', 'TEXT'
110   * @return String: the current default column type
111   */
112  public function setDefaultType($type)
113  {
114    $type=strtoupper($type);
115
116    if($type=='INTEGER' or $type=='REAL' or $type=='TEXT')
117    {
118      $this->defaultType=$type;
119    }
120    return($this->defaultType);
121  } // setDefaultType
122
123  /**
124   * set columns definition
125   *  a definition is an array:
126   *   'name'   => (String) Name of the column (mandatory)
127   *   'type'   => (String) Type of column ('INTEGER', 'REAL', 'TEXT')
128   *   'format' => (String) Format applied to the column (sprintf format)
129   *
130   *  if 'type' if not defined, the $defaultType will be used
131   *  if 'format' if not defined, the $defaultFormat will be used
132   *
133   *  an empty array means to use default definition for the column
134   *
135   * @param Array $colsTypes: array of definition
136   * @return Array: the current columns definition
137   */
138  public function setColumnsDef($columnsDef)
139  {
140    if(!is_array($columnsDef))
141      return($this->colsTypes);
142
143    $this->columnsDef=array();
144    foreach($columnsDef as $colDef)
145    {
146      if(isset($colDef['name']))
147      {
148        $type=(isset($colDef['type']) and ($colDef['type']=='INTEGER' or $colDef['type']=='REAL' or $colDef['type']=='TEXT'))?$colDef['type']:$this->defaultType;
149        $format=isset($colDef['format'])?$colDef['format']:$this->defaultFormat[$type];
150        $this->columnsDef[]=array(
151            'name' => $colDef['name'],
152            'type' => $type,
153            'format' => $format
154          );
155      }
156    }
157    return($this->columnsDef);
158  } // setColumnsDef
159
160  /**
161   * get the current columns definition
162   *
163   * @return Array: the columns definition
164   */
165  public function getColumnsDef()
166  {
167    return($this->columnsDef);
168  } // getColumnsDef
169
170  /**
171   * set options values; need to be overrided...
172   *
173   * @param Array $options: associative array of options
174   * @return Array: current options
175   */
176  public function setOptions($options)
177  {
178    if(is_array($options))
179      $this->options=$options;
180    return($this->options);
181  } // setOptions
182
183  /**
184   * get options values
185   *
186   * @param String $option: optional option key
187   * @return Array: current options; if $option if set, return only the option value
188   */
189  public function getOptions($option=null)
190  {
191    if($option!=null and isset($this->options[$option]))
192      return($this->options[$option]);
193    return($this->options);
194  } // getOptions
195
196
197  /**
198   * set the file name
199   * if a directory is given in the filename, the $fileDir is overrided
200   *
201   * @param String $fileName: the file name
202   * @return String: the current file name
203   */
204  public function setFileName($fileName)
205  {
206    $tmpDir=dirname($fileName);
207    $tmpName=basename($fileName);
208    if($tmpName!='')
209      $this->fileName=$tmpName;
210    if($tmpDir!='')
211      $this->setFileDir($tmpDir);
212    return($this->fileName);
213  } // setFileName
214
215  /**
216   * get the file name
217   *
218   * @param Boolean $path: if true, return the file name with the complete path
219   * @return String: the current file name
220   */
221  public function getFileName($path=false)
222  {
223    $returned=$this->fileName;
224    if($path)
225      $returned=$this->fileDir.'/'.$returned;
226    return($returned);
227  } // getFileName
228
229  /**
230   * set the file directory
231   *
232   * @param String $fileDir: the file directory
233   * @return String: the current file directory
234   */
235  public function setFileDir($fileDir)
236  {
237    if($fileDir!='')
238      $this->fileDir=$fileDir;
239    if(substr($this->fileDir,-1)=='/')
240      $this->fileDir=substr($this->fileDir,0,-1);
241    return($this->fileDir);
242  } // setFileDir
243
244  /**
245   * get the file directory
246   *
247   * @return String: the current file directory
248   */
249  public function getFileDir()
250  {
251    return($this->fileDir);
252  } // getFileDir
253
254  /**
255   * set the file writting mode
256   *  'a' => append data to existing file; if file doesn't exist, create it
257   *  'w' => delete file if exists and create a new one
258   *
259   * @param String $mode: the file mode 'a' or 'w'
260   * @return String: the current file mode
261   */
262  public function setFileMode($fileMode)
263  {
264    if($fileMode=='a' or $fileMode=='w')
265      $this->fileMode=$fileMode;
266
267    return($this->fileMode);
268  } // setFileMode
269
270  /**
271   * get the file writting mode
272   *
273   * @return String: the current file mode
274   */
275  public function getFileMode()
276  {
277    return($this->fileMode);
278  }
279} // GPCGenericExport
280
281
282
283/**
284 * Class used to export data into CSV file
285 */
286class GPCCSVExport extends GPCGenericExport {
287  protected $options=array(
288                'separator' => ';',
289                'decimalDot' => ',',
290                'useQuotes' => false,
291                'lineFeed' => "\x0A"
292              );
293
294  /**
295   * set options values; need to be overrided...
296   *
297   * @param Array $options: associative array of options
298   * @return Array: current options
299   */
300  public function setOptions($options)
301  {
302    if(!is_array($options))
303      return($this->options);
304
305    foreach($options as $option => $value)
306    {
307      switch($option)
308      {
309        case 'separator':
310          if($value=='tab') $value=chr(9);
311          $this->options[$option]=$value;
312          break;
313        case 'decimalDot':
314          if($value=='.' or $value==',')
315            $this->options[$option]=$value;
316          break;
317        case 'useQuotes':
318          if($value==true or $value==false)
319            $this->options[$option]=$value;
320          break;
321        case 'lineFeed':
322          if($value=='unix')
323          {
324            $value="\x0A";
325          }
326          elseif($value=='windows')
327          {
328            $value="\x0D\x0A";
329          }
330
331          if($value=="\x0A" or $value=="\x0D\x0A")
332            $this->options[$option]=$value;
333          break;
334      }
335    }
336    return($this->options);
337  } // setOptions
338
339  /**
340   * write the CSV file
341   *
342   * @param Array $data: data to write
343   * @return Boolean: true if file is written, otherwise false
344   */
345  public function write($data)
346  {
347    if(!is_array($data)) return(false);
348
349    if(!file_exists($this->fileDir))
350        mkdir($this->fileDir, 0755, true);
351
352    $fHandle=fopen($this->getFileName(true), $this->fileMode);
353    if($fHandle)
354    {
355      $fileContent='';
356      // columns name
357      $line=array();
358      foreach($this->columnsDef as $column)
359      {
360        $value=$column['name'];
361        if($this->options['useQuotes']) $value='"'.$value.'"';
362        $line[]=$value;
363      }
364      $line=implode($this->options['separator'], $line).$this->options['lineFeed'];
365      $fileContent.=$line;
366
367      // rows
368      foreach($data as $row)
369      {
370        $i=0;
371        $line=array();
372        foreach($row as $column)
373        {
374          $value='';
375          switch($this->columnsDef[$i]['type'])
376          {
377            case 'INTEGER':
378              $value=sprintf($this->columnsDef[$i]['format'], $column);
379              break;
380            case 'REAL':
381              $value=sprintf($this->columnsDef[$i]['format'], $column);
382              if($this->options['decimalDot']!='.')
383                $value=str_replace('.', $this->options['decimalDot'], $value);
384              break;
385            case 'TEXT':
386              $value=sprintf($this->columnsDef[$i]['format'], $column);
387              if($this->options['useQuotes']) $value='"'.$value.'"';
388              break;
389          }
390          $line[]=$value;
391          $i++;
392        }
393        $line=implode($this->options['separator'], $line).$this->options['lineFeed'];
394        $fileContent.=$line;
395      }
396      fwrite($fHandle, $fileContent);
397      fclose($fHandle);
398      return(true);
399    }
400    return(false);
401  } //write
402
403} // GPCCSVExport
404
405
406
407
408/**
409 * Class used to export data into ODS file
410 */
411class GPCODSExport extends GPCGenericExport {
412  protected $options=array(
413                'sheetName' => 'Sheet1',
414                'fileTitle' => '',
415                'fileSubject' => '',
416                'keywords' => '',
417                'comments' => ''
418              );
419
420  /**
421   * set options values; need to be overrided...
422   *
423   * @param Array $options: associative array of options
424   * @return Array: current options
425   */
426  public function setOptions($options)
427  {
428    if(!is_array($options))
429      return($this->options);
430
431    foreach($options as $option => $value)
432    {
433      switch($option)
434      {
435        case 'sheetName':
436        case 'fileTitle':
437        case 'fileSubject':
438        case 'keywords':
439        case 'comments':
440          $this->options[$option]=$value;
441          break;
442      }
443    }
444    return($this->options);
445  } // setOptions
446
447  /**
448   * write the ODS file
449   *
450   * @param Array $data: data to write
451   * @return Boolean: true if file is written, otherwise false
452   */
453  public function write($data)
454  {
455    if(!is_array($data)) return(false);
456
457    if(!file_exists($this->fileDir))
458        mkdir($this->fileDir, 0755, true);
459
460    // append mode will be managed later...
461    if(file_exists($this->getFileName(true)))
462      unlink($this->getFileName(true));
463
464    $ods=new ods();
465
466    $ods->setTitle($this->options['fileTitle']);
467    $ods->setSubject($this->options['fileSubject']);
468    $ods->setKeyword($this->options['keywords']);
469    $ods->setDescription($this->options['comments']);
470
471    $sheet=new odsTable($this->options['sheetName']);
472    $sheet->setVerticalSplit(1);
473
474    // columns name
475    $headerStyle = new odsStyleTableCell();
476    $headerStyle->setFontWeight('bold');
477    $row=new odsTableRow();
478    foreach($this->columnsDef as $column)
479    {
480      $row->addCell(new odsTableCellString($column['name'], $headerStyle));
481    }
482    $sheet->addRow($row);
483
484    // rows
485    $bodyStyle = new odsStyleTableCell();
486    //$bodyStyle->setFontWeight('bold');
487    foreach($data as $dataRow)
488    {
489      $i=0;
490      $row=new odsTableRow();
491      foreach($dataRow as $column)
492      {
493        switch($this->columnsDef[$i]['type'])
494        {
495          case 'INTEGER':
496          case 'REAL':
497            $cell=new odsTableCellFloat(1*sprintf($this->columnsDef[$i]['format'], $column), $bodyStyle);
498            break;
499          case 'TEXT':
500            $cell=new odsTableCellString(sprintf($this->columnsDef[$i]['format'], $column), $bodyStyle);
501            break;
502          default:
503            $cell=new odsTableCellEmpty();
504            break;
505        }
506        $row->addCell($cell);
507        $i++;
508      }
509      $sheet->addRow($row);
510    }
511
512    $ods->addTable($sheet);
513    return($ods->genOdsFile($this->getFileName(true)));
514  } //write
515
516} // GPCODSExport
517
518
519
520
521
522
523/**
524 * Class used to export data into SQLite file
525 */
526class GPCSQLiteExport extends GPCGenericExport {
527  protected $options=array(
528                'tableName' => 'exported'
529              );
530  protected $dbHandle=null;
531
532  /**
533   * set options values; need to be overrided...
534   *
535   * @param Array $options: associative array of options
536   * @return Array: current options
537   */
538  public function setOptions($options)
539  {
540    if(!is_array($options))
541      return($this->options);
542
543    foreach($options as $option => $value)
544    {
545      switch($option)
546      {
547        case 'tableName':
548          $this->options[$option]=$value;
549          break;
550      }
551    }
552    return($this->options);
553  } // setOptions
554
555  /**
556   * write the SQLite file
557   *
558   * @param Array $data: data to write
559   * @return Boolean: true if file is written, otherwise false
560   */
561  public function write($data)
562  {
563    if(!is_array($data)) return(false);
564
565    if(!file_exists($this->fileDir))
566        mkdir($this->fileDir, 0755, true);
567
568
569    if($this->createSQLiteFile($this->getFileName(true)))
570    {
571      $this->dbHandle->exec("BEGIN TRANSACTION");
572
573      // rows
574      foreach($data as $row)
575      {
576        $i=0;
577        $line=array();
578        foreach($row as $column)
579        {
580          $value='';
581          switch($this->columnsDef[$i]['type'])
582          {
583            case 'INTEGER':
584            case 'REAL':
585              $value=sprintf($this->columnsDef[$i]['format'], $column);
586              break;
587            case 'TEXT':
588              $value=sprintf("'".$this->columnsDef[$i]['format']."'", $this->dbHandle->escapeString($column));
589              break;
590          }
591          $line[]=$value;
592          $i++;
593        }
594        $sql="INSERT INTO ".$this->options['tableName']." VALUES (".implode(',', $line).");";
595        $this->dbHandle->exec($sql);
596      }
597      $this->dbHandle->exec("COMMIT TRANSACTION");
598      $this->closeSQLiteFile();
599      return(true);
600    }
601    return(false);
602  } //write
603
604  /**
605   * create the SQLite file and create the table
606   *
607   * @param String $fileName: SQLite file
608   * @return Boolean: true if Ok, otherwise false
609   */
610  private function createSQLiteFile($file)
611  {
612    $this->dbHandle=new SQLite3($file, SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE);
613
614    if($this->dbHandle)
615    {
616      $columns=array();
617      foreach($this->columnsDef as $column)
618      {
619        $columns[]=" '".$column['name']."' ".$column['type'];
620      }
621
622      $sql="CREATE TABLE '".$this->options['tableName']."' (".implode(', ', $columns).");";
623      $this->dbHandle->exec($sql);
624      return(true);
625    }
626    $this->dbHandle=false;
627    return(false);
628  }
629
630  /**
631   * close the SQLite file
632   */
633  private function closeSQLiteFile()
634  {
635    if($this->dbHandle)
636    {
637      $this->dbHandle->close();
638      $this->dbHandle=false;
639    }
640    return(true);
641  }
642
643} // GPCSQLiteExport
644
645
646
647?>
Note: See TracBrowser for help on using the repository browser.