Framework  3.9
csv_import.inc
Go to the documentation of this file.
1 <?php
2 /**************************************************************
3 
4  Copyright (c) 2007-2010 Sonjara, Inc
5 
6  Permission is hereby granted, free of charge, to any person
7  obtaining a copy of this software and associated documentation
8  files (the "Software"), to deal in the Software without
9  restriction, including without limitation the rights to use,
10  copy, modify, merge, publish, distribute, sublicense, and/or sell
11  copies of the Software, and to permit persons to whom the
12  Software is furnished to do so, subject to the following
13  conditions:
14 
15  The above copyright notice and this permission notice shall be
16  included in all copies or substantial portions of the Software.
17 
18  Except as contained in this notice, the name(s) of the above
19  copyright holders shall not be used in advertising or otherwise
20  to promote the sale, use or other dealings in this Software
21  without prior written authorization.
22 
23  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
25  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
27  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
28  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
29  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
30  OTHER DEALINGS IN THE SOFTWARE.
31 
32 *****************************************************************/
33 
34 require_once realpath(dirname(__FILE__)."/data_item.inc");
35 require_once realpath(dirname(__FILE__)."/transaction.inc");
36 
74 class CSVImport
75 {
76  var $class;
77  var $index_field = null;
78  var $truncate = false;
79  var $update = false;
80  var $ignoreUnknown = false;
81  var $disablePrimaryKey = false;
82  var $onPreImport = null;
83  var $onPostImport = null;
84  var $lines = 0;
85  var $imported = 0;
86  var $limit = -1;
87  var $tx;
88 
89  function __construct($class)
90  {
91  $this->class = $class;
92  }
93 
94  function import($file = null)
95  {
96  if (!$file)
97  {
98  $file = $_FILES["importFile"]["tmp_name"];
99  }
100 
101  $tx = new DataTransaction();
102 
103  try
104  {
105  $proto = new $this->class;
106  $proto->joinTransaction($tx);
107 
108  if ($this->truncate)
109  {
110  $proto->deleteAll();
111  }
112 
113  if ($this->disablePrimaryKey)
114  {
115  $proto->disablePrimaryKey();
116  }
117 
118  $indexed = array();
119 
120  if ($this->index_field)
121  {
122  $indexed = IndexedQuery::create($this->class, "", $this->index_field);
123  }
124 
125  $fp = fopen($file, "r");
126 
127  $fields = fgetcsv($fp);
128 
129  $fileIdx = -1;
130 
131  $i = 0;
132 
133  trace("Importing fields: ".implode(",", $fields), 3);
134 
135  // First column must contain field names that match the target class
136 
137  foreach($fields as $field)
138  {
139  if (!$proto->hasField($field) && !$this->ignoreUnknown)
140  {
141  throw new FakoliException("Unrecognized column: $field");
142  }
143 
144  if ($this->index_field && $field == $this->index_field)
145  {
146  $fileIdx = $i;
147  break;
148  }
149 
150  $i++;
151  }
152 
153  if ($fileIdx < 0 && !$this->ignoreUnknown && !$this->onPreImportItem)
154  {
155  throw new FakoliException("'{$this->index_field}' column not present");
156  }
157 
158  $this->lines = 0;
159  $this->imported = 0;
160 
161  while($values = fgetcsv($fp))
162  {
163  $this->lines++;
164 
165  if ($this->limit > -1 && $this->imported >= $this->limit) continue;
166 
167  $item = new $this->class;
168  $item->joinTransaction($tx);
169 
170  $i = 0;
171  foreach($fields as $field)
172  {
173  $item->set($field, $values[$i++]);
174  }
175 
176  if ($this->onPreImport)
177  {
178  trace("** Calling onPreImport", 3);
179 
180  call_user_func($this->onPreImport, $item);
181  }
182 
183  if ($this->index_field && array_key_exists($values[$fileIdx], $indexed))
184  {
185  if ($this->update)
186  {
187  $src = $indexed[$values[$fileIdx]];
188  foreach($item->getFields() as $f)
189  {
190  if (!isset($item->$f)) $item->set($f, $src->get($f));
191  }
192  }
193  else
194  {
195  trace("Skipping record {$values[$fileIdx]}", 3);
196  continue;
197  }
198  }
199 
200  if ($fileIdx)
201  {
202  trace("Importing record {$values[$fileIdx]} at line {$this->lines}", 3);
203  }
204  else
205  {
206  trace("Importing record at line $iterations", 3);
207  }
208 
209  $item->save();
210 
211  $this->imported++;
212 
213  if ($this->onPostImport)
214  {
215  call_user_func($this->onPostImport, $item);
216  }
217  }
218 
219 
220  if ($this->disablePrimaryKey)
221  {
222  $proto->enablePrimaryKey();
223  }
224 
225  trace ("No more values from CSV", 3);
226 
227  $tx->commit();
228  }
229  catch(Exception $e)
230  {
231  $tx->rollback();
232  throw $e;
233  }
234  }
235 
236  function drawForm()
237  {
238 ?>
239 <form method="POST" action="" enctype='multipart/form-data'>
240 <label for="importFile">Import File (CSV Format): </label>
241 <input type="file" name="import_file"></input>
242 <br/>
243 <input type="checkbox" class="checkbox" name="truncate" value="1"/>&nbsp;Delete existing records<br/>
244 <br/>
245 <input type="submit" value="Import Records" class='button'></input>
246 </form>
247 <?
248  }
249 }
250 
251 ?>
CSVImport provides a generic method for importing Comma-Separated Value files into DataItem mapped da...
Definition: csv_import.inc:75
$disablePrimaryKey
Definition: csv_import.inc:81
__construct($class)
Definition: csv_import.inc:89
The DataTransaction class wraps the underlying database's transaction model.
Definition: transaction.inc:48
static create($class, $constraints="", $indexBy="")
trace($msg, $lvl=3, $callStack=null)
Send output to the trace log.
Definition: functions.inc:1010