-
Notifications
You must be signed in to change notification settings - Fork 6
/
lib_intertext.php
executable file
·3109 lines (2998 loc) · 141 KB
/
lib_intertext.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 (c) 2010-2017 Pavel Vondřička ([email protected])
* Copyright (c) 2010-2017 Charles University in Prague, Faculty of Arts,
* Institute of the Czech National Corpus
*
* This file is part of InterText Server.
*
* InterText Server is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* InterText Server is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with InterText Server. If not, see <http://www.gnu.org/licenses/>.
*
*/
$ALSTAT = array('0'=>'open', '1'=>'finished', '2'=>'closed', '3'=>'blocked', '4'=>'remote editor');
$STATUS = array('1'=>'man','2'=>'auto','3'=>'plain');
$CHANGE = array('D'=>'deleted (in a merger)', 'X'=>'deleted and merged across parental border', 'M'=>'merged', 'S'=>'split', 'E'=>'edited', 'I'=>'inserted (by splitting)');
$CHANGE_ALIGN = array('S'=>'shift first element up', 'P'=>'pop last element down', 'U'=>'move text version up', 'D'=>'move text version down', 'M'=>'merge segments (move both versions up)', 'I'=>'insert segment (move both versions down)');
define('STATUS_MANUAL',1);
define('STATUS_AUTOMATIC',2);
define('STATUS_PLAIN',3);
define('ALSTAT_OPEN',0);
define('ALSTAT_FINISHED',1);
define('ALSTAT_CLOSED',2);
define('ALSTAT_BLOCKED',3);
define('ALSTAT_REMOTE',4);
if (!IsSet($LOG_ALIGN_CHANGES)) $LOG_ALIGN_CHANGES = false;
if (!IsSet($FORCE_SIMPLE_NUMBERING)) $FORCE_SIMPLE_NUMBERING = false;
if (!IsSet($DISABLE_FULLTEXT)) $DISABLE_FULLTEXT = false;
class InterText
{
var $DB;
var $auto_status_update = TRUE;
# Initialization (constructor)
function InterText () {
global $DB_SERVER,$DB_USER,$DB_PASSWORD,$DB_DATABASE,$DISABLE_FULLTEXT;
if (!$this->DB = @mysqli_connect($DB_SERVER,$DB_USER,$DB_PASSWORD,$DB_DATABASE))
$this->_fail("Cannot connect to database: ".mysqli_error($this->DB));
if (!mysqli_set_charset($this->DB,"utf8"))
$this->_fail("Cannot set encoding: ".mysqli_error($this->DB));
$this->autor = array();
if (!$DISABLE_FULLTEXT) {
if (!$dbresult = mysqli_query($this->DB,"SELECT VERSION()>5.5"))
die("Cannot access database: ".mysqli_error($this->DB));
$ret = mysqli_fetch_row($dbresult);
if (!$ret[0]) {
die("Failure: You need MySQL version >= 5.6 in order to use fulltext search in InterText >= 2.2 ! Either upgrade your MySQL or disable fulltext in config.php by adding '\$DISABLE_FULLTEXT = true;';\n");
}
}
}
# Fatal failure handling
function _fail ($message) {
die("Failure: $message\n");
}
# New failure handling
function _failure ($message) {
global $_ERROR;
$_ERROR = "$message\n";
mysqli_query($this->DB,"ROLLBACK");
#if (!$result = mysqli_query($this->DB,"ROLLBACK"))
#$_ERROR .= "Rollback failed as well: ".mysqli_error($this->DB)."\nThe database is corrupt now. Send this message to your administrator immediately and do not try to make any more changes!";
}
# Import new XML from file
function import_document($docname,$docversion,$filename,$text_elements,$debug=FALSE,$origfilename='',$validate=false) {
global $_ERROR;
global $txt_elements; # OK. this is just to avoid giving one more argument to parse_xml, a dirty lazy trick...
if ($origfilename=='') $origfilename = $filename;
$origfilename = preg_replace('/.*?([^\/]*)$/','\1',$origfilename);
if (preg_match('/^\s*$/',$docname)) {
$_ERROR = "Error: Invalid document name '$docname'.";
return FALSE;
}
if (preg_match('/^\s*$/',$docversion)) {
$_ERROR = "Error: Invalid version name '$docversion'.";
return FALSE;
}
$txtid = $this->register_text($docname);
if ($txtid===FALSE) {
return FALSE;
}
if ($this->txtver_info($txtid,$docversion)) {
$_ERROR = "Error: Document '$docname' version '$docversion' already exists in database.";
return FALSE;
}
$txt_elements = explode(' ',$text_elements);
//$_ERROR = "Error: Invalid XML document."; # just a default in case of failure when parsing
$_ERROR = '';
$xml = new XMLReader();
libxml_use_internal_errors(TRUE);
#if (!$xmldata=file_get_contents($filename)) {
# $_ERROR = "Error: Error opening input file.";
# return FALSE;
#}
#$xmldata = html_entity_decode($xmldata,ENT_QUOTES,'UTF-8'); # Latin1 only :-(
#if (!$xml->xml($xmldata)) {
if ($validate)
$libxmlflags = LIBXML_NOENT|LIBXML_DTDLOAD|LIBXML_DTDVALID;
else
$libxmlflags = LIBXML_NOENT|LIBXML_DTDLOAD;
if (!$xml->open($filename,NULL,$libxmlflags)) {
#if (!$xml->open($filename)) {
$_ERROR = "Error: Error reading XML.\n";
return FALSE;
}
if ($validate) {
$xml->setParserProperty(XMLReader::VALIDATE, true);
if (!$xml->isValid()) {
$_ERROR .= "Initial validation error.\n";
$arErrors = libxml_get_errors();
$xml_errors = "";
foreach ($arErrors AS $xmlError) $xml_errors .= $xmlError->message;
if ($xml_errors != "") {
$_ERROR .= "XML errors:\n".$xml_errors."\n";
}
return FALSE;
}
}
if (!$dbresult = mysqli_query($this->DB,"START TRANSACTION")) {
$this->_failure("Cannot start transaction: ".mysqli_error($this->DB));
return FALSE;
}
$root_id = $this->_insert_element($txtid,0,0,'NULL',1,'__DOCUMENT__',$docname.'.'.$docversion);
if ($root_id===FALSE)
return FALSE;
$verid = $this->insert_version($txtid,$docversion,$root_id,$text_elements,$origfilename);
if ($verid===FALSE)
return FALSE;
if (!$dbresult = mysqli_query($this->DB,"UPDATE `{$txtid}_elements` SET txtver_id='$verid' WHERE (id='$root_id')")) {
$this->_failure("Cannot access database: ".mysqli_error($this->DB));
return FALSE;
}
$stat = FALSE;
# XMLreader's error reporting is strange...let's just let the user choose...
if (!$debug) $ers = error_reporting(0);
$_ERROR = '';
if ($xml->read()) {
$stat = $this->parse_xml($xml,$root_id,$txtid,$verid,0,$debug,$validate); # and uses $txt_elements as a global variable/argument as well
} else $_ERROR .= "Error: Initial XML read failed.\n";
if (!$debug) $ers = error_reporting($ers);
$xml->close();
if (!$stat) {
$arErrors = libxml_get_errors();
$xml_errors = "";
foreach ($arErrors AS $xmlError) $xml_errors .= $xmlError->message;
if ($xml_errors != "") {
$_ERROR .= "XML errors:\n".$xml_errors."\n";
}
$this->delete_document($txtid,$verid);
return FALSE;
} else {
if (!$dbresult = mysqli_query($this->DB,"COMMIT")) {
$this->_failure("Cannot commit transaction: ".mysqli_error($this->DB));
return FALSE;
}
}
$_ERROR = '';
# Check existence of IDs on text elements
foreach($txt_elements as $element) { $ealignables[]="e.element_name='$element'"; $ialignables[]="i.element_name='$element'"; }
$ealignable = join(' OR ',$ealignables); $ialignable = join(' OR ',$ialignables);
$query="SELECT e.id FROM `{$txtid}_elements` e WHERE txtver_id=$verid AND ($ealignable) AND TRIM(element_id)=''";
if (!$dbresult = mysqli_query($this->DB,$query))
$this->_fail("Cannot check database: ".mysqli_error($this->DB)." Query: $query\n");
if (!mysqli_num_rows($dbresult)) {
# Check uniqueness of IDs on text elements
$query="SELECT e.id FROM `{$txtid}_elements` e, `{$txtid}_elements` i WHERE e.txtver_id=$verid AND i.txtver_id=$verid AND ($ealignable) AND ($ialignable) AND e.element_id=i.element_id AND e.id!=i.id";
if (!$dbresult = mysqli_query($this->DB,$query))
$this->_fail("Cannot check database: ".mysqli_error($this->DB)." Query: $query\n");
if (!mysqli_num_rows($dbresult)) $this->set_uniq_ids($txtid,$verid,true);
}
return TRUE;
}
# Update document from file
function update_document($docname,$docversion,$filename,$userid=0,$verbose=true,$validate=false) {
global $_ERROR;
$_ERROR = '';
$txtid = $this->text_id_by_name($docname);
if (!$txtid) {
$_ERROR = "Error: Document '$docname' not found in database.";
return FALSE;
}
$ver = $this->txtver_info($txtid,$docversion);
if (!$ver) {
$_ERROR = "Error: Version '$docversion' not found in database.";
return FALSE;
}
$txt_elements = explode(' ',$ver['text_elements']);
$_ERROR = "Error: Invalid XML document."; # just a default in case of failure when parsing
$xml = new XMLReader();
libxml_use_internal_errors(TRUE);
if ($validate)
$libxmlflags = LIBXML_NOENT|LIBXML_DTDLOAD|LIBXML_DTDVALID;
else
$libxmlflags = LIBXML_NOENT;
if (!$xml->open($filename,NULL,$validate)) {
$_ERROR = "Error: Error reading XML.";
return FALSE;
}
if ($validate) {
$xml->setParserProperty(XMLReader::VALIDATE, true);
if (!$xml->isValid()) {
$_ERROR .= "Initial validation error.\n";
$arErrors = libxml_get_errors();
$xml_errors = "";
foreach ($arErrors AS $xmlError) $xml_errors .= $xmlError->message;
if ($xml_errors != "") {
$_ERROR .= "XML errors:\n".$xml_errors."\n";
}
return FALSE;
}
}
$stat = FALSE;
# XMLreader's error reporting is strange...let's just let the user choose...
if (!$verbose) $ers = error_reporting(0);
if ($xml->read()) {
$stat = $this->parse_xml_update($xml,$txtid,$ver['id'],$txt_elements,$userid,$verbose,$validate);
} else $_ERROR = "Error: Invalid XML file!";
if (!$stat) {
$arErrors = libxml_get_errors();
$xml_errors = "";
foreach ($arErrors AS $xmlError) $xml_errors .= $xmlError->message;
if ($xml_errors != "") {
$_ERROR .= "XML errors:\n".$xml_errors."\n";
}
}
if (!$verbose) $ers = error_reporting($ers);
$xml->close();
return $stat;
}
# Export document
function export_document($txt,$id,$cor_aid=0,$format='xml',$maxcor_stat=STATUS_AUTOMATIC) {
global $_ERROR;
$segs = false;
list($format,$idformat) = explode(':',$format,2);
if ($format=='segs') $segs=true;
elseif ($format=='xml' || $format=='orig') $cor_aid=0;
elseif ($format!='corresp') {
$_ERROR = "Error: Unknown format.";
return FALSE;
}
$txtver = $this->txtver_by_id($id);
if (!$txtver['uniq_ids']) { $this->update_eids($txt,$txtver['id']); $txtver = $this->txtver_by_id($id); }
if (!$txtver['uniq_ids']) {
$_ERROR = "ERROR: Renumbering IDs failed!";
return FALSE;
}
$corr=array(); $seg=array();
if ($cor_aid) {
$al = $this->alignment_info($cor_aid);
if (!$al) {
$_ERROR = "Error: Alignment for correspondence attributes not found.";
return FALSE;
}
if (!$al['v1uniq_ids']) { $this->update_eids($txt,$al['ver1_id']); $al = $this->alignment_info($cor_aid); }
if (!$al['v2uniq_ids']) { $this->update_eids($txt,$al['ver1_id']); $al = $this->alignment_info($cor_aid); }
if (!$al['v1uniq_ids'] OR !$al['v2uniq_ids']) {
$_ERROR = "ERROR: Renumbering IDs failed!";
return FALSE;
}
}
if ($segs) {
$query = "SELECT e.id as id, l.position as pos FROM `{$txt}_elements` e, `{$txt}_links` l WHERE e.txtver_id=$id AND l.alignment_id=$cor_aid AND l.element_id=e.id ORDER BY e.txt_position";
if (!$dbresult = mysqli_query($this->DB,$query))
$this->_fail("Cannot access database: ".mysqli_error($this->DB));
while ($ret = mysqli_fetch_assoc($dbresult)) { $seg[$ret['id']] = $ret['pos']; $lastid=$ret['id']; }
$res = $this->alignment_info($cor_aid);
$maxpos = $res['link_count'];
$cor_aid = 0;
} elseif ($cor_aid) {
$query = "SELECT e.id, GROUP_CONCAT(c.element_id ORDER BY c.txt_position SEPARATOR ' ') as corresp, l1.position as pos FROM `{$txt}_elements` e, `{$txt}_links` l1, `{$txt}_links` l2, `{$txt}_elements` c WHERE e.txtver_id=$id AND l1.element_id=e.id AND l1.alignment_id=$cor_aid AND l2.alignment_id=$cor_aid AND l2.version_id!=$id AND l1.status <= $maxcor_stat AND l2.position=l1.position AND c.id=l2.element_id GROUP BY e.id ORDER BY e.txt_position";
if (!$dbresult = mysqli_query($this->DB,$query))
$this->_fail("Cannot access database: ".mysqli_error($this->DB));
while ($ret = mysqli_fetch_assoc($dbresult)) $corr[$ret['id']] = $ret['corresp'];
}
$out = format_exported_header($txtver['text_name'],$txtver['version_name'],$format,$idformat);
#$out.= $this->element_to_xml($txtver['root_id'],$corr);
$query = "SELECT * FROM `{$txt}_elements` WHERE txtver_id=$id ORDER BY txt_position";
if (!$dbresult = mysqli_query($this->DB,$query))
$this->_fail("Cannot read database: ".mysqli_error($this->DB));
$openel=array(); $close=FALSE; $pos=0; $openseg=false;
$alignables = explode(' ',$txtver['text_elements']);
while ($e = mysqli_fetch_assoc($dbresult)) {
while (count($openel) AND $e['parent']!=$openel[count($openel)-1]['id']) {
$lastel=array_pop($openel);
# Close open SEG - NO! ParaConc does not understand it, the output must break XML validity for PC compatibility!
#if ($segs && $openseg) { $out.="</seg>\n"; $openseg=false; }
if ($e['txt_position']==$lastel['txt_position']+1) $out.="/>";
else $out.="</{$lastel['element_name']}>";
$close=FALSE;
}
if ($close) $out.='>'; $close=FALSE;
$e['element_id'] = format_exported_ids($e['element_name'],$e['element_id'],$txtver['text_name'],$txtver['version_name'],$format,$idformat,$txtver['filename']);
if ($e['element_id']!='') {
$e['attributes'] = preg_replace('/\s*id="[^"]*"/','',$e['attributes']);
$e['attributes'] = ' id="'.$e['element_id'].'"'.$e['attributes'];
}
$corresp = $corr[$e['id']];
if (!$corresp) { $corresp='0'; }
$alignable = in_array($e['element_name'],$alignables);
$e['attributes'] = preg_replace('/\s*corresp="[^"]*"/','',$e['attributes']);
if ($cor_aid AND $alignable) {
$e['attributes'].= " corresp=\"$corresp\"";
}
# SEGment start
if ($segs && $alignable && ($seg[$e['id']]!=$pos || !$openseg)) {
if ($openseg) $out.="</seg>\n";
while ($pos<$seg[$e['id']]-1) { $pos++; $out.="<seg id=\"$pos\"></seg>\n"; }
$pos=$seg[$e['id']];
$out.="<seg id=\"$pos\">\n";
$openseg=true;
}
if (substr($e['element_name'],0,2)!='__') {
if ($e['contents']!='') $out.="<{$e['element_name']}{$e['attributes']}>".$e['contents']."</{$e['element_name']}>";
else {
$out.="<{$e['element_name']}{$e['attributes']}";
$openel[] = $e; $close=TRUE;
}
# Fill the rest of empty SEGments after the last element
if ($e['id']==$lastid && $pos<$maxpos) {
$out.="</seg>\n"; $openseg = false;
while ($pos<$maxpos) { $pos++; $out.="<seg id=\"$pos\"></seg>\n"; }
}
}
elseif ($e['element_name']=='__TEXT__' || $e['element_name']=='__WS__')
$out.=$e['contents'];
elseif ($e['element_name']=='__COMMENT__')
$out.='<!--'.$e['contents'].'-->';
elseif (substr($e['element_name'],0,6)=='__PI__') {
list($tmp,$name) = explode(':',$e['element_name'],2);
$out.="<?$name ".$e['contents'].'?>';
}
}
while (count($openel)) {
$lastel=array_pop($openel);
$out.="</{$lastel['element_name']}>";
}
return $out."\n";
}
# Print element (subtree) as XML
function element_to_xml($txt,$id,$corr=array()) {
$e = $this->get_element($txt,$id);
if ($e['element_id']!='') $e['attributes'] = " id=\"{$e['element_id']}\"".$e['attributes'];
$corresp = $corr[$e['id']];
if ($corresp) {
$e['attributes'] = preg_replace('/\s*corresp="[^"]*"/','',$e['attributes']);
$e['attributes'].= " corresp=\"$corresp\"";
}
if (substr($e['element_name'],0,2)!='__') {
if (count($e['children'])) {
$out.="<{$e['element_name']}{$e['attributes']}>";
foreach($e['children'] as $id) $out.=$this->element_to_xml($txt,$id,$corr);
$out.="</{$e['element_name']}>";
}
elseif ($e['contents']!='')
$out.="<{$e['element_name']}{$e['attributes']}>".$e['contents']."</{$e['element_name']}>";
else
$out.="<{$e['element_name']}{$e['attributes']}/>";
}
elseif ($e['element_name']=='__DOCUMENT__')
foreach($e['children'] as $id) $out.=$this->element_to_xml($txt,$id,$corr);
elseif ($e['element_name']=='__TEXT__' || $e['element_name']=='__WS__')
$out.=$e['contents'];
elseif ($e['element_name']=='__COMMENT__')
$out.="<!--".$e['contents'].'-->';
elseif (substr($e['element_name'],0,6)=='__PI__') {
list($tmp,$name) = explode(':',$e['element_name'],2);
$out.="<?$name ".$e['contents'].' ?>';
}
return $out;
}
# Import alignment
function import_alignment($data,$aid,$default_status=STATUS_MANUAL,$report=TRUE,$ignoreheader=FALSE,$method='',$profile='',$resp=0, $editor=0,$edit='',$swap=false) {
global $STATUS,$_ERROR,$DEFAULT_METHOD,$DEFAULT_PROFILE,$DEFAULT_EDIT_PERMISSION;
if ($method=='') $method = $DEFAULT_METHOD;
if ($profile=='') $profile = $DEFAULT_PROFILE;
if ($edit=='') $edit = $DEFAULT_EDIT_PERMISSION;
if ($aid>0) {
$al = $this->alignment_info($aid);
$txt = $al['text_id'];
$v1_id = $al['ver1_id']; $v2_id = $al['ver2_id'];
if (!$al) { $_ERROR = "Error: Alignment not found."; return FALSE; }
if (!$al['v1uniq_ids']) { $this->update_eids($txt,$v1_id); $al = $this->alignment_info($aid); }
if (!$al['v2uniq_ids']) { $this->update_eids($txt,$v2_id); $al = $this->alignment_info($aid); }
if (!$al['v1uniq_ids'] OR !$al['v2uniq_ids']) { $_ERROR = "Error: Cannot update IDs."; return FALSE; }
}
if ($report) { print("Process: Initializing import...\nProgress: 0\n"); flush(); ob_flush(); }
if (substr($data,0,5)!='<?xml')
$data = file_get_contents($data);
$total = substr_count($data,'<link '); if (!$total) $total = substr_count($data,'<LINK ');
if (!$total) {
if ($report) { print("Process: Initializing import...<br />ERROR: No links found in file!\n"); flush(); ob_flush(); }
$_ERROR .= "Error: No links found in file!";
return FALSE;
}
$xml = new XMLReader();
$xml->xml($data);
//$xml->open($filename);
while ($xml->name!='linkGrp') {
$step=@$xml->read();
if (!$step) {
if ($report) { print("Process: Initializing import...<br />ERROR: Invalid XML file!\n"); flush(); ob_flush(); }
$xml->close();
$_ERROR = 'Error: Invalid XML file.';
return FALSE;
}
}
while ($xml->moveToNextAttribute()) {
if ($xml->name=='fromDoc') $src = $xml->value;
if ($xml->name=='toDoc') $dst = $xml->value;
}
if ($swap) {
$temp=$src; $src=$dst; $dst=$temp;
}
list($text,$ver1) = explode('.',$src,3);
list($textd,$ver2) = explode('.',$dst,3);
if ($aid) {
$myal = false;
$al = $this->alignment_info($aid);
$txt = $al['text_id'];
$swap=false;
if (!$ignoreheader) {
if ($src==$al['ver1_filename'] && $dst==$al['ver2_filename']) { # filenames match, OK!
} elseif ($src==$al['ver2_filename'] && $dst==$al['ver1_filename']) { #... just swap...
$swap=true;
} else { # check for <text_name>.<version_name>.<anything>
if ($text!=$textd OR $text!=$al['text_name']) {
if ($report) { print("Process: Initializing import...<br />ERROR: Alignment file links completely different texts!?\n"); flush(); ob_flush(); }
$xml->close();
$_ERROR = "Error: Alignment file concerns other document than requested: '$text' and '$textd'. Requested: '{$al['text_name']}'";
return FALSE;
}
if ($ver1!=$al['ver1_name']) {
if ($ver1==$al['ver2_name']) $swap=true;
else {
if ($report)
{ print("Process: Initializing import...<br />ERROR: Alignment links different text versions!\n"); flush(); ob_flush(); }
$xml->close();
$_ERROR = 'Error: Alignment links other versions than those requested.';
return FALSE;
}
}
if ($ver2!=$al['ver2_name'] AND ($swap AND $ver2!=$al['ver1_name'])) {
if ($report) { print("Process: Initializing import...<br/>ERROR: Alignment links different text versions!\n"); flush(); ob_flush(); }
$xml->close();
$_ERROR = 'Error: Alignment links other versions than those requested.';
return FALSE;
}
}
}
} else {
if (!($v1=$this->txtver_by_filename($src)) || !($v2=$this->txtver_by_filename($dst))) {
if ($text!=$textd) {
$_ERROR = 'Error: Alignment links different documents. Correct the toDoc and srcDoc attributes of the linkGrp element.';
return FALSE;
}
if (!($txtid=$this->text_id_by_name($text))) {
$_ERROR = "Error: Document '$text' not found in the database.";
return FALSE;
}
if (!($v1=$this->txtver_info($txtid,$ver1))) {
$_ERROR = "Error: Version '$ver1' not found in the database.";
return FALSE;
}
if (!($v2=$this->txtver_info($txtid,$ver2))) {
$_ERROR = "Error: Version '$ver2' not found in the database.";
return FALSE;
}
} else {
$txtid = $v1['text_id'];
}
$aid = $this->insert_alignment($txtid,$v1['id'],$v2['id'],$method,$profile,$resp,$editor,$edit);
if (!$aid) {
$_ERROR = "Error: Such alignment already exists.";
return FALSE;
} else $myal = true;
$al = $this->alignment_info($aid);
$txt = $al['text_id'];
}
if (!$dbresult = mysqli_query($this->DB,"START TRANSACTION")) {
$this->_failure("Cannot start transaction: ".mysqli_error($this->DB));
return FALSE;
}
$v1i = $this->txtver_by_id($al['ver1_id']); $v2i = $this->txtver_by_id($al['ver2_id']);
foreach(explode(' ',$v1i['text_elements']) as $element) $alignables1[]="element_name='$element'";
foreach(explode(' ',$v2i['text_elements']) as $element) $alignables2[]="element_name='$element'";
$alignable1 = join(' OR ',$alignables1);
$alignable2 = join(' OR ',$alignables2);
$v1idx=array(); $v2idx=array();$v1list=array(); $v2list=array();
if (!$dbresult = mysqli_query($this->DB,"SELECT id,element_id FROM `{$txt}_elements` WHERE (txtver_id='{$al['ver1_id']}' AND ($alignable1)) ORDER BY txt_position")) {
$this->_failure("Cannot access database: ".mysqli_error($this->DB));
if ($report) print("$_ERROR\n");
return FALSE;
}
while ($ret = mysqli_fetch_assoc($dbresult)) { $v1idx[$ret['element_id']]= $ret['id']; $v1list[]= $ret['element_id']; }
if (!$dbresult = mysqli_query($this->DB,"SELECT id,element_id FROM `{$txt}_elements` WHERE (txtver_id='{$al['ver2_id']}' AND ($alignable2)) ORDER BY txt_position")) {
$this->_failure("Cannot access database: ".mysqli_error($this->DB));
if ($report) print("$_ERROR\n");
return FALSE;
}
while ($ret = mysqli_fetch_assoc($dbresult)) { $v2idx[$ret['element_id']]= $ret['id']; $v2list[]= $ret['element_id']; }
$position = 0;
if ($report) { print("Process: Importing alignment from file...\nProgress: 0\n"); flush(); ob_flush(); }
while (@$xml->read()) {
$status = FALSE;
if ($xml->name=='link') {
$cnt++; $prog=round(($cnt/$total)*100);
if ($report AND $prog!=$lastprog) { $lastprog=$prog; print "Progress: $prog\n"; flush(); ob_flush(); }
while ($xml->moveToNextAttribute()) {
if ($xml->name=='xtargets') $link = $xml->value;
if ($xml->name=='status') $status = array_search($xml->value,$STATUS);
if ($xml->name=='mark') $mark = $xml->value; else $mark=0;
if ($xml->name=='type') $type = $xml->value;
}
if (!$status) $status = $default_status;
if ($swap) {
list($v1_grp,$v2_grp) = explode(';',$link);
list($cnt1,$cnt2) = explode('-',$type);
} else {
list($v2_grp,$v1_grp) = explode(';',$link);
list($cnt2,$cnt1) = explode('-',$type);
}
if (intval($cnt1)==0) $v1_eids = array(); else $v1_eids = explode(' ',$v1_grp);
if (intval($cnt2)==0) $v2_eids = array(); else $v2_eids = explode(' ',$v2_grp);
# Get database IDs by element IDs
$v1_ids = array(); $v2_ids = array();
foreach ($v1_eids as $eid) {
if (preg_match('/([0-9]+([\.:\-_,][0-9]+)?)$/',$eid,$m)) {
$eid = strtr($m[1],'.:-_,',':::::');
if (!array_key_exists($eid,$v1idx)) {
if ($report) { print "Process: Importing alignment from file...<br />ERROR: Element '$eid' not found in text version '{$al['ver1_name']}'! (at link #$cnt)\n"; flush(); ob_flush(); }
$xml->close();
$this->_failure("Error: Element '$eid' not found in text version '{$al['ver1_name']}'! (at link #$cnt)");
if ($myal) $this->delete_alignment($aid);
return FALSE;
}
$mydbid = $v1idx[$eid];
$nextid = array_shift($v1list);
if ($eid==$nextid) {
$v1_ids[] = $mydbid; $last1id = $eid;
} else {
if ($report) { print "Process: Importing alignment from file...<br />ERROR: Gap found in the alignment. In text version '{$al['ver1_name']}', there are alignable elements between the element '$last1id' and '$eid' which are not aligned by the imported alignment! (at link #$cnt)\n"; flush(); ob_flush(); }
$xml->close();
$this->_failure("Error: Gap found in the alignment. In text version '{$al['ver1_name']}', there are alignable elements between the element '$last1id' and '$eid' which are not aligned by the imported alignment! (at link #$cnt) e.g. '$nextid' but '$eid'");
if ($myal) $this->delete_alignment($aid);
return FALSE;
}
} elseif ($eid!='') {
if ($report) { print "Process: Importing alignment from file...<br />ERROR: Unrecognized format of identificator '$eid' for text version '{$ver1}'! (at link #$cnt)\n"; flush(); ob_flush(); }
$xml->close();
$this->_failure("Error: Unrecognized format of identificator '$eid' for text version '{$ver1}'! (at link #$cnt)");
if ($myal) $this->delete_alignment($aid);
return FALSE;
}
}
foreach ($v2_eids as $eid) {
if (preg_match('/([0-9]+([\.:\-_,][0-9]+)?)$/',$eid,$m)) {
$eid = strtr($m[1],'.:-_,',':::::');
if (!array_key_exists($eid,$v2idx)) {
if ($report) { print "Process: Importing alignment from file...<br />ERROR: Element '$eid' not found in text version '{$al['ver2_name']}'! (at link #$cnt)\n"; flush(); ob_flush(); }
$xml->close();
$this->_failure("Error: Element '$eid' not found in text version '{$al['ver2_name']}'! (at link #$cnt)");
if ($myal) $this->delete_alignment($aid);
return FALSE;
}
$mydbid = $v2idx[$eid];
$nextid = array_shift($v2list);
if ($eid==$nextid) {
$v2_ids[] = $mydbid; $last2id = $eid;
} else {
if ($report) { print "Process: Importing alignment from file...<br />ERROR: Gap found in the alignment. In text version '{$al['ver2_name']}', there are alignable elements between the element '$last2id' and '$eid' which are not aligned by the imported alignment! (at link #$cnt)\n"; flush(); ob_flush(); }
$xml->close();
$this->_failure("Error: Gap found in the alignment. In text version '{$al['ver2_name']}', there are alignable elements between the element '$last2id' and '$eid' which are not aligned by the imported alignment! (at link #$cnt)");
if ($myal) $this->delete_alignment($aid);
return FALSE;
}
} elseif ($eid!='') {
if ($report) { print "Process: Importing alignment from file...<br />ERROR: Unrecognized format of identificator '$eid' for text version '{$ver2}'! (at link #$cnt)\n"; flush(); ob_flush(); }
$xml->close();
$this->_failure("Error: Unrecognized format of identificator '$eid' for text version '{$ver2}'! (at link #$cnt)");
if ($myal) $this->delete_alignment($aid);
return FALSE;
}
}
$position++;
if (!$this->_add_link($txt,$aid,$al['ver1_id'],$al['ver2_id'],$v1_ids,$v2_ids,$position,$status,$mark)) {
$xml->close();
if ($report) print("Process: Importing alignment from file...<br/>$_ERROR\n");
if ($myal) $this->delete_alignment($aid);
return FALSE;
}
}
}
if ($xml->nodeType) {
if ($report) { print("Process: Importing alignment from file...<br/>ERROR: Invalid XML file!\n"); flush(); ob_flush(); }
$xml->close();
$this->_failure('Error: Invalid XML file.');
if ($myal) $this->delete_alignment($aid);
return FALSE;
}
$xml->close();
if (!$dbresult = mysqli_query($this->DB,"COMMIT")) {
$this->_failure("Cannot commit transaction: ".mysqli_error($this->DB));
if ($report) print("$_ERROR\n");
return FALSE;
}
return $aid;
}
# Export alignment
function export_alignment($aid,$format='xml',$skipempty=false,$maxstatus=STATUS_PLAIN) {
global $STATUS, $_ERROR;
$al = $this->alignment_info($aid);
if (!$al) { $_ERROR = "Error: Alignment not found."; return FALSE; }
$txt = $al['text_id'];
$v1_id = $al['ver1_id']; $v2_id = $al['ver2_id'];
if (!$al['v1uniq_ids']) { $this->update_eids($txt,$v1_id); $al = $this->alignment_info($aid); }
if (!$al['v2uniq_ids']) { $this->update_eids($txt,$v2_id); $al = $this->alignment_info($aid); }
if (!$al['v1uniq_ids'] OR !$al['v2uniq_ids']) { $_ERROR = "Error: Cannot update IDs."; return FALSE; }
list($format,$idformat) = explode(':',$format,2);
if ($format=='xml' || $format=='xml_links') {
$out = "<?xml version='1.0' encoding='utf-8'?>\n";
$out.= "<linkGrp toDoc='{$al['text_name']}.{$al['ver2_name']}.xml' fromDoc='{$al['text_name']}.{$al['ver1_name']}.xml'>\n";
$from=1;
do {
$res = $this->get_aligned_items($txt,$aid,$from,200,$maxstatus);
foreach ($res as $pos => $row) {
$v1ids=array(); $v2ids=array(); $stat = 0; $maxmark = 0;
$v1c = 0; $v2c = 0;
if (IsSet($row[$v1_id])) {
$v1c=count($row[$v1_id]);
foreach ($row[$v1_id] as $item) {
$v1ids[]= format_exported_ids('_alignable_',$item['element_id'],$al['text_name'],$al['ver1_name'],$format,$idformat);
if ($item['link_status']>$stat) $stat = $item['link_status'];
if ($item['link_mark']>$maxmark) $maxmark = $item['link_mark'];
}
}
if (IsSet($row[$v2_id])) {
$v2c=count($row[$v2_id]);
foreach ($row[$v2_id] as $item) {
$v2ids[]= format_exported_ids('_alignable_',$item['element_id'],$al['text_name'],$al['ver2_name'],$format,$idformat);
if ($item['link_status']>$stat) $stat = $item['link_status'];
if ($item['link_mark']>$maxmark) $maxmark = $item['link_mark'];
}
}
if ($skipempty && $v1c==0 && $v2c==0) continue;
if ($maxmark) $mark=" mark='{$maxmark}'"; else $mark='';
natsort($v1ids); natsort($v2ids);
$v1l = join(' ',$v1ids); $v2l = join(' ',$v2ids);
$out.= "<link type='$v2c-$v1c' xtargets='$v2l;$v1l' status='{$STATUS[$stat]}'$mark/>\n";
}
$from=$from+200;
} while ($from<=$al['link_count']);
$out.= "</linkGrp>\n";
} else {
$_ERROR = "Error: Unknown format.";
return FALSE;
}
return $out;
}
# Add new aligenment link - no checking
function _add_link($txt,$aid,$v1_id,$v2_id,$v1_eids,$v2_eids,$position,$status=STATUS_MANUAL,$mark=0) {
# Insert link items
foreach ($v1_eids as $id) {
if ($this->_new_link_item($txt,$aid,$v1_id,$id,$position,$status,$mark)===FALSE)
return FALSE;
}
foreach ($v2_eids as $id) {
if ($this->_new_link_item($txt,$aid,$v2_id,$id,$position,$status,$mark)===FALSE)
return FALSE;
}
return TRUE;
}
# Plain alignment 1:1
function plain_alignment($aid,$report=TRUE) {
if ($report) { print "Process: Prepairing plain alignment...\nProgress: 0\n"; flush(); ob_flush(); }
$al = $this->alignment_info($aid);
$txt = $al['text_id'];
$v1 = $al['ver1_id']; $v2 = $al['ver2_id'];
$v1i = $this->txtver_by_id($v1); $v2i = $this->txtver_by_id($v2);
foreach(explode(' ',$v1i['text_elements']) as $element) $alignables1[]="element_name='$element'";
foreach(explode(' ',$v2i['text_elements']) as $element) $alignables2[]="element_name='$element'";
$alignable1 = join(' OR ',$alignables1);
$alignable2 = join(' OR ',$alignables2);
# CHECK TABLE accelerates the query in our version of MySQL by multiple orders!
mysqli_query($this->DB,"CHECK TABLE `{$txt}_links`");
if (!$dbresult = mysqli_query($this->DB,"START TRANSACTION")) {
$this->_failure("Cannot start transaction: ".mysqli_error($this->DB));
return FALSE;
}
# Get list of unaligned elements from text version 1
if (!$dbresult = mysqli_query($this->DB,"SELECT id FROM `{$txt}_elements` WHERE (txtver_id='$v1' AND ($alignable1) AND id NOT IN (SELECT element_id FROM `{$txt}_links` WHERE alignment_id='$aid' AND version_id='$v1')) ORDER BY txt_position")) {
$this->_failure("Cannot access database: ".mysqli_error($this->DB));
return FALSE;
}
$v1_ids = array(); $v2_ids = array();
if (mysqli_num_rows($dbresult))
while ($ret = mysqli_fetch_assoc($dbresult)) $v1_ids[]=$ret['id'];
# Get list of unaligned elements from text version 2
if (!$dbresult = mysqli_query($this->DB,"SELECT id FROM `{$txt}_elements` WHERE (txtver_id='$v2' AND ($alignable2) AND id NOT IN (SELECT element_id FROM `{$txt}_links` WHERE alignment_id='$aid' AND version_id='$v2')) ORDER BY txt_position")) {
$this->_failure("Cannot access database: ".mysqli_error($this->DB));
return FALSE;
}
if (mysqli_num_rows($dbresult))
while ($ret = mysqli_fetch_assoc($dbresult)) $v2_ids[]=$ret['id'];
# Nothing more to do here? ...return
if (count($v1_ids)==0 AND count($v2_ids)==0) {
if ($report) { print "Process: Nothing to align.\n"; flush(); ob_flush(); }
if (!$dbresult = mysqli_query($this->DB,"COMMIT")) {
$this->_failure("Cannot commit transaction: ".mysqli_error($this->DB)); // Is this a problem...?
}
return TRUE;
}
# Otherwise align the rest 1:1
# first: get the position of the last alignment link
if (!$dbresult = mysqli_query($this->DB,"SELECT max(position) as last FROM `{$txt}_links` WHERE (alignment_id='$aid')")) {
$this->_failure("Cannot access database: ".mysqli_error($this->DB));
return FALSE;
}
if (!mysqli_num_rows($dbresult)) $position=0;
else {
$ret = mysqli_fetch_assoc($dbresult);
$position = $ret['last'];
}
# Align 1:1 while there are unaligned elements from text version 1
$total = count($v1_ids); if (count($v2_ids)>$total) $total=count($v2_ids); $cnt=0;
if ($report) { print "Process: Aligning unaligned elements...\nProgress: 0\n"; flush(); ob_flush(); }
while ($e1=array_shift($v1_ids)) {
$position++; $cnt++; $prog=round(($cnt/$total)*100);
if ($e2=array_shift($v2_ids)) $el2arr = array($e2); else $el2arr = array();
if (!$this->_add_link($txt,$aid,$v1,$v2,array($e1),$el2arr,$position,STATUS_PLAIN))
return FALSE;
if ($report AND $prog!=$lastprog) { $lastprog=$prog; print "Progress: $prog\n"; flush(); ob_flush(); }
}
# Align 0:1 if there are any unaligned elements left from text version 2
while ($e2=array_shift($v2_ids)) {
$position++; $cnt++; $prog=round(($cnt/$total)*100);
if (!$this->_add_link($txt,$aid,$v1,$v2,array(),array($e2),$position,STATUS_PLAIN))
return FALSE;
if ($report AND $prog!=$lastprog) { $lastprog=$prog; print "Progress: $prog\n"; flush(); ob_flush(); }
}
if (!$dbresult = mysqli_query($this->DB,"COMMIT")) {
$this->_failure("Cannot commit transaction: ".mysqli_error($this->DB));
return FALSE;
}
return TRUE;
}
# Delete document from database
function delete_document($txt,$id) {
$txtver = $this->txtver_by_id($id);
if (!$dbresult = mysqli_query($this->DB,"SELECT id FROM alignments WHERE (ver1_id=$id OR ver2_id=$id)"))
$this->_fail("Cannot access database: ".mysqli_error($this->DB));
if (mysqli_num_rows($dbresult))
$this->_fail("Cannot delete document - it is used by one or more alignments!");
# Now delete the record for the version
if (!$dbresult = mysqli_query($this->DB,"DELETE FROM `{$txt}_elements` WHERE (txtver_id=$id)"))
$this->_fail("Cannot access database: ".mysqli_error($this->DB));
if (!$dbresult = mysqli_query($this->DB,"DELETE FROM `{$txt}_changelog` WHERE (txtver_id=$id)"))
$this->_fail("Cannot access database: ".mysqli_error($this->DB));
if (!$dbresult = mysqli_query($this->DB,"DELETE FROM versions WHERE (text_id=$txt AND id=$id)"))
$this->_fail("Cannot access database: ".mysqli_error($this->DB));
# Any more versions of this text? If not, delete the text record too
if (!$dbresult = mysqli_query($this->DB,"SELECT id FROM versions WHERE text_id=$txt"))
$this->_fail("Cannot access database: ".mysqli_error($this->DB));
if (!mysqli_num_rows($dbresult)) {
if (!$dbresult = mysqli_query($this->DB,"DELETE FROM texts WHERE id=$txt"))
$this->_fail("Cannot access database: ".mysqli_error($this->DB));
if (!$dbresult = mysqli_query($this->DB,"DROP TABLE `{$txt}_elements`, `{$txt}_links`, `{$txt}_changelog`"))
$this->_fail("Cannot access database: ".mysqli_error($this->DB));
if (!$dbresult = mysqli_query($this->DB,"DROP TABLE IF EXISTS `{$txt}_align_changelog`"))
$this->_fail("Cannot access database: ".mysqli_error($this->DB));
}
}
# Get info about document version by name
function txtver_info($txt,$version) {
#$txtid = $this->text_id_by_name($name);
$version = mysqli_real_escape_string($this->DB,$version);
if (!$dbresult = mysqli_query($this->DB,"SELECT * FROM versions WHERE text_id=$txt AND version_name='$version'"))
return FALSE; #$this->_fail("Cannot access database: ".mysqli_error($this->DB));
if (!mysqli_num_rows($dbresult))
return FALSE;
else {
$res = mysqli_fetch_assoc($dbresult);
return $res;
}
}
# Get info about document version by filename
function txtver_by_filename($filename) {
#$txtid = $this->text_id_by_name($name);
$filename = mysqli_real_escape_string($this->DB,$filename);
if (!$dbresult = mysqli_query($this->DB,"SELECT * FROM versions WHERE filename='$filename'"))
return FALSE; #$this->_fail("Cannot access database: ".mysqli_error($this->DB));
if (!mysqli_num_rows($dbresult))
return FALSE;
else {
$res = mysqli_fetch_assoc($dbresult);
return $res;
}
}
# Get info about document version by its id
function txtver_by_id($id) {
$txt = mysqli_real_escape_string($this->DB,$txt);
if (!$dbresult = mysqli_query($this->DB,"SELECT v.*, t.name as text_name, t.id as text_id FROM versions v, texts t WHERE v.text_id=t.id AND v.id='$id'")) {
$this->_failure("Cannot access database: ".mysqli_error($this->DB));
return FALSE;
}
if (!mysqli_num_rows($dbresult)) {
$this->_failure("Document not found.");
return FALSE;
} else {
$res = mysqli_fetch_assoc($dbresult);
return $res;
}
}
# Get info about alignment
function alignment_info($id) {
if (!$dbresult = mysqli_query($this->DB,"SELECT a.*, t.name as text_name, t.id as text_id, v1.version_name as ver1_name, v1.id as ver1_id, v1.filename as ver1_filename, v2.version_name as ver2_name, v2.id as ver2_id, v2.filename as ver2_filename, v1.uniq_ids as v1uniq_ids, v2.uniq_ids as v2uniq_ids FROM alignments as a, texts as t, versions as v1, versions as v2 WHERE a.id=$id AND t.id=v1.text_id AND v1.id=a.ver1_id AND v2.id=a.ver2_id"))
$this->_fail("Cannot access database: ".mysqli_error($this->DB));
if (!mysqli_num_rows($dbresult))
return FALSE;
else {
$res = mysqli_fetch_assoc($dbresult);
if (!$dbresult = mysqli_query($this->DB,"SELECT max(position) as link_count FROM `{$res['text_id']}_links` WHERE alignment_id=$id"))
$this->_fail("Cannot access database: ".mysqli_error($this->DB));
$res1 = mysqli_fetch_assoc($dbresult);
$res['link_count'] = $res1['link_count'];
if (!$dbresult = mysqli_query($this->DB,"SHOW TABLES LIKE '{$res['text_id']}_align_changelog'"))
$this->_fail("Cannot access database: ".mysqli_error($this->DB));
if (mysqli_num_rows($dbresult)>0)
$res['alchangelog'] = true;
else
$res['alchangelog'] = false;
return $res;
}
}
# Get name of text by id
function textname_by_id($id) {
if (!$dbresult = mysqli_query($this->DB,"SELECT * FROM texts WHERE id=$id"))
$this->_fail("Cannot access database: ".mysqli_error($this->DB));
if (mysqli_num_rows($dbresult)) {
$res = mysqli_fetch_assoc($dbresult);
return $res['name'];
} else {
return FALSE;
}
}
# Get text id by its name
function text_id_by_name($name) {
return $this->register_text($name,TRUE);
}
# Register text or get text-id
function register_text($name,$donotcreate=FALSE) {
global $DISABLE_FULLTEXT;
$name = mysqli_real_escape_string($this->DB,$name);
#if (!$dbresult = mysqli_query($this->DB,"SHOW TABLES LIKE '{$name}_versions'"))
if (!$dbresult = mysqli_query($this->DB,"SELECT * FROM texts WHERE name='$name'"))
$this->_fail("Cannot check tables in database: ".mysqli_error($this->DB));
if (mysqli_num_rows($dbresult)) {
$res = mysqli_fetch_assoc($dbresult);
return $res['id'];
} else {
if ($donotcreate) return FALSE;
else {
if (!$dbresult = mysqli_query($this->DB,"START TRANSACTION")) {
$this->_failure("Cannot start transaction: ".mysqli_error($this->DB));
return FALSE;
}
if (!$dbresult = mysqli_query($this->DB,"INSERT INTO texts (name) VALUES ('$name')")) {
$this->_failure("Cannot insert new text into database: ".mysqli_error($this->DB));
return FALSE;
}
$txtid= mysqli_insert_id($this->DB);
# SQL table definitions
// $table_versions = "CREATE TABLE `{$name}_versions` (
// id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
// version_name TINYTEXT,
// root_id BIGINT UNSIGNED,
// text_changed BOOL DEFAULT FALSE,
// uniq_ids BOOL DEFAULT FALSE,
// text_elements TEXT NOT NULL,
//
// PRIMARY KEY (id),
// INDEX index_name (version_name(20))
// )";
// $table_alignments = "CREATE TABLE `{$name}_alignments` (
// id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
// ver1_id BIGINT UNSIGNED,
// ver2_id BIGINT UNSIGNED,
// method TINYTEXT NOT NULL,
// profile TINYTEXT NOT NULL,
// resp INT UNSIGNED,
// editor INT UNSIGNED,
// c_chstruct BOOLEAN DEFAULT 0,
// chtext BOOLEAN DEFAULT 0,
//
// PRIMARY KEY (id),
// INDEX index_ver1 (ver1_id),
// INDEX index_ver2 (ver2_id),
// INDEX index_resp (resp),
// INDEX index_editor (editor)
// )";
$table_elements = "CREATE TABLE `{$txtid}_elements` (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
txtver_id BIGINT UNSIGNED,
txt_position BIGINT UNSIGNED,
parent BIGINT UNSIGNED,
position BIGINT UNSIGNED,
element_name TINYTEXT,
element_id TINYTEXT,
attributes TEXT,
contents LONGTEXT,
PRIMARY KEY (id),
INDEX index_text (txtver_id),
INDEX index_txt_position (txt_position),
INDEX index_parent (parent),
INDEX index_position (position),
INDEX index_element_name (element_name(10)),
INDEX index_element_id (element_id(10))
";
if (!$DISABLE_FULLTEXT)
$table_elements .= ",\nFULLTEXT index_ft_contents (contents)";
//else
// $table_elements .= "INDEX index_contents (contents)\n)";
$table_elements .= "\n)";
$table_links = "CREATE TABLE `{$txtid}_links` (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
alignment_id BIGINT UNSIGNED,
version_id BIGINT UNSIGNED,
element_id BIGINT UNSIGNED,
position BIGINT UNSIGNED,
status INT UNSIGNED,
mark INT UNSIGNED DEFAULT 0,
PRIMARY KEY (id),
INDEX index_alignment (alignment_id),
INDEX index_version (version_id),
INDEX index_element (element_id),
INDEX index_position (position),
INDEX index_status (status),
INDEX index_mark (mark)
)";
$table_changelog = "CREATE TABLE `{$txtid}_changelog` (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
txtver_id BIGINT UNSIGNED,
element_id BIGINT UNSIGNED,
chtype CHAR(1) NOT NULL,
assoc_id BIGINT UNSIGNED DEFAULT NULL,
userid INT UNSIGNED,
ts DATETIME NOT NULL,
old_contents TEXT,
open BOOLEAN DEFAULT FALSE,
PRIMARY KEY(id),
INDEX index_txtver_id (txtver_id),
INDEX index_element_id (element_id),
INDEX index_chtype (chtype),
INDEX index_assoc_id (assoc_id),
INDEX index_userid (userid),
INDEX index_ts (ts),
INDEX index_open (open)
)";
/* FULLTEXT index_ft_old_contents (old_contents) - not used */
/* if (!$dbresult = mysqli_query($this->DB,$table_versions))
$this->_fail("Cannot create new text in the database: ".mysqli_error($this->DB));*/
if (!$dbresult = mysqli_query($this->DB,"SET default_storage_engine=InnoDB")) {
$this->_failure("Cannot set default storage engine to InnoDB: ".mysqli_error($this->DB));
return FALSE;
}
if (!$dbresult = mysqli_query($this->DB,$table_elements)) {
$this->_failure("Cannot create new text elements table in the database: ".mysqli_error($this->DB).". Are you sure you have a supported version of MySQL (>=5.6)?");
if (!$dbresult = mysqli_query($this->DB,"DELETE FROM texts WHERE id=$txtid")) { // just to be sure for bad upgraders
$this->_failure("Cannot insert new text into database: ".mysqli_error($this->DB));