This repository has been archived by the owner on Sep 3, 2024. It is now read-only.
forked from mmaunder/DeployMint
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathDeployMintAbstract.php
1670 lines (1491 loc) · 68.8 KB
/
DeployMintAbstract.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
abstract class DeployMintAbstract implements DeployMintInterface
{
const PAGE_INDEX = 'deploymint';
const PAGE_BLOGS = 'deploymint/blogs';
const PAGE_PROJECTS = 'deploymint/projects';
const PAGE_REVERT = 'deploymint/revert';
const PAGE_OPTIONS = 'deploymint/options';
const PAGE_HELP = 'deploymint/help';
const DP_TABLE_ALL = 'table_all';
const DP_DIR_UPLOADS = 'dir_uploads';
protected $wpTables = array('commentmeta', 'comments', 'links', 'options', 'postmeta', 'posts', 'term_relationships', 'term_taxonomy', 'terms', 'users', 'usermeta');
protected $pdb;
protected $defaultOptions = array(
'git' => '',
'mysql' => '',
'mysqldump' => '',
'rsync' => '',
'numBackups' => 5,
'datadir' => '',
'preserveBlogName' => 1,
'backupDisabled' => 0,
'temporaryDatabase' => '',
'backupDatabase' => '',
);
protected $dbVersion = "1.0";
public function __construct()
{
global $wpdb;
$this->pdb = $wpdb;
}
public function install()
{
$this->createSchema();
$this->updateOptions($this->detectOptions());
}
public function uninstall()
{
}
public function checkUpdate()
{
if (get_site_option('deploymint_db_version') != $this->dbVersion) {
$this->createSchema();
}
}
public function setup()
{
add_action('init', array($this, 'initHandler'));
add_action('wp_enqueue_scripts', array($this, 'enqueueScripts'));
add_action('wp_ajax_deploymint_createProject', array($this, 'actionCreateProject'));
add_action('wp_ajax_deploymint_deleteProject', array($this, 'actionRemoveProject'));
add_action('wp_ajax_deploymint_reloadProjects', array($this, 'actionReloadProjects'));
add_action('wp_ajax_deploymint_addBlogToProject', array($this, 'actionAddBlogToProject'));
add_action('wp_ajax_deploymint_removeBlogFromProject', array($this, 'actionRemoveBlogFromProject'));
add_action('wp_ajax_deploymint_updateOrigin', array($this, 'actionUpdateOrigin'));
add_action('wp_ajax_deploymint_updateTables', array($this, 'actionUpdateTables'));
add_action('wp_ajax_deploymint_updateCreateSnapshot', array($this, 'actionGetProjectBlogs'));
add_action('wp_ajax_deploymint_createSnapshot', array($this, 'actionCreateSnapshot'));
add_action('wp_ajax_deploymint_updateDeploySnapshot', array($this, 'actionGetDeployOptions'));
add_action('wp_ajax_deploymint_deploySnapshot', array($this, 'actionDeploySnapshot'));
add_action('wp_ajax_deploymint_archiveSnapshot', array($this, 'actionArchiveSnapshot'));
add_action('wp_ajax_deploymint_deploy', array($this, 'ajax_deploy_callback'));
add_action('wp_ajax_deploymint_updateSnapDesc', array($this, 'ajax_updateSnapDesc_callback'));
add_action('wp_ajax_deploymint_undoDeploy', array($this, 'ajax_undoDeploy_callback'));
add_action('wp_ajax_deploymint_deleteBackups', array($this, 'ajax_deleteBackups_callback'));
add_action('wp_ajax_deploymint_updateOptions', array($this, 'ajax_updateOptions_callback'));
$opt = $this->getOptions();
DeployMintProjectTools::setGit($opt['git']);
}
protected function createSchema()
{
$schemaVersion = get_option("deploymint_db_version", null);
if ($schemaVersion != $this->dbVersion) {
$tables = array();
$tables['options'] = "CREATE TABLE dep_options (
name varchar(100) NOT NULL PRIMARY KEY,
val varchar(255) default ''
) default charset=utf8";
$tables['projects'] = "CREATE TABLE dep_projects (
id int UNSIGNED NOT NULL auto_increment PRIMARY KEY,
ctime int UNSIGNED NOT NULL,
name varchar(100) NOT NULL,
dir varchar(120) NOT NULL,
origin varchar(255) NOT NULL,
tables varchar(255) NOT NULL,
project_uuid varchar(36) NOT NULL,
deleted tinyint UNSIGNED default 0
) default charset=utf8";
$tables['members'] = "CREATE TABLE dep_members (
blog_id int UNSIGNED NOT NULL,
project_id int UNSIGNED NOT NULL,
deleted tinyint UNSIGNED default 0,
KEY k1(blog_id, project_id)
) default charset=utf8";
$tables['blogs'] = "CREATE TABLE dep_blogs (
id int UNSIGNED NOT NULL auto_increment PRIMARY KEY,
blog_url varchar(255) NOT NULL,
blog_name varchar(255) NOT NULL,
blog_uuid varchar(36) NOT NULL,
ignore_cert tinyint UNSIGNED default 0,
deleted tinyint UNSIGNED default 0
) default charset=utf8";
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
foreach($tables as $sql) {
dbDelta($sql);
/*$success = $this->pdb->query($sql);
if (!$success) {
die($this->pdb->print_error());
}*/
}
}
if ($schemaVersion == null) {
add_option("deploymint_db_version", $this->dbVersion);
} else {
update_option("deploymint_db_version", $this->dbVersion);
}
}
protected function detectOptions()
{
$options = $this->getOptions();
foreach (array('git', 'mysql', 'mysqldump', 'rsync') as $n) {
$options[$n] = $options[$n] ? $options[$n] : trim(DeployMintTools::mexec("which $n"));
}
return $options;
}
protected function updateOptions($o)
{
foreach ($o as $n => $v) {
$this->setOption($n, $v);
}
}
protected function setOption($name, $val)
{
$this->pdb->query($this->pdb->prepare("INSERT INTO dep_options (name, val) VALUES (%s, %s) ON DUPLICATE KEY UPDATE val=%s", $name, $val, $val));
}
protected function getOptions($createTemporaryDatabase = false, $createBackupDatabase = false)
{
$res = $this->pdb->get_results("SELECT name, val FROM dep_options", ARRAY_A);
$options = $this->getDefaultOptions();
for ($i = 0; $i < sizeof($res); $i++) {
$options[$res[$i]['name']] = $res[$i]['val'];
}
$options['backupDisabled'] = ($options['backupDisabled'] == '1');
$options['temporaryDatabaseCreated'] = false;
if ($options['temporaryDatabase'] == '' && $createTemporaryDatabase) {
for ($i = 1; $i < 10; $i++) {
$options['temporaryDatabase'] = 'dep_tmpdb' . preg_replace('/\./', '', microtime(true));
$res = $this->pdb->get_results("SHOW TABLES FROM " . $options['temporaryDatabase'], ARRAY_A);
if (sizeof($res) < 1) {
break;
}
if ($i > 4) {
throw new Exception("We could not create a temporary database name after 5 tries. You may not have the create DB privelege.");
}
}
$this->pdb->query("CREATE DATABASE " . $options['temporaryDatabase']);
$options['temporaryDatabaseCreated'] = true;
}
$options['backupDatabaseCreated'] = false;
if ($createBackupDatabase && !$options['backupDisabled'] && ($options['numBackups'] != 1 || ($options['numBackups'] == 1 && $options['backupDatabase'] == ''))) {
$dbPrefix = ($options['backupDatabase'] == '') ? 'depbak' : $options['backupDatabase'];
$options['backupDatabase'] = $dbPrefix . '__' . preg_replace('/\./', '', microtime(true));
$success = $this->pdb->query('CREATE DATABASE ' . $options['backupDatabase']);
if ($succss === false){
throw new Exception('Could not create backup database. ' . mysql_error($dbh));
}
$options['backupDatabaseCreated'] = true;
}
return $options;
}
protected function allOptionsSet()
{
$options = $this->getOptions();
foreach (array('git', 'mysql', 'mysqldump', 'rsync', 'datadir') as $v) {
if (!$options[$v]) {
return false;
}
}
if (!preg_match('/^\d+$/', $options['numBackups'])) {
return false;
}
return true;
}
protected function getDefaultOptions()
{
return $this->defaultOptions;
}
protected function checkPerms()
{
if (!is_user_logged_in()) {
die("<h2>You are not logged in.</h2>");
}
if ( (is_multisite() && !current_user_can('manage_network'))
|| !is_multisite() && !current_user_can('manage_options')) {
die("<h2>You don't have permission to access this page.</h2><p>You need the 'manage_network' Super Admin capability to use DeployMint.</p>");
}
}
protected function ajaxError($msg)
{
die(json_encode(array('err' => $msg)));
}
public function setPdb($pdb)
{
$this->pdb = $pdb;
}
public function getPdb()
{
return $this->pdb;
}
public function enqueueScripts()
{
//wp_deregister_script( 'jquery' );
//wp_enqueue_script('jquery', plugin_dir_url( __FILE__ ) . 'js/jquery-1.6.2.js', array( ) );
}
public function initHandler()
{
if (is_admin()) {
wp_enqueue_script('jquery-templates', plugin_dir_url(__FILE__) . 'js/jquery.tmpl.min.js', array('jquery'));
wp_enqueue_script('jquery-leadmodal-js', plugin_dir_url(__FILE__) . 'js/jquery.easyModal.min.js', array('jquery'));
wp_enqueue_script('deploymint-js', plugin_dir_url(__FILE__) . 'js/deploymint.js', array('jquery'));
wp_localize_script('deploymint-js', 'DeployMintVars', array(
'ajaxURL' => admin_url('admin-ajax.php')
));
wp_register_style('DeployMintCSS', plugins_url('css/admin.css', __FILE__));
wp_enqueue_style('DeployMintCSS');
}
}
public function actionIndex()
{
if (!$this->allOptionsSet()) {
return $this->actionOptions();
}
include 'views/index.php';
}
public function actionManageProjects()
{
return $this->actionIndex();
}
public function actionManageBlogs()
{
if (!$this->allOptionsSet()) {
return $this->actionOptions();
}
include 'views/manageBlogs.php';
}
public function actionManageProject($id)
{
extract($this->getOptions(), EXTR_OVERWRITE);
if (!$this->allOptionsSet()) {
return $this->actionOptions();
}
$this->checkPerms();
if (!$this->allOptionsSet()) {
echo '<div class="wrap"><h2 class="depmintHead">Please visit the options page and configure all options</h2></div>';
return;
}
$proj = $this->getProject($id);
$dir = $datadir . $proj['dir'] . '/';
DeployMintProjectTools::setRemote($dir, $proj['origin']);
if (strlen($proj['origin']) > 0 && !DeployMintProjectTools::connectedToRemote($dir)) {
$this->showMessage("Please ensure that your project data directory ($dir) has access to its remote repository at {$proj['origin']}");
return;
}
include 'views/manageProject.php';
}
public function actionRevert()
{
$this->checkPerms();
if (!$this->allOptionsSet()) {
return $this->actionOptions();
}
extract($this->getOptions(), EXTR_OVERWRITE);
$dbuser = DB_USER;
$dbpass = DB_PASSWORD;
$dbhost = DB_HOST;
$dbname = DB_NAME;
$dbh = mysql_connect($dbhost, $dbuser, $dbpass, true);
mysql_select_db($dbname, $dbh);
$res1 = mysql_query("SHOW DATABASES", $dbh);
if (mysql_error($dbh)) {
$this->ajaxError("A database error occured: " . substr(mysql_error($dbh), 0, 200));
}
function readBackupData($dbname, $dbh)
{
$res2 = mysql_query("SELECT * FROM $dbname.dep_backupdata", $dbh);
if (mysql_error($dbh)) {
$this->ajaxError("A database error occured: " . substr(mysql_error($dbh), 0, 200));
}
$dbData = array();
while ($row2 = mysql_fetch_array($res2, MYSQL_ASSOC)) {
$dbData[$row2['name']] = $row2['val'];
}
$dbData['dbname'] = $dbname;
$dbData['deployTimeH'] = date('l jS \of F Y h:i:s A', sprintf('%d', $dbData['deployTime']));
return $dbData;
}
$dbs = array();
if ($backupDatabase == '' || ($numBackups != 1)) {
while ($row1 = mysql_fetch_array($res1, MYSQL_NUM)) {
$dbPrefix = ($backupDatabase == '') ? 'depbak' : $backupDatabase;
if (preg_match('/^' . $dbPrefix . '__/', $row1[0])) {
array_push($dbs, readBackupData($row1[0], $dbh));
}
}
function deployTimeSort($b, $a)
{
if ($a['deployTime'] == $b['deployTime']) {
return 0;
} return ($a['deployTime'] < $b['deployTime']) ? -1 : 1;
}
usort($dbs, 'deployTimeSort');
} else {
if (!$backupDisabled) {
array_push($dbs, readBackupData($backupDatabase, $dbh));
}
}
include 'views/revert.php';
}
public function actionOptions()
{
$opt = $this->getOptions();
include 'views/options.php';
}
public function actionHelp()
{
include 'views/help.php';
}
public function __call($name, $args)
{
$matches = array();
if (preg_match('/^actionManageProject_(\d+)$/', $name, $matches)) {
$this->actionManageProject($matches[1]);
} else {
die("Method $name doesn't exist!");
}
}
public function actionCreateProject()
{
$this->checkPerms();
$name = $_POST['name'];
$origin = $_POST['origin'];
try {
if ($this->createProject($name, $origin, $tables)) {
die(json_encode(array('ok' => 1)));
}
} catch (Exception $e) {
die(json_encode(array('err' => $e->getMessage())));
}
}
public function actionRemoveProject()
{
$this->checkPerms();
$id = $_POST['id'];
try {
if ($this->removeProject($id)) {
die(json_encode(array('ok' => 1)));
}
} catch (Exception $e) {
die(json_encode(array('err' => $e->getMessage())));
}
}
public function actionReloadProjects()
{
$this->checkPerms();
extract($this->getOptions(), EXTR_OVERWRITE);
try {
$projects = $this->getProjects();
for ($i = 0; $i < sizeof($projects); $i++) {
$dir = $datadir . $projects[$i]['dir'] . '/';
DeployMintProjectTools::setRemote($dir, $projects[$i]['origin']);
$fetch = DeployMintProjectTools::fetch($dir);
$projects[$i]['originAvailable'] = !DeployMintProjectTools::isFatalResponse($fetch);
$projects[$i]['originAvailableMessage'] = trim($fetch);
$projects[$i]['memberBlogs'] = $this->getProjectBlogs($projects[$i]['id']);
$projects[$i]['nonmemberBlogs'] = $this->getBlogsNotInProject($projects[$i]['id']);
$projects[$i]['numNonmembers'] = sizeof($projects[$i]['nonmemberBlogs']);
}
die(json_encode(array(
'projects' => $projects
)));
} catch (Exception $e){
die(json_encode(array('err' => $e->getMessage())));
}
}
public function actionAddBlogToProject()
{
$this->checkPerms();
try {
if ($this->addBlogToProject($_POST['blogID'], $_POST['projectID'], $_POST['username'], $_POST['password'])) {
die(json_encode(array('ok' => 1)));
}
} catch (Exception $e){
die(json_encode(array('err' => $e->getMessage())));
}
}
public function actionRemoveBlogFromProject()
{
$this->checkPerms();
try {
if ($this->removeBlogFromProject($_POST['blogID'], $_POST['projectID'], $_POST['username'], $_POST['password'])) {
die(json_encode(array('ok' => 1)));
}
} catch (Exception $e){
die(json_encode(array('err' => $e->getMessage())));
}
}
public function actionUpdateOrigin()
{
$this->checkPerms();
try {
if ($this->updateOrigin($_POST['projectId'], $_POST['origin'])) {
die(json_encode(array('ok' => 1)));
}
} catch (Exception $e){
die(json_encode(array('err' => $e->getMessage())));
}
}
protected function updateOrigin($projectId, $origin)
{
$opt = $this->getOptions();
$proj = $this->getProject($projectId);
$dir = $opt['datadir'] . $proj['dir'] . '/';
$this->pdb->update('dep_projects', array('origin'=>$origin), array('id'=>$projectId));
DeployMintProjectTools::setRemote($dir, $origin);
return true;
}
public function actionUpdateTables()
{
$this->checkPerms();
try {
if ($this->updateTables($_POST['projectId'], $_POST['tables'])) {
die(json_encode(array('ok' => 1)));
}
} catch (Exception $e){
die(json_encode(array('err' => $e->getMessage())));
}
}
protected function updateTables($projectId, $tables)
{
$proj = $this->getProject($projectId);
$this->pdb->update('dep_projects', array('tables'=>$tables), array('id'=>$projectId));
return true;
}
public function actionGetProjectBlogs()
{
$this->checkPerms();
try {
$blogs = $this->getProjectBlogs($_REQUEST['projectid']);
die(json_encode(array('blogs'=>$blogs)));
} catch (Exception $e){
die(json_encode(array('err' => $e->getMessage())));
}
}
protected function projectExists($name)
{
$result = $this->pdb->get_results($this->pdb->prepare("SELECT name FROM dep_projects WHERE name=%s AND deleted=0", $name), ARRAY_A);
return sizeof($result) > 0;
}
protected function createProject($name, $origin, $tables="", $uuid=null)
{
$this->checkPerms();
$opt = $this->getOptions();
extract($opt, EXTR_OVERWRITE);
if ($this->projectExists($name)) {
throw new Exception('A project with that name already exists');
}
if ($uuid == null) {
$uuid = DeployMintTools::generateUUID();
}
$dir = $name;
$dir = preg_replace('/[^a-zA-Z0-9]+/', '_', $dir);
$fulldir = $dir . '-1';
$counter = 2;
while (is_dir($datadir . $fulldir)) {
$fulldir = preg_replace('/\-\d+$/', '', $fulldir);
$fulldir .= '-' . $counter;
$counter++;
if ($counter > 1000) {
throw new Exception('Too many directories already exist starting with "'.$dir.'"');
}
}
$finaldir = $datadir . $fulldir;
if (!@mkdir($finaldir, 0755)) {
throw new Exception('Could not create directory ' . $finaldir);
}
$git1 = DeployMintTools::mexec("$git init ; $git add . ", $finaldir);
if (strlen($origin) > 0) {
DeployMintProjectTools::setRemote($finaldir, $origin);
DeployMintProjectTools::fetch($finaldir);
}
$insertToDb = $this->pdb->query($this->pdb->prepare("INSERT INTO dep_projects (ctime, name, dir, origin, tables, project_uuid) VALUES (unix_timestamp(), %s, %s, %s, %s, %s)", $name, $fulldir, $origin, $tables, $uuid));
if ($insertToDb) {
return true;
} else {
rmdir($finaldir);
throw new Exception($this->pdb->last_error);
}
}
protected function removeProject($id)
{
$this->pdb->query($this->pdb->prepare("UPDATE dep_members SET deleted=1 WHERE project_id=%d", $_POST['blogID'], $_POST['projectID']));
$this->pdb->query($this->pdb->prepare("UPDATE dep_projects SET deleted=1 WHERE id=%d", $_POST['projectID']));
return true;
}
protected function getProject($id)
{
return $this->pdb->get_row($this->pdb->prepare("SELECT * FROM dep_projects WHERE id=%d AND deleted=0", array($id)), ARRAY_A);
}
protected function getProjectByName($name)
{
return $this->pdb->get_row($this->pdb->prepare("SELECT * FROM dep_projects WHERE name=%s AND deleted=0", array($name)), ARRAY_A);
}
protected function getProjectByUUID($uuid)
{
return $this->pdb->get_row($this->pdb->prepare("SELECT * FROM dep_projects WHERE project_uuid=%s AND deleted=0", array($uuid)), ARRAY_A);
}
protected function getProjects()
{
return $this->pdb->get_results("SELECT * FROM dep_projects WHERE deleted=0", ARRAY_A);
}
protected function getProjectBlogs($project)
{
$blogsTable = $this->pdb->base_prefix . 'blogs';
return $this->pdb->get_results($this->pdb->prepare("SELECT $blogsTable.blog_id AS blog_id, $blogsTable.domain AS domain, $blogsTable.path AS path, $blogsTable.blog_name AS name FROM dep_members, $blogsTable WHERE dep_members.deleted=0 AND dep_members.project_id=%d AND dep_members.blog_id = $blogsTable.blog_id", $project), ARRAY_A);
}
protected function getBlogsIds()
{
$blogs = $this->getBlogs();
$ids = array();
foreach($blogs as $b) {
$ids[] = $b['blog_id'];
}
return $ids;
}
protected function getProjectBlogsIds($projectId)
{
$blogs = $this->getProjectBlogs($projectId);
$ids = array();
foreach($blogs as $b) {
$ids[] = $b['blog_id'];
}
return $ids;
}
protected function getBlogsNotInProject($project)
{
$availableBlogs = array();
$allBlogs = $this->getBlogs();
$projectBlogs = $this->getProjectBlogs($project);
if (sizeof($projectBlogs) == 0) {
return $allBlogs;
}
$pBlogIds = array_map(function($e){
return $e['blog_id'];
}, $projectBlogs);
foreach($allBlogs as $b) {
if (!in_array($b['blog_id'], $pBlogIds)) {
$availableBlogs[] = $b;
}
}
return $availableBlogs;
}
protected function getBlog($id)
{
$blogsTable = $this->pdb->base_prefix . 'blogs';
return $this->pdb->get_row($this->pdb->prepare("SELECT * FROM $blogsTable WHERE blog_id = %d ORDER BY domain ASC", array($id)), ARRAY_A);
}
protected function getBlogs()
{
$blogsTable = $this->pdb->base_prefix . 'blogs';
return $this->pdb->get_results("SELECT blog_id, domain, path FROM $blogsTable ORDER BY domain ASC", ARRAY_A);
}
protected function removeBlogFromProject($blogId, $projectId, $username=null, $password=null)
{
$this->pdb->query($this->pdb->prepare("UPDATE dep_members SET deleted=1 WHERE blog_id=%d and project_id=%d", $blogId, $projectId));
return true;
}
protected function addBlogToProject($blogId, $projectId, $username=null, $password=null)
{
if (!$this->projectHasBlog($blogId, $projectId)) {
$this->pdb->query($this->pdb->prepare("INSERT INTO dep_members (blog_id, project_id) VALUES (%d, %d)", $blogId, $projectId));
}
return true;
}
protected function projectHasBlog($blogId, $projectId)
{
$result = $this->pdb->get_results($this->pdb->prepare("SELECT project_id FROM dep_members WHERE blog_id=%d AND project_id=%d AND deleted=0", array($blogId, $projectId)), ARRAY_A);
return sizeof($result) > 0;
}
public function actionCreateSnapshot()
{
$this->checkPerms();
try {
if ($this->createSnapshot($_REQUEST['projectid'], $_REQUEST['blogid'], $_REQUEST['name'], $_REQUEST['desc'], $_REQUEST['username'], $_REQUEST['password'])) {
die(json_encode(array('ok' => 1)));
}
} catch (Exception $e){
//$this->ajaxError($e->getMessage());
die(json_encode(array('err' => $e->getMessage())));
}
}
protected function createSnapshot($projectId, $blogId, $name, $desc, $username=null, $password=null)
{
// Validate name and description
if (!preg_match('/\w+/', $name)) {
throw new Exception("Please enter a name for this snapshot");
}
if (strlen($name) > 20) {
throw new Exception("Your snapshot name must be 20 characters or less.");
}
if (preg_match('/[^a-zA-Z0-9\_\-\.]/', $name)) {
throw new Exception("Your snapshot name can only contain characters a-z A-Z 0-9 and dashes, underscores and dots.");
}
if (!$desc) {
throw new Exception("Please enter a description for this snapshot.");
}
$prec = $this->getProject($projectId);
if (sizeof($prec) < 1) {
throw new Exception("That project doesn't exist.");
}
return true;
}
protected function getTablePrefix($blogId)
{
return $this->pdb->base_prefix;
}
protected function copyFilesToDataDir($blogId, $dest){}
protected function copyFilesFromDataDir($blogId, $src, $deployParts=array()){}
/**
* Gets the various aspects that could potentially be included in the deployment
*/
protected function getAvailableDeployParts()
{
return array(
self::DP_TABLE_ALL => 'Database Tables',
self::DP_DIR_UPLOADS => 'Uploaded Media',
);
}
protected function getTablesToSnapshot($projectId=0, $prefix='')
{
$stdTables = $this->getTablesWithPrefix($prefix);
$projTables = $this->getProjectSpecificTables($projectId, $prefix);
return array_merge($stdTables, $projTables);
}
protected function getTablesToDeploy($projectId=0, $prefix='')
{
$stdTables = array();
foreach($this->wpTables as $key=>$value) {
$stdTables[$key] = $prefix . $value;
}
$projTables = $this->getProjectSpecificTables($projectId, $prefix);
return array_merge($stdTables, $projTables);
}
protected function getTablesWithPrefix($prefix, $pdb=null)
{
if ($pdb == null) {
$pdb = $this->getPdb();
}
$tables = $pdb->get_results("SHOW TABLES", ARRAY_N);
$prefixedTables = array();
foreach($tables as $table) {
$t = trim($table[0]);
if (strlen($t) && preg_match("/^$prefix/", $t)) {
$prefixedTables[] = $t;
}
}
return $prefixedTables;
}
protected function getProjectSpecificTables($projectId=0, $prefix='')
{
$projTables = array();
if ($projectId) {
$project = $this->getProject($projectId);
if (strlen(trim($project['tables']))) {
$projTables = explode(',', $project['tables']);
foreach($projTables as $key=>$value) {
$v = trim($value);
if (strlen($v) > 0) {
if (substr($v, 0, 1) == '\\') {
$projTables[$key] = $v;
} else {
$projTables[$key] = $prefix . $v;
}
}
}
}
}
return $projTables;
}
protected function doSnapshot($projectId, $blogId, $name, $desc)
{
$this->checkPerms();
$opt = $this->getOptions();
extract($opt, EXTR_OVERWRITE);
$proj = $this->getProject($projectId);
$dir = $datadir . $proj['dir'] . '/';
$pdb = $this->getPdb();
// Check that project directory exists
if (!is_dir($dir)) {
throw new Exception("The directory " . $dir . " for this project doesn't exist for some reason. Did you delete it?");
}
// Make sure we are current from the remote
DeployMintProjectTools::fetch($dir);
// Make sure project directory is a working git directory
if (!DeployMintProjectTools::isGitRepo($dir)) {
throw new Exception("The directory $dir is not a valid git repository. The output we received is: $branchOut");
}
// Check if branch exists
if (DeployMintProjectTools::branchExists($dir, $name)) {
throw new Exception("A snapshot with the name $name already exists. Please choose another.");
}
$cout1 = DeployMintTools::mexec("$git checkout master 2>&1", $dir);
//Before we do our initial commit we will get an error trying to checkout master because it doesn't exist.
if (!preg_match("/(?:Switched to branch|Already on|error: pathspec 'master' did not match)/", $cout1)) {
throw new Exception("We could not switch the git repository in $dir to 'master'. The output was: $cout1");
}
$prefix = $this->getTablePrefix($blogId);
$prefixFile = $dir . 'deployData.txt';
$fh2 = fopen($prefixFile, 'w');
if (!fwrite($fh2, $prefix . ':' . microtime(true))) {
throw new Exception("We could not write to deployData.txt in the directory $dir");
}
fclose($fh2);
// Add the Media locations
$this->copyFilesToDataDir($blogId, $dir);
$add = DeployMintProjectTools::git('add .', $dir);
$siteURLRes = $this->pdb->get_row("SELECT option_name, option_value FROM {$prefix}options WHERE option_name = 'siteurl'", ARRAY_A);
$siteURL = $siteURLRes['option_value'];
$desc = "Snapshot of: $siteURL\n" . $desc;
$dumpErrs = array();
$tables = $this->getTablesToSnapshot($projectId, $prefix);
DeployMintTools::mexec("rm -fr $dir/*.sql");
foreach ($tables as $t) {
$tableFile = preg_replace("/^$prefix/", '', $t) . '.sql';
$tableName = $t;
$path = $dir . $tableFile;
$dbuser = DB_USER;
$dbpass = DB_PASSWORD;
$dbhost = DB_HOST;
$dbname = DB_NAME;
$o1 = DeployMintTools::mexec("$mysqldump --skip-comments --extended-insert --complete-insert --skip-comments -u $dbuser -p$dbpass -h $dbhost $dbname $tableName > $path 2>&1", $dir);
if (preg_match('/\w+/', $o1)) {
array_push($dumpErrs, $o1);
} else {
$grepOut = DeployMintTools::mexec("grep CREATE $path 2>&1");
if (!preg_match('/CREATE/', $grepOut)) {
array_push($dumpErrs, "We could not create a valid table dump file for $tableName");
} else {
$gitAddOut = DeployMintTools::mexec("$git add $tableFile 2>&1", $dir);
if (preg_match('/\w+/', $gitAddOut)) {
throw new Exception("We encountered an error running '$git add $tableFile' the error was: $gitAddOut");
}
}
}
}
if (sizeof($dumpErrs) > 0) {
$resetOut = DeployMintProjectTools::git('reset --hard HEAD', $dir);
if (!preg_match('/HEAD is now at/', $resetOut)) {
throw new Exception("Errors occured during mysqldump and we could not revert the git repository in $dir back to it's original state using '$git reset --hard HEAD'. The output we got was: " . $resetOut);
}
throw new Exception("Errors occured during mysqldump: " . implode(', ', $dumpErrs));
}
$tmpfile = $datadir . microtime(true) . '.tmp';
$fh = fopen($tmpfile, 'w');
fwrite($fh, $desc);
fclose($fh);
global $current_user;
get_currentuserinfo();
$user_name = trim($current_user->user_firstname . ' ' . $current_user->user_lastname);
if ($user_name == '') {
$user_name = $current_user->display_name;
}
$commitUser = $user_name . ' <' . $current_user->user_email . '>';
$commitOut2 = DeployMintProjectTools::git("commit --author=\"$commitUser\" -a -F \"$tmpfile\"", $dir);
unlink($tmpfile);
if (!preg_match('/files changed/', $commitOut2)) {
throw new Exception("git commit failed. The output we got was: $commitOut2");
}
$brOut2 = DeployMintProjectTools::git('branch ' . $name, $dir);
if (preg_match('/\w+/', $brOut2)) {
throw new Exception("We encountered an error running '$git branch $name' the output was: $brOut2");
}
DeployMintProjectTools::git('push origin ' . $name, $dir);
return true;
}
public function actionGetDeployOptions()
{
$this->checkPerms();
try {
$blogs = $this->getProjectBlogs($_REQUEST['projectid']);
$snapshots = $this->getProjectSnapshots($_REQUEST['projectid']);
die(json_encode(array('blogs'=>$blogs,'snapshots'=>$snapshots,'deployParts'=>$this->getAvailableDeployParts())));
} catch (Exception $e){
die(json_encode(array('err' => $e->getMessage())));
}
}
protected function getProjectSnapshots($projectId)
{
$opt = $this->getOptions();
extract($opt, EXTR_OVERWRITE);
$project = $this->getProject($projectId);
$dir = $datadir . $project['dir'];
if (!is_dir($dir)) {
throw new Exception("The directory $dir for this project does not exist.");
}
$fetch = DeployMintProjectTools::fetch($dir);
$branches = DeployMintProjectTools::getAllBranches($dir);
$bprefix = DeployMintProjectTools::remoteExists($dir) ? 'remotes/origin/' : '';
$snapshots = array();
for ($i = 0; $i < sizeof($branches); $i++) {
if (preg_match('/\w+/', $branches[$i])) {
$bname = $branches[$i];
if ($bname == 'master') {
continue;
}
$dateOut = DeployMintTools::mexec("$git log -n 1 {$bprefix}{$bname} | grep Date 2>&1", $dir);
$m = '';
if (preg_match('/Date:\s+(.+)$/', $dateOut, $m)) {
$ctime = strtotime($m[1]);
$date = $m[1];
array_push($snapshots, array('name' => $branches[$i], 'created' => $date, 'ctime' => $ctime));
}
} else {
unset($branches[$i]);
}
}
if (sizeof($snapshots) > 0) {
function ctimeSort($b, $a)
{
if ($a['ctime'] == $b['ctime']) {
return 0;
} return ($a['ctime'] < $b['ctime']) ? -1 : 1;
}
usort($snapshots, 'ctimeSort');
}
return $snapshots;
}
public function actionDeploySnapshot()
{
$this->checkPerms();
try {
if ($this->deploySnapshot($_REQUEST['name'], $_REQUEST['blogid'], $_REQUEST['projectid'], $_REQUEST['username'], $_REQUEST['password'], $_REQUEST['deployParts'])) {
die(json_encode(array('ok' => 1)));
}
} catch (Exception $e){
//$this->ajaxError($e->getMessage());
die(json_encode(array('err' => $e->getMessage())));
}
}
public function actionArchiveSnapshot()
{
$this->checkPerms();
try {
if ($this->archiveSnapshot($_REQUEST['projectId'], $_REQUEST['snapshots'])) {
die(json_encode(array('ok' => 1)));
}
} catch (Exception $e){
//$this->ajaxError($e->getMessage());
die(json_encode(array('err' => $e->getMessage())));
}
}
protected function deploySnapshot($snapshot, $blogId, $projectId, $username=null, $password=null, $deployParts=array())
{