-
Notifications
You must be signed in to change notification settings - Fork 0
/
moadmin.php
executable file
·2427 lines (2281 loc) · 102 KB
/
moadmin.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 error_reporting(E_ALL | E_STRICT);
/**
* phpMoAdmin - built on a stripped-down version of the Vork framework
*
* www.phpMoAdmin.com
* www.Vork.us
* www.MongoDB.org
*
* @version 1.0.9
* @author Eric David Benari, Chief Architect, phpMoAdmin
* @license GPL v3 - http://vork.us/go/mvz5
*/
/**
* To enable password protection, uncomment below and then change the username => password
* You can add as many users as needed, eg.: array('scott' => 'tiger', 'samantha' => 'goldfish', 'gene' => 'alpaca')
*/
//$accessControl = array('scott' => 'tiger');
/**
* Uncomment to restrict databases-access to just the databases added to the array below
* uncommenting will also remove the ability to create a new database
*/
//moadminModel::$databaseWhitelist = array('admin');
/**
* Sets the design theme - themes options are: swanky-purse, trontastic and classic
*/
define('THEME', 'trontastic');
/**
* To connect to a remote or authenticated Mongo instance, define the connection string in the MONGO_CONNECTION constant
* mongodb://[username:password@]host1[:port1][,host2[:port2:],...]
* If you do not know what this means then it is not relevant to your application and you can safely leave it as-is
*/
define('MONGO_CONNECTION', '');
/**
* Set to true when connecting to a Mongo replicaSet
* If you do not know what this means then it is not relevant to your application and you can safely leave it as-is
*/
define('REPLICA_SET', false);
/**
* Default limit for number of objects to display per page - set to 0 for no limit
*/
define('OBJECT_LIMIT', 100);
/**
* Vork core-functionality tools
*/
class get {
/**
* Opens up public access to config constants and variables and the cache object
* @var object
*/
public static $config;
/**
* Index of objects loaded, used to maintain uniqueness of singletons
* @var array
*/
public static $loadedObjects = array();
/**
* Gets the current URL
*
* @param mixed $ssl Boolean (true=https, false=http) or null (auto-selects the current protocol)
* @param Boolean $noGet Adds the GET request if true
* @return string
*/
public static function url($ssl = null, $noGet = true) {
if ($ssl === null) {
$ssl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on');
}
return (!$ssl ? 'http://' : 'https://') . $_SERVER['HTTP_HOST']
. $_SERVER[$noGet ? 'SCRIPT_NAME' : 'REQUEST_URI'];
}
/**
* Overloads the php function htmlentities and changes the default charset to UTF-8 and the default value for the
* fourth parameter $doubleEncode to false. Also adds ability to pass a null value to get the default $quoteStyle
* and $charset (removes need to repeatedly define ENT_COMPAT, 'UTF-8', just to access the $doubleEncode argument)
*
* If you are using a PHP version prior to 5.2.3 the $doubleEncode parameter is not available so you will need
* to comment out the last parameter in the return clause (including the preceding comma)
*
* @param string $string
* @param int $quoteStyle Uses ENT_COMPAT if null or omitted
* @param string $charset Uses UTF-8 if null or omitted
* @param boolean $doubleEncode
* @return string
*/
public static function htmlentities($string, $quoteStyle = ENT_COMPAT, $charset = 'UTF-8', $doubleEncode = false) {
return htmlentities($string, (!is_null($quoteStyle) ? $quoteStyle : ENT_COMPAT),
(!is_null($charset) ? $charset : 'UTF-8'), $doubleEncode);
}
/**
* Initialize the character maps needed for the xhtmlentities() method and verifies the argument values
* passed to it are valid.
*
* @param int $quoteStyle
* @param string $charset Only valid options are UTF-8 and ISO-8859-1 (Latin-1)
* @param boolean $doubleEncode
*/
protected static function initXhtmlentities($quoteStyle, $charset, $doubleEncode) {
$chars = get_html_translation_table(HTML_ENTITIES, $quoteStyle);
if (isset($chars)) {
unset($chars['<'], $chars['>']);
$charMaps[$quoteStyle]['ISO-8859-1'][true] = $chars;
$charMaps[$quoteStyle]['ISO-8859-1'][false] = array_combine(array_values($chars), $chars);
$charMaps[$quoteStyle]['UTF-8'][true] = array_combine(array_map('utf8_encode', array_keys($chars)), $chars);
$charMaps[$quoteStyle]['UTF-8'][false] = array_merge($charMaps[$quoteStyle]['ISO-8859-1'][false],
$charMaps[$quoteStyle]['UTF-8'][true]);
self::$loadedObjects['xhtmlEntities'] = $charMaps;
}
if (!isset($charMaps[$quoteStyle][$charset][$doubleEncode])) {
if (!isset($chars)) {
$invalidArgument = 'quoteStyle = ' . $quoteStyle;
} else if (!isset($charMaps[$quoteStyle][$charset])) {
$invalidArgument = 'charset = ' . $charset;
} else {
$invalidArgument = 'doubleEncode = ' . (string) $doubleEncode;
}
trigger_error('Undefined argument sent to xhtmlentities() method: ' . $invalidArgument, E_USER_NOTICE);
}
}
/**
* Converts special characters in a string to XHTML-valid ASCII encoding the same as htmlentities except
* this method allows the use of HTML tags within your string. Signature is the same as htmlentities except
* that the only character sets available (third argument) are UTF-8 (default) and ISO-8859-1 (Latin-1).
*
* @param string $string
* @param int $quoteStyle Constants available are ENT_NOQUOTES (default), ENT_QUOTES, ENT_COMPAT
* @param string $charset Only valid options are UTF-8 (default) and ISO-8859-1 (Latin-1)
* @param boolean $doubleEncode Default is false
* @return string
*/
public static function xhtmlentities($string, $quoteStyle = ENT_NOQUOTES, $charset = 'UTF-8',
$doubleEncode = false) {
$quoteStyles = array(ENT_NOQUOTES, ENT_QUOTES, ENT_COMPAT);
$quoteStyle = (!in_array($quoteStyle, $quoteStyles) ? current($quoteStyles) : $quoteStyle);
$charset = ($charset != 'ISO-8859-1' ? 'UTF-8' : $charset);
$doubleEncode = (Boolean) $doubleEncode;
if (!isset(self::$loadedObjects['xhtmlEntities'][$quoteStyle][$charset][$doubleEncode])) {
self::initXhtmlentities($quoteStyle, $charset, $doubleEncode);
}
return strtr($string, self::$loadedObjects['xhtmlEntities'][$quoteStyle][$charset][$doubleEncode]);
}
/**
* Loads an object as a singleton
*
* @param string $objectType
* @param string $objectName
* @return object
*/
protected static function _loadObject($objectType, $objectName) {
if (isset(self::$loadedObjects[$objectType][$objectName])) {
return self::$loadedObjects[$objectType][$objectName];
}
$objectClassName = $objectName . ucfirst($objectType);
if (class_exists($objectClassName)) {
$objectObject = new $objectClassName;
self::$loadedObjects[$objectType][$objectName] = $objectObject;
return $objectObject;
} else {
$errorMsg = 'Class for ' . $objectType . ' ' . $objectName . ' could not be found';
}
trigger_error($errorMsg, E_USER_WARNING);
}
/**
* Returns a helper object
*
* @param string $model
* @return object
*/
public static function helper($helper) {
if (is_array($helper)) {
array_walk($helper, array('self', __METHOD__));
return;
}
if (!isset(self::$config['helpers']) || !in_array($helper, self::$config['helpers'])) {
self::$config['helpers'][] = $helper;
}
return self::_loadObject('helper', $helper);
}
}
/**
* Public interface to load elements and cause redirects
*/
class load {
/**
* Sends a redirects header and disables view rendering
* This redirects via a browser command, this is not the same as changing controllers which is handled within MVC
*
* @param string $url Optional, if undefined this will refresh the page (mostly useful for dumping post values)
*/
public static function redirect($url = null) {
header('Location: ' . ($url ? $url : get::url(null, false)));
}
}
/**
* Thrown when the mongod server is not accessible
*/
class cannotConnectToMongoServer extends Exception {
public function __toString() {
return '<h1>Cannot connect to the MongoDB database.</h1> ' . PHP_EOL . 'If Mongo is installed then be sure that'
. ' an instance of the "mongod" server, not "mongo" shell, is running. <br />' . PHP_EOL
. 'Instructions and database download: <a href="http://vork.us/go/fhk4">http://vork.us/go/fhk4</a>';
}
}
/**
* Thrown when the mongo extension for PHP is not installed
*/
class mongoExtensionNotInstalled extends Exception {
public function __toString() {
return '<h1>PHP cannot access MongoDB, you need to install the Mongo extension for PHP.</h1> '
. PHP_EOL . 'Instructions and driver download: '
. '<a href="http://vork.us/go/tv27">http://vork.us/go/tv27</a>';
}
}
/**
* phpMoAdmin data model
*/
class moadminModel {
/**
* mongo connection - if a MongoDB object already exists (from a previous script) then only DB operations use this
* @var Mongo
*/
protected $_db;
/**
* Name of last selected DB
* @var string Defaults to admin as that is available in all Mongo instances
*/
public static $dbName = 'admin';
/**
* MongoDB
* @var MongoDB
*/
public $mongo;
/**
* Returns a new Mongo connection
* @return Mongo
*/
protected function _mongo() {
$connection = (!MONGO_CONNECTION ? 'mongodb://localhost:27017' : MONGO_CONNECTION);
return (!REPLICA_SET ? new Mongo($connection) : new Mongo($connection, array('replicaSet' => true)));
}
/**
* Connects to a Mongo database if the name of one is supplied as an argument
* @param string $db
*/
public function __construct($db = null) {
if (self::$databaseWhitelist && !in_array($db, self::$databaseWhitelist)) {
$db = self::$dbName = $_GET['db'] = current(self::$databaseWhitelist);
}
if ($db) {
if (!extension_loaded('mongo')) {
throw new mongoExtensionNotInstalled();
}
try {
$this->_db = $this->_mongo();
$this->mongo = $this->_db->selectDB($db);
} catch (MongoConnectionException $e) {
throw new cannotConnectToMongoServer();
}
}
}
/**
* Executes a native JS MongoDB command
* This method is not currently used for anything
* @param string $cmd
* @return mixed
*/
protected function _exec($cmd) {
$exec = $this->mongo->execute($cmd);
return $exec['retval'];
}
/**
* Change the DB connection
* @param string $db
*/
public function setDb($db) {
if (self::$databaseWhitelist && !in_array($db, self::$databaseWhitelist)) {
$db = current(self::$databaseWhitelist);
}
if (!isset($this->_db)) {
$this->_db = $this->_mongo();
}
$this->mongo = $this->_db->selectDB($db);
self::$dbName = $db;
}
/**
* Total size of all the databases
* @var int
*/
public $totalDbSize = 0;
/**
* Adds ability to restrict databases-access to those on the whitelist
* @var array
*/
public static $databaseWhitelist = array();
/**
* Gets list of databases
* @return array
*/
public function listDbs() {
$return = array();
$restrictDbs = (bool) self::$databaseWhitelist;
$dbs = $this->_db->selectDB('admin')->command(array('listDatabases' => 1));
$this->totalDbSize = $dbs['totalSize'];
foreach ($dbs['databases'] as $db) {
if (!$restrictDbs || in_array($db['name'], self::$databaseWhitelist)) {
$return[$db['name']] = $db['name'] . ' ('
. (!$db['empty'] ? round($db['sizeOnDisk'] / 1000000) . 'mb' : 'empty') . ')';
}
}
ksort($return);
$dbCount = 0;
foreach ($return as $key => $val) {
$return[$key] = ++$dbCount . '. ' . $val;
}
return $return;
}
/**
* Generate system info and stats
* @return array
*/
public function getStats() {
$admin = $this->_db->selectDB('admin');
$return = array_merge($admin->command(array('buildinfo' => 1)),
$admin->command(array('serverStatus' => 1)));
$profile = $admin->command(array('profile' => -1));
$return['profilingLevel'] = $profile['was'];
$return['mongoDbTotalSize'] = round($this->totalDbSize / 1000000) . 'mb';
$prevError = $admin->command(array('getpreverror' => 1));
if (!$prevError['n']) {
$return['previousDbErrors'] = 'None';
} else {
$return['previousDbErrors']['error'] = $prevError['err'];
$return['previousDbErrors']['numberOfOperationsAgo'] = $prevError['nPrev'];
}
$return['globalLock']['totalTime'] .= ' µSec';
$return['uptime'] = round($return['uptime'] / 60) . ':' . str_pad($return['uptime'] % 60, 2, '0', STR_PAD_LEFT)
. ' minutes';
$unshift['mongo'] = $return['version'] . ' (' . $return['bits'] . '-bit)';
$unshift['mongoPhpDriver'] = Mongo::VERSION;
$unshift['phpMoAdmin'] = '1.0.9';
$unshift['php'] = PHP_VERSION . ' (' . (PHP_INT_MAX > 2200000000 ? 64 : 32) . '-bit)';
$unshift['gitVersion'] = $return['gitVersion'];
unset($return['ok'], $return['version'], $return['gitVersion'], $return['bits']);
$return = array_merge(array('version' => $unshift), $return);
$iniIndex = array(-1 => 'Unlimited', 'Off', 'On');
$phpIni = array('allow_persistent', 'auto_reconnect', 'chunk_size', 'cmd', 'default_host', 'default_port',
'max_connections', 'max_persistent');
foreach ($phpIni as $ini) {
$key = 'php_' . $ini;
$return[$key] = ini_get('mongo.' . $ini);
if (isset($iniIndex[$return[$key]])) {
$return[$key] = $iniIndex[$return[$key]];
}
}
return $return;
}
/**
* Repairs a database
* @return array Success status
*/
public function repairDb() {
return $this->mongo->repair();
}
/**
* Drops a database
*/
public function dropDb() {
$this->mongo->drop();
return;
if (!isset($this->_db)) {
$this->_db = $this->_mongo();
}
$this->_db->dropDB($this->mongo);
}
/**
* Gets a list of database collections
* @return array
*/
public function listCollections() {
$collections = array();
$MongoCollectionObjects = $this->mongo->listCollections();
foreach ($MongoCollectionObjects as $collection) {
$collection = substr(strstr((string) $collection, '.'), 1);
$collections[$collection] = $this->mongo->selectCollection($collection)->count();
}
ksort($collections);
return $collections;
}
/**
* Drops a collection
* @param string $collection
*/
public function dropCollection($collection) {
$this->mongo->selectCollection($collection)->drop();
}
/**
* Creates a collection
* @param string $collection
*/
public function createCollection($collection) {
if ($collection) {
$this->mongo->createCollection($collection);
}
}
/**
* Renames a collection
*
* @param string $from
* @param string $to
*/
public function renameCollection($from, $to) {
$result = $this->_db->selectDB('admin')->command(array(
'renameCollection' => self::$dbName . '.' . $from,
'to' => self::$dbName . '.' . $to,
));
}
/**
* Gets a list of the indexes on a collection
*
* @param string $collection
* @return array
*/
public function listIndexes($collection) {
return $this->mongo->selectCollection($collection)->getIndexInfo();
}
/**
* Ensures an index
*
* @param string $collection
* @param array $indexes
* @param array $unique
*/
public function ensureIndex($collection, array $indexes, array $unique) {
$unique = ($unique ? true : false); //signature requires a bool in both Mongo v. 1.0.1 and 1.2.0
$this->mongo->selectCollection($collection)->ensureIndex($indexes, $unique);
}
/**
* Removes an index
*
* @param string $collection
* @param array $index Must match the array signature of the index
*/
public function deleteIndex($collection, array $index) {
$this->mongo->selectCollection($collection)->deleteIndex($index);
}
/**
* Sort array - currently only used for collections
* @var array
*/
public $sort = array('_id' => 1);
/**
* Number of rows in the entire resultset (before limit-clause is applied)
* @var int
*/
public $count;
/**
* Array keys in the first and last object in a collection merged together (used to build sort-by options)
* @var array
*/
public $colKeys = array();
/**
* Get the records in a collection
*
* @param string $collection
* @return array
*/
public function listRows($collection) {
foreach ($this->sort as $key => $val) { //cast vals to int
$sort[$key] = (int) $val;
}
$col = $this->mongo->selectCollection($collection);
$find = array();
if (isset($_GET['find']) && $_GET['find']) {
$_GET['find'] = trim($_GET['find']);
if (strpos($_GET['find'], 'array') === 0) {
eval('$find = ' . $_GET['find'] . ';');
} else if (is_string($_GET['find'])) {
if ($findArr = json_decode($_GET['find'], true)) {
$find = $findArr;
}
}
}
if (isset($_GET['search']) && $_GET['search']) {
switch (substr(trim($_GET['search']), 0, 1)) { //first character
case '/': //regex
$find[$_GET['searchField']] = new mongoRegex($_GET['search']);
break;
case '{': //JSON
if ($search = json_decode($_GET['search'], true)) {
$find[$_GET['searchField']] = $search;
}
break;
case '(':
$types = array('bool', 'boolean', 'int', 'integer', 'float', 'double', 'string', 'array', 'object',
'null', 'mongoid');
$closeParentheses = strpos($_GET['search'], ')');
if ($closeParentheses) {
$cast = strtolower(substr($_GET['search'], 1, ($closeParentheses - 1)));
if (in_array($cast, $types)) {
$search = trim(substr($_GET['search'], ($closeParentheses + 1)));
if ($cast == 'mongoid') {
$search = new MongoID($search);
} else {
settype($search, $cast);
}
$find[$_GET['searchField']] = $search;
break;
}
} //else no-break
default: //text-search
if (strpos($_GET['search'], '*') === false) {
if (!is_numeric($_GET['search'])) {
$find[$_GET['searchField']] = $_GET['search'];
} else { //$_GET is always a string-type
$in = array((string) $_GET['search'], (int) $_GET['search'], (float) $_GET['search']);
$find[$_GET['searchField']] = array('$in' => $in);
}
} else { //text with wildcards
$regex = '/' . str_replace('\*', '.*', preg_quote($_GET['search'])) . '/i';
$find[$_GET['searchField']] = new mongoRegex($regex);
}
break;
}
}
$cols = (!isset($_GET['cols']) ? array() : array_fill_keys($_GET['cols'], true));
$cur = $col->find($find, $cols)->sort($sort);
$this->count = $cur->count();
//get keys of first object
if ($_SESSION['limit'] && $this->count > $_SESSION['limit']) { //more results than per-page limit
if ($this->count > 1) {
$this->colKeys = phpMoAdmin::getArrayKeys($col->findOne());
}
$cur->limit($_SESSION['limit']);
if (isset($_GET['skip'])) {
if ($this->count <= $_GET['skip']) {
$_GET['skip'] = ($this->count - $_SESSION['limit']);
}
$cur->skip($_GET['skip']);
}
} else if ($this->count) { // results exist but are fewer than per-page limit
$this->colKeys = phpMoAdmin::getArrayKeys($cur->getNext());
} else if ($find && $col->count()) { //query is not returning anything, get cols from first obj in collection
$this->colKeys = phpMoAdmin::getArrayKeys($col->findOne());
}
//get keys of last or much-later object
if ($this->count > 1) {
$curLast = $col->find()->sort($sort);
if ($this->count > 2) {
$curLast->skip(min($this->count, 100) - 1);
}
$this->colKeys = array_merge($this->colKeys, phpMoAdmin::getArrayKeys($curLast->getNext()));
ksort($this->colKeys);
}
return $cur;
}
/**
* Returns a serialized element back to its native PHP form
*
* @param string $_id
* @param string $idtype
* @return mixed
*/
protected function _unserialize($_id, $idtype) {
if ($idtype == 'object' || $idtype == 'array') {
$errLevel = error_reporting();
error_reporting(0); //unserializing an object that is not serialized throws a warning
$_idObj = unserialize($_id);
error_reporting($errLevel);
if ($_idObj !== false) {
$_id = $_idObj;
}
} else if (gettype($_id) != $idtype) {
settype($_id, $idtype);
}
return $_id;
}
/**
* Removes an object from a collection
*
* @param string $collection
* @param string $_id
* @param string $idtype
*/
public function removeObject($collection, $_id, $idtype) {
$this->mongo->selectCollection($collection)->remove(array('_id' => $this->_unserialize($_id, $idtype)));
}
/**
* Retieves an object for editing
*
* @param string $collection
* @param string $_id
* @param string $idtype
* @return array
*/
public function editObject($collection, $_id, $idtype) {
return $this->mongo->selectCollection($collection)->findOne(array('_id' => $this->_unserialize($_id, $idtype)));
}
/**
* Saves an object
*
* @param string $collection
* @param string $obj
* @return array
*/
public function saveObject($collection, $obj) {
eval('$obj=' . $obj . ';'); //cast from string to array
return $this->mongo->selectCollection($collection)->save($obj);
}
}
/**
* phpMoAdmin application control
*/
class moadminComponent {
/**
* $this->mongo is used to pass properties from component to view without relying on a controller to return them
* @var array
*/
public $mongo = array();
/**
* Model object
* @var moadminModel
*/
public static $model;
/**
* Removes the POST/GET params
*/
protected function _dumpFormVals() {
load::redirect(get::url() . '?action=listRows&db=' . urlencode($_GET['db'])
. '&collection=' . urlencode($_GET['collection']));
}
/**
* Routes requests and sets return data
*/
public function __construct() {
if (class_exists('mvc')) {
mvc::$view = '#moadmin';
}
$this->mongo['dbs'] = self::$model->listDbs();
if (isset($_GET['db'])) {
if (strpos($_GET['db'], '.') !== false) {
$_GET['db'] = $_GET['newdb'];
}
self::$model->setDb($_GET['db']);
}
if (isset($_POST['limit'])) {
$_SESSION['limit'] = (int) $_POST['limit'];
} else if (!isset($_SESSION['limit'])) {
$_SESSION['limit'] = OBJECT_LIMIT;
}
$action = (isset($_GET['action']) ? $_GET['action'] : 'listCollections');
if (isset($_POST['object'])) {
if (self::$model->saveObject($_GET['collection'], $_POST['object'])) {
return $this->_dumpFormVals();
} else {
$action = 'editObject';
$_POST['errors']['object'] = 'Error: object could not be saved - check your array syntax.';
}
} else if ($action == 'createCollection') {
self::$model->$action($_GET['collection']);
} else if ($action == 'renameCollection'
&& isset($_POST['collectionto']) && $_POST['collectionto'] != $_POST['collectionfrom']) {
self::$model->$action($_POST['collectionfrom'], $_POST['collectionto']);
$_GET['collection'] = $_POST['collectionto'];
$action = 'listRows';
}
if (isset($_GET['sort'])) {
self::$model->sort = array($_GET['sort'] => $_GET['sortdir']);
}
$this->mongo['listCollections'] = self::$model->listCollections();
if ($action == 'editObject') {
$this->mongo[$action] = (isset($_GET['_id'])
? self::$model->$action($_GET['collection'], $_GET['_id'], $_GET['idtype']) : '');
return;
} else if ($action == 'removeObject') {
self::$model->$action($_GET['collection'], $_GET['_id'], $_GET['idtype']);
return $this->_dumpFormVals();
} else if ($action == 'ensureIndex') {
foreach ($_GET['index'] as $key => $field) {
$indexes[$field] = (isset($_GET['isdescending'][$key]) && $_GET['isdescending'][$key] ? -1 : 1);
}
self::$model->$action($_GET['collection'], $indexes, ($_GET['unique'] == 'Unique' ? array('unique' => true)
: array()));
$action = 'listCollections';
} else if ($action == 'deleteIndex') {
self::$model->$action($_GET['collection'], unserialize($_GET['index']));
return $this->_dumpFormVals();
} else if ($action == 'getStats') {
$this->mongo[$action] = self::$model->$action();
unset($this->mongo['listCollections']);
} else if ($action == 'repairDb' || $action == 'getStats') {
$this->mongo[$action] = self::$model->$action();
$action = 'listCollections';
} else if ($action == 'dropDb') {
self::$model->$action();
load::redirect(get::url());
return;
}
if (isset($_GET['collection']) && $action != 'listCollections' && method_exists(self::$model, $action)) {
$this->mongo[$action] = self::$model->$action($_GET['collection']);
$this->mongo['count'] = self::$model->count;
$this->mongo['colKeys'] = self::$model->colKeys;
}
if ($action == 'listRows') {
$this->mongo['listIndexes'] = self::$model->listIndexes($_GET['collection']);
} else if ($action == 'dropCollection') {
return load::redirect(get::url() . '?db=' . urlencode($_GET['db']));
}
}
}
/**
* HTML helper tools
*/
class htmlHelper {
/**
* Internal storage of the link-prefix and hypertext protocol values
* @var string
*/
protected $_linkPrefix, $_protocol;
/**
* Internal list of included CSS & JS files used by $this->_tagBuilder() to assure that files are not included twice
* @var array
*/
protected $_includedFiles = array();
/**
* Flag array to avoid defining singleton JavaScript & CSS snippets more than once
* @var array
*/
protected $_jsSingleton = array(), $_cssSingleton = array();
/**
* Sets the protocol (http/https)
*/
public function __construct() {
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
$this->_linkPrefix = 'http://' . $_SERVER['HTTP_HOST'];
$this->_protocol = 'https://';
} else {
$this->_protocol = 'http://';
}
}
/**
* Creates simple HTML wrappers, accessed via $this->__call()
*
* JS and CSS files are never included more than once even if requested twice. If DEBUG mode is enabled than the
* second request will be added to the debug log as a duplicate. The jsSingleton and cssSingleton methods operate
* the same as the js & css methods except that they will silently skip duplicate requests instead of logging them.
*
* jsInlineSingleton and cssInlineSingleton makes sure a JavaScript or CSS snippet will only be output once, even
* if echoed out multiple times and this method will attempt to place the JS code into the head section, if <head>
* has already been echoed out then it will return the JS code inline the same as jsInline. Eg.:
* $helloJs = "function helloWorld() {alert('Hello World');}";
* echo $html->jsInlineSingleton($helloJs);
*
* Adding an optional extra argument to jsInlineSingleton/cssInlineSingleton will return the inline code bare (plus
* a trailing linebreak) if it cannot place it into the head section, this is used for joint JS/CSS statements:
* echo $html->jsInline($html->jsInlineSingleton($helloJs, true) . 'helloWorld();');
*
* @param string $tagType
* @param array $args
* @return string
*/
protected function _tagBuilder($tagType, $args = array()) {
$arg = current($args);
if (empty($arg) || $arg === '') {
$errorMsg = 'Missing argument for ' . __CLASS__ . '::' . $tagType . '()';
trigger_error($errorMsg, E_USER_WARNING);
}
if (is_array($arg)) {
foreach ($arg as $thisArg) {
$return[] = $this->_tagBuilder($tagType, array($thisArg));
}
$return = implode(PHP_EOL, $return);
} else {
switch ($tagType) {
case 'js':
case 'jsSingleton':
case 'css': //Optional extra argument to define CSS media type
case 'cssSingleton':
case 'jqueryTheme':
if ($tagType == 'jqueryTheme') {
$arg = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/'
. str_replace(' ', '-', strtolower($arg)) . '/jquery-ui.css';
$tagType = 'css';
}
if (!isset($this->_includedFiles[$tagType][$arg])) {
if ($tagType == 'css' || $tagType == 'cssSingleton') {
$return = '<link rel="stylesheet" type="text/css" href="' . $arg . '"'
. ' media="' . (isset($args[1]) ? $args[1] : 'all') . '" />';
} else {
$return = '<script type="text/javascript" src="' . $arg . '"></script>';
}
$this->_includedFiles[$tagType][$arg] = true;
} else {
$return = null;
if (DEBUG_MODE && ($tagType == 'js' || $tagType == 'css')) {
debug::log($arg . $tagType . ' file has already been included', 'warn');
}
}
break;
case 'cssInline': //Optional extra argument to define CSS media type
$return = '<style type="text/css" media="' . (isset($args[1]) ? $args[1] : 'all') . '">'
. PHP_EOL . '/*<![CDATA[*/'
. PHP_EOL . '<!--'
. PHP_EOL . $arg
. PHP_EOL . '//-->'
. PHP_EOL . '/*]]>*/'
. PHP_EOL . '</style>';
break;
case 'jsInline':
$return = '<script type="text/javascript">'
. PHP_EOL . '//<![CDATA['
. PHP_EOL . '<!--'
. PHP_EOL . $arg
. PHP_EOL . '//-->'
. PHP_EOL . '//]]>'
. PHP_EOL . '</script>';
break;
case 'jsInlineSingleton': //Optional extra argument to supress adding of inline JS/CSS wrapper
case 'cssInlineSingleton':
$tagTypeBase = substr($tagType, 0, -15);
$return = null;
$md5 = md5($arg);
if (!isset($this->{'_' . $tagTypeBase . 'Singleton'}[$md5])) {
$this->{'_' . $tagTypeBase . 'Singleton'}[$md5] = true;
if (!$this->_bodyOpen) {
$this->vorkHead[$tagTypeBase . 'Inline'][] = $arg;
} else {
$return = (!isset($args[1]) || !$args[1] ? $this->{$tagTypeBase . 'Inline'}($arg)
: $arg . PHP_EOL);
}
}
break;
case 'div':
case 'li':
case 'p':
case 'h1':
case 'h2':
case 'h3':
case 'h4':
$return = '<' . $tagType . '>' . $arg . '</' . $tagType . '>';
break;
default:
$errorMsg = 'TagType ' . $tagType . ' not valid in ' . __CLASS__ . '::' . __METHOD__;
throw new Exception($errorMsg);
break;
}
}
return $return;
}
/**
* Creates virtual wrapper methods via $this->_tagBuilder() for the simple wrapper functions including:
* $html->css, js, cssInline, jsInline, div, li, p and h1-h4
*
* @param string $method
* @param array $arg
* @return string
*/
public function __call($method, $args) {
$validTags = array('css', 'js', 'cssSingleton', 'jsSingleton', 'jqueryTheme',
'cssInline', 'jsInline', 'jsInlineSingleton', 'cssInlineSingleton',
'div', 'li', 'p', 'h1', 'h2', 'h3', 'h4');
if (in_array($method, $validTags)) {
return $this->_tagBuilder($method, $args);
} else {
$errorMsg = 'Call to undefined method ' . __CLASS__ . '::' . $method . '()';
trigger_error($errorMsg, E_USER_ERROR);
}
}
/**
* Flag to make sure that header() can only be opened one-at-a-time and footer() can only be used after header()
* @var boolean
*/
private $_bodyOpen = false;
/**
* Sets the default doctype to XHTML 1.1
* @var string
*/
protected $_docType = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">';
/**
* Allows modification of the docType
*
* Can either set to an actual doctype definition or to one of the presets (case-insensitive):
* XHTML Mobile 1.2
* XHTML Mobile 1.1
* XHTML Mobile 1.0
* Mobile 1.2 (alias for XHTML Mobile 1.2)
* Mobile 1.1 (alias for XHTML Mobile 1.1)
* Mobile 1.0 (alias for XHTML Mobile 1.0)
* Mobile (alias for the most-strict Mobile DTD, currently 1.2)
* XHTML 1.1 (this is the default DTD, there is no need to apply this method for an XHTML 1.1 doctype)
* XHTML (Alias for XHTML 1.1)
* XHTML 1.0 Strict
* XHTML 1.0 Transitional
* XHTML 1.0 Frameset
* XHTML 1.0 (Alias for XHTML 1.0 Strict)
* HTML 5
* HTML 4.01
* HTML (Alias for HTML 4.01)
*
* @param string $docType
*/
public function setDocType($docType) {
$docType = str_replace(' ', '', strtolower($docType));
if ($docType == 'xhtml1.1' || $docType == 'xhtml') {
return; //XHTML 1.1 is the default
} else if ($docType == 'xhtml1.0') {
$docType = 'strict';
}
$docType = str_replace(array('xhtml mobile', 'xhtml1.0'), array('mobile', ''), $docType);
$docTypes = array(
'mobile1.2' => '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" '
. '"http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">',
'mobile1.1' => '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.1//EN '
. '"http://www.openmobilealliance.org/tech/DTD/xhtml-mobile11.dtd">',
'mobile1.0' => '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" '
. '"http://www.wapforum.org/DTD/xhtml-mobile10.dtd">',
'strict' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" '
. '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
'transitional' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" '
. '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
'frameset' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" '
. '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">',
'html4.01' => '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" '
. '"http://www.w3.org/TR/html4/strict.dtd">',
'html5' => '<!DOCTYPE html>'
);
$docTypes['mobile'] = $docTypes['mobile1.2'];
$docTypes['html'] = $docTypes['html4.01'];
$this->_docType = (isset($docTypes[$docType]) ? $docTypes[$docType] : $docType);
}
/**
* Array used internally by Vork to cache JavaScript and CSS snippets and place them in the head section
* Changing the contents of this property may cause Vork components to be rendered incorrectly.
* @var array