/
core.js
627 lines (534 loc) · 14.1 KB
/
core.js
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
/**
* Contains the most low-level helpers methods in Johana:
*
* - Environment initialization
* - Locating files within the cascading filesystem
* - Auto-loading and transparent extension of objects
* - Variable and path debugging
*
* @package Johana
* @category Base
* @author Johana Team
* @copyright (c) 2011 Johana Team
* @license http://johanaframework.org/license
*/
JohanaCore = {};
// Release version and codename
JohanaCore.VERSION = '0.0.1.1';
JohanaCore.CODENAME = 'dubhe';
// Common environment type constants for consistency and convenience
JohanaCore.PRODUCTION = 1;
JohanaCore.STAGING = 2;
JohanaCore.TESTING = 3;
JohanaCore.DEVELOPMENT = 4;
/**
* @var String Current environment name
*/
JohanaCore.environment = JohanaCore.DEVELOPMENT;
/**
* @var Boolean True if Johana is running on windows
*/
JohanaCore.isWindows = false;
/**
* @var Boolean Should errors and exceptions be logged
*/
JohanaCore.logErrors = false;
/**
* @var String
*/
JohanaCore.contentType = 'text/html';
/**
* @var String character set of input and output
*/
JohanaCore.charset = 'utf-8';
/**
* @var String the name of the server Johana is hosted upon
*/
JohanaCore.serverName = '';
/**
* @var Object list of valid host names for this instance
*/
JohanaCore.hostnames = {};
/**
* @var String base URL to the application
*/
JohanaCore.baseUrl = '/';
/**
* @var String Cache directory, used by [Johana.cache]. Set by [Johana.init]
*/
JohanaCore.cacheDir;
/**
* @var Number Default lifetime for caching, in seconds, used by [Johana.cache]. Set by [Johana.init]
*/
JohanaCore.cacheLife = 60;
/**
* @var Boolean Whether to use internal caching for [Johana.findFile], does not apply to [Johana.cache]. Set by [Johana.init]
*/
JohanaCore.caching = false;
/**
* @var Boolean Whether to enable [profiling](Johana/profiling). Set by [Johana.init]
*/
JohanaCore.profiling = false;
/**
* @var Boolean Enable Johana catching and displaying errors. Set by [Johana.init]
*/
JohanaCore.errors = true;
/**
* @var Boolean set the X-Powered-By header
*/
JohanaCore.expose = false;
/**
* @var Log logging object
*/
JohanaCore.log;
/**
* @var Config config object
*/
JohanaCore.conf;
/**
* @var Boolean Has [Johana.init] been called?
*/
var _init = false;
/**
* @var Object Currently active modules
*/
var _modules = [];
/**
* @var Array Include paths that are used to find files
*/
var _paths = [APPPATH, SYSPATH];
/**
* @var Array File path cache, used when caching is true in [Johana.init]
*/
var _files = [];
/**
* @var Boolean Has the file path cache changed during this execution? Used internally when when caching is true in [Johana.init]
*/
var _filesChanged = false;
/**
* Initializes the environment:
*
* - Determines the current environment
* - Set global settings
*
* The following settings can be set:
*
* Type | Setting | Description | Default Value
* ----------|------------|------------------------------------------------|---------------
* `String` | baseUrl | The base URL for your application. This should be the *relative* path from your DOCROOT to your `/`, in other words, if JohanaCore is in a subfolder, set this to the subfolder name, otherwise leave it as the default. **The leading slash is required**, trailing slash is optional. | `"/"`
* `String` | charset | Character set used for all input and output | `"utf-8"`
* `String` | cacheDir | JohanaCore's cache directory. Used by [JohanaCore.cache] for simple internal caching, like [Fragments](JohanaCore/fragments) and **\[caching database queries](this should link somewhere)**. This has nothing to do with the [Cache module](cache). | `APPPATH + "cache"`
* `Number` | cacheLife | Lifetime, in seconds, of items cached by [JohanaCore.cache] | `60`
* `Boolean` | errors | Should JohanaCore catch errors and uncaught Exceptions and show the `error_view`. See [Error Handling](JohanaCore/errors) for more info. <br /> <br /> Recommended setting: `true` while developing, `false` on production servers. | `true`
* `Boolean` | profile | Whether to enable the [Profiler](JohanaCore/profiling). <br /> <br />Recommended setting: `true` while developing, `false` on production servers. | `true` * `Boolean` | caching | Cache file locations to speed up [JohanaCore.findFile]. This has nothing to do with [JohanaCore.cache], [Fragments](JohanaCore/fragments) or the [Cache module](cache). <br /> <br /> Recommended setting: `false` while developing, `true` on production servers. | `false`
*
* @throws Error
* @param Object Array of settings. See above.
* @return void
* @uses JohanaCore.cache
* @uses Profiler
*/
JohanaCore.init = function(settings)
{
settings = settings || {};
if (_init)
{
// Do not allow execution twice
return;
}
// JohanaCore is now initialized
_init = true;
if (settings['profile'] !== undefined)
{
// Enable profiling
Johana.profiling = settings['profile'];
}
if (settings['errors'] !== undefined)
{
// Enable error handling
Johana.errors = settings['errors'];
}
if (Johana.errors === true)
{
// // Enable JohanaCore exception handling, adds stack traces and error source.
// set_exception_handler(Object('JohanaCore_Exception', 'handler'));
//
// // Enable JohanaCore error handling, converts all PHP errors to exceptions.
// set_error_handler(Object('JohanaCore', 'error_handler'));
}
if (settings['expose'] !== undefined)
{
Johana.expose = settings['expose'];
}
// Determine if we are running in a Windows environment
if (process.platform === 'win32')
{
Johana.isWindows = true;
}
if (settings['cacheDir'] !== undefined)
{
try
{
var cacheDirExists = require('fs').statSync(settings['cacheDir']).isDirectory();
}
catch (e)
{
// Invalid cache path
var cacheDirExists = false;
}
if (!cacheDirExists)
{
try
{
// Create the cache directory
require('fs').mkdirSync(settings['cacheDir'], 0755);
}
catch (e)
{
throw new Error('Could not create cache directory ' +
settings['cacheDir']);
}
}
// Set the cache directory path
Johana.cacheDir = require('fs').realpathSync(settings['cacheDir']);
}
else
{
// Use the default cache directory
Johana.cacheDir = APPPATH + 'cache';
}
try
{
// Check if cache dir it writable
require('fs').chmodSync(Johana.cacheDir, 0755);
}
catch (e)
{
throw new Error('Directory ' + Johana.cacheDir + ' must be writable');
}
if (settings['cacheLife'] !== undefined)
{
// Set the default cache lifetime
Johana.cacheLife = settings['cacheLife'];
}
if (settings['caching'] !== undefined)
{
// Enable or disable internal caching
Johana.caching = settings['caching'];
}
if (settings['charset'] !== undefined)
{
// Set the system character set
Johana.charset = settings['charset'].toLowerCase();
}
if (settings['baseUrl'] !== undefined)
{
// Set the base URL
Johana.baseUrl = settings['baseUrl'].replace(/\/$/, '') + '/';
}
// // Load the logger
// Johana.log = Log.instance();
//
// Load the config
Johana.conf = Config.instance();
};
/**
* Cleans up the environment:
*
* - Restore the previous error and exception handlers
* - Destroy the Johana.log and Johana.config objects
*
* @return void
*/
JohanaCore.deinit = function()
{
if (_init)
{
// Destroy objects created by init
Johana.log = Johana.config = null;
// Reset internal storage
_modules = _files = [];
_paths = [APPPATH, SYSPATH];
// Reset file cache status
_filesChanged = false;
// Kohana is no longer initialized
_init = false;
}
};
/**
* Provides auto-loading support of base objects
*
* @param String prototype name
* @return Boolean
*/
JohanaCore.autoLoad = function(lib)
{
var file = lib.replace(/[A-Z]/g, '/$&').replace(/^\//, '').toLowerCase();
var path = Johana.findFile('prototypes', file);
if (global[lib] !== undefined)
{
// Object was loaded before
return true;
}
if (path)
{
// Make some magic
global.__defineGetter__(lib, function(){
delete global[lib];
return global[lib] = require(path);
});
global.__defineSetter__(lib, function(){
return global[lib] = require(path);
});
// Object has been found
return true;
}
// Object is not in the filesystem
return false;
};
/**
* Changes the currently enabled modules. Module paths may be relative
* or absolute, but must point to a directory:
*
* Kohana.modules({'modules/foo': MODPATH+'bar'});
*
* @param Object list of module paths
* @return Object enabled modules
*/
JohanaCore.modules = function(modules)
{
modules = modules || null;
if (modules === null)
{
// Not changing modules, just return the current set
return _modules;
}
// Start a new list of include paths, APPPATH first
var paths = new Array(APPPATH);
for (var name in modules)
{
try
{
// Check if module is valid
var module = require('fs').statSync(modules[name]);
}
catch (e)
{
var module = false;
}
if (module && module.isDirectory())
{
// Add the module to include paths
modules[name] = require('fs').realpathSync(modules[name]) + '/';
paths.push(modules[name]);
}
else
{
// This module is invalid, remove it
delete modules[name];
}
}
// Finish the include paths by adding SYSPATH
paths.push(SYSPATH);
// Set the new include paths
_paths = paths;
// Set the current module list
_modules = modules;
for(var path in _modules)
{
var file = _modules[path] + 'init.js';
try
{
// Check if exists initialization file
var init = require('fs').statSync(file);
}
catch (e)
{
var init = false;
}
if (init && init.isFile())
{
// Include the module initialization file once
require(file);
}
// load module prototypes
Autoload.init(_modules[path] + 'prototypes');
}
return _modules;
};
/**
* Returns the the currently active include paths, including the
* application, system, and each module's path.
*
* @return Object
*/
JohanaCore.includePaths = function()
{
return _paths;
};
/**
* Searches for a file in the [Cascading Filesystem](johana/files), and
* returns the path to the file that has the highest precedence, so that it
* can be included.
*
* When searching the "config", "messages", or "i18n" directories, or when
* the `list` flag is set to true, an object of all the files that match
* that path in the [Cascading Filesystem](johana/files) will be returned.
* These files will return Objects which must be merged together.
*
* If no extension is given, the default extension '.js' will be used.
*
* // Returns an absolute path to views/template.js
* Johana.findFile('views', 'template');
*
* // Returns an absolute path to media/css/style.css
* Johana.findFile('media', 'css/style', 'css');
*
* // Returns an Object of all the "mimes" configuration files
* Johana.findFile('config', 'mimes');
*
* @param String directory name (views, i18n, classes, extensions, etc.)
* @param String filename with subdirectory
* @param String extension to search for
* @param Boolean return an array of files?
* @return Object a list of files when list is true
* @return String single file path
*/
JohanaCore.findFile = function(dir, file, ext, list)
{
ext = ext || null; list = list || false;
if (ext === null)
{
// Use the default extension
ext = '.js';
}
else if (ext)
{
// Prefix the extension with a period
ext = '.' + ext;
}
else
{
// Use no extension
ext = '';
}
// Create a partial path of the filename
var path = dir + '/' + file + ext;
if (Johana.caching === true && _files[path + (list ? '_list' : '_path')] !== undefined)
{
// This path has been cached
return _files[path + (list ? '_list' : '_path')];
}
if (Johana.profiling === true)
{
// Start a new benchmark
var benchmark = Profiler.start('Johana', 'findFile');
}
else
{
var benchmark = false;
}
if (list || dir === 'config' || dir === 'i18n' || dir === 'messages')
{
// Include paths must be searched in reverse
var paths = _paths.slice().reverse();
// Array of files that have been found
var found = [];
for (var dir in paths)
{
try
{
// check if file exists
var file = require('fs').statSync(paths[dir] + path);
}
catch (e)
{
var file = false;
}
if (file && file.isFile())
{
// This path has a file, add it to the list
found.push(paths[dir] + path);
}
}
}
else
{
// The file has not been found yet
found = false;
for (var dir in _paths)
{
try
{
// check if file exists
var file = require('fs').statSync(_paths[dir] + path);
}
catch (e)
{
var file = false;
}
if (file && file.isFile())
{
// This path has a file, add it to the list
found = _paths[dir] + path;
break;
}
}
}
if (Johana.caching === true)
{
// Add the path to the cache
_files[path + (list ? '_list' : '_path')] = found;
// Files have been changed
_filesChanged = true;
}
if (benchmark)
{
// Stop the benchmark
Profiler.stop(benchmark);
}
return found;
};
/**
* Returns the configuration array for the requested group. See
* [configuration files](johana/files/config) for more information.
*
* // Get all the configuration in config/database.js
* var config = Johana.config('database');
*
* // Get only the default connection configuration
* var default = Johana.config('database.default')
*
* // Get only the hostname of the default connection
* var host = Johana.config('database.default.connection.hostname')
* var host = Johana.config('database').default.connection.hostname
*
* @param String group name
* @return Config
*/
var _configCache = {};
JohanaCore.config = function(group)
{
var path = false;
var dot = group.indexOf('.');
if (dot !== -1)
{
// Split the config group and path
var path = group.substring(dot + 1);
group = group.substring(0, dot);
}
if (_configCache[group] === undefined)
{
// Load the config group into the cache
_configCache[group] = Johana.conf.load(group);
}
if (path !== false)
{
return Arr.path(_config[group], path, null, '.');
}
else
{
return _configCache[group];
}
};
module.exports = JohanaCore;