This repository has been archived by the owner on Jan 3, 2023. It is now read-only.
forked from sjsrey/gtd-php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinstall.php
1744 lines (1532 loc) · 70 KB
/
install.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
/*---------------------------------------------------------------------------------
user-configurable options
---------------------------------------------------------------------------------*/
/* _MAXKEYLENGTH = integer -
sets the maximum length of indexes, used for sorting */
define("_MAXKEYLENGTH",10);
/* _ALLOWUPGRADEINPLACE = false | true -
allow the user to upgrade the current installation by over-writing it.
If false, then the user should enter a new prefix in config.inc.php */
define("_ALLOWUPGRADEINPLACE",true);
/* _ALLOWUNINSTALL = false | true -
allow the user to remove tables associated with a particular GTD installation */
define("_ALLOWUNINSTALL",true);
/*---------------------------------------
Debugging options
---------------------------------------*/
/* _DEBUG = false | true -
show lots of debugging information during execution */
define("_DEBUG",false);
/* _DRY_RUN = false | true - dry run won't change the database, but will
mime all the actions that would be done: use _DEBUG true to see these */
define("_DRY_RUN",false);
/*---------------------------------------------------------------------------------
End of user options
---------------------------------------------------------------------------------*/
/* _USEFULLTEXT = false | true - use FULLTEXT indexes, which take up a lot of
space, but allow you to use MATCH ... AGAINST NB GTD-php does not currently use this */
define("_USEFULLTEXT",false);
include_once 'ses.inc.php';
require_once 'admin.inc.php';
require_once 'gtd_constants.inc.php';
define("_DEFAULTDATE","1990-01-01");
define ("_TEMPPREFIX","_gtdphp_temptable_");
if (_USEFULLTEXT) {
define("_CREATESUFFIX",' ENGINE=MyISAM ');
define("_FULLTEXT",' FULLTEXT ');
define ("_INDEXLEN",'');
}else{
define("_CREATESUFFIX",' ');
define("_FULLTEXT",' ');
define ("_INDEXLEN",'('._MAXKEYLENGTH.')');
}
/* ============================================================================
global variables
*/
$tablesByVersion=array( // NB the order of tables in these arrays is CRITICAL. they must be consistent across the 0.8 sub-versions
// we don't offer an upgrade path from 0.5. Any 0.5 installations should first upgrade to 0.7, then run this routine
'0.5' => array('context','goals','maybe','maybesomeday','nextactions','projects','reference','waitingon')
// 0.7 is the earliest version that we can upgrade from, here
,'0.7' => array('categories','checklist','checklistItems','context','goals','itemattributes','items','itemstatus','list','listItems','nextactions','projectattributes','projects','projectstatus','tickler','timeitems')
// 0.8rc-1 was a major change, with goals, actions and projects all being merged into the items files
,'0.8rc-1' => array('categories','checklist','checklistItems','context','itemattributes','items','itemstatus','list','listItems','lookup','nextactions','tickler','timeitems','version')
// 0.8rc-2 added the preferences table
,'0.8rc-3' => array('categories','checklist','checklistItems','context','itemattributes','items','itemstatus','list','listItems','lookup','nextactions','tickler','timeitems','version','preferences')
// 0.8rc-4 saw all table names being standardised to lower case:
,'0.8rc-4' => array('categories','checklist','checklistitems','context','itemattributes','items','itemstatus','list','listitems','lookup','nextactions','tickler','timeitems','version','preferences')
// 0.8z.04 - tagmap table introduced; checklist,checklistitems,list,listitems,nextactions tables removed; items,itemstatus,itemattributes reworked
,'0.8z.04' => array('categories','context','itemattributes','items','itemstatus','lookup','tagmap','timeitems','version','preferences')
// 0.8z.05 - preferences table revised, no change to list of tables
// 0.8z.06 - perspectives and perspectivemap tables added
,'0.8z.06' => array('categories','context','itemattributes','items','itemstatus','lookup','perspectivemap','perspectives','tagmap','timeitems','version','preferences')
// 0.8z.07 - merged itemattributes into itemstatus, and dropped perspectives and perspectivemap
,'0.8z.07' => array('categories','context','items','itemstatus','lookup','tagmap','timeitems','version','preferences')
);
$versions=array(
'0.5'=> array( 'tables'=>'0.5',
'database'=>'0.5',
'upgradepath'=>'X')
,'0.7'=> array( 'tables'=>'0.7',
'database'=>'0.7',
'upgradepath'=>'0.7')
,'0.8rc-1'=> array( 'tables'=>'0.8rc-1',
'database'=>'0.8rc-1',
'upgradepath'=>'0.8rc-1')
,'0.8rc-3'=> array( 'tables'=>'0.8rc-3',
'database'=>'0.8rc-3',
'upgradepath'=>'0.8rc-3')
,'0.8rc-4'=> array( 'tables'=>'0.8rc-4',
'database'=>'0.8rc-4',
'upgradepath'=>'0.8rc-4')
,'0.8z.04'=> array( 'tables'=>'0.8z.04',
'database'=>'0.8z.04',
'upgradepath'=>'0.8z.04')
,'0.8z.05'=> array( 'tables'=>'0.8z.04',
'database'=>'0.8z.05',
'upgradepath'=>'0.8z.05')
,'0.8z.06'=> array( 'tables'=>'0.8z.06',
'database'=>'0.8z.06',
'upgradepath'=>'0.8z.06')
,'0.8z.07'=> array( 'tables'=>'0.8z.07',
'database'=>'0.8z.07',
'upgradepath'=>'0.8z.07')
,'0.8z.08'=> array( 'tables'=>'0.8z.07',
'database'=>'0.8z.08',
'upgradepath'=>'0.8z.08')
,'0.8z.09'=> array( 'tables'=>'0.8z.07',
'database'=>'0.8z.09',
'upgradepath'=>'copy')
,'0.9.00'=> array( 'tables'=>'0.8z.07',
'database'=>'0.8z.09',
'upgradepath'=>'copy')
);
/*
end of global variables
============================================================================*/
// initialise variables used for checking what this run is supposed to do
$pagename='install';
$onInstall=true;
$areUpdating=false;
$wantToDelete=false;
$areDeleting=false;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>gtd-php installer</title>
<?php if (_DEBUG) { ?>
<style>pre,.debug {}</style>
<script>
GTD={debugKey:'h'};
</script>
<script src="jquery.js"></script>
<script src="gtdfuncs.js"></script>
<?php } ?>
<link rel="stylesheet" href="themes/default/style.css">
<link rel="stylesheet" href="themes/default/style_screen.css" media="screen">
</head>
<body>
<?php include 'showMessage.inc.php'; ?>
<h2>This is the gtd-php installer</h2>
<?php
if (_DEBUG) echo "<pre class='debug'>"
,(_DRY_RUN)?'Executing Dry run - no tables will be amended in this run':'This is a <b>live</b> run'
,'<br>POST variables: ',print_r($_POST,true),"</pre>\n";
if (isset($_POST['cancel']))
; // we've cancelled an over-write or a delete, so go back to the installation menu
elseif (isset($_POST['install'])) {
$toPrefix=$_POST['prefix'];
$toDB=$_POST['db'];
// check to see whether the prefix in config.inc.php hsa been changed between POST and now
require 'config.inc.php';
if ($toPrefix===$config['prefix'] && $toDB===$config['db']) {
$areUpdating=true; // ok, it's safe to update.
} else {
echo "<p class='error warning'>config.inc.php has changed during the installation process. "
," The upgrade cannot continue. Please select your upgrade option again.";
}
}elseif (_ALLOWUNINSTALL && !isset($_POST['check'])) {
foreach ($_POST as $thiskey=>$thisval) {
if (_DEBUG)echo "<p class='debug'>Is $thiskey is a delete key? ";
if ($thiskey!==($tst=preg_replace('/^Delete_(.*)$/','$1',$thiskey))) {
if (_DEBUG)echo "Yes</p>\n";
$wantToDelete=true;
$versionToDelete=$thisval;
break;
}
if (_DEBUG)echo "No</p>\n";
}
if (isset($_POST['delete'])) $areDeleting=true;
}
if (isset($versionToDelete)) {
$args=explode('=',$versionToDelete);
$fromPrefix=$args[1];
$installType=$args[2];
} elseif (isset($_POST['installkey'])) {
$args=explode('=',$_POST['installkey']);
$installType=$args[0];
$fromPrefix=(count($args)>1)?$args[1]:null;
}
if ($areUpdating) {
if ($fromPrefix===$toPrefix && !isset($_POST['upgrade']))
getConfirmation('upgrade',$toPrefix);
else {
$install_success = false;
$rollback = array();
doInstall($installType,$fromPrefix);
}
}elseif ($areDeleting)
deleteInstall($installType,$fromPrefix);
elseif ($wantToDelete)
getConfirmation('delete',$fromPrefix);
else {
$checkState='in';
checkInstall();
}
?>
</div>
</body>
</html>
<?php
return;
/*
======================================================================================
end of main output.
Function to decide what installation action(s) to offer to the user:
======================================================================================
*/
function checkInstall() {
global $versions,$tablelist,$checkState,$tablesByVersion;
register_shutdown_function('failDuringCheck');
$goodToGo=true; // assume we'll be able to upgrade, until we find something to stop us
require_once 'gtdfuncs.inc.php';
// check for register globals - instruct user to turn it off in .htaccess if it's on
$checkState='preflight';
echo "<p>Read the <a href='INSTALL'>INSTALL</a> file for information on using this install/upgrade program</p>\n",checkRegisterGlobals();
if (_DEBUG) {
$included_files = get_included_files();
echo "<pre class='debug'>Included files:",print_r($included_files,true),'</pre>';
}
// check the config file
$checkState='config';
include_once 'config.inc.php';
if (_DEBUG) {
$configsav=$config;
$configsav['pass']='********';
echo "<p class='debug'>Got config.inc.php:</p><pre class='debug'>",print_r($configsav,true),'</pre>';
}
if (empty($config['db'])) {
echo "<p class='warning'>Fatal Error: no valid config.inc.php file has been found. "
," you should update the config.inc.php file, based on the config.sample.php "
," file supplied with GTD-PHP, before using this installer.</p>\n";
exit;
}
// try to open the database
$checkState='db';
require_once 'headerDB.inc.php';
// got a database; now get a list of its tables
$checkState='tables';
$tablelist = getDBTables($config['db']);
$nt=count($tablelist);
if (_DEBUG) echo "<pre class='debug'>Number of tables: $nt<br>",print_r($tablelist,true),"</pre>";
// validate the prefix
$checkState='prefix';
if (!checkPrefix($config['prefix'])) exit; // invalid prefix = fatal error
/*
Build an array of current installlations,
and offer choice of upgrading from one of these, or doing a fresh install
*/
$checkState='installations';
$gotVersions=array();
$destInUse=false;
$gotPrefixes=(preg_grep("/.*version$/",$tablelist));
if (_DEBUG) echo "<pre class='debug'>Version tables:",print_r($gotPrefixes,true),'</pre>';
foreach ($gotPrefixes as $thisVersionTable) {
$thisPrefix=substr($thisVersionTable,0,-7);
$thisVer=checkPrefixedTables($thisPrefix);
if ($thisVer!='') $gotVersions["{$thisVer}={$thisPrefix}"]=$thisVer;
if ($thisPrefix==$config['prefix']) { // we have an installation already using our target prefix
$destInUse=true;
if ($thisVer==_GTD_VERSION) { // and it's the latest version - so no upgrade needed!
// this destination is already in use - let's go!
$title='Installation is already up to date';
require_once 'headerMenu.inc.php';
echo "<div id='main'>\n<h2>Installed Version is up to date</h2>\n"
,"<p>There is already an installation of "
,_GTDPHP_VERSION," with prefix '{$config['prefix']}'</p>"
,"<p>It's ready for you to <a href='index.php'>start using it.</a></p>\n"
,"<p> </p><p> </p><p> </p><p> </p>\n";
$goodToGo=false;
if (_ALLOWUNINSTALL)
offerToDeleteOne($thisPrefix,$thisVer);
} else if (_ALLOWUPGRADEINPLACE || $versions[$thisVer]['database']===$versions[_GTD_VERSION]['database'])
/* now reset the versions array, and quit this loop,
because if we already have an installation with this prefix,
we don't want to offer any other kind of upgrade */
$gotVersions=array("{$thisVer}={$thisPrefix}"=>$thisVer);
else { // not allowed to upgrade in place, but an upgrade is required, so abort
$goodToGo=false;
showNoUpgradeMsg($thisPrefix,$thisVer);
}
break;
}
}
$checkState='report';
// get server information for problem reports
if ($goodToGo)
echo "<div id='main'><h1>gtd-php installation/upgrade</h1>\n";
echo "<h2>Installation Info</h2>\n"
,"<p>php: ",phpversion(),"</p>\n"
,"<p>database: ",getDBVersion(),"</p>\n";
// check for 0.8rc-1
if (!$destInUse && checkTables('0.8rc-1','',false) && checkVersion('')==='0.8rc-1') {
if ($config['prefix']=='') { // prefixes weren't used in 0.8rc-1, so a blank target prefix means we are trying to upgrade in place, over the top of 0.8rc-1
if (_ALLOWUPGRADEINPLACE) {
$destInUse=true;
/* now reset the versions array, because if we already have an
installation with this prefix, we don't want to offer any other
kind of upgrade */
$gotVersions=array('0.8rc-1='=>'0.8rc-1');
} else {
$goodToGo=false;
if (_ALLOWUNINSTALL)
offerToDeleteOne($config['prefix'],'0.8rc-1');
else showNoUpgradeMsg($config['prefix'],'0.8rc-1');
}
} else $gotVersions['0.8rc-1=']='0.8rc-1';
}
$checkState='v0.7search';
if (!$destInUse && checkTables('0.7','',false)) {
if ($config['prefix']=='') { // prefixes weren't used in 0.7, so a blank target prefix means we are trying to upgrade in place, over the top of 0.8rc-1
if (_ALLOWUPGRADEINPLACE) {
$gotVersions=array('0.7'=>'0.7');
$destInUse=true;
} else {
$goodToGo=false;
if (_ALLOWUNINSTALL)
offerToDeleteOne('','0.7');
else showNoUpgradeMsg('','0.7');
}
} else $gotVersions['0.7']='0.7';
// check to see if there are any tables with that prefix, left over from a failed upgrade
$temp = $config['prefix']._TEMPPREFIX;
$tmptables=array();
foreach ($tablelist as $table)
if (strpos($table,$temp)===0)
$tmptables[]=$table;
if (count($tmptables)) {
$gotVersions['0.7']='!';
$msg="Some temporary files from a previous aborted upgrade of 0.7 have been "
." left over and these are preventing you from upgrading the current "
." installation of 0.7 to the latest version, using this prefix.";
if (_ALLOWUNINSTALL) echo showDeleteWarning(true)
,"<form action='install.php' method='post'>\n"
,"<p class='warning'>$msg<br>\n"
,"You can delete these temporary files here:"
,makeDeleteButton('temporary','tables')
,"<input type='hidden' name='tablesToDelete' value='"
,implode(' ',$tmptables)
,"'></p></form>\n";
else echo "<p class='warning'>$msg<br>Change the installation prefix in config.inc.php, or consult your administrator, to fix the problem.</p>\n";
}
}
$checkState='v0.5search';
if (!count(array_diff($tablesByVersion['0.5'],$tablelist))) {
echo '<p>Found what looks like a version of GTD-PHP earlier than 0.7: this install program cannot upgrade this</p>';
if ($config['prefix']=='') { // prefixes weren't used before 0.8, so a blank target prefix means we are trying to upgrade in place
$goodToGo=false;
$destInUse=true;
}
$gotVersions['0.5']=true;
}
if (_DEBUG) echo "<pre class='debug'>Versions found: ",print_r($gotVersions,true),"</pre>\n";
if ($goodToGo) {
echo '<form action="install.php" method="post">'
,"\n<h2>Select an upgrade or installation</h2>\n"
,"<h3>Creating "._GTDPHP_VERSION." installation with "
,(($config['prefix']=='')?'no prefix':"prefix '{$config['prefix']}'")
,"</h3>\n";
if (($destInUse || _ALLOWUNINSTALL) && count($gotVersions)) showDeleteWarning();
echo "<table summary='table of installation alternatives'>\n"
,"<thead><tr><th>Use</th><th>From</th>\n";
if (_DEBUG) echo "<th class='debug'>name</th>\n";
if (_ALLOWUNINSTALL && count($gotVersions)) echo "<th class='warning'>Press to delete: no installation will be done; the only action that will be taken is the removal of tables</th>\n";
echo "</tr></thead><tbody>\n";
foreach ($gotVersions as $thisKey=>$thisVer) {
$tmp=explode('=',$thisKey);
$fromVer=$tmp[0];
$fromPrefix=(empty($tmp[1]))?'':$tmp[1];
$isUpdate= ($fromPrefix==$config['prefix']);
$action=($fromVer==_GTD_VERSION)?"Copy":'Update';
$msg="$action current $fromVer installation"
.(($fromPrefix=='')?' with no prefix':" with prefix $fromPrefix");
$key=$versions[$fromVer]['upgradepath']."=$fromPrefix";
echo '<tr>',tabulateOption($thisVer,$key,$msg);
if (_ALLOWUNINSTALL)
echo "<td>",makeDeleteButton($fromPrefix,$fromVer),"</td>\n";
echo "</tr>\n";
}
if (!$destInUse) {
echo "<tr>"
,tabulateOption('','1',"New install with sample data")
,(_ALLOWUNINSTALL && count($gotVersions)) ? "<td> </td>\n" : ''
,"</tr>\n"
,"<tr>"
,tabulateOption('','0',"New install with empty database")
,(_ALLOWUNINSTALL && count($gotVersions)) ? "<td> </td>\n" : ''
,"</tr>\n";
}
// and finally, close the table
echo "</tbody></table>\n<div>\n"
,"<input type='hidden' name='prefix' value='{$config['prefix']}' />\n"
,"<input type='hidden' name='db' value='{$config['db']}' />\n"
,"<input type='submit' name='install' value='Install' />\n";
if ($destInUse)
echo "<span class='warning'>Warning: this will over-write your current installation! "
,"<br>Make sure you have a "
," <a href='backup.php?prefix={$config['prefix']}'>backup</a> "
," of your data first! (click on the link to save a copy locally)<br> "
," If you're not sure, change the prefix in config.inc.php, "
," to create a new installation, "
," rather than over-writing the current one.</span>\n";
echo "</div>\n</form>\n";
}
$checkState='ok';
}
/*
======================================================================================
Do an installation / upgrade:
======================================================================================
*/
function doInstall($installType,$fromPrefix) {
global $temp,$install_success,$versions,$tablesByVersion;
require 'config.inc.php';
require_once "headerDB.inc.php";
$toPrefix=$config['prefix'];
$endMsg=$temp='';
register_shutdown_function('cleanup');
if (_DEBUG) echo "<pre class='debug'>Install type is: $installType<br>Source database has prefix $fromPrefix</pre>";
if ($installType=='0' || $installType=='1')
echo "<p>Installing ... please wait</p>\n";
else
echo "<p>Upgrading will take place in several stages ... please wait</p>\n";
flushAndResetTimer();
//---------------------------------------------------
switch($installType){
//---------------------------------------------------
case '0': // new install
create_tables($toPrefix);
updateVersion($toPrefix);
importOldConfig();
$install_success = true;
// give some direction about what happens next for the user.
$endMsg="<h2>Welcome to GTD-PHP</h2>\n
<p>You have just successfully installed GTD-PHP.\n
There are some preliminary steps you should take to set up your\n
installation for use and familiarize yourself with the system.</p>\n
<ol>\n
<li>You need to set up <a href='editCat.php?field=category&id=0'>categories</a>,
and <a href='editCat.php?field=context&id=0'>spatial</a> and\n
<a href='editCat.php?field=time-context&id=0'>time contexts</a> that suit your situation.</li>\n
<li>Then go to the <a href='weekly.php'>weekly review</a>, and follow it,
transferring the contents of your inboxes into gtd-php</li>\n
</ol>\n";
// end new install
break;
//---------------------------------------------------
case '1': // new install with sample data
create_tables($toPrefix);
updateVersion($toPrefix);
create_data($toPrefix);
importOldConfig();
$install_success = true;
// give some direction about what happens next for the user.
$endMsg="<h2>Welcome to GTD-PHP</h2>\n"
."<p>You have just successfully installed GTD-PHP. "
."Sample data has been created as part of the installation.</p>\n";
break;
//---------------------------------------------------
case 'copy': // already at latest release
if ($fromPrefix===$toPrefix){
$install_success = false;
$endMsg="<p class='warning'>Cannot copy database to itself!</p>";
} else {
create_tables($toPrefix);
foreach ($tablesByVersion[$versions[_GTD_VERSION]['tables']] as $table){
$q = "INSERT INTO `$toPrefix$table` SELECT * FROM `$fromPrefix$table`";
send_query($q);
}
updateVersion($toPrefix);
$install_success = true;
$endMsg='<p>Database copied.</p>';
}
break;
//---------------------------------------------------
case '0.7': // ugprade from 0.7
echo '<h2>Upgrading database from 0.7 to 0.8rc-4</h2>';
up07TO08rc4('',$toPrefix);
$fromPrefix=$toPrefix;
// deliberately flows through to next case
//---------------------------------------------------
case '0.8rc-4': // ugprade from 0.8rc-4
copyToNewPrefix('0.8rc-4','0.8z.04',$fromPrefix,$toPrefix);
up08rc4TO08z04($fromPrefix,$toPrefix);
$fromPrefix=$toPrefix; // must only copy to new prefix ONCE, so prevent it happening again
// deliberately flows through to next case
//---------------------------------------------------
case '0.8z.04': // ugprade from 0.8z.04
copyToNewPrefix('0.8z.04','0.8z.05',$fromPrefix,$toPrefix);
up08z04TO08z05($fromPrefix,$toPrefix);
// deliberately flows through to next case
//---------------------------------------------------
case '0.8z.05': // ugprade from 0.8z.05
//copyToNewPrefix('0.8z.05','0.8z.06',$fromPrefix,$toPrefix);
$skip08z06=true;
// deliberately flows through to next case
//---------------------------------------------------
case '0.8z.06': // ugprade from 0.8z.06
copyToNewPrefix('0.8z.05','0.8z.07',$fromPrefix,$toPrefix);
if (!empty($skip08z06)) {
drop_table("{$toPrefix}perspectives");
drop_table("{$toPrefix}perspectivemap");
}
up08z05TO08z07($fromPrefix,$toPrefix);
// deliberately flows through to next case
//---------------------------------------------------
case '0.8z.07': // ugprade from 0.8z.07
copyToNewPrefix('0.8z.07','0.8z.08',$fromPrefix,$toPrefix);
up08z07TO08z08($fromPrefix,$toPrefix);
// deliberately flows through to next case
//---------------------------------------------------
case '0.8z.08': // ugprade from 0.8z.08
copyToNewPrefix('0.8z.08','0.8z.09',$fromPrefix,$toPrefix);
up08z08TO08z09($fromPrefix,$toPrefix);
// deliberately flows through to next case
//---------------------------------------------------
case '0.8z.09': // ugprade from 0.8z.09
copyToNewPrefix('0.8z.09','0.9.00',$fromPrefix,$toPrefix);
up08z00TO09($fromPrefix,$toPrefix);
//---------------------------------------------------
// end of chained upgrade process
updateVersion($toPrefix);
$endMsg.="<p>GTD-PHP database upgraded to "._GTD_VERSION."</p>";
$install_success=true;
break;
//---------------------------------------------------
default: // no idea what the current installation is
$endMsg='<p class="error">The install script has not been able to work out'
.' whether this is an installation, or an upgrade;'
.' and if the latter, what version we are upgrading from.<br>'
.'Note that this installation script cannot upgrade'
.' an installation from gtd-php versions earlier than 0.7</p>';
break;
} // end of switch
//---------------------------------------------------
if ($install_success) {
echo "<h2>Final stage: cleaning the data</h2>";
flushAndResetTimer();
fixData($toPrefix);
$title='Installation Complete';
require_once 'headerMenu.inc.php';
echo "<div id='main'>";
echo checkRegisterGlobals(),
"<p>Installation completed:",
"<a href='preferences.php'>Now check the preferences</a>,",
" and make any necessary changes</p></div>";
/*
Force the session to restart, to ensure that
session variables will be initialised correctly,
for the new installation.
*/
$_SESSION = array();
session_destroy(); // TOFIX - seems to then go into next screen without a theme!
} else echo "<div id='main'>";
echo $endMsg;
}
/*
======================================================================================
utility functions
======================================================================================
*/
function flushAndResetTimer() {
@set_time_limit(120); // upgrades can take a long time!
@ob_flush();
flush();
}
/*
======================================================================================
*/
function create_data($toPrefix) {
// a load of inserts here to create the sample data
$sample=fopen('gtdsample.inc.sql','r');
if ($sample) {
while (!feof($sample)) {
$insert = fgets($sample, 8192);
if (!empty($insert) && $insert[0]!=='-') {
$insert=str_replace('gtdsample_',$toPrefix,$insert);
send_query($insert);
}
}
fclose($sample);
}
}
/*
======================================================================================
*/
function failDuringCheck() {
ignore_user_abort(true); // don't want to abort, while already handling an abort!
global $checkState;
switch ($checkState) {
case 'ok':return; // reached end ok, so nothing to do
case 'in': // barely started
echo "<p class='error'>Unable to start the installation pre-flight checks</p>";
break;
case 'config': // no valid config.inc.php
echo "<p class='error'>No valid config.inc.php file found.<br>"
,"Copy the config.sample.php file to config.inc.php, and set the MySQL parameters. "
,"Here's the <a href='http://www.gtd-php.com/Users/Config09'>online help</a>.</p>\n";
break;
case 'db': // failed during attempt to open database
echo "<p class='error'>"
,"Please check your config.inc.php file. gtd-php has been unable to connect to your database."
," It may be that the database is not yet created, "
," or that the database user name or password in the config.inc.php file are incorrect."
," Either create the database, adjust the user permissions, or set the username and password correctly, "
," (contact your administrator if you don't know how to do this)"
," and then return to this page.</p>\n";
break;
case 'tables':
echo "<p class='error'>Failed to get a list of the current tables in the database: check your MySQL database structure</p>\n";
break;
case 'prefix':
echo "<p class='error'>Change the prefix value in config.inc.php file, then return to this page</p>\n";
break;
case 'installations':
echo "<p class='error'>Failed while examining current installations</p>\n";
break;
case 'report':
echo "<p class='error'>Failed while producing table of installation options</p>\n";
break;
default: // failed some other time
echo "<p class='error'>Failed during check, at the '$checkState' stage</p>\n";
break;
}
echo "</div></body></html>";
}
/*
======================================================================================
*/
function copyToNewPrefix($ver,$tover,&$fromPrefix,$toPrefix) {
echo "<h2>Upgrading database from version $ver to $tover</h2>";
flushAndResetTimer();
if ($fromPrefix===$toPrefix) return false; // nothing to do!
global $tablesByVersion,$versions;
foreach ($tablesByVersion[$versions[$ver]['tables']] as $key=>$table) {
send_query("CREATE TABLE `{$toPrefix}$table` LIKE `$fromPrefix$table`");
send_query("INSERT INTO `{$toPrefix}$table` SELECT * FROM `$fromPrefix$table`");
}
$fromPrefix=$toPrefix; // must only copy to new prefix ONCE, so prevent it happening again
return true; // completed successfully
}
/*
======================================================================================
*/
function checkTables($ver,$prefix='',$casesensitive=false) {
global $versions,$tablelist,$tablesByVersion;
$doneOK=true;
if ($casesensitive) {
$needle=$tablesByVersion[$versions[$ver]['tables']];
$haystack=$tablelist;
} else {
$needle=array();
$haystack=array();
foreach ($tablesByVersion[$versions[$ver]['tables']] as $table)
$needle[]=strtolower($table);
foreach ($tablelist as $table)
$haystack[]=strtolower($table);
}
if (empty($needle))
$doneOK=false;
else foreach ($needle as $table)
if (!in_array($prefix.$table,$haystack,true)) {
$doneOK=false;
break;
}
return $doneOK;
}
/*
======================================================================================
*/
function tabulateOption($prefix,$key,$msg) {
static $isChecked=' checked="checked" ';
$result="<td>";
if ($prefix==='!')
$result.="X";
else {
$result.="<input type='radio' name='installkey' value='$key' $isChecked />";
$isChecked='';
}
$result.="</td><td>$msg</td>"
.((_DEBUG)?"<td class='debug'>Option: $key</td>":"")
."\n";
return $result;
}
/*
======================================================================================
*/
function showNoUpgradeMsg($prefix,$ver) {
echo "<div id='main'>\n"
,"<p class='warning'>Found an earlier GTD-PHP installation "
," (version $ver) with prefix '$prefix'<br>\n"
," The installation options that are currently set do "
," not allow you to upgrade the current installation in place: change the "
," prefix in config.inc.php to allow you to create a new installation.</p>\n";
}
/*
======================================================================================
*/
function send_query($q,$dieOnFail=true) {
global $rollback;
if (_DEBUG) echo "<p class='debug'>{$q}</p>\n";
if (_DRY_RUN)
$result=true;
else
$result = rawQuery($q);
if ($result) {
if (_DEBUG) echo "<p class='debug'>",mysql_affected_rows()," rows affected</p>\n";
if (stristr($q,'create table')!==FALSE) {
$tmp=explode('`',$q);
$newfile=$tmp[1];
$rollback[$newfile] = "DROP TABLE IF EXISTS `$newfile`";
} elseif (stristr($q,'rename table')!==FALSE) {
$tmp=explode('`',$q);
$oldfile=$tmp[1];
$newfile=$tmp[3];
$rollback[$newfile] = "DROP TABLE IF EXISTS `$newfile`";
unset($rollback[$oldfile]);
}
} else {
if($dieOnFail) {
echo "<p class='error'>Fatal error: Failed to do database query: '$q'<br>",mysql_error(),"</p>\n";
die("<p class='error'>Installation terminated</p>");
}elseif (_DEBUG)
echo "<p class='warning debug'>Warning: Failed to do database query: '$q'<br>",mysql_error(),"</p>\n";
}
return($result);
}
/*
======================================================================================
*/
function updateVersion($toPrefix) {
$q="TRUNCATE `{$toPrefix}version`";
send_query($q,false);
$q="INSERT INTO `{$toPrefix}version` VALUES('"._GTD_VERSION."',NULL)";
send_query($q,false);
}
/*
======================================================================================
*/
function cleanup($message='cleaning up the mess') {
ignore_user_abort(true); // don't want to abort, while already handling an abort!
global $rollback,$install_success;
if ($install_success) return $message;
foreach($rollback as $query) send_query($query,false);
echo "<p class='error'>Installation aborted, and cleanup done - <a href='install.php'>return to main install screen</a></p></div></body></html>";
return $message;
}
/*
======================================================================================
*/
function checkPrefixedTables($prefix) {
global $versions;
if (_DEBUG) echo "<p class='debug'>Is there a current installation with prefix '$prefix'?</p>";
$retval=checkVersion($prefix);
if ($retval && checkTables($retval,$prefix,true)) {
$doneOK=true;
} else {
$doneOK=checkTables('0.8rc-4',$prefix,false);
if ($doneOK) {
// check to see if it's really 0.8rc3 masquerading as 0.8rc4, by doing a case-sensitive table check
if ($retval==='0.8rc-4' && !checkTables('0.8rc-4',$prefix,true)) {
$retval='0.8rc-3';
}
} else {
$retval=false;
}
}
if (_DEBUG) echo "<p class='debug'>",(($doneOK)?'YES':'NO')," - resolved version number as: '$retval'</p>\n";
return $retval;
}
/*
======================================================================================
*/
function checkVersion($prefix) {
$q="SELECT `version` from `{$prefix}version`";
$result = send_query($q,false);
if (empty($result)) {
$retval='0.8rc-2';
} else {
$last=array(0=>null);
while ($out=mysql_fetch_row($result)) $last=$out;
$retval=$last[0];
if (_DEBUG) echo "<p class='debug'>Found Version field: $retval </p>";
}
return $retval;
}
/*
======================================================================================
Incremental upgraders
======================================================================================
*/
function up07TO08rc4($fromPrefix,$toPrefix) {
flushAndResetTimer();
global $tablesByVersion,$versions;
// temp table prefix
$temp = _TEMPPREFIX;
$tempPrefix=$toPrefix.$temp;
// categories---------------------------------------------
$q="CREATE TABLE `{$tempPrefix}categories` (
`categoryId` int(10) unsigned NOT NULL auto_increment,
`category` text NOT NULL,
`description` text,
PRIMARY KEY (`categoryId`), ".
_FULLTEXT." KEY `category` (`category`"._INDEXLEN."), ".
_FULLTEXT." KEY `description` (`description`"._INDEXLEN."))"._CREATESUFFIX;
send_query($q);
$q="INSERT INTO {$tempPrefix}categories select * from `categories`";
send_query($q);
// checklist---------------------------------------------
$q="CREATE TABLE `{$tempPrefix}checklist` (
`checklistId` int(10) unsigned NOT NULL auto_increment,
`title` text NOT NULL,
`categoryId` int(10) unsigned NOT NULL default '0',
`description` text,
PRIMARY KEY (`checklistId`))"; // no need to do additional keys, as we will be discarding this table later
send_query($q);
$q="INSERT INTO {$tempPrefix}checklist SELECT * FROM `checklist`";
send_query($q);
// checklistitems---------------------------------------------
$q="CREATE TABLE `{$tempPrefix}checklistitems` (
`checklistItemId` int(10) unsigned NOT NULL auto_increment,
`item` text NOT NULL,
`notes` text,
`checklistId` int(10) unsigned NOT NULL default '0',
`checked` enum ('y', 'n') NOT NULL default 'n',
PRIMARY KEY (`checklistItemId`))"; // no need to do additional keys, as we will be discarding this table later
send_query($q);
$q="INSERT INTO {$tempPrefix}checklistitems SELECT * FROM `checklistItems`";
send_query($q);
// context---------------------------------------------
$q="CREATE TABLE `{$tempPrefix}context` (
`contextId` int(10) unsigned NOT NULL auto_increment,
`name` text NOT NULL,
`description` text,
PRIMARY KEY (`contextId`), ".
_FULLTEXT." KEY `name` (`name`"._INDEXLEN."), ".
_FULLTEXT." KEY `description` (`description`"._INDEXLEN."))"._CREATESUFFIX;
send_query($q);
$q="INSERT INTO {$tempPrefix}context SELECT * FROM `context`";
send_query($q);
// goals---------------------------------------------
$q="CREATE TABLE `{$tempPrefix}goals` (
`id` int(11) NOT NULL auto_increment,
`goal` longtext,
`description` longtext,
`created` date default NULL,
`deadline` date default NULL,
`completed` date default NULL,
`type` enum('weekly', 'quarterly') default NULL ,
`projectId` int(11) default NULL, PRIMARY KEY (`id`) )";
send_query($q);
$q="INSERT INTO {$tempPrefix}goals SELECT * FROM `goals`";
send_query($q);
// remove unwanted line breaks from title field - allowed in 0.7, but not in 0.8 or later
$q="UPDATE `{$tempPrefix}goals` SET `goal`=replace(replace(`goal`,'\r',' '),'\n',' ')";
send_query($q);
// itemattributes---------------------------------------------
$q="create table `{$tempPrefix}itemattributes` (";
$q.="`itemId` int(10) NOT NULL auto_increment, ";
$q.="`type` enum('a', 'r', 'w') NOT NULL default 'a' ,";
$q.="`projectId` int(10) unsigned NOT NULL default '0', ";
$q.="`contextId` int(10) unsigned NOT NULL default '0', ";
$q.="`timeframeId` int(10) unsigned NOT NULL default '0', ";
$q.="`deadline` date default NULL , ";
$q.="`repeat` int( 10 ) unsigned NOT NULL default '0', ";
$q.=" `suppress` enum( 'y', 'n' ) NOT NULL default 'n', ";
$q.="`suppressUntil` int( 10 ) unsigned default NULL , ";
$q.="PRIMARY KEY ( `itemId` ) , KEY `projectId` ( `projectId` ) ,";
$q.="KEY `contextId` ( `contextId` ) , ";
$q.="KEY `suppress` ( `suppress` ) , KEY `type` ( `type` ) ,";
$q.=" KEY `timeframeId` ( `timeframeId` ) )";
send_query($q);
$q="INSERT INTO {$tempPrefix}itemattributes SELECT * FROM `itemattributes`";
send_query($q);
// items---------------------------------------------
$q="CREATE TABLE `{$tempPrefix}items` (
`itemId` int(10) unsigned NOT NULL auto_increment,
`title` text NOT NULL,
`description` longtext,
`desiredOutcome` text,
PRIMARY KEY (`itemId`), ".
_FULLTEXT." KEY `title` (`title`"._INDEXLEN."), ".
_FULLTEXT." KEY `desiredOutcome` (`desiredOutcome`"._INDEXLEN."), ".
_FULLTEXT." KEY `description` (`description`"._INDEXLEN."))"._CREATESUFFIX;
send_query($q);
$q="INSERT INTO {$tempPrefix}items (itemId,title,description) SELECT * from `items` ";
send_query($q);
// itemstatus---------------------------------------------
$q="CREATE TABLE `{$tempPrefix}itemstatus` ( ";
$q.="`itemId` int( 10 ) unsigned NOT NULL auto_increment ,";
$q.=" `dateCreated` date default NULL, ";
$q.="`lastModified` timestamp default '"._DEFAULTDATE."' ,";
$q.="`dateCompleted` date default NULL , ";
$q.=" `completed` int( 10 ) unsigned default NULL , ";
$q.="PRIMARY KEY ( `itemId` ) ) ";
send_query($q);
$q="INSERT INTO {$tempPrefix}itemstatus SELECT * FROM `itemstatus`";
send_query($q);
// list---------------------------------------------
$q="CREATE TABLE `{$tempPrefix}list` (
`listId` int(10) unsigned NOT NULL auto_increment,
`title` text NOT NULL,
`categoryId` int(10) unsigned NOT NULL default '0',
`description` text,
PRIMARY KEY (`listId`) )";
send_query($q);
$q="INSERT INTO {$tempPrefix}list SELECT * FROM `list` ";
send_query($q);
// listitems---------------------------------------------
$q="CREATE TABLE `{$tempPrefix}listitems` (
`listItemId` int(10) unsigned NOT NULL auto_increment,
`item` text NOT NULL,
`notes` text,
`listId` int(10) unsigned NOT NULL default '0',
`dateCompleted` date default NULL,
PRIMARY KEY (`listItemId`) )";
send_query($q);
$q="INSERT INTO {$tempPrefix}listitems SELECT * FROM `listItems`";
send_query($q);
// nextactions---------------------------------------------
$q="CREATE TABLE `{$tempPrefix}nextactions` (
`projectId` int( 10 ) unsigned NOT NULL default '0',
`nextaction` int( 10 ) unsigned NOT NULL default '0',