-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathProcessHannaCode.module
More file actions
1008 lines (859 loc) · 29 KB
/
ProcessHannaCode.module
File metadata and controls
1008 lines (859 loc) · 29 KB
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 namespace ProcessWire;
require_once(__DIR__ . '/HannaCodes.php');
/**
* Process Hanna Code
*
* Copyright (C) 2021 by Ryan Cramer
* Licensed under MPL 2.0
* https://processwire.com
*
* @property array $typeLabels
* @property TextformatterHannaCode $hanna
*
*/
class ProcessHannaCode extends Process implements ConfigurableModule {
/**
* Return information about this module (required)
*
*/
public static function getModuleInfo() {
return array(
'title' => 'Hanna Code',
'summary' => 'Easily insert any complex HTML, Javascript or PHP output in your ProcessWire content by creating your own Hanna code tags.',
'version' => 32,
'permission' => 'hanna-code',
'permissions' => array(
'hanna-code' => 'List and view Hanna Codes',
'hanna-code-edit' => 'Add/edit/delete Hanna Codes (text/html, javascript only)',
'hanna-code-php' => 'Add/edit/delete Hanna Codes (text/html, javascript and PHP)'
),
'useNavJSON' => true,
'icon' => 'sun-o',
'requires' => 'TextformatterHannaCode, ProcessWire>=3.0.133'
);
}
/**
* The name that will be used for the page this module creates
*
*/
const pageName = 'hanna-code';
/**
* Default theme for the Ace Editor
*
*/
const defaultAceTheme = 'monokai';
/**
* Default keybinding for the Ace Editor
*
*/
const defaultAceKeybinding = 'none';
/**
* Default height (in pixels) for the Ace Editor
*
*/
const defaultAceHeight = '400';
/**
* Default ace behavior bitmask
*
*/
const defaultAceBehaviors = 0;
/**
* Ace editor version
*
*/
const aceVersion = '1.10.1';
/**
* Ace behavior pairing
*
*/
const aceBehaviorPair = 2;
/**
* Ace behavior
*
*/
const aceBehaviorWrap = 4;
/**
* Instance of TextformatterHannaCode
*
* @var TextformatterHannaCode|null
*
*/
protected $textformatter = null;
/**
* Allow HannaCodes to be edited and saved?
*
* @var bool|null
*
*/
protected $allowSave = null;
/**
* @var string
*
*/
protected $saveInfo = '';
/**
* Construct
*
*/
public function __construct() {
$this->set('aceTheme', self::defaultAceTheme);
$this->set('aceKeybinding', self::defaultAceKeybinding);
$this->set('aceHeight', self::defaultAceHeight);
$this->set('aceBehaviors', self::defaultAceBehaviors);
parent::__construct();
}
/**
* This is an optional initialization function called before any execute functions.
*
*/
public function init() {
parent::init(); // required
$this->set('typeLabels', array(
HannaCode::typeHTML => $this->_('Text/HTML'),
HannaCode::typeJS => $this->_('Javascript code'),
HannaCode::typePHP => $this->_('PHP code'),
));
$config = $this->wire()->config;
$hannaEdit = $config->get('HannaCodeEdit');
$recommended = $this->_('This is recommended for security on live/production sites.');
if(is_bool($hannaEdit)) {
$this->allowSave = $hannaEdit;
} else {
$this->allowSave = $config->debug;
}
if($this->allowSave) {
if($hannaEdit === true) {
$suggestion = '$config->HannaCodeEdit = false;';
} else {
$suggestion = '$config->debug = false;';
}
$this->saveInfo = sprintf(
$this->_('Please set %s in your {file} file when finished editing Hanna Codes.') . " $recommended",
"<code>$suggestion</code>"
);
} else {
$this->saveInfo =
'<strong>' . $this->_('“Edit” and “Add” features are currently disabled.') . '</strong> ' .
$recommended . ' ' .
sprintf(
$this->_('To enable, edit {file} and temporarily set %s or %s'),
'<code>$config->debug = true;</code>',
'<code>$config->HannaCodeEdit = true;</code>'
) . ' ' .
$this->_('(Remember to reverse this change when you are done editing/adding Hanna Codes, especially on live sites).');
}
$this->saveInfo = str_replace('{file}', '<u>/site/config.php</u>', $this->saveInfo);
}
/**
* @param array $options
* @return string|array
*
*/
public function ___executeNavJSON(array $options = array()) {
$options['add'] = 'edit/';
$options['edit'] = 'edit/?id={id}';
$options['items'] = $this->hannaCodes()->getAll();
$options['itemLabel'] = 'name';
return parent::___executeNavJSON($options);
}
/**
* @return TextformatterHannaCode
*
*/
public function textformatter() {
if($this->textformatter === null) {
$this->textformatter = $this->wire()->modules->get('TextformatterHannaCode');
}
return $this->textformatter;
}
/**
* @return HannaCodes
*
*/
public function hannaCodes() {
return $this->textformatter()->hannaCodes();
}
/**
* Set property
*
* @param string $key
* @param mixed $value
* @return self|Process
*
*/
public function set($key, $value) {
if($key == 'aceBehaviors' && is_array($value)) {
$bitmask = 0;
foreach($value as $v) $bitmask = $bitmask | $v;
$value = $bitmask;
}
return parent::set($key, $value);
}
/**
* Does user have permission?
*
* @param string $name
* @return bool
*
*/
protected function hasPermission($name) {
$user = $this->wire()->user;
if($user->isSuperuser()) return true;
if($name === 'hanna-code-edit' || $name === 'hanna-code-php') {
$permission = $this->permissions->get($name);
// before new permissions, there was just hanna-code which assigned all access
// so if new permissions aren't installed, we fallback to old behavior
if(!$permission->id) $name = 'hanna-code';
}
$has = $user->hasPermission($name);
if(!$has && $name === 'hanna-code-edit') {
// if user has hanna-code-php permission, then hanna-code-edit is assumed
$has = $user->hasPermission('hanna-code-php');
}
return $has;
}
/**
* Is given HannaCode or type editable?
*
* @param HannaCode|int $h
* @return bool
*
*/
protected function editable($h) {
if($h instanceof HannaCode) {
$isPHP = $h->isPHP();
} else {
$type = (int) $h;
$isPHP = $type === HannaCode::typePHP || $type & HannaCode::typePHP;
}
if($isPHP) return $this->hasPermission('hanna-code-php');
return $this->hasPermission('hanna-code-edit');
}
/**
* List Hanna Codes
*
*/
public function ___execute() {
$sanitizer = $this->wire()->sanitizer;
$modules = $this->wire()->modules;
$typeLabels = $this->typeLabels;
$sort = $this->wire()->input->get->text('sort');
$editable = $this->hasPermission('hanna-code-edit');
$welcome = '';
$out = '';
if(empty($sort)) $sort = 'name';
$hannaCodes = $this->hannaCodes()->getAll($sort);
if(count($hannaCodes)) {
/** @var MarkupAdminDataTable $table */
$table = $modules->get('MarkupAdminDataTable');
$table->setEncodeEntities(false);
$table->headerRow(array(
$this->_x('Name', 'list-table'),
$this->_x('Tag', 'list-table'),
$this->_x('Type', 'list-table'),
$this->_x('Modified', 'list-table'),
$this->_x('Accessed', 'list-table')
));
foreach($hannaCodes as $h) {
$type = $h->isNotConsuming() ? $h->type - HannaCode::typeNotConsuming : $h->type;
$table->row(array(
$sanitizer->entities($h->name) => "edit/?id=$h->id",
"<code>" . $sanitizer->entities($this->tagExample($h)) . "</code>",
$typeLabels[$type],
wireRelativeTimeStr($h->modified),
wireRelativeTimeStr($h->accessed)
));
}
$out .= $table->render();
} else if($editable) {
// no Hanna codes
if($this->allowSave) {
$welcome = $this->_('No Hanna Codes yet, go ahead and add one!');
} else {
$welcome =
$this->_('There are no Hanna Codes yet! Please follow the instructions below to start using Hanna Code.') .
'<br /><br />' .
$this->saveInfo;
}
} else {
$welcome = $this->_('There are no Hanna Codes to display.');
}
if($welcome) $out .= "<p>$welcome</p>";
if($editable) {
if($this->allowSave) {
/** @var InputfieldButton $button1 */
$button1 = $modules->get('InputfieldButton');
$button1->attr('id', 'button_add');
$button1->attr('value', $this->_('Add New'));
$button1->attr('href', './edit/');
$button1->showInHeader(true);
/** @var InputfieldButton $button2 */
$button2 = $modules->get('InputfieldButton');
$button2->attr('id', 'button_import');
$button2->attr('value', $this->_('Import'));
$button2->attr('href', './import/');
$button2->setSecondary(true);
$out .= $button1->render() . $button2->render();
}
if(count($hannaCodes) || $this->allowSave) {
$out .= "<p class='description'>$this->saveInfo</p>";
}
}
return $out;
}
/**
* Execute import of Hanna code
*
* @return string
* @throws WireException
* @throws WirePermissionException
*
*/
public function ___executeImport() {
$modules = $this->wire()->modules;
$input = $this->wire()->input;
$session = $this->wire()->session;
if(!$this->hasPermission('hanna-code-edit')) throw new WireException("No permission");
if(!$this->allowSave) throw new WireException("Save disabled");
/** @var InputfieldForm $form */
$form = $modules->get('InputfieldForm');
/** @var InputfieldTextarea $f */
$f = $modules->get('InputfieldTextarea');
$f->attr('id+name', 'hc_import');
$f->label = $this->_("Paste in Import Data");
$form->add($f);
/** @var InputfieldSubmit $f */
$f = $modules->get('InputfieldSubmit');
$f->attr('name', 'submit_import');
$form->add($f);
$this->headline($this->_("Import Hanna Code"));
if(!$input->post('submit_import')) return $form->render();
$form->processInput($input->post);
$data = $form->get('hc_import')->value;
if(!preg_match('{!HannaCode:([^:]+):(.*?)/!HannaCode}s', $data, $matches)) {
throw new WireException("Unrecognized Hanna Code format");
}
$name = $matches[1];
$data = $matches[2];
$data = base64_decode($data);
if($data === false) {
throw new WireException("Failed to base64 decode import data");
}
$data = json_decode($data, true);
if($data === false) {
throw new WireException("Failed to json decode import data");
}
if(empty($data['name']) || empty($data['code'])) {
throw new WireException("Import data does not contain all required fields");
}
$h = $this->hannaCodes()->get($name);
if($h->id) {
$this->error($this->_('Hanna Code with that name already exists'));
$session->redirect('../');
return '';
}
$data['type'] = (int) $data['type'];
if($data['type'] & HannaCode::typePHP && !$this->hasPermission('hanna-code-php')) {
throw new WireException("You don't have permission to add/edit PHP Hanna Codes");
}
$h = new HannaCode();
$this->wire($h);
$h->name = $name;
$h->type = $data['type'];
$h->code = $data['code'];
$h->modified = time();
if($this->hannaCodes()->save($h)) {
$this->message($this->_('Imported Hanna Code:') . " $name");
$session->redirect("../edit/?id=$h->id");
} else {
throw new WireException("Error importing Hanna code");
}
return '';
}
/**
* Execute test of Hanna code
*
* @throws WireException
*
*/
public function ___executeTest() {
$name = $this->wire()->sanitizer->pageName($this->wire()->input->get('name'));
if(empty($name)) throw new WireException('Nothing provided to test');
$tag = $this->textformatter()->openTag . $name . $this->textformatter()->closeTag;
$t = new TemplateFile();
$this->wire($t);
$t->setFilename(__DIR__ . '/test-results.php');
$t->set('textformatter', $this->textformatter());
$t->set('tag', $tag);
echo $t->render();
exit;
}
/**
* Execute edit of Hanna code
*
* Called when the URL is this module's page URL + "/something/"
*
* @return string
*
*/
public function ___executeEdit() {
$input = $this->wire()->input;
$modules = $this->wire()->modules;
$config = $this->wire()->config;
$user = $this->wire()->user;
// add a breadcrumb that returns to our main page
$this->breadcrumb('../', $this->page->title);
$modules->get('JqueryWireTabs');
$id = (int) $input->get('id');
$h = $id ? $this->hannaCodes()->get($id) : $this->hannaCodes()->getNew();
if($h->id) {
if($h->id !== $id) throw new WireException('Unknown HannaCode');
$exportData = array(
'name' => $h->name,
'type' => $h->type,
'code' => $this->hannaCodes()->packCode($h->code, $h->attrs),
);
$attr = '';
foreach($h->attrs as $attrName => $attrValue) {
$attr .= strlen($attrValue) ? "$attrName=$attrValue\n" : "$attrName\n";
}
$this->headline($this->_("Edit Hanna Code:") . " $h->name");
} else {
$attr = '';
$exportData = null;
$this->headline($this->_("Adding New Hanna Code"));
if(!$this->editable($h)) throw new WireException("You don't have permission to add new Hanna Codes");
if(!$this->allowSave) {
$this->warning($this->saveInfo, Notice::allowMarkup);
$this->wire()->session->redirect('../');
}
}
$editable = $this->editable($h);
if(!$editable) $this->message($this->_('This Hanna Code is read-only'));
/** @var InputfieldForm $form */
$form = $modules->get('InputfieldForm');
$form->attr('id', 'HannaCodeEdit');
$form->attr('action', './');
$form->attr('method', 'post');
$tab = $this->newTab(array('title' => $this->_('Basics')));
/** @var InputfieldName $nameField */
$nameField = $modules->get('InputfieldName');
$nameField->attr('name', 'hc_name');
$nameField->attr('value', $h->name);
$nameField->description = $this->_('Any combination of these characters: -_.a-zA-Z0-9 (i.e. letters, numbers, hyphens, underscores, periods, no spaces)');
$nameField->icon = 'id-badge';
$tab->add($nameField);
/** @var InputfieldRadios $typeField */
$typeField = $modules->get('InputfieldRadios');
$typeField->attr('name', 'hc_type');
foreach($this->typeLabels as $key => $label) {
if($key === HannaCode::typePHP && !$this->editable($key) && $h->codeType() != HannaCode::typePHP) continue;
$typeField->addOption($key, $label);
}
$typeField->attr('value', $h->codeType());
$typeField->label = $this->_('Code type');
$typeField->icon = 'code';
$typeField->optionColumns = 1;
$tab->add($typeField);
$yes = $this->_('Yes');
$no = $this->_('No');
$value = $h->isNotConsuming() ? 1 : 0;
/** @var InputfieldRadios $f */
$f = $modules->get('InputfieldRadios');
$f->attr('name', 'hc_not_consuming');
$f->addOption(0, $yes);
$f->addOption(1, $no);
$f->attr('value', $value);
$f->label = $this->_('Replace surrounding HTML tag?') . ' [' . ($value ? $no : $yes) . ']';
$f->icon = 'scissors';
$f->description = $this->_('Should the output of this Hanna Code replace the immediate surrounding HTML tag if it is the only thing in the tag? If your Hanna Code outputs block-level HTML (like `<ul>` or `<p>` tags), this should probably be yes.');
$f->collapsed = Inputfield::collapsedYes;
$f->optionColumns = 1;
$tab->add($f);
/** @var InputfieldTextarea $f */
$f = $modules->get('InputfieldTextarea');
$f->attr('id+name', 'hc_attr');
$f->attr('value', trim($attr));
$f->label = $this->_('Attributes');
$f->icon = 'map-signs';
$f->description = $this->_('Optional but recommended if using attributes with PHP or Javascript: Enter one attribute name per line that your Hanna code uses. To specify a default value, enter it as `attr=value`. If no default specified, value defaults to a blank string.');
$f->notes = $this->_('Examples:') .
"\n`" . $this->_('some_attribute') . '`' .
"\n`" . $this->_('attribute_with_default=The Default Value') . '`';
$f->collapsed = Inputfield::collapsedBlank;
$tab->add($f);
$form->add($tab);
$tab = $this->newTab(array('title' => $this->_('Code')));
$userData = $user->meta('HannaCode');
if(!is_array($userData)) $userData = array();
$userDefaults = array(
'aceTheme' => self::defaultAceTheme,
'aceKeybinding' => self::defaultAceKeybinding,
'aceHeight' => self::defaultAceHeight,
'aceBehaviors' => self::defaultAceBehaviors
);
$userData = array_merge($userDefaults, $userData);
if($userData['aceHeight'] < 100) $userData['aceHeight'] = self::defaultAceHeight;
if($userData['aceHeight'] > 2000) $userData['aceHeight'] = 2000;
$code = $h->code;
$openPHP = '<' . '?php';
if((empty($code) || trim($code) === $openPHP) && $h->isPHP()) {
$code = "$openPHP namespace ProcessWire;\n";
}
/** @var InputfieldTextarea $f */
$f = $modules->get('InputfieldTextarea');
$f->attr('id+name', 'hc_code');
$f->attr('value', $code);
$f->label = $this->_('Code editor');
$f->icon = 'code';
$f->attr('rows', 20);
$f->attr('data-theme', $userData['aceTheme']);
$f->attr('data-keybinding', $userData['aceKeybinding']);
$f->attr('data-height', $userData['aceHeight']);
$f->attr('data-behaviors', (int) $userData['aceBehaviors']);
$tab->add($f);
/** @var InputfieldFieldset $fs */
$fs = $modules->get('InputfieldFieldset');
$fs->label = $this->_('Code editor options');
$fs->icon = 'sliders';
$fs->description = $this->_('Settings selected here will be remembered with your user account when you “Save” this Hanna Code.');
$fs->collapsed = true;
$tab->add($fs);
foreach($this->getModuleConfigInputfields($userData) as $f) {
$f->notes = '';
$fs->add($f);
}
/** @var InputfieldMarkup $f */
$f = $modules->get('InputfieldMarkup');
$f->label = $this->_('PHP and Javascript Usage Notes');
$f->value = file_get_contents(dirname(__FILE__) . '/usage-notes.php');
$f->collapsed = Inputfield::collapsedYes;
$f->icon = 'info-circle';
$tab->add($f);
$form->add($tab);
if($exportData) {
$tab = $this->newTab(array('title' => $this->_('Export')));
/** @var InputfieldTextarea $f */
$f = $modules->get('InputfieldTextarea');
$f->attr('id+name', 'hc_export');
$f->attr('value', "!HannaCode:$h->name:" . base64_encode(json_encode($exportData)) . "/!HannaCode");
$f->label = $tab->attr('title');
$f->description = $this->_('To export this Hanna code and import somewhere else, copy the contents of this field and paste into the import box somewhere else.');
$f->notes = $this->_('If you have made any changes in other tabs, make sure to save before copying the export data here.');
$f->icon = 'paper-plane';
$tab->add($f);
$form->add($tab);
}
if($id && $editable) {
$tab = $this->newTab(array('title' => $this->_('Delete'), 'id' => 'HannaCodeDelete'));
/** @var InputfieldCheckbox $f */
$f = $modules->get('InputfieldCheckbox');
$f->attr('name', 'hc_delete');
$f->attr('value', $id);
$f->label = $tab->attr('title');
$f->label2 = $this->_('Delete this Hanna Code');
$f->icon = 'trash-o';
$f->description = $this->_('Check the box and click “Save” to permanently delete this Hanna Code.');
$tab->add($f);
$form->add($tab);
}
if($this->input->get('test')) {
$label = $this->_('Test results');
$tab = $this->newTab(array('title' => $label, 'id' => 'HannaCodeTestResults'));
/** @var InputfieldMarkup $f */
$f = $modules->get('InputfieldMarkup');
$f->label = $label;
$f->description =
$this->_('This test is here primarily to check for parse errors. Blank output indicates that there were no parse errors.') . ' ' .
$this->_('You should still test in a real-world context before assuming it works. Output is in the box below.');
$f->icon = 'flask';
list($ifr, $scr) = array('iframe', 'script');
$f->value =
"<$ifr frameborder='0' id='HannaCodeTestPort' src='../test/?name=$h->name&modal=1'></$ifr>" .
"<$scr>$(document).ready(function() { setTimeout(function() { $('#_HannaCodeTestResults').click(); }, 500); });</$scr>";
$tab->add($f);
$form->add($tab);
}
/** @var InputfieldHidden $f */
$f = $modules->get('InputfieldHidden');
$f->attr('name', 'hc_id');
$f->attr('value', $id);
$form->add($f);
if($editable && $this->allowSave) {
/** @var InputfieldSubmit $f */
$f = $modules->get('InputfieldSubmit');
$f->showInHeader(true);
$f->attr('id+name', 'hc_save');
$f->attr('value', $this->_('Save'));
$form->add($f);
if($id) {
/** @var InputfieldSubmit $f */
$f = $modules->get('InputfieldSubmit');
$f->attr('id+name', 'hc_save_test');
$f->attr('value', $this->_('Save & Test'));
$f->setSecondary(true);
$form->add($f);
}
/** @var InputfieldSubmit $f */
$f = $modules->get('InputfieldSubmit');
$f->attr('id+name', 'hc_save_exit');
$f->setSecondary(true);
$f->attr('value', $this->_('Save & Exit'));
$form->add($f);
if($input->post('hc_save') || $input->post('hc_save_exit') || $input->post('hc_save_test')) {
$this->save($form);
}
$icon = wireIconMarkup('warning');
$form->appendMarkup .= "<p class='description'>$icon $this->saveInfo</p>";
} else if($editable) {
$notice = new NoticeMessage($this->saveInfo, Notice::allowMarkup);
$notice->icon = 'sun-o fa-spin';
$notice->class = 'HannaCode';
$this->wire()->notices->add($notice);
}
$config->scripts->add($config->urls('ProcessHannaCode') . "ace-" . self::aceVersion . "/src-min/ace.js");
return $form->render();
}
/**
* Save Hanna code
*
* @param InputfieldForm $form
* @return bool
* @throws WireException
*
*/
protected function save($form) {
$input = $this->wire()->input;
$session = $this->wire()->session;
$permissionError = $this->_('You do not have permission to save this');
if(!$this->hasPermission('hanna-code-edit')) throw new WireException($permissionError);
$id = (int) $input->post('hc_id');
$type = (int) $input->post('hc_type');
$delete = (int) $input->post('hc_delete');
$exitAfterSave = $input->post('hc_save_exit');
$testAfterSave = $input->post('hc_save_test');
$prevType = 0;
$phpType = HannaCode::typePHP;
if($id) {
$h = $this->hannaCodes()->get($id);
$prevType = $h->id ? $h->type : 0;
} else {
$h = $this->hannaCodes()->getNew();
}
if(($type === $phpType || $prevType === $phpType) && !$this->hasPermission('hanna-code-php')) {
throw new WireException($permissionError);
}
if($type !== $phpType && $type !== HannaCode::typeJS && $type !== HannaCode::typeHTML) {
throw new WireException('Unknown HannaCode type');
}
$form->processInput($input->post);
if($delete && $delete === $id) {
$this->hannaCodes()->delete($h);
$this->message($this->_('Deleted Hanna Code'));
$this->session->redirect('../');
}
// session specific
$userData = array(
'aceTheme' => $form->getChildByName('aceTheme')->val(),
'aceKeybinding' => $form->getChildByName('aceKeybinding')->val(),
'aceHeight' => $form->getChildByName('aceHeight')->val(),
);
$value = 0;
foreach($form->getChildByName('aceBehaviors')->val() as $behavior) {
$value = $value | (int) $behavior;
}
$userData['aceBehaviors'] = $value;
$this->wire()->user->meta('HannaCode', $userData);
// specific to this hanna code
$name = $form->getChildByName('hc_name')->val();
$type = (int) $form->getChildByName('hc_type')->val();
$code = $form->getChildByName('hc_code')->val();
$notc = $form->getChildByName('hc_not_consuming')->val();
$attr = $form->getChildByName('hc_attr')->val();
if($notc) {
$type = $type | HannaCode::typeNotConsuming;
}
if(empty($name)) {
$form->getChildByName('hc_name')->error('Name is required');
return false;
}
if(empty($code)) $code = '';
$h->name = $name;
$h->type = $type;
$h->code = $code;
$h->attrs = $attr;
$h->modified = time();
$result = $this->hannaCodes()->save($h);
if($result) {
if(!$id) $id = $h->id;
$this->message($this->_("Saved Hanna Code") . " - $h->name");
if($exitAfterSave) {
$session->redirect("../?sort=-modified");
} else if($testAfterSave) {
$session->redirect("./?id=$id&test=1");
} else {
$session->redirect("./?id=$id");
}
} else {
$this->error("Error saving");
}
return $result;
}
/**
* @param array $attrs
* @return InputfieldWrapper
*
*/
protected function newTab(array $attrs = array()) {
$tab = new InputfieldWrapper();
$this->wire($tab);
$tab->addClass('WireTab');
foreach($attrs as $name => $value) {
$tab->attr($name, $value);
}
return $tab;
}
/**
* Render a tag example for given HannaCode
*
* @param HannaCode $h
* @return string
*
*/
protected function tagExample(HannaCode $h) {
$textformatter = $this->textformatter();
$openTag = $textformatter->openTag;
$closeTag = $textformatter->closeTag;
$name = $h->name;
$attrs = '';
foreach($h->attrs() as $attrName => $attrValue) {
$attrs .= " $attrName=\"$attrValue\"";
}
if(preg_match('/[a-zA-Z0-9]$/', $openTag)) $name = " name=\"$name\"";
return $openTag . $name . $attrs . $closeTag;
}
/**
* Called only when your module is installed
*
* This version creates a new page with this Process module assigned.
*
*/
public function ___install() {
// create the page our module will be assigned to
$page = new Page();
$page->template = 'admin';
$page->name = self::pageName;
// installs to the admin "Setup" menu ... change as you see fit
$page->parent = $this->pages->get($this->config->adminRootPageID)->child('name=setup');
$page->process = $this;
// we will make the page title the same as our module title
// but you can make it whatever you want
$info = self::getModuleInfo();
$page->title = $info['title'];
// save the page
$page->save();
// tell the user we created this page
$this->message("Created Page: $page->path");
}
/**
* Called only when your module is uninstalled
*
* This should return the site to the same state it was in before the module was installed.
*
*/
public function ___uninstall() {
// find the page we installed, locating it by the process field (which has the module ID)
// it would probably be sufficient just to locate by name, but this is just to be extra sure.
$moduleID = $this->modules->getModuleID($this);
$page = $this->pages->get("template=admin, process=$moduleID, name=" . self::pageName);
if($page->id) {
// if we found the page, let the user know and delete it
$this->message("Deleting Page: $page->path");
$page->delete();
}
}
/**
* Get Ace Editor file options for themes and keybindings
*
* @return array
*
*/
protected static function getAceOptions() {
$options = array(
'themes' => array(),
'keybindings' => array(),
);
$dir = new \DirectoryIterator(dirname(__FILE__) . '/ace-' . self::aceVersion . '/src-min/');
foreach($dir as $file) {
$name = $file->getBasename();
if(preg_match('/^(theme|keybinding)-([^.]+)\.js$/', $name, $matches)) {
if($matches[1] == 'theme') {
$options['themes'][] = $matches[2];
} else if($matches[1] == 'keybinding') {
$options['keybindings'][] = $matches[2];
}
}
}
sort($options['themes']);
sort($options['keybindings']);
return $options;
}
/**
* Module config
*
* @param array $data
* @return InputfieldWrapper
*
*/
public function getModuleConfigInputfields(array $data) {
$form = new InputfieldWrapper();
$this->wire($form);
$aceOptions = self::getAceOptions();
$modules = $this->wire()->modules;
if(!isset($data['aceKeybinding'])) $data['aceKeybinding'] = self::defaultAceKeybinding;
if(!isset($data['aceBehaviors'])) $data['aceBehaviors'] = self::defaultAceBehaviors;
/** @var InputfieldSelect $f */
$f = $modules->get('InputfieldSelect');
$f->label = $this->_('Theme');
$f->attr('id+name', 'aceTheme');
foreach($aceOptions['themes'] as $theme) $f->addOption($theme);
$f->attr('value', !empty($data['aceTheme']) ? $data['aceTheme'] : self::defaultAceTheme);
$f->notes = $this->_('See the [Ace Editor demo](https://ace.c9.io/build/kitchen-sink.html) to preview what the different themes look like.');
$f->columnWidth = 34;
$form->add($f);
/** @var InputfieldSelect $f */
$f = $modules->get('InputfieldSelect');
$f->label = $this->_('Keyboard');
$f->attr('id+name', 'aceKeybinding');
$f->addOption(self::defaultAceKeybinding, __('Normal'));
foreach($aceOptions['keybindings'] as $keybinding) $f->addOption($keybinding);
$f->attr('value', !empty($data['aceKeybinding']) ? $data['aceKeybinding'] : self::defaultAceKeybinding);
$f->columnWidth = 33;
$f->required = true;
$form->add($f);
/** @var InputfieldInteger $f */
$f = $modules->get('InputfieldInteger');
$f->label = $this->_('Editor Height (in pixels)');
$f->attr('id+name', 'aceHeight');
$f->inputType = 'number';
$f->attr('value', isset($data['aceHeight']) ? $data['aceHeight'] : self::defaultAceHeight);
$f->columnWidth = 33;
$form->add($f);
/** @var InputfieldCheckboxes $f */
$f = $modules->get('InputfieldCheckboxes');
$f->attr('id+name', 'aceBehaviors');
$f->label = $this->_('Behaviors');
$f->addOption(self::aceBehaviorPair, $this->_('Pair: auto-pairing of special characters, like quotation marks, parenthesis, or brackets.'));
$f->addOption(self::aceBehaviorWrap, $this->_('Wrap: wrapping the selection with characters such as brackets when such a character is typed in.'));
$value = array();
if(is_array($data['aceBehaviors'])) {
$value = $data['aceBehaviors'];
} else {
if($data['aceBehaviors'] & self::aceBehaviorPair) $value[] = self::aceBehaviorPair;
if($data['aceBehaviors'] & self::aceBehaviorWrap) $value[] = self::aceBehaviorWrap;
}
$f->attr('value', $value);
$form->add($f);