forked from vanilla/porter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
class.exportmodel.php
executable file
·1718 lines (1480 loc) · 56.9 KB
/
class.exportmodel.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @copyright Vanilla Forums Inc. 2010
* @license http://opensource.org/licenses/gpl-2.0.php GNU GPL2
* @package VanillaPorter
*/
/**
* Object for exporting other database structures into a format that can be imported.
*/
class ExportModel {
const COMMENT = '//';
const DELIM = ',';
const ESCAPE = '\\';
const NEWLINE = "\n";
const NULL = '\N';
const QUOTE = '"';
public $CaptureOnly = FALSE;
/** @var array Any comments that have been written during the export. */
public $Comments = array();
/** @var ExportController **/
public $Controller = NULL;
/** @var string The charcter set to set as the connection anytime the database connects. */
public $CharacterSet = 'utf8';
/**
* @var int The chunk size when exporting large tables.
*/
public $ChunkSize = 100000;
/** @var array **/
public $CurrentRow = NULL;
public $Destination = 'file';
public $DestPrefix = 'GDN_z';
public static $EscapeSearch = array();
public static $EscapeReplace = array();
/** @var object File pointer */
public $File = NULL;
/** @var string A prefix to put into an automatically generated filename. */
public $FilenamePrefix = '';
public $_Host;
public static $Mb = FALSE;
/** @var object PDO instance */
protected $_PDO = NULL;
protected $_Password;
/** @var string The path to the export file. */
public $Path = '';
/**
* @var string The database prefix. When you pass a sql string to ExportTable() it will replace occurances of :_ with this property.
* @see ExportModel::ExportTable()
*/
public $Prefix = '';
public $Queries = array();
protected $_QueryStructures = array();
/** @var string The path to the source of the export in the case where a file is being converted. */
public $SourcePath = '';
/**
* @var string
*/
public $SourcePrefix = '';
public $ScriptCreateTable = TRUE;
/*Porter Plus*/
private $_TopLevelFilters=array();
protected $_Options=array();
/*Porter Plus*/
/**
* @var array Strucutes that define the format of the export tables.
*/
protected $_Structures = array(
'Activity' => array(
'ActivityType' => 'varchar(20)',
'ActivityUserID' => 'int',
'RegardingUserID' => 'int',
'NotifyUserID' => 'int',
'HeadlineFormat' => 'varchar(255)',
'Story' => 'text',
'Format' => 'varchar(10)',
'InsertUserID' => 'int',
'DateInserted' => 'datetime',
'InsertIPAddress' => 'varchar(15)'),
'Category' => array(
'CategoryID' => 'int',
'Name' => 'varchar(30)',
'UrlCode' => 'varchar(255)',
'Description' => 'varchar(250)',
'ParentCategoryID' => 'int',
'DateInserted' => 'datetime',
'InsertUserID' => 'int',
'DateUpdated' => 'datetime',
'UpdateUserID' => 'int',
'Sort' => 'int',
'Archived' => 'tinyint(1)'),
'Comment' => array(
'CommentID' => 'int',
'DiscussionID' => 'int',
'DateInserted' => 'datetime',
'InsertUserID' => 'int',
'InsertIPAddress' => 'varchar(15)',
'DateUpdated' => 'datetime',
'UpdateUserID' => 'int',
'UpdateIPAddress' => 'varchar(15)',
'Format' => 'varchar(20)',
'Body' => 'text',
'Score' => 'float'),
'Conversation' => array(
'ConversationID' => 'int',
'Subject' => 'varchar(255)',
'FirstMessageID' => 'int',
'DateInserted' => 'datetime',
'InsertUserID' => 'int',
'DateUpdated' => 'datetime',
'UpdateUserID' => 'int'),
'ConversationMessage' => array(
'MessageID' => 'int',
'ConversationID' => 'int',
'Body' => 'text',
'Format' => 'varchar(20)',
'InsertUserID' => 'int',
'DateInserted' => 'datetime',
'InsertIPAddress' => 'varchar(15)'),
'Discussion' => array(
'DiscussionID' => 'int',
'Name' => 'varchar(100)',
'Body' => 'text',
'Format' => 'varchar(20)',
'CategoryID' => 'int',
'DateInserted' => 'datetime',
'InsertUserID' => 'int',
'InsertIPAddress' => 'varchar(15)',
'DateUpdated' => 'datetime',
'UpdateUserID' => 'int',
'UpdateIPAddress' => 'varchar(15)',
'DateLastComment' => 'datetime',
'CountComments' => 'int',
'CountViews' => 'int',
'Score' => 'float',
'Closed' => 'tinyint',
'Announce' => 'tinyint',
'Sink' => 'tinyint',
'Type' => 'varchar(20)'),
'Media' => array(
'MediaID' => 'int',
'Name' => 'varchar(255)',
'Type' => 'varchar(128)',
'Size' => 'int',
'StorageMethod' => 'varchar(24)',
'Path' => 'varchar(255)',
'InsertUserID' => 'int',
'DateInserted' => 'datetime',
'ForeignID' => 'int',
'ForeignTable' => 'varchar(24)',
'ImageWidth' => 'int',
'ImageHeight' => 'int'
),
'Permission' => array(
'RoleID' => 'int',
'JunctionTable' => 'varchar(100)',
'JunctionColumn' => 'varchar(100)',
'JunctionID' => 'int',
'_Permissions' => 'varchar(255)',
'Garden.SignIn.Allow' => 'tinyint',
'Garden.Activity.View' => 'tinyint',
'Garden.Profiles.View' => 'tinyint',
'Vanilla.Discussions.View' => 'tinyint',
'Vanilla.Discussions.Add' => 'tinyint',
'Vanilla.Comments.Add' => 'tinyint'
),
'Poll' => array(
'PollID' => 'int',
'Name' => 'varchar(255)',
'DiscussionID' => 'int',
'Anonymous' => 'tinyint',
'DateInserted' => 'datetime',
'InsertUserID' => 'int',
'DateUpdated' => 'datetime',
'UpdateUserID' => 'int'
),
'PollOption' => array(
'PollOptionID' => 'int',
'PollID' => 'int',
'Body' => 'varchar(500)',
'Format' => 'varchar(20)',
'Sort' => 'smallint',
'DateInserted' => 'datetime',
'InsertUserID' => 'int',
'DateUpdated' => 'datetime',
'UpdateUserID' => 'int'
),
'PollVote' => array(
'UserID' => 'int',
'PollOptionID' => 'int',
'DateInserted' => 'datetime'
),
'Rank' => array(
'RankID' => 'int',
'Name' => 'varchar(100)',
'Level' => 'smallint',
'Label' => 'varchar(255)',
'Body' => 'text',
'Attributes' => 'text'
),
'Role' => array(
'RoleID' => 'int',
'Name' => 'varchar(100)',
'Description' => 'varchar(200)',
'CanSession' => 'tinyint'),
'Tag' => array(
'TagID' => 'int',
'Name' => 'varchar(255)',
'InsertUserID' => 'int',
'DateInserted' => 'datetime'),
'TagDiscussion' => array(
'TagID' => 'int',
'DiscussionID' => 'int'),
'User' => array(
'UserID' => 'int',
'Name' => 'varchar(20)',
'Email' => 'varchar(200)',
'Password' => 'varbinary(100)',
'HashMethod' => 'varchar(10)',
//'Gender' => array('m', 'f'),
'Title' => 'varchar(100)',
'Location' => 'varchar(100)',
'Score' => 'float',
'InviteUserID' => 'int',
'HourOffset' => 'int',
'CountDiscussions' => 'int',
'CountComments' => 'int',
'DiscoveryText' => 'text',
'Photo' => 'varchar(255)',
'DateOfBirth' => 'datetime',
'DateFirstVisit' => 'datetime',
'DateLastActive' => 'datetime',
'DateInserted' => 'datetime',
'InsertIPAddress' => 'varchar(15)',
'LastIPAddress' => 'varchar(15)',
'DateUpdated' => 'datetime',
'Banned' => 'tinyint',
'ShowEmail' => 'tinyint',
'RankID' => 'int'),
'UserAuthentication' => array(
'ForeignUserKey' => 'varchar(255)',
'ProviderKey' => 'varchar(64)',
'UserID' => 'varchar(11)',
'Attributes' => 'text'
),
'UserConversation' => array(
'UserID' => 'int',
'ConversationID' => 'int',
'Deleted' => 'tinyint(1)',
'LastMessageID' => 'int'),
'UserDiscussion' => array(
'UserID' => 'int',
'DiscussionID' => 'int',
'Bookmarked' => 'tinyint',
'DateLastViewed' => 'datetime',
'CountComments' => 'int'),
'UserMeta' => array(
'UserID' => 'int',
'Name' => 'varchar(255)',
'Value' => 'text'),
'UserNote' => array(
'UserNoteID' => 'int',
'Type' => 'varchar(10)',
'UserID' => 'int',
'Body' => 'text',
'Format' => 'varchar(10)',
'InsertUserID' => 'int',
'DateInserted' => 'datetime',
'InsertIPAddress' => 'varchar(15)'
),
'UserRole' => array(
'UserID' => 'int',
'RoleID' => 'int'),
'Ban' => array(
'BanID' => 'int',
'BanType' => 'varchar(50)',
'BanValue' => 'varchar(50)',
'Notes' => 'varchar(255)',
'CountUsers' => 'int',
'CountBlockRegistrations' => 'int',
'InsertUserID' => 'int',
'DateInserted' => 'datetime'),
'Group' => array(
'GroupID' => 'int',
'Name' => 'varchar(255)',
'Description' => 'text',
'Format' => 'varchar(10)',
'CategoryID' => 'int',
'Icon' => 'varchar(255)',
'Banner' => 'varchar(255)',
'Privacy' => 'varchar(255)',
'Registration' => 'varchar(255)',
'Visibility' => 'varchar(255)',
'CountMembers' => 'int',
'CountDiscussions' => 'int',
'DateLastComment' => 'datetime',
'DateInserted' => 'datetime',
'InsertUserID' => 'int',
'DateUpdated' => 'datetime',
'UpdateUserID' => 'int',
'Attributes' => 'text'
),
'UserGroup' => array(
'UserGroupID' => 'int',
'GroupID' => 'int',
'UserID' => 'int',
'DateInserted' => 'datetime',
'InsertUserID' => 'int',
'Role' => 'varchar(255)'
)
);
public $TestMode = FALSE;
public $TestLimit = 10;
/**
* @var bool Whether or not to use compression when creating the file.
*/
protected $_UseCompression = TRUE;
protected $_Username;
/**
*
* @var bool Whether or not to stream the export the the output rather than save a file.
*/
public $UseStreaming = FALSE;
public function __construct() {
self::$Mb = function_exists('mb_detect_encoding');
// Set the search and replace to escape strings.
self::$EscapeSearch = array(self::ESCAPE, self::DELIM, self::NEWLINE, self::QUOTE); // escape must go first
self::$EscapeReplace = array(self::ESCAPE.self::ESCAPE, self::ESCAPE.self::DELIM, self::ESCAPE.self::NEWLINE, self::ESCAPE.self::QUOTE);
}
/**
* Create the export file and begin the export.
* @param string $Path The path to the export file.
* @param string $Source The source program that created the export. This may be used by the import routine to do additional processing.
*/
public function BeginExport($Path = '', $Source = '', $Header = array()) {
$this->Comments = array();
$this->BeginTime = microtime(TRUE);
if($Path)
$this->Path = $Path;
if(!$this->Path)
$this->Path = 'export_'.($this->FilenamePrefix ? $this->FilenamePrefix.'_' : '').date('Y-m-d_His').'.txt'.($this->UseCompression() ? '.gz' : '');
$fp = $this->_OpenFile();
$Comment = 'Vanilla Export: '.$this->Version();
if($Source)
$Comment .= self::DELIM.' Source: '.$Source;
foreach ($Header as $Key => $Value) {
$Comment .= self::DELIM." $Key: $Value";
}
if ($this->CaptureOnly)
$this->Comment($Comment);
else
fwrite($fp, $Comment.self::NEWLINE.self::NEWLINE);
$this->Comment('Export Started: '.date('Y-m-d H:i:s'));
return $fp;
}
/**
* Write a comment to the export file.
* @param string $Message The message to write.
* @param bool $Echo Whether or not to echo the message in addition to writing it to the file.
*/
public function Comment($Message, $Echo = TRUE) {
if ($this->Destination == 'file')
$Char = self::COMMENT;
else
$Char = '--';
$Comment = $Char.' '.str_replace(self::NEWLINE, self::NEWLINE.self::COMMENT.' ', $Message).self::NEWLINE;
fwrite($this->File, $Comment);
if($Echo) {
if (defined('CONSOLE'))
echo $Comment;
else
$this->Comments[] = $Message;
}
}
/**
* End the export and close the export file. This method must be called if BeginExport() has been called or else the export file will not be closed.
*/
public function EndExport() {
$this->EndTime = microtime(TRUE);
$this->TotalTime = $this->EndTime - $this->BeginTime;
$this->Comment($this->Path);
$this->Comment('Export Completed: '.date('Y-m-d H:i:s'));
$this->Comment(sprintf('Elapsed Time: %s', self::FormatElapsed($this->TotalTime)));
if ($this->TestMode || $this->Controller->Param('dumpsql') || $this->CaptureOnly) {
$Queries = implode("\n\n", $this->Queries);
if ($this->Destination == 'database')
fwrite($this->File, $Queries);
else
$this->Comment($Queries, TRUE);
}
if($this->UseStreaming) {
//ob_flush();
} else {
if($this->UseCompression() && function_exists('gzopen'))
gzclose($this->File);
else
fclose($this->File);
}
}
/**
* Export a table to the export file.
* @param string $TableName the name of the table to export. This must correspond to one of the accepted Vanilla tables.
* @param mixed $Query The query that will fetch the data for the export this can be one of the following:
* - <b>String</b>: Represents a string of SQL to execute.
* - <b>PDOStatement</b>: Represents an already executed query result set.
* - <b>Array</b>: Represents an array of associative arrays or objects containing the data in the export.
* @param array $Mappings Specifies mappings, if any, between the source and the export where the keys represent the source columns and the values represent Vanilla columns.
* - If you specify a Vanilla column then it must be in the export structure contained in this class.
* - If you specify a MySQL type then the column will be added.
* - If you specify an array you can have the following keys: Column, and Type where Column represents the new column name and Type represents the MySQL type.
* For a list of the export tables and columns see $this->Structure().
*/
public function ExportTable($TableName, $Query, $Mappings = array()) {
$BeginTime = microtime(TRUE);
$RowCount = $this->_ExportTable($TableName, $Query, $Mappings);
$EndTime = microtime(TRUE);
$Elapsed = self::FormatElapsed($BeginTime, $EndTime);
$this->Comment("Exported Table: $TableName ($RowCount rows, $Elapsed)");
fwrite($this->File, self::NEWLINE);
}
protected function _ExportTableImport($TableName, $Query, $Mappings = array()) {
// Backup the settings.
$DestinationBak = $this->Destination;
$this->Destination = 'file';
$_FileBak = $this->File;
$Path = dirname(__FILE__).'/'.$TableName.'.csv';
$this->Comment("Exporting To: $Path");
$fp = fopen($Path, 'wb');
$this->File = $fp;
// First export the file to a file.
$this->_ExportTable($TableName, $Query, $Mappings, array('NoEndline' => TRUE));
// Now define a table to import into.
$this->_CreateExportTable($TableName, $Query, $Mappings);
// Now load the data.
$Sql = "load data local infile '$Path' into table {$this->DestDb}.{$this->DestPrefix}$TableName
character set utf8
columns terminated by ','
optionally enclosed by '\"'
escaped by '\\\\'
lines terminated by '\\n'
ignore 2 lines";
$this->Query($Sql);
// Restore the settings.
$this->Destination = $DestinationBak;
$this->File = $_FileBak;
}
public function ExportBlobs($Sql, $BlobColumn, $PathColumn, $Thumbnail = FALSE) {
$this->Comment("Exporting blobs...");
$Result = $this->Query($Sql);
$Count = 0;
while ($Row = mysql_fetch_assoc($Result)) {
// vBulletin attachment hack (can't do this in MySQL)
if (strpos($Row[$PathColumn], '.attach') && strpos($Row[$PathColumn], 'attachments/') !== FALSE) {
$PathParts = explode('/', $Row[$PathColumn]); // 3 parts
// Split up the userid into a path, digit by digit
$n = strlen($PathParts[1]);
$DirParts = array();
for($i = 0; $i < $n; $i++) {
$DirParts[] = $PathParts[1]{$i};
}
$PathParts[1] = implode('/', $DirParts);
// Rebuild full path
$Row[$PathColumn] = implode('/', $PathParts);
}
$Path = $Row[$PathColumn];
// Build path
if (!file_exists(dirname($Path))) {
$R = mkdir(dirname($Path), 0777, TRUE);
if (!$R)
die("Could not create ".dirname($Path));
}
if ($Thumbnail) {
$PicPath = str_replace('/avat', '/pavat', $Path);
$fp = fopen($PicPath, 'wb');
} else {
$fp = fopen($Path, 'wb');
}
if (!is_resource($fp))
die("Could not open $Path.");
fwrite($fp, $Row[$BlobColumn]);
fclose($fp);
$this->Status('.');
if ($Thumbnail) {
if ($Thumbnail === TRUE)
$Thumbnail = 50;
$ThumbPath = str_replace('/avat', '/navat', $Path);
$this->GenerateThumbnail($PicPath, $ThumbPath, $Thumbnail, $Thumbnail);
}
$Count++;
}
$this->Status("$Count Blobs.\n");
$this->Comment("$Count Blobs.", FALSE);
}
protected function _ExportTable($TableName, $Query, $Mappings = array(), $Options = array()) {
$fp = $this->File;
// Make sure the table is valid for export.
if (!array_key_exists($TableName, $this->_Structures)) {
$this->Comment("Error: $TableName is not a valid export."
." The valid tables for export are ". implode(", ", array_keys($this->_Structures)));
fwrite($fp, self::NEWLINE);
return;
}
if ($this->Destination == 'database') {
$this->_ExportTableDB($TableName, $Query, $Mappings);
return;
}
// Check for a chunked query.
$Query = str_replace('{from}', -2000000000, $Query);
$Query = str_replace('{to}', 2000000000, $Query);
if (strpos($Query, '{from}') !== FALSE) {
$this->_ExportTableDBChunked($TableName, $Query, $Mappings);
return;
}
// If we are in test mode then limit the query.
if ($this->TestMode && $this->TestLimit) {
$Query = rtrim($Query, ';');
if (stripos($Query, 'select') !== FALSE && stripos($Query, 'limit') === FALSE) {
$Query .= " limit {$this->TestLimit}";
}
}
$Structure = $this->_Structures[$TableName];
$LastID = 0;
$IDName = 'NOTSET';
$FirstQuery = TRUE;
$Data = $this->Query($Query);
// Loop through the data and write it to the file.
$RowCount = 0;
if ($Data !== FALSE) {
while (($Row = mysql_fetch_assoc($Data)) !== FALSE) {
$Row = (array)$Row; // export%202010-05-06%20210937.txt$TableName
$this->CurrentRow =& $Row;
$RowCount++;
if($FirstQuery) {
// Get the export structure.
$ExportStructure = $this->GetExportStructure($Row, $Structure, $Mappings, $TableName);
$RevMappings = $this->FlipMappings($Mappings);
$this->WriteBeginTable($fp, $TableName, $ExportStructure);
$FirstQuery = FALSE;
}
$this->WriteRow($fp, $Row, $ExportStructure, $RevMappings, $TableName);
// // Loop through the columns in the export structure and grab their values from the row.
// $ExRow = array();
// foreach ($ExportStructure as $Field => $Type) {
// // Get the value of the export.
// $Value = NULL;
// if (array_key_exists($Field, $Mappings)) {
// if (isset($Row[$Mappings[$Field]])) {
// // The column is mapped.
// $Value = $Row[$Mappings[$Field]];
// }
// } elseif (array_key_exists($Field, $Row)) {
// // The column has an exact match in the export.
// $Value = $Row[$Field];
// }
//
// // Check to see if there is a callback filter.
// if (isset($Filters[$Field])) {
// $Callback = $Filters[$Field];
// $Row2 =& $Row;
// $Value = call_user_func($Filters[$Field], $Value, $Field, $Row2, $Column);
// $Row = $this->CurrentRow;
// }
//
// // Format the value for writing.
// if (is_null($Value)) {
// $Value = self::NULL;
// } elseif (is_numeric($Value)) {
// // Do nothing, formats as is.
// } elseif (is_string($Value)) {
//
// // Check to see if there is a callback filter.
// if (isset($Filters[$Field])) {
// //$Value = call_user_func($Filters[$Field], $Value, $Field, $Row);
// } else {
// if($Mb && mb_detect_encoding($Value) != 'UTF-8')
// $Value = utf8_encode($Value);
// }
//
// $Value = str_replace(array("\r\n", "\r"), array(self::NEWLINE, self::NEWLINE), $Value);
// $Value = self::QUOTE
// .str_replace($EscapeSearch, $EscapeReplace, $Value)
// .self::QUOTE;
// } elseif (is_bool($Value)) {
// $Value = $Value ? 1 : 0;
// } else {
// // Unknown format.
// $Value = self::NULL;
// }
//
// $ExRow[] = $Value;
// }
// // Write the data.
// fwrite($fp, implode(self::DELIM, $ExRow));
// // End the record.
// fwrite($fp, self::NEWLINE);
}
}
if($Data !== FALSE)
mysql_free_result($Data);
unset($Data);
if (!isset($Options['NoEndline'])) {
$this->WriteEndTable($fp);
}
mysql_close();
return $RowCount;
}
protected function _CreateExportTable($TableName, $Query, $Mappings = array()) {
if (!$this->ScriptCreateTable)
return;
// Limit the query to grab any additional columns.
$QueryStruct = rtrim($Query, ';').' limit 1';
$Structure = $this->_Structures[$TableName];
$Data = $this->Query($QueryStruct, TRUE);
// $Mb = function_exists('mb_detect_encoding');
// Loop through the data and write it to the file.
if ($Data === FALSE)
return;
// Get the export structure.
while (($Row = mysql_fetch_assoc($Data)) !== FALSE) {
$Row = (array)$Row;
// Get the export structure.
$ExportStructure = $this->GetExportStructure($Row, $Structure, $Mappings, $TableName);
break;
}
mysql_close($Data);
// Build the create table statement.
$ColumnDefs = array();
foreach ($ExportStructure as $ColumnName => $Type) {
$ColumnDefs[] = "`$ColumnName` $Type";
}
$DestDb = '';
if (isset($this->DestDb))
$DestDb = $this->DestDb.'.';
$this->Query("drop table if exists {$DestDb}{$this->DestPrefix}$TableName");
$CreateSql = "create table {$DestDb}{$this->DestPrefix}$TableName (\n ".implode(",\n ", $ColumnDefs)."\n) engine=innodb";
$this->Query($CreateSql);
}
protected function _ExportTableDB($TableName, $Query, $Mappings = array()) {
if ($this->HasFilter($Mappings) || strpos($Query, 'union all') !== FALSE) {
$this->_ExportTableImport($TableName, $Query, $Mappings);
return;
}
// Check for a chunked query.
if (strpos($Query, '{from}') !== FALSE) {
$this->_ExportTableDBChunked($TableName, $Query, $Mappings);
return;
}
$DestDb = '';
if (isset($this->DestDb))
$DestDb = $this->DestDb.'.';
// Limit the query to grab any additional columns.
$QueryStruct = $this->GetQueryStructure($Query, $TableName);
$Structure = $this->_Structures[$TableName];
$ExportStructure = $this->GetExportStructure($QueryStruct, $Structure, $Mappings, $TableName);
$Mappings = $this->FlipMappings($Mappings);
// Build the create table statement.
$ColumnDefs = array();
foreach ($ExportStructure as $ColumnName => $Type) {
$ColumnDefs[] = "`$ColumnName` $Type";
}
if ($this->ScriptCreateTable) {
$this->Query("drop table if exists {$DestDb}{$this->DestPrefix}$TableName");
$CreateSql = "create table {$DestDb}{$this->DestPrefix}$TableName (\n ".implode(",\n ", $ColumnDefs)."\n) engine=innodb";
$this->Query($CreateSql);
}
$Query = rtrim($Query, ';');
// Build the insert statement.
if ($this->TestMode && $this->TestLimit) {
$Query .= " limit {$this->TestLimit}";
}
// echo $Query."\n\n\n";
// die();
// print_r(ParseSelect($Query));
$InsertColumns = array();
$SelectColumns = array();
foreach ($ExportStructure as $ColumnName => $Type) {
$InsertColumns[] = '`'.$ColumnName.'`';
if (isset($Mappings[$ColumnName])) {
$SelectColumns[$ColumnName] = $Mappings[$ColumnName];
} else {
$SelectColumns[$ColumnName] = $ColumnName;
}
}
// print_r($SelectColumns);
$Query = ReplaceSelect($Query, $SelectColumns);
$InsertSql = "replace {$DestDb}{$this->DestPrefix}$TableName"
." (\n ".implode(",\n ", $InsertColumns)."\n)\n"
.$Query;
// die($InsertSql);
$this->Query($InsertSql);
}
protected function _ExportTableDBChunked($TableName, $Query, $Mappings = array()) {
// Grab the table name from the first from.
if (preg_match('`\sfrom\s([^\s]+)`', $Query, $Matches)) {
$From = $Matches[1];
} else {
trigger_error("Could not figure out table for $TableName chunking.", E_USER_WARNING);
return;
}
$Sql = "show table status like '{$From}';";
$R = $this->Query($Sql, TRUE);
$Row = mysql_fetch_assoc($R);
mysql_free_result($R);
$Max = $Row['Auto_increment'];
if (!$Max)
$Max = 2000000;
for ($i = 0; $i < $Max; $i += $this->ChunkSize) {
$From = $i;
$To = $From + $this->ChunkSize - 1;
$Sql = str_replace(array('{from}', '{to}'), array($From, $To), $Query);
$this->_ExportTableDB($TableName, $Sql, $Mappings);
}
}
public function FixPermissionColumns($Columns) {
$Result = array();
foreach ($Columns as $Index => $Value) {
if (is_string($Value) && strpos($Value, '.') !== FALSE)
$Value = array('Column' => $Value, 'Type' => 'tinyint(1)');
$Result[$Index] = $Value;
}
return $Result;
}
public function FlipMappings($Mappings) {
$Result = array();
foreach ($Mappings as $Column => $Mapping) {
if (is_string($Mapping))
$Result[$Mapping] = array('Column' => $Column);
else {
$Col = $Mapping['Column'];
$Mapping['Column'] = $Column;
$Result[$Col] = $Mapping;
}
}
return $Result;
}
public function ForceDate($Value) {
if (!$Value || preg_match('`0000-00-00`', $Value)) {
return gmdate('Y-m-d H:i:s');
}
return $Value;
}
static function FormatElapsed($Start, $End = NULL) {
if($End === NULL)
$Elapsed = $Start;
else
$Elapsed = $End - $Start;
$m = floor($Elapsed / 60);
$s = $Elapsed - $m * 60;
$Result = sprintf('%02d:%05.2f', $m, $s);
return $Result;
}
static function FormatValue($Value) {
// Format the value for writing.
if (is_null($Value)) {
$Value = self::NULL;
} elseif (is_numeric($Value)) {
// Do nothing, formats as is.
} elseif (is_string($Value)) {
if(self::$Mb && mb_detect_encoding($Value) != 'UTF-8')
$Value = utf8_encode($Value);
$Value = str_replace(array("\r\n", "\r"), array(self::NEWLINE, self::NEWLINE), $Value);
$Value = self::QUOTE
.str_replace(self::$EscapeSearch, self::$EscapeReplace, $Value)
.self::QUOTE;
} elseif (is_bool($Value)) {
$Value = $Value ? 1 : 0;
} else {
// Unknown format.
$Value = self::NULL;
}
return $Value;
}
public function GenerateThumbnail($Path, $ThumbPath, $Height = 50, $Width = 50) {
list($WidthSource, $HeightSource, $Type) = getimagesize($Path);
$XCoord = 0;
$YCoord = 0;
$HeightDiff = $HeightSource - $Height;
$WidthDiff = $WidthSource - $Width;
if ($WidthDiff > $HeightDiff) {
// Crop the original width down
$NewWidthSource = round(($Width * $HeightSource) / $Height);
// And set the original x position to the cropped start point.
$XCoord = round(($WidthSource - $NewWidthSource) / 2);
$WidthSource = $NewWidthSource;
} else {
// Crop the original height down
$NewHeightSource = round(($Height * $WidthSource) / $Width);
// And set the original y position to the cropped start point.
$YCoord = round(($HeightSource - $NewHeightSource) / 2);
$HeightSource = $NewHeightSource;
}
try {
switch ($Type) {
case 1:
$SourceImage = imagecreatefromgif($Path);
break;
case 2:
$SourceImage = imagecreatefromjpeg($Path);
break;
case 3:
$SourceImage = imagecreatefrompng($Path);
imagealphablending($SourceImage, TRUE);
break;
}
$TargetImage = imagecreatetruecolor($Width, $Height);
imagecopyresampled($TargetImage, $SourceImage, 0, 0, $XCoord, $YCoord, $Width, $Height, $WidthSource, $HeightSource);
imagedestroy($SourceImage);
switch ($Type) {
case 1:
imagegif($TargetImage, $ThumbPath);
break;
case 2:
imagejpeg($TargetImage, $ThumbPath);
break;
case 3:
imagepng($TargetImage, $ThumbPath);
break;
}
imagedestroy($TargetImage);
}
catch (Exception $e) {
echo "Could not generate a thumnail for ".$TargetImage;
}
// die('</pre>foo');
}
/**
* Execute an sql statement and return the result.
*
* @param type $Sql
* @param type $IndexColumn
* @return type
*/
public function Get($Sql, $IndexColumn = FALSE) {
$R = $this->_Query($Sql, TRUE);
$Result = array();
while ($Row = mysql_fetch_assoc($R)) {
if ($IndexColumn)
$Result[$Row[$IndexColumn]] = $Row;
else
$Result[] = $Row;
}
return $Result;
}
public function GetCharacterSet($Table) {
// First get the collation for the database.
$Data = $this->Query("show table status like ':_{$Table}';");
if (!$Data)
return FALSE;
if ($StatusRow = mysql_fetch_assoc($Data))
$Collation = $StatusRow['Collation'];
else
return FALSE;
// Grab the character set from the database.
$Data = $this->Query("show collation like '$Collation'");
if (!$Data)
return FALSE;
if ($CollationRow = mysql_fetch_assoc($Data)) {
$CharacterSet = $CollationRow['Charset'];
return $CharacterSet;
}
return FALSE;
}
public function GetDatabasePrefixes() {
// Grab all of the tables.
$Data = $this->Query('show tables');
if ($Data === FALSE)
return array();
// Get the names in an array for easier parsing.
$Tables = array();