/
drupalgap.js
15435 lines (14413 loc) · 502 KB
/
drupalgap.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
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
/*! drupalgap 2016-12-09 */
// Initialize the drupalgap json object.
var drupalgap = drupalgap || drupalgap_init(); // Do not remove this line.
// Init _GET for url path query strings.
var _dg_GET = _dg_GET || {};
/**
* Initializes the drupalgap json object.
* @return {Object}
*/
function drupalgap_init() {
var dg = {
modules: {
core: [
{ name: 'comment' },
{ name: 'contact' },
{ name: 'entity' },
{ name: 'field' },
{ name: 'file' },
{ name: 'image' },
{ name: 'menu' },
{ name: 'mvc' },
{ name: 'node' },
{ name: 'search' },
{ name: 'system' },
{ name: 'taxonomy' },
{ name: 'user' },
{ name: 'views' }
]
},
module_paths: [],
includes: [
{ name: 'block' },
{ name: 'common' },
{ name: 'form' },
{ name: 'go' },
{ name: 'menu' },
{ name: 'page' },
{ name: 'region' },
{ name: 'theme' },
{ name: 'title' }
],
online: false,
destination: '',
api: {},
back: false, /* moving backwards or not */
back_path: [], /* paths to move back to */
blocks: [],
connected: false, // Becomes true once DrupalGap performs a System Connect call.
content_types_list: {}, /* holds info about each content type */
date_formats: { }, /* @see system_get_date_formats() in Drupal core */
date_types: { }, /* @see system_get_date_types() in Drupal core */
entity_info: {},
field_info_fields: {},
field_info_instances: {},
field_info_extra_fields: {},
form_errors: {},
form_states: [],
loading: false, /* indicates if the loading message is shown or not */
loader: 'loading', /* used to determine the jQM loader mode */
locale: {}, /* holds onto language json objects, keyed by language code */
messages: [],
menus: {},
menu_links: {},
menu_router: {}, /* @todo - doesn't appear to be used at all, remove it */
mvc: {
models: {},
views: {},
controllers: {}
},
output: '', /* hold output generated by menu_execute_active_handler() */
page: {
jqm_events: [],
title: '',
variables: {},
process: true,
options: {} /* holds the current page's options, eg. reloadPage, etc. */
},
pages: [], /* Collection of page ids that are loaded into the DOM. */
path: '', /* The current menu path. */
remote_addr: null, /* php's $_SERVER['REMOTE_ADDR'] via system connect */
router_path: '', /* The current menu router path. */
services: {},
sessid: null,
settings: {},
site_settings: {}, /* holds variable settings from the Drupal site */
taxonomy_vocabularies: false, /* holds vocabs from system connect */
theme_path: '',
themes: [],
theme_registry: {},
toast: {
shown: false
},
views: {
ids: []
},
views_datasource: {}
};
// Extend jDrupal as needed...
// Forms will expire upon install and don't have an expiration time.
if (!Drupal.cache_expiration) { Drupal.cache_expiration = {}; }
if (!Drupal.cache_expiration.forms) { Drupal.cache_expiration.forms = {}; }
// Finally return the JSON object.
return dg;
}
/**
* This is called once the <body> element's onload is fired.
*/
function drupalgap_onload() {
try {
// At this point, the Drupal object has been initialized by jDrupal and the
// app/settings.js file was loaded in <head>. Let's add DrupalGap's modules
// onto the Drupal JSON object. Remember, all of the module source code is
// included via the makefile's bin generation. However, the core modules
// hook_install() implementations haven't been called yet, so we add them to
// the module listing so they can be invoked later on.
var modules = [
'drupalgap',
'block',
'comment',
'contact',
'entity',
'field',
'file',
'image',
'menu',
'mvc',
'node',
'search',
'system',
'taxonomy',
'user',
'views'
];
for (var i = 0; i < modules.length; i++) {
var module = modules[i];
Drupal.modules.core[module] = module_object_template(module);
}
// Depending on the mode, we'll move on to _drupalgap_deviceready()
// accordingly. By default we'll assume the mode is for phonegap, unless
// otherwise specified by the settings.js file. If it is for phonegap, we'll
// attach its device ready listener, otherwise we'll just move on.
if (typeof drupalgap.settings.mode === 'undefined') {
drupalgap.settings.mode = 'phonegap';
}
switch (drupalgap.settings.mode) {
case 'phonegap':
document.addEventListener('deviceready', _drupalgap_deviceready, false);
break;
case 'web-app':
_drupalgap_deviceready();
break;
default:
console.log(
'drupalgap_onload - unknown mode (' + drupalgap.settings.mode + ')'
);
return;
break;
}
}
catch (error) { console.log('drupalgap_onload - ' + error); }
}
/**
* Implements PhoneGap's deviceready().
*/
function _drupalgap_deviceready() {
try {
// Set some jQM properties to better handle the back button on iOS9.
if (
typeof device !== 'undefined' &&
device.platform === "iOS" &&
parseInt(device.version) === 9
) {
$.mobile.hashListeningEnabled = false;
$.mobile.pushStateEnabled = false;
}
// The device is now ready, it is now safe for DrupalGap to start...
drupalgap_bootstrap();
// Verify site path is set.
if (!Drupal.settings.site_path || Drupal.settings.site_path == '') {
var msg = t('No site_path to Drupal set in the app/settings.js file!');
drupalgap_alert(msg, {
title: t('Error')
});
return;
}
// Device is ready, let's call any implementations of hook_deviceready(). If any implementation returns
// false, that means they would like to take over the rest of the deviceready procedure (aka the System
// Connect call)
var proceed = true;
var invocation_results = module_invoke_all('deviceready');
if (invocation_results && invocation_results.length > 0) {
for (var i = 0; i < invocation_results.length; i++) {
if (!invocation_results[i]) {
proceed = false;
break;
}
}
}
// If the device is offline, warn the user and then go to the offline page, unless someone implemented
// hook_offline, then let them handle it.
if (!drupalgap_has_connection()) {
if (!module_implements('device_offline')) {
if (drupalgap.settings.offline_message) {
drupalgap_alert(drupalgap.settings.offline_message, {
title: t('Offline'),
alertCallback: function() { drupalgap_goto('offline'); }
});
}
else { drupalgap_goto('offline'); }
}
else { setTimeout(function() { module_invoke_all('device_offline'); }, 1); }
}
else if (proceed) {
// Device is online and no one has taken over the deviceready, continue with the System Connect call.
system_connect(_drupalgap_deviceready_options());
}
}
catch (error) { console.log('_drupalgap_deviceready - ' + error); }
}
/**
* Builds the default system connect options.
* @return {Object}
*/
function _drupalgap_deviceready_options() {
try {
var page_options = arguments[0] ? arguments[0] : {};
return {
success: function(result) {
// Set the connection and invoke hook_device_connected().
drupalgap.connected = true;
module_invoke_all('device_connected');
// If there is a hash url present and it can be routed go directly to that page,
// otherwise go to the app's front page.
var path = '';
if (window.location.hash.indexOf('#') != -1) {
var routedPath = drupalgap_get_path_from_page_id(window.location.hash.replace('#', ''));
if (routedPath) { path = routedPath; }
}
drupalgap_goto(path, page_options);
},
error: function(jqXHR, textStatus, errorThrown) {
// Build an informative error message and display it.
var msg = t('Failed connection to') + ' ' + Drupal.settings.site_path;
if (errorThrown != '') { msg += ' - ' + errorThrown; }
msg += ' - ' + t('Check your device\'s connection and check that') +
' ' + Drupal.settings.site_path + ' ' + t('is online.');
drupalgap_alert(msg, {
title: t('Unable to Connect'),
alertCallback: function() { drupalgap_goto('offline'); }
});
}
};
}
catch (error) { console.log('_drupalgap_deviceready_options - ' + error); }
}
/**
* Loads up all necessary assets to make DrupalGap ready.
*/
function drupalgap_bootstrap() {
try {
// Load up any contrib and/or custom modules (the DG core moodules have
// already been loaded at this point), load the theme and all blocks. Then
// build the menu router, load the menus, and build the theme registry.
drupalgap_load_modules();
drupalgap_load_theme();
drupalgap_load_blocks();
drupalgap_load_locales();
menu_router_build();
drupalgap_menus_load();
drupalgap_theme_registry_build();
// Attach device back button handler (Android).
document.addEventListener('backbutton', drupalgap_back, false);
}
catch (error) { console.log('drupalgap_bootstrap - ' + error); }
}
/**
* Loads any contrib or custom modules specifed in the settings.js file. Then
* invoke hook_install() on all modules, including core.
*/
function drupalgap_load_modules() {
try {
var module_types = ['contrib', 'custom'];
// We only need to load contrib and custom modules because core modules are
// already included in the binary.
for (var index in module_types) {
if (!module_types.hasOwnProperty(index)) { continue; }
var bundle = module_types[index];
// Let's be nice and try to load any old drupalgap.modules declarations
// in developers settings.js files for a while, but throw a warning to
// encourage them to update. This code can be removed after a few
// releases to help developers get caught up without angering them.
if (
drupalgap.modules &&
drupalgap.modules[bundle] &&
drupalgap.modules[bundle].length != 0
) {
for (var index in drupalgap.modules[bundle]) {
if (!drupalgap.modules[bundle].hasOwnProperty(index)) { continue; }
var module = drupalgap.modules[bundle][index];
if (module.name) {
var msg = 'WARNING: The module "' + module.name + '" defined ' +
'in settings.js needs to be added to ' +
'Drupal.modules[\'' + bundle + '\'] instead! See ' +
'default.settings.js for examples on the new syntax!';
console.log(msg);
Drupal.modules[bundle][module.name] = module;
}
}
}
for (var module_name in Drupal.modules[bundle]) {
if (!Drupal.modules[bundle].hasOwnProperty(module_name)) { continue; }
var module = Drupal.modules[bundle][module_name];
// If the module object is empty, initialize a module object.
if ($.isEmptyObject(module)) {
Drupal.modules[bundle][module_name] =
module_object_template(module_name);
module = Drupal.modules[bundle][module_name];
}
// If the module's name isn't set, set it.
if (!module.name) {
Drupal.modules[bundle][module_name].name = module_name;
module = Drupal.modules[bundle][module_name];
}
// Determine module directory.
var dir = drupalgap_modules_get_bundle_directory(bundle);
module_base_path = dir + '/' + module.name;
// Add module .js file to array of paths to load.
var extension = module.minified ? '.min.js' : '.js';
module_path = module_base_path + '/' + module.name + extension;
modules_paths = [module_path];
// If there are any includes with this module, add them to the
// list of paths to include.
if (module.includes != null && module.includes.length != 0) {
for (var include_index in module.includes) {
if (!module.includes.hasOwnProperty(include_index)) { continue; }
var include_object = module.includes[include_index];
modules_paths.push(
module_base_path + '/' + include_object.name + '.js'
);
}
}
// Now load all the paths for this module.
for (var modules_paths_index in modules_paths) {
if (!modules_paths.hasOwnProperty(modules_paths_index)) { continue; }
var modules_paths_object = modules_paths[modules_paths_index];
jQuery.ajax({
async: false,
type: 'GET',
url: modules_paths_object,
data: null,
success: function() {
if (Drupal.settings.debug) { console.log(modules_paths_object); }
},
dataType: 'script',
error: function(xhr, textStatus, errorThrown) {
console.log(
t('Failed to load module!') + ' (' + module.name + ')',
textStatus,
errorThrown.message
);
}
});
}
}
}
// Now invoke hook_install on all modules, including core.
module_invoke_all('install');
}
catch (error) { console.log('drupalgap_load_modules - ' + error); }
}
/**
* Load the theme specified by drupalgap.settings.theme into drupalgap.theme
* Returns true on success, false if it fails.
* @return {Boolean}
*/
function drupalgap_load_theme() {
try {
if (!drupalgap.settings.theme) {
var msg = 'drupalgap_load_theme - ' +
t('no theme specified in settings.js');
drupalgap_alert(msg);
}
else {
// Pull the theme name from the settings.js file.
var theme_name = drupalgap.settings.theme;
var theme_path = 'themes/' + theme_name + '/' + theme_name + '.js';
if (theme_name != 'easystreet3' && theme_name != 'ava') {
theme_path = 'app/themes/' + theme_name + '/' + theme_name + '.js';
}
if (!drupalgap_file_exists(theme_path)) {
var error_msg = 'drupalgap_theme_load - ' + t('Failed to load theme!') +
' ' + t('The theme\'s JS file does not exist') + ': ' + theme_path;
drupalgap_alert(error_msg);
return false;
}
// We found the theme's js file, add it to the page.
drupalgap_add_js(theme_path);
// Call the theme's template_info implementation.
var template_info_function = theme_name + '_info';
if (drupalgap_function_exists(template_info_function)) {
var fn = window[template_info_function];
drupalgap.theme = fn();
// For each region in the name, set the 'name' value on the region JSON.
for (var name in drupalgap.theme.regions) {
if (!drupalgap.theme.regions.hasOwnProperty(name)) { continue; }
var region = drupalgap.theme.regions[name];
drupalgap.theme.regions[name].name = name;
}
// Make sure the theme implements the required regions.
var regions = system_regions_list();
for (var i = 0; i < regions.length; i++) {
var region = regions[i];
if (typeof drupalgap.theme.regions[region] === 'undefined') {
console.log('WARNING: drupalgap_load_theme() - The "' +
theme_name + '" theme does not have the "' + region +
'" region specified in "' + theme_name + '_info()."');
}
}
// Theme loaded successfully! Set the drupalgap.theme_path and return
// true.
drupalgap.theme_path = theme_path.replace('/' + theme_name + '.js', '');
return true;
}
else {
var error_msg = 'drupalgap_load_theme() - ' + t('failed') + ' - ' +
template_info_function + '() ' + t('does not exist!');
drupalgap_alert(error_msg);
}
}
return false;
}
catch (error) { console.log('drupalgap_load_theme - ' + error); }
}
/**
* Given a path to a javascript file relative to the app's www directory,
* this will load the javascript file so it will be available in scope.
*/
function drupalgap_add_js() {
try {
var data;
if (arguments[0]) { data = arguments[0]; }
jQuery.ajax({
async: false,
type: 'GET',
url: data,
data: null,
success: function() {
if (Drupal.settings.debug) {
// Print the js path to the console.
console.log(data);
}
},
dataType: 'script',
error: function(xhr, textStatus, errorThrown) {
console.log(
'drupalgap_add_js - error - (' +
data + ' : ' + textStatus +
') ' + errorThrown
);
}
});
}
catch (error) {
console.log('drupalgap_add_js - ' + error);
}
}
/**
* Given a path to a css file relative to the app's www directory, this will
* attempt to load the css file so it will be available in scope.
*/
function drupalgap_add_css() {
try {
var data;
if (arguments[0]) { data = arguments[0]; }
$('<link/>', {rel: 'stylesheet', href: data}).appendTo('head');
}
catch (error) { console.log('drupalgap_add_css - ' + error); }
}
/**
* Rounds up all blocks defined by hook_block_info and places them in the
* drupalgap.blocks array.
*/
function drupalgap_load_blocks() {
try {
drupalgap.blocks = module_invoke_all('block_info');
}
catch (error) { console.log('drupalgap_load_blocks - ' + error); }
}
/**
* Loads language files.
*/
function drupalgap_load_locales() {
try {
// Load any drupalgap.settings.locale specified language files.
if (typeof drupalgap.settings.locale === 'undefined') { return; }
for (var language_code in drupalgap.settings.locale) {
if (!drupalgap.settings.locale.hasOwnProperty(language_code)) {
continue;
}
var language = drupalgap.settings.locale[language_code];
var file_path = 'locale/' + language_code + '.json';
if (!drupalgap_file_exists(file_path)) { continue; }
drupalgap.locale[language_code] = drupalgap_file_get_contents(
file_path,
{ dataType: 'json' }
);
}
// Load any language files specified by modules, and merge them into the
// global language file (or create a new one if it doesn't exist).
var modules = module_implements('locale');
for (var i = 0; i < modules.length; i++) {
var module = modules[i];
var fn = window[module + '_locale'];
var languages = fn();
for (var j = 0; j < languages.length; j++) {
var language_code = languages[j];
var file_path = drupalgap_get_path('module', module) + '/locale/' + language_code + '.json';
var translations = drupalgap_file_get_contents(
file_path,
{ dataType: 'json' }
);
if (typeof drupalgap.locale[language_code] === 'undefined') {
drupalgap.locale[language_code] = translations;
}
else {
$.extend(
drupalgap.locale[language_code],
drupalgap.locale[language_code],
translations
);
}
}
}
}
catch (error) { console.log('drupalgap_load_locales - ' + error); }
}
/**
* Checks for an Internet connection, returns true if connected, false otherwise.
* @returns {boolean}
*/
function drupalgap_has_connection() {
try {
drupalgap_check_connection();
module_invoke_all('device_connection');
return drupalgap.online;
}
catch (error) { console.log('drupalgap_has_connection - ' + error); }
}
/**
* Checks the devices connection and sets drupalgap.online to true if the
* device has a connection, false otherwise.
* @return {String}
* A string indicating the type of connection according to PhoneGap.
*/
function drupalgap_check_connection() {
try {
// If we're not in phonegap, just use the navigator.onLine value.
if (drupalgap.settings.mode != 'phonegap' || typeof parent.window.ripple === 'function' ) {
drupalgap.online = navigator.onLine;
return 'Ethernet connection'; // @TODO detect real connection type.
}
// Determine what connection phonegap has.
var networkState = navigator.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.NONE] = 'No network connection';
drupalgap.online = states[networkState] != 'No network connection';
return states[networkState];
}
catch (error) { console.log('drupalgap_check_connection - ' + error); }
}
/**
* @deprecated Use empty() instead.
* Returns true if given value is empty. A generic way to test for emptiness.
* @param {*} value
* @return {Boolean}
*/
function drupalgap_empty(value) {
try {
console.log(
'WARNING: drupalgap_empty() is deprecated! ' +
'Use empty() instead.'
);
return empty(value);
}
catch (error) { console.log('drupalgap_empty - ' + error); }
}
/**
* Checks if a given file exists, returns true or false.
* @param {string} path
* A path to a file
* @return {bool}
* True if file exists, else false.
*/
function drupalgap_file_exists(path) {
try {
var file_exists = false;
jQuery.ajax({
async: false,
type: 'HEAD',
dataType: 'text',
url: path,
success: function() { file_exists = true; },
error: function(xhr, textStatus, errorThrown) { }
});
return file_exists;
}
catch (error) { console.log('drupalgap_file_exists - ' + error); }
}
/**
* Reads entire file into a string and returns the string. Returns false if
* it fails.
* @param {String} path
* @param {Object} options
* @return {String}
*/
function drupalgap_file_get_contents(path, options) {
try {
var file = false;
var default_options = {
type: 'GET',
url: path,
dataType: 'html',
data: null,
async: false,
success: function(data) { file = data; },
error: function(xhr, textStatus, errorThrown) {
console.log(
'drupalgap_file_get_contents - failed to load file (' + path + ')'
);
}
};
$.extend(default_options, options);
jQuery.ajax(default_options);
return file;
}
catch (error) { console.log('drupalgap_file_get_contents - ' + error); }
}
/**
* @see https://api.drupal.org/api/drupal/includes!common.inc/function/format_interval/7
* @param {Number} interval The length of the interval in seconds.
* @return {String}
*/
function drupalgap_format_interval(interval) {
try {
// @TODO - deprecate this and move it to jDrupal as format_interval().
var granularity = 2; if (arguments[1]) { granularity = arguments[1]; }
var langcode = null; if (arguments[2]) { langcode = langcode[2]; }
var units = {
'1 year|@count years': 31536000,
'1 month|@count months': 2592000,
'1 week|@count weeks': 604800,
'1 day|@count days': 86400,
'1 hour|@count hours': 3600,
'1 min|@count min': 60,
'1 sec|@count sec': 1
};
var output = '';
for (var key in units) {
if (!units.hasOwnProperty(key)) { continue; }
var value = units[key];
var key = key.split('|');
if (interval >= value) {
var count = Math.floor(interval / value);
output +=
(output ? ' ' : '') +
drupalgap_format_plural(
count,
key[0],
key[1]
);
if (output.indexOf('@count') != -1) {
output = output.replace('@count', count);
}
interval %= value;
granularity--;
}
if (granularity == 0) { break; }
}
return output ? output : '0 sec';
}
catch (error) { console.log('drupalgap_format_interval - ' + error); }
}
/**
* @see http://api.drupal.org/api/drupal/includes%21common.inc/function/format_plural/7
* @param {Number} count
* @param {String} singular
* @param {String} plural
* @return {String}
*/
function drupalgap_format_plural(count, singular, plural) {
// @TODO - deprecate this and move it to jDrupal as format_plural().
if (count == 1) { return singular; }
return plural;
}
/**
* @deprecated - Use function_exists() instead.
* @param {String} name
* @return {Boolean}
*/
function drupalgap_function_exists(name) {
try {
return function_exists(name);
}
catch (error) { console.log('drupalgap_function_exists - ' + error); }
}
/**
* Given an html string from a *.tpl.html file, this will extract all of the
* placeholders names and return them in an array. Returns false otherwise.
* @param {String} html
* @return {*}
*/
function drupalgap_get_placeholders_from_html(html) {
try {
var placeholders = false;
if (html) {
placeholders = html.match(/(?!{:)([\w]+)(?=:})/g);
}
return placeholders;
}
catch (error) {
console.log('drupalgap_get_placeholders_from_html - ' + error);
}
}
/**
* Returns the current page's title.
* @return {String}
*/
function drupalgap_get_title() {
try {
return drupalgap.page.title;
}
catch (error) { console.log('drupalgap_get_title - ' + error); }
}
/**
* Returns the IP Address of the current user as reported by PHP via the last
* System Connect call's $_SERVER['REMOTE_ADDR'] value.
* @return {String|Null}
*/
function drupalgap_get_ip() {
try {
return drupalgap.remote_addr;
}
catch (error) { console.log('drupalgap_get_ip - ' + error); }
}
/**
* Given a router path, this will return an array containing the indexes of
* where the wildcards (%) are present in the router path. Returns false if
* there are no wildcards present.
* @param {String} router_path
* @return {Boolean}
*/
function drupalgap_get_wildcards_from_router_path(router_path) {
// @todo - Is this function even used? Doesn't look like it.
var wildcards = false;
return wildcards;
}
/**
* Given a drupal image file uri, this will return the path to the image on the
* Drupal site.
* @param {String} uri
* @return {String}
*/
function drupalgap_image_path(uri) {
try {
var altered = false;
// If any modules want to alter the path, let them do it.
var modules = module_implements('image_path_alter');
if (modules) {
for (var index in modules) {
if (!modules.hasOwnProperty(index)) { continue; }
var module = modules[index];
var result = module_invoke(module, 'image_path_alter', uri);
if (result) {
altered = true;
uri = result;
break;
}
}
}
if (!altered) {
// No one modified the image path, we'll use the default approach to
// generating the image src path.
var src = Drupal.settings.site_path + Drupal.settings.base_path + uri;
if (src.indexOf('public://') != -1) {
src = src.replace('public://', Drupal.settings.file_public_path + '/');
}
else if (src.indexOf('private://') != -1) {
src = src.replace(
'private://',
Drupal.settings.file_private_path + '/'
);
}
return src;
}
else { return uri; }
}
catch (error) { console.log('drupalgap_image_path - ' + error); }
}
/**
* @deprecated - This is no longer needed since the includes are built via the
* makefile. Loads the js files in includes specified by drupalgap.includes.
*/
function drupalgap_includes_load() {
try {
if (drupalgap.includes != null && drupalgap.includes.length != 0) {
for (var index in drupalgap.includes) {
if (!drupalgap.includes.hasOwnProperty(index)) { continue; }
var include = drupalgap.includes[index];
var include_path = 'includes/' + include.name + '.inc.js';
jQuery.ajax({
async: false,
type: 'GET',
url: include_path,
data: null,
success: function() {
if (Drupal.settings.debug) {
// Print the include path to the console.
dpm(include_path);
}
},
dataType: 'script',
error: function(xhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}
}
}
catch (error) { console.log('drupalgap_includes_load - ' + error); }
}
/**
* Given an html list element id and an array of items, this will clear the
* list, populate it with the items, and then refresh the list.
* @param {String} list_css_selector
* @param {Array} items
*/
function drupalgap_item_list_populate(list_css_selector, items) {
try {
// @todo - This could use some validation and alerts for improper input.
$(list_css_selector).html('');
for (var i = 0; i < items.length; i++) {
$(list_css_selector).append($('<li></li>', { html: items[i] }));
}
$(list_css_selector).listview('refresh').listview();
}
catch (error) { console.log('drupalgap_item_list_populate - ' + error); }
}
/**
* Given an html table element id and an array of rows, this will clear the
* table, populate it with the rows, and then refresh the table.
* @param {String} table_css_selector
* @param {Array} rows
* rows follow the.
*/
function drupalgap_table_populate(table_css_selector, rows) {
try {
// Select only the body. Other things are already setup
table_css_selector = table_css_selector + '> tbody ';
$(table_css_selector).html('');
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var rowhtml = '';
for (var j = 0; j < row.length; j++) {
rowhtml = rowhtml + '<td>' + row[j] + '</td>';
}
$('<tr>').html(rowhtml).appendTo($(table_css_selector));
}
$(table_css_selector).rebuild();
}
catch (error) { console.log('drupalgap_table_populate - ' + error); }
}
/**
* Given a jQM page event, and the corresponding callback function name that
* handles the event, this function will call the callback function, if it has
* not already been called on the current page. This really is only used by
* menu_execute_active_handler() to prevent jQM from firing inline page event
* handlers more than once. You may optionally pass in a 4th argument, a string,
* to append to the suffix of the unique key of recorded fired page events.
* @param {String} event
* @param {String} callback
* @param {*} page_arguments
*/
function drupalgap_jqm_page_event_fire(event, callback, page_arguments) {
try {
// Concatenate the event name and the callback name together into a unique
// key so multiple callbacks can handle the same event.
var key = event + '-' + callback;
// Is there an optional 4th argument coming in (the suffix)?
if (typeof arguments[3] !== 'undefined') {
if (arguments[3]) { key += '-' + arguments[3]; }
}
if ($.inArray(key, drupalgap.page.jqm_events) == -1 &&
drupalgap_function_exists(callback)) {
drupalgap.page.jqm_events.push(key);
var fn = window[callback];
if (page_arguments) {
// If the page arguments aren't an array, place them into an array so
// they can be applied to the callback function.
if (!$.isArray(page_arguments)) { page_arguments = [page_arguments]; }
fn.apply(null, Array.prototype.slice.call(page_arguments));
}
else { fn(); }
}
}
catch (error) { console.log('drupalgap_jqm_page_event_fire - ' + error); }
}
/**
* Returns array of jQM Page event names.
* @return {Array}
* @see http://api.jquerymobile.com/category/events/
*/
function drupalgap_jqm_page_events() {
return [
'pagebeforechange',
'pagebeforecreate',
'pagebeforehide',
'pagebeforeload',
'pagebeforeshow',
'pagechange',
'pagechangefailed',
'pagecreate',
'pagehide',
'pageinit',
'pageload',
'pageloadfailed',
'pageremove',
'pageshow'
];
}
/**
* Given a JSON object with a page id, a jQM page event name, a callback
* function to handle the jQM page event and any page arguments (as a JSON
* string), this function will return the inline JS code needed to handle the
* event. You may optionally pass in a unique second argument (string) to
* allow the same page event handler to be fired more than once on a page.
* @param {Object} options
* @return {String}
*/
function drupalgap_jqm_page_event_script_code(options) {