phpBMS

root/trunk/phpbms/include/imports.php

Revision 710, 13.0 KB (checked in by nate, 2 years ago)
  • Changed imports to incorporate changes made to tables.php (as a result of uuids).
Line 
1<?php
2        class phpbmsImport{
3
4                var $table;
5                var $error = "";
6                var $docError = "";
7                var $row = 0;
8                var $transactionIDs = array();
9                var $importType;
10                var $data;
11                var $revertID = 0;
12
13                // Do not manually override
14                var $transactionRecords = array();
15                var $tempFileID = 0;
16                var $pageType = "main";
17
18
19                function phpbmsImport($table, $importType = "csv"){
20
21                        $this->table = $table;
22                        $this->importType = $importType;
23                        switch($this->importType){
24                                case "csv":
25                                        $this->parser = new parseCSV;
26                                break;
27                        }//end switch
28
29                        $this->table->db->logError = true;
30                        //So, that, when there is a db error, it will go all the way through and not just stop
31                        $this->table->db->stopOnError = false;
32                        //Won't display db errors, just log them.
33                        $this->table->db->showError = false;
34
35                }//end method --imports--
36
37                function _parseFromData($data){
38
39                        switch($this->importType){
40
41                                case "csv":
42
43                                        if(is_readable($data)){
44                                                $contents = $this->_getFile($data);
45
46                                                if(is_readable($contents)){
47                                                        $this->docError = "invalid csv document";
48                                                        return false;
49                                                }//end if
50
51                                        }//end if
52
53                                        $this->parser->parse($data);
54
55                                        if(!count($this->parser->titles) || !count($this->parser->data)){
56                                                $this->docError = "invalid csv document";
57                                                return false;
58                                        }//end if
59
60                                        return true;
61                                break;
62
63                        }//end swtich
64
65                }//end method --_parseFromFile--
66
67
68                function _getTransactionData(){
69                //needs to be changed for more complicated tables
70                        $inStatement = "";
71                        foreach($this->transactionIDs as $theid)
72                                $inStatement .= $theid.",";
73
74                        if($inStatement){
75
76                                $inStatement = substr($inStatement, 0, -1);
77
78                                $querystatement = "
79                                        SELECT
80                                                *
81                                        FROM
82                                                `".$this->table->maintable."`
83                                        WHERE
84                                                `id` IN (".$inStatement.");
85                                        ";
86
87                                $queryresult = $this->table->db->query($querystatement);
88
89                                while($therecord = $this->table->db->fetchArray($queryresult))
90                                        $this->transactionRecords[] = $therecord;
91
92                        }//end if
93
94                }//end method --_getTransactionData--
95
96
97                function _getFile($fileName){
98                        if(function_exists('file_get_contents')){
99                                $file = addslashes(file_get_contents($fileName));
100                        }else{
101                                // If using PHP < 4.3.0 use the following:
102                                $file = addslashes(fread(fopen($fileName, 'r'), filesize($fileName)));
103                        }//end if
104
105                        return $file;
106                }//end method --_getFile--
107
108                //DO NOT CALL IN TRANSACTION
109                function _storeTempCSV($fileName){
110                       
111                        $querystatement = "
112                                INSERT INTO
113                                        `files`
114                                        (
115                                                `uuid`,
116                                                `name`,
117                                                `description`,
118                                                `file`,
119                                                `type`,
120                                                `roleid`,
121                                                `creationdate`,
122                                                `createdby`,
123                                                `modifiedby`
124                                        )
125                                        VALUES
126                                        (
127                                                '".uuid(getUuidPrefix($this->table->db, "tbld:80b4f38d-b957-bced-c0a0-ed08a0db6475"))."',
128                                                'temporary',
129                                                'This is a temporary import file',
130                                                '".$this->_getFile($fileName)."',
131                                                'phpbms/temp',
132                                                'Admin',
133                                                NOW(),
134                                                '".$_SESSION["userinfo"]["id"]."',
135                                                '".$_SESSION["userinfo"]["id"]."'
136
137                                        )
138                                ";
139
140                        $this->table->db->query($querystatement);
141
142                        $id = $this->table->db->insertId();
143
144                        if($id)
145                                $this->tempFileID = ((int) $id);
146                        else
147                                $this->error .= '<li> inserting temporary file failure </li>';
148
149                }//end method --_storeTempCSV--
150
151
152                function _getTempCSV($tempFileID){
153
154                        if($tempFileID){
155
156                                $querystatement = "
157                                        SELECT
158                                                `file`
159                                        FROM
160                                                `files`
161                                        WHERE
162                                                id = ".((int)$tempFileID)."
163                                        ";
164
165                                $queryresult = $this->table->db->query($querystatement);
166
167                                $therecord = $this->table->db->fetchArray($queryresult);
168
169                                return $therecord["file"];
170
171                        }//end if
172
173                        return false;
174
175                }//end method --_getTempCSV--
176
177                //DO NOT CALL IN TRANSACTION
178                function _removeTempCSV($tempFileID = 0){
179
180                        $querystatement = "
181                                DELETE FROM
182                                        `files`
183                                WHERE
184                                        `type` = 'phpbms/temp'
185                                        AND
186                                        (
187                                                `id` = ".((int)$tempFileID)."
188                                                OR
189                                                `creationdate` <= NOW() - INTERVAL 30 MINUTE
190                                        );
191                                ";
192
193                        $queryresult = $this->table->db->query($querystatement);
194
195                        $querystatement = "
196                                ALTER TABLE
197                                        `files`
198                                AUTO_INCREMENT = ".((int) $tempFileID).";
199                                ";
200
201                        $queryresult = $this->table->db->query($querystatement);
202
203                }//end method --_removeTempCSV--
204
205                //DO NOT USE THIS METHOD INSIDE AN OPEN TRANSACTION.
206                //IT WILL AUTOMATICALLY COMMIT THE TRANSACTION
207                function _revertAutoIncrement($revertID = 0){
208
209                        //check to see if there is a revert id (i.e. there was a valid insert)
210                        if($revertID)
211                                if(is_numeric($revertID)){
212
213                                        $querystatement = "
214                                                ALTER TABLE
215                                                        `".$this->table->maintable."`
216                                                AUTO_INCREMENT = ".((int) $revertID).";
217                                                ";
218
219                                        $this->table->db->query($querystatement);
220
221                                }//end if
222
223                }//end method --_revertAutoIncrement--
224
225
226                function importRecords($rows, $titles){
227
228                        switch($this->importType){
229
230                                case "csv":
231                                        //count total fieldnames (top row of csv document)
232                                        $fieldNum = count($titles);
233
234                                        //the file starts at line number 1, but since line 1 is
235                                        //supposed to be the fieldnames in the table(s), the lines
236                                        //being insereted start @ 2.
237                                        $rowNum = 2;
238
239                                        //get the data one row at a time
240                                        foreach($rows as $rowData){
241
242                                                $theid = 0; // set for when verifification does not pass
243                                                $verify = array(); //set for when number of field rows does not match number of titles
244
245                                                //trim off leading/trailing spaces
246                                                $trimmedRowData = array();
247
248                                                foreach($rowData as $name => $data)
249                                                        $trimmedRowData[$name] = trim($data);
250
251                                                //check to see if number of fieldnames is consistent for each row
252                                                $rowFieldNum = count($trimmedRowData);
253
254                                                //if valid, insert, if not, log error and don't insert.
255                                                if($rowFieldNum == $fieldNum){
256                                                        $verify = $this->table->verifyVariables($trimmedRowData);
257                                                        if(!count($verify)){
258                                                                $createdby = NULL;
259                                                                $overrideID = true;
260                                                                $replace = false;
261                                                                if(!isset($trimmedRowData["uuid"])){
262                                                                        $useUuid = true;
263                                                                        $thereturn = $this->table->insertRecord($trimmedRowData, $createdby, $overrideID, $replace, $useUuid);
264                                                                        $theid = $thereturn["id"];
265                                                                }else{
266                                                                        $useUuid = false;
267                                                                        $thereturn = $this->table->insertRecord($trimmedRowData, $createdby, $overrideID, $replace, $useUuid);
268                                                                        $theid = $thereturn;
269                                                                }
270                                                        }//end if
271                                                }else
272                                                        $this->error .= '<li> incorrect amount of fields for line number '.$rowNum.'.</li>';
273
274                                                if($theid){
275                                                        //keep track of the ids in the transaction to be able to select them
276                                                        //for preview purposes
277                                                        $this->transactionIDs[] = $theid;
278
279                                                        //get first id to correct auto increment
280                                                        if(!$this->revertID)
281                                                                $this->revertID = $theid;
282                                                }else
283                                                        $this->error .= '<li> failed insert for line number '.$rowNum.'.</li>';
284
285                                                foreach($verify as $error)
286                                                        $this->error .= '<li class="subError">'.$error.'</li>';
287
288                                                $rowNum++;
289
290                                        }//end foreach
291                                break;
292
293                        }//end switch
294
295                }//end method --importRecords--
296
297
298                function displayTransaction($recordsArray, $fieldsArray){
299                //needs to be changed for more complicated tables
300                        if(count($recordsArray) && count($fieldsArray)){
301                                ?>
302                                <h2>Import Preview</h2>
303                                <div id="transactionDiv">
304                                <table id="transactionTable">
305                                        <thead>
306                                                <tr>
307                                                        <?php
308                                                        foreach($fieldsArray as $field => $junk){
309                                                                ?><th align="left" nowrap="nowrap"><?php
310                                                                echo formatVariable($field);
311                                                                ?></th><?php
312                                                        }//end foreach
313                                                        $field = NULL;
314                                                        ?>
315                                                </tr>
316                                        </thead>
317                                        <tbody>
318                                                <?php
319                                                $i = 1;
320                                                foreach($recordsArray as $record){
321                                                        ?><tr class="qr<?php echo $i ?>" ><?php
322                                                        foreach($fieldsArray as $field => $junk){
323                                                                ?><td nowrap="nowrap"><?php
324                                                                echo formatVariable($record[$field]);
325                                                                ?></td><?php
326                                                        }//end foreach
327                                                        ?></tr><?php
328                                                        $i = ($i == 1)?2:1;
329                                                }//end while
330                                                ?>
331                                        </tbody>
332                                </table>
333                                </div>
334                                <?php
335                        }//end if
336
337                }//end method --displayTransaction--
338
339
340                function processImportPage(){
341
342                        $this->table->getTableInfo();
343
344                        if(isset($_POST["pageType"]))
345                                $this->pageType = $_POST["pageType"];
346
347                        if(isset($_POST["tempFileID"]))
348                                $this->tempFileID = ((int)$_POST["tempFileID"]);
349
350                        if(!isset($_POST["command"])){
351
352                                //happens upon first coming to page
353
354                                //remove any other temporary csv files in the `files` table
355                                //present from previous imports
356                                $this->_removeTempCSV();
357
358                                //check to see if user has the rights to be here.
359                                //If not, kick him to the no access page.
360                                if(!hasRights($this->table->importroleid))
361                                        goURL(APP_PATH."noaccess.php");
362
363                        }else{
364                                //form has been submitted
365                                switch($_POST["command"]){
366
367                                        //cancel button pressed.
368                                        case "cancel":
369                                                //Cancel button needs to do different things depending upon which page
370                                                //its at.
371                                                if($this->pageType == "main")
372                                                        goURL($this->table->backurl);
373                                                else{
374                                                        $this->_removeTempCSV($this->tempFileID);
375                                                        $therecord["phpbmsStatus"] = "Record(s) Not Imported";
376                                                        $this->pageType = "main";
377                                                }//end if
378                                        break;
379
380                                        case "upload":
381
382                                                //check for valid file upload
383                                                if(!$_FILES["import"]["error"] && ($_FILES["import"]["size"] > 0)){
384
385                                                        //check and parse the file
386                                                        if($this->_parseFromData($_FILES["import"]["tmp_name"])){
387
388                                                                //start transaction
389                                                                $this->table->db->startTransaction();
390
391                                                                $this->importRecords($this->parser->data, $this->parser->titles);
392
393                                                                //get data for preview purposes
394                                                                $this->_getTransactionData();
395                                                                //"undo" any inserts
396                                                                $this->table->db->rollbackTransaction();
397
398                                                                //DO NOT CALL IN TRANSACTION
399                                                                //ALTER TABLES AUTO COMMIT AND THE FILE NEEDS TO CARRY
400                                                                //OVER.
401                                                                $this->_revertAutoIncrement($this->revertID);
402                                                                $this->_storeTempCSV($_FILES["import"]["tmp_name"]);
403
404                                                        }//end if
405
406                                                }else
407                                                        $this->docError .= "failed file upload";
408
409                                                //switch page types
410                                                $this->pageType = "confirm";
411
412                                                if(!$this->error && !$this->docError){
413                                                        $therecord["phpbmsStatus"] = "Confirm Import";
414                                                }elseif($this->docError){
415                                                        $therecord["phpbmsStatus"] = "Import Error: ".$this->docError;
416                                                        $this->pageType = "main";
417                                                }else
418                                                        $therecord["phpbmsStatus"] = "Import Error";
419
420                                        break;
421
422                                        case "import":
423
424                                                //get the contents of the stored csv document
425                                                $CSVcontents = $this->_getTempCSV($this->tempFileID);
426
427                                                //parser uses newline character to be able to parse the last line
428                                                if(substr($CSVcontents,-1,1) != "\n")
429                                                        $CSVcontents .= "\n";
430
431
432                                                $this->parser->parse($CSVcontents);
433
434                                                $this->importRecords($this->parser->data, $this->parser->titles);
435
436                                                $this->table->db->commitTransaction();
437
438                                                //DO NOT CALL IN TRANSACTION
439
440                                                //get rid of temporary csv document
441                                                $this->_removeTempCSV($this->tempFileID);
442
443                                                $therecord["phpbmsStatus"] = "Record(s) Imported";
444                                                //change page type
445                                                $this->pageType = "main";
446                                        break;
447
448                                }//end command switch
449
450                        }// end if
451
452                        //display the title
453                        $therecord["title"] = $this->table->displayname." Import";
454                        return $therecord;
455
456                }//end method --imports--
457
458        }//end class --imports--
459
460
461        //this class is to have different buttons, and no created/modified.
462        if(class_exists("phpbmsForm")){
463                class importForm extends phpbmsForm{
464
465                        function importForm($action = NULL, $method="post", $name="record", $onsubmit="return validateForm(this);", $dontSubmit = true){
466
467                                parent::phpbmsForm($action,$method,$name,$onsubmit,$dontSubmit);
468
469                        }//end method --importForm--
470
471                        function startForm($pageTitle, $pageType, $numberOfRecords = 0){
472
473                                ?><form action="<?php echo htmlentities($this->action) ?>" method="<?php echo $this->method?>" name="<?php echo $this->name?>" onsubmit="<?php echo $this->onsubmit?>" <?php
474                                        if(isset($this->enctype)) echo ' enctype="'.$this->enctype.'" ';
475                                        if(isset($this->id)) echo ' id="'.$this->id.'" ';
476                                ?>><?php
477                                if($this->dontSubmit){
478                                        ?><div id="dontSubmit"><input type="submit" value=" " onclick="return false;" /></div><?php
479                                } ?>
480                                <div id="topButtons"><?php $this->showButtons(1, $pageType, $numberOfRecords); ?></div>
481                                <h1 id="h1Title"><span><?php echo $pageTitle ?></span></h1><?php
482
483                        }//end method --startForm--
484
485                        function showButtons($ids = 1, $pageType = "main", $numberOfRecords = 0){
486                                ?>
487                                <div class="importCancels">
488                                        <?php if($pageType == "main"){ ?>
489                                        <input <?php if($ids==1) {?>accesskey="u"<?php }?> title="Upload (alt+u)" id="uploadButton<?php echo $ids?>" name="command" type="submit" value="upload" class="Buttons" />
490                                        <input id="cancelButton<?php echo $ids?>" name="command" type="submit" value="cancel" class="Buttons" <?php if($ids==1) {?>accesskey="x" <?php }?> title="(access key+x)" />
491                                        <?php }else{?>
492                                        <input type="submit" class="Buttons" value="import" name="command" id="import<?php echo $ids?>" title="commit" <?php if($ids==1) {?>accesskey="i"<?php }?> <?php echo ($numberOfRecords? '':'disabled="disabled"') ?>/>
493                                        <input type="submit" class="Buttons" value="cancel" name="command" id="cancelButton<?php echo $ids?>" <?php if($ids==1) {?>accesskey="x"<?php }?> title="rollback"/>
494                                        <?php }//end if ?>
495                                </div><?php
496                        }//end method --showButtons--
497
498                }//end class --importForm--
499        }
500?>
Note: See TracBrowser for help on using the browser.
Scanned by Orvant Copyright © 2010 Kreotek, LLC. All Rights reserved.