-
-
Notifications
You must be signed in to change notification settings - Fork 200
/
Copy pathController.php
1594 lines (1402 loc) · 50.6 KB
/
Controller.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 namespace Cms\Classes;
use Cms;
use Url;
use App;
use View;
use Lang;
use Flash;
use Config;
use Session;
use Request;
use Response;
use Exception;
use SystemException;
use BackendAuth;
use Twig\Environment as TwigEnvironment;
use Twig\Cache\FilesystemCache as TwigCacheFilesystem;
use Twig\Extension\SandboxExtension;
use Cms\Twig\Loader as TwigLoader;
use Cms\Twig\DebugExtension;
use Cms\Twig\Extension as CmsTwigExtension;
use Cms\Models\MaintenanceSetting;
use System\Models\RequestLog;
use System\Helpers\View as ViewHelper;
use System\Classes\CombineAssets;
use System\Twig\Extension as SystemTwigExtension;
use System\Twig\SecurityPolicy;
use Winter\Storm\Exception\AjaxException;
use Winter\Storm\Exception\ValidationException;
use Winter\Storm\Parse\Bracket as TextParser;
use Illuminate\Http\RedirectResponse;
/**
* The CMS controller class.
* The controller finds and serves requested pages.
*
* @package winter\wn-cms-module
* @author Alexey Bobkov, Samuel Georges
*/
class Controller
{
use \System\Traits\AssetMaker;
use \System\Traits\EventEmitter;
use \System\Traits\ResponseMaker;
use \System\Traits\SecurityController;
/**
* @var \Cms\Classes\Theme A reference to the CMS theme processed by the controller.
*/
protected $theme;
/**
* @var \Cms\Classes\Router A reference to the Router object.
*/
protected $router;
/**
* @var \Cms\Twig\Loader A reference to the Twig template loader.
*/
protected $loader;
/**
* @var \Cms\Classes\Page A reference to the CMS page template being processed.
*/
protected $page;
/**
* @var \Cms\Classes\CodeBase A reference to the CMS page code section object.
*/
protected $pageObj;
/**
* @var \Cms\Classes\Layout A reference to the CMS layout template used by the page.
*/
protected $layout;
/**
* @var \Cms\Classes\CodeBase A reference to the CMS layout code section object.
*/
protected $layoutObj;
/**
* @var TwigEnvironment Keeps the Twig environment object.
*/
protected $twig;
/**
* @var string Contains the rendered page contents string.
*/
protected $pageContents;
/**
* @var array A list of variables to pass to the page.
*/
public $vars = [];
/**
* @var self Cache of self
*/
protected static $instance;
/**
* @var \Cms\Classes\ComponentBase Object of the active component, used internally.
*/
protected $componentContext;
/**
* @var array Component partial stack, used internally.
*/
protected $partialStack = [];
/**
* Creates the controller.
* @param \Cms\Classes\Theme $theme Specifies the CMS theme.
* If the theme is not specified, the current active theme used.
*/
public function __construct($theme = null)
{
$this->theme = $theme ?: Theme::getActiveTheme();
if (!$this->theme) {
throw new CmsException(Lang::get('cms::lang.theme.active.not_found'));
}
$this->assetPath = Config::get('cms.themesPath', '/themes') . '/' . $this->theme->getDirName();
$this->router = new Router($this->theme);
$this->partialStack = new PartialStack;
$this->initTwigEnvironment();
self::$instance = $this;
}
/**
* Finds and serves the requested page.
* If the page cannot be found, returns the page with the URL /404.
* If the /404 page doesn't exist, returns the system 404 page.
* If the parameter is null, the current URL used. If it is not
* provided then '/' is used
*
* @param string|null $url Specifies the requested page URL.
* @return BaseResponse Returns the response to the provided URL
*/
public function run($url = '/')
{
if ($url === null) {
$url = Request::path();
}
if (trim($url) === '') {
$url = '/';
}
/*
* Hidden page
*/
$page = $this->router->findByUrl($url);
if ($page && $page->is_hidden && !BackendAuth::getUser()) {
$page = null;
}
/*
* Maintenance mode
*/
if (
MaintenanceSetting::isConfigured() &&
MaintenanceSetting::get('is_enabled', false) &&
!BackendAuth::getUser()
) {
if (!Request::ajax()) {
$this->setStatusCode(503);
}
$page = Page::loadCached($this->theme, MaintenanceSetting::get('cms_page'));
}
/**
* @event cms.page.beforeDisplay
* Provides an opportunity to swap the page that gets displayed immediately after loading the page assigned to the URL.
*
* Example usage:
*
* Event::listen('cms.page.beforeDisplay', function ((\Cms\Classes\Controller) $controller, (string) $url, (\Cms\Classes\Page) $page) {
* if ($url === '/tricked-you') {
* return \Cms\Classes\Page::loadCached('trick-theme-code', 'page-file-name');
* }
* });
*
* Or
*
* $CmsController->bindEvent('page.beforeDisplay', function ((string) $url, (\Cms\Classes\Page) $page) {
* if ($url === '/tricked-you') {
* return \Cms\Classes\Page::loadCached('trick-theme-code', 'page-file-name');
* }
* });
*
*/
if ($event = $this->fireSystemEvent('cms.page.beforeDisplay', [$url, $page])) {
if ($event instanceof Page) {
$page = $event;
} else {
return $event;
}
}
/*
* If the page was not found, render the 404 page - either provided by the theme or the built-in one.
*/
if (!$page || $url === '404' || ($url === 'error' && !Config::get('app.debug', false))) {
if (!Request::ajax()) {
$this->setStatusCode(404);
}
// Log the 404 request
if (!App::runningUnitTests()) {
RequestLog::add();
}
if (!$page = $this->router->findByUrl('/404')) {
return Response::make(View::make('cms::404'), $this->statusCode);
}
}
/*
* Run the page
*/
$result = $this->runPage($page);
/*
* Post-processing
*/
$result = $this->postProcessResult($page, $url, $result);
/**
* @event cms.page.display
* Provides an opportunity to modify the response after the page for the URL has been processed. `$result` could be a string representing the HTML to be returned or it could be a Response instance.
*
* Example usage:
*
* Event::listen('cms.page.display', function ((\Cms\Classes\Controller) $controller, (string) $url, (\Cms\Classes\Page) $page, (mixed) $result) {
* if ($url === '/tricked-you') {
* return Response::make('Boo!', 200);
* }
* });
*
* Or
*
* $CmsController->bindEvent('page.display', function ((string) $url, (\Cms\Classes\Page) $page, (mixed) $result) {
* if ($url === '/tricked-you') {
* return Response::make('Boo!', 200);
* }
* });
*
*/
if ($event = $this->fireSystemEvent('cms.page.display', [$url, $page, $result])) {
$result = $event;
}
/*
* Prepare and return response
* @see \System\Traits\ResponseMaker
*/
return $this->makeResponse($result);
}
/**
* Renders a page in its entirety, including component initialization.
* AJAX will be disabled for this process.
* @param string $pageFile Specifies the CMS page file name to run.
* @param array $parameters Routing parameters.
* @param \Cms\Classes\Theme $theme Theme object
*/
public static function render($pageFile, $parameters = [], $theme = null)
{
if (!$theme && (!$theme = Theme::getActiveTheme())) {
throw new CmsException(Lang::get('cms::lang.theme.active.not_found'));
}
$controller = new static($theme);
$controller->getRouter()->setParameters($parameters);
if (($page = Page::load($theme, $pageFile)) === null) {
throw new CmsException(Lang::get('cms::lang.page.not_found_name', ['name'=>$pageFile]));
}
return $controller->runPage($page, false);
}
/**
* Runs a page directly from its object and supplied parameters.
* @param \Cms\Classes\Page $page Specifies the CMS page to run.
* @return string
*/
public function runPage($page, $useAjax = true)
{
$this->page = $page;
/*
* If the page doesn't refer any layout, create the fallback layout.
* Otherwise load the layout specified in the page.
*/
if (!$page->layout) {
$layout = Layout::initFallback($this->theme);
}
elseif (($layout = Layout::loadCached($this->theme, $page->layout)) === null) {
throw new CmsException(Lang::get('cms::lang.layout.not_found_name', ['name'=>$page->layout]));
}
$this->layout = $layout;
/*
* The 'this' variable is reserved for default variables.
*/
$this->vars['this'] = [
'page' => $this->page,
'layout' => $this->layout,
'theme' => $this->theme,
'param' => $this->router->getParameters(),
'controller' => $this,
'environment' => App::environment(),
'session' => App::make('session'),
];
/*
* Check for the presence of validation errors in the session.
*/
$this->vars['errors'] = (Config::get('session.driver') && Session::has('errors'))
? Session::get('errors')
: new \Illuminate\Support\ViewErrorBag;
/*
* Handle AJAX requests and execute the life cycle functions
*/
$this->initCustomObjects();
$this->initComponents();
/*
* Give the layout and page an opportunity to participate
* after components are initialized and before AJAX is handled.
*/
if ($this->layoutObj) {
CmsException::mask($this->layout, 300);
$this->layoutObj->onInit();
CmsException::unmask();
}
CmsException::mask($this->page, 300);
$this->pageObj->onInit();
CmsException::unmask();
/**
* @event cms.page.init
* Provides an opportunity to return a custom response from Controller->runPage() before AJAX handlers are executed
*
* Example usage:
*
* Event::listen('cms.page.init', function ((\Cms\Classes\Controller) $controller, (\Cms\Classes\Page) $page) {
* return \Cms\Classes\Page::loadCached('trick-theme-code', 'page-file-name');
* });
*
* Or
*
* $CmsController->bindEvent('page.init', function ((\Cms\Classes\Page) $page) {
* return \Cms\Classes\Page::loadCached('trick-theme-code', 'page-file-name');
* });
*
*/
if ($event = $this->fireSystemEvent('cms.page.init', [$page])) {
return $event;
}
/*
* Execute AJAX event
*/
if ($useAjax && $ajaxResponse = $this->execAjaxHandlers()) {
return $ajaxResponse;
}
/*
* Execute postback handler
*/
if (
$useAjax &&
($handler = post('_handler')) &&
$this->verifyCsrfToken() &&
($handlerResponse = $this->runAjaxHandler($handler)) &&
$handlerResponse !== true
) {
return $handlerResponse;
}
/*
* Execute page lifecycle
*/
if ($cycleResponse = $this->execPageCycle()) {
return $cycleResponse;
}
/**
* @event cms.page.beforeRenderPage
* Fires after AJAX handlers are dealt with and provides an opportunity to modify the page contents
*
* Example usage:
*
* Event::listen('cms.page.beforeRenderPage', function ((\Cms\Classes\Controller) $controller, (\Cms\Classes\Page) $page) {
* return 'Custom page contents';
* });
*
* Or
*
* $CmsController->bindEvent('page.beforeRenderPage', function ((\Cms\Classes\Page) $page) {
* return 'Custom page contents';
* });
*
*/
if ($event = $this->fireSystemEvent('cms.page.beforeRenderPage', [$page])) {
$this->pageContents = $event;
}
else {
/*
* Render the page
*/
CmsException::mask($this->page, 400);
$this->loader->setObject($this->page);
$template = $this->twig->loadTemplate($this->page->getFilePath());
$this->pageContents = $template->render($this->vars);
CmsException::unmask();
}
/*
* Render the layout
*/
CmsException::mask($this->layout, 400);
$this->loader->setObject($this->layout);
$template = $this->twig->loadTemplate($this->layout->getFilePath());
$result = $template->render($this->vars);
CmsException::unmask();
return $result;
}
/**
* Invokes the current page cycle without rendering the page,
* used by AJAX handler that may rely on the logic inside the action.
*/
public function pageCycle()
{
return $this->execPageCycle();
}
/**
* Executes the page life cycle.
* Creates an object from the PHP sections of the page and
* it's layout, then executes their life cycle functions.
*/
protected function execPageCycle()
{
/**
* @event cms.page.start
* Fires before all of the page & layout lifecycle handlers are run
*
* Example usage:
*
* Event::listen('cms.page.start', function ((\Cms\Classes\Controller) $controller) {
* return Response::make('Taking over the lifecycle!', 200);
* });
*
* Or
*
* $CmsController->bindEvent('page.start', function () {
* return Response::make('Taking over the lifecycle!', 200);
* });
*
*/
if ($event = $this->fireSystemEvent('cms.page.start')) {
return $event;
}
/*
* Run layout functions
*/
if ($this->layoutObj) {
CmsException::mask($this->layout, 300);
$response = (
($result = $this->layoutObj->onStart()) ||
($result = $this->layout->runComponents()) ||
($result = $this->layoutObj->onBeforePageStart())
) ? $result : null;
CmsException::unmask();
if ($response) {
return $response;
}
}
/*
* Run page functions
*/
CmsException::mask($this->page, 300);
$response = (
($result = $this->pageObj->onStart()) ||
($result = $this->page->runComponents()) ||
($result = $this->pageObj->onEnd())
) ? $result : null;
CmsException::unmask();
if ($response) {
return $response;
}
/*
* Run remaining layout functions
*/
if ($this->layoutObj) {
CmsException::mask($this->layout, 300);
$response = ($result = $this->layoutObj->onEnd()) ? $result : null;
CmsException::unmask();
}
/**
* @event cms.page.end
* Fires after all of the page & layout lifecycle handlers are run
*
* Example usage:
*
* Event::listen('cms.page.end', function ((\Cms\Classes\Controller) $controller) {
* return Response::make('Taking over the lifecycle!', 200);
* });
*
* Or
*
* $CmsController->bindEvent('page.end', function () {
* return Response::make('Taking over the lifecycle!', 200);
* });
*
*/
if ($event = $this->fireSystemEvent('cms.page.end')) {
return $event;
}
return $response;
}
/**
* Post-processes page HTML code before it's sent to the client.
* Note for pre-processing see cms.template.processTwigContent event.
* @param \Cms\Classes\Page $page Specifies the current CMS page.
* @param string $url Specifies the current URL.
* @param string $content The page markup to post-process.
* @return string Returns the updated result string.
*/
protected function postProcessResult($page, $url, $content)
{
$content = MediaViewHelper::instance()->processHtml($content);
/**
* @event cms.page.postprocess
* Provides opportunity to hook into the post-processing of page HTML code before being sent to the client. `$dataHolder` = {content: $htmlContent}
*
* Example usage:
*
* Event::listen('cms.page.postprocess', function ((\Cms\Classes\Controller) $controller, (string) $url, (\Cms\Classes\Page) $page, (object) $dataHolder) {
* return 'My custom content';
* });
*
* Or
*
* $CmsController->bindEvent('page.postprocess', function ((string) $url, (\Cms\Classes\Page) $page, (object) $dataHolder) {
* return 'My custom content';
* });
*
*/
$dataHolder = (object) ['content' => $content];
$this->fireSystemEvent('cms.page.postprocess', [$url, $page, $dataHolder]);
return $dataHolder->content;
}
//
// Initialization
//
/**
* Initializes the Twig environment and loader.
* Registers the \Cms\Twig\Extension object with Twig.
* @return void
*/
protected function initTwigEnvironment()
{
$this->loader = new TwigLoader;
$useCache = !Config::get('cms.twigNoCache');
$isDebugMode = Config::get('app.debug', false);
$strictVariables = Config::get('cms.enableTwigStrictVariables', false);
$strictVariables = $strictVariables ?? $isDebugMode;
$forceBytecode = Config::get('cms.forceBytecodeInvalidation', false);
$options = [
'auto_reload' => true,
'debug' => $isDebugMode,
'strict_variables' => $strictVariables,
];
if ($useCache) {
$options['cache'] = new TwigCacheFilesystem(
storage_path().'/cms/twig',
$forceBytecode ? TwigCacheFilesystem::FORCE_BYTECODE_INVALIDATION : 0
);
}
$this->twig = new TwigEnvironment($this->loader, $options);
$this->twig->addExtension(new CmsTwigExtension($this));
$this->twig->addExtension(new SystemTwigExtension);
$this->twig->addExtension(new SandboxExtension(new SecurityPolicy, true));
if ($isDebugMode) {
$this->twig->addExtension(new DebugExtension($this));
}
}
/**
* Initializes the custom layout and page objects.
* @return void
*/
protected function initCustomObjects()
{
$this->layoutObj = null;
if (!$this->layout->isFallBack()) {
CmsException::mask($this->layout, 300);
$parser = new CodeParser($this->layout);
$this->layoutObj = $parser->source($this->page, $this->layout, $this);
CmsException::unmask();
}
CmsException::mask($this->page, 300);
$parser = new CodeParser($this->page);
$this->pageObj = $parser->source($this->page, $this->layout, $this);
CmsException::unmask();
}
/**
* Initializes the components for the layout and page.
* @return void
*/
protected function initComponents()
{
if (!$this->layout->isFallBack()) {
foreach ($this->layout->settings['components'] as $component => $properties) {
list($name, $alias) = strpos($component, ' ')
? explode(' ', $component)
: [$component, $component];
$this->addComponent($name, $alias, $properties, true);
}
}
foreach ($this->page->settings['components'] as $component => $properties) {
list($name, $alias) = strpos($component, ' ')
? explode(' ', $component)
: [$component, $component];
$this->addComponent($name, $alias, $properties);
}
/**
* @event cms.page.initComponents
* Fires after the components for the given page have been initialized
*
* Example usage:
*
* Event::listen('cms.page.initComponents', function ((\Cms\Classes\Controller) $controller, (\Cms\Classes\Page) $page, (\Cms\Classes\Layout) $layout) {
* \Log::info($page->title . ' components have been initialized');
* });
*
* Or
*
* $CmsController->bindEvent('page.initComponents', function ((\Cms\Classes\Page) $page, (\Cms\Classes\Layout) $layout) {
* \Log::info($page->title . ' components have been initialized');
* });
*
*/
$this->fireSystemEvent('cms.page.initComponents', [$this->page, $this->layout]);
}
//
// AJAX
//
/**
* Returns the AJAX handler for the current request, if available.
* @return string
*/
public function getAjaxHandler()
{
if (!Request::ajax() || Request::method() != 'POST') {
return null;
}
if ($handler = Request::header('X_WINTER_REQUEST_HANDLER')) {
return trim($handler);
}
return null;
}
/**
* Executes the page, layout, component and plugin AJAX handlers.
* @return mixed Returns the AJAX Response object or null.
*/
protected function execAjaxHandlers()
{
if ($handler = $this->getAjaxHandler()) {
try {
/*
* Validate the handler name
*/
if (!preg_match('/^(?:\w+\:{2})?on[A-Z]{1}[\w+]*$/', $handler)) {
throw new CmsException(Lang::get('cms::lang.ajax_handler.invalid_name', ['name'=>$handler]));
}
/*
* Validate the handler partial list
*/
if ($partialList = trim(Request::header('X_WINTER_REQUEST_PARTIALS'))) {
$partialList = explode('&', $partialList);
foreach ($partialList as $partial) {
if (!preg_match('/^(?:\w+\:{2}|@)?[a-z0-9\_\-\.\/]+$/i', $partial)) {
throw new CmsException(Lang::get('cms::lang.partial.invalid_name', ['name'=>$partial]));
}
}
}
else {
$partialList = [];
}
$responseContents = [];
/*
* Execute the handler
*/
if (!$result = $this->runAjaxHandler($handler)) {
throw new CmsException(Lang::get('cms::lang.ajax_handler.not_found', ['name'=>$handler]));
}
/*
* Render partials and return the response as array that will be converted to JSON automatically.
*/
foreach ($partialList as $partial) {
$responseContents[$partial] = $this->renderPartial($partial);
}
/*
* If the handler returned a redirect, process the URL and dispose of it so
* framework.js knows to redirect the browser and not the request!
*/
if ($result instanceof RedirectResponse) {
$responseContents['X_WINTER_REDIRECT'] = $result->getTargetUrl();
$result = null;
}
/*
* No redirect is used, look for any flash messages
*/
elseif (Request::header('X_WINTER_REQUEST_FLASH') && Flash::check()) {
$responseContents['X_WINTER_FLASH_MESSAGES'] = Flash::all();
}
/*
* If the handler returned an array, we should add it to output for rendering.
* If it is a string, add it to the array with the key "result".
* If an object, pass it to Laravel as a response object.
*/
if (is_array($result)) {
$responseContents = array_merge($responseContents, $result);
}
elseif (is_string($result)) {
$responseContents['result'] = $result;
}
elseif (is_object($result)) {
return $result;
}
return Response::make($responseContents, $this->statusCode);
}
catch (ValidationException $ex) {
/*
* Handle validation errors
*/
$responseContents['X_WINTER_ERROR_FIELDS'] = $ex->getFields();
$responseContents['X_WINTER_ERROR_MESSAGE'] = $ex->getMessage();
throw new AjaxException($responseContents);
}
catch (Exception $ex) {
throw $ex;
}
}
return null;
}
/**
* Tries to find and run an AJAX handler in the page, layout, components and plugins.
* The method stops as soon as the handler is found.
* @param string $handler name of the ajax handler
* @return boolean Returns true if the handler was found. Returns false otherwise.
*/
protected function runAjaxHandler($handler)
{
/**
* @event cms.ajax.beforeRunHandler
* Provides an opportunity to modify an AJAX request
*
* The parameter provided is `$handler` (the requested AJAX handler to be run)
*
* Example usage (forwards AJAX handlers to a backend widget):
*
* Event::listen('cms.ajax.beforeRunHandler', function ((\Cms\Classes\Controller) $controller, (string) $handler) {
* if (strpos($handler, '::')) {
* list($componentAlias, $handlerName) = explode('::', $handler);
* if ($componentAlias === $this->getBackendWidgetAlias()) {
* return $this->backendControllerProxy->runAjaxHandler($handler);
* }
* }
* });
*
* Or
*
* $this->controller->bindEvent('ajax.beforeRunHandler', function ((string) $handler) {
* if (strpos($handler, '::')) {
* list($componentAlias, $handlerName) = explode('::', $handler);
* if ($componentAlias === $this->getBackendWidgetAlias()) {
* return $this->backendControllerProxy->runAjaxHandler($handler);
* }
* }
* });
*
*/
if ($event = $this->fireSystemEvent('cms.ajax.beforeRunHandler', [$handler])) {
return $event;
}
/*
* Process Component handler
*/
if (strpos($handler, '::')) {
list($componentName, $handlerName) = explode('::', $handler);
$componentObj = $this->findComponentByName($componentName);
if ($componentObj && $componentObj->methodExists($handlerName)) {
$this->componentContext = $componentObj;
$result = $componentObj->runAjaxHandler($handlerName);
return $result ?: true;
}
}
/*
* Process code section handler
*/
else {
if (method_exists($this->pageObj, $handler)) {
$result = $this->pageObj->$handler();
return $result ?: true;
}
if (!$this->layout->isFallBack() && method_exists($this->layoutObj, $handler)) {
$result = $this->layoutObj->$handler();
return $result ?: true;
}
/*
* Cycle each component to locate a usable handler
*/
if (($componentObj = $this->findComponentByHandler($handler)) !== null) {
$this->componentContext = $componentObj;
$result = $componentObj->runAjaxHandler($handler);
return $result ?: true;
}
}
/*
* Generic handler that does nothing
*/
if ($handler == 'onAjax') {
return true;
}
return false;
}
//
// Rendering
//
/**
* Renders a requested page.
* The framework uses this method internally.
*/
public function renderPage()
{
$contents = $this->pageContents;
/**
* @event cms.page.render
* Provides an opportunity to manipulate the page's rendered contents
*
* Example usage:
*
* Event::listen('cms.page.render', function ((\Cms\Classes\Controller) $controller, (string) $pageContents) {
* return 'My custom contents';
* });
*
* Or
*
* $CmsController->bindEvent('page.render', function ((string) $pageContents) {
* return 'My custom contents';
* });
*
*/
if ($event = $this->fireSystemEvent('cms.page.render', [$contents])) {
return $event;
}
return $contents;
}
/**
* Renders a requested partial.
* The framework uses this method internally.
* @param string $name The view to load.
* @param array $parameters Parameter variables to pass to the view.
* @param bool $throwException Throw an exception if the partial is not found.
* @return mixed Partial contents or false if not throwing an exception.
*/
public function renderPartial($name, $parameters = [], $throwException = true)
{
$vars = $this->vars;
$this->vars = array_merge($this->vars, $parameters);
/*
* Alias @ symbol for ::
*/
if (substr($name, 0, 1) == '@') {
$name = '::' . substr($name, 1);
}
/**
* @event cms.page.beforeRenderPartial
* Provides an opportunity to manipulate the name of the partial being rendered before it renders
*
* Example usage:
*
* Event::listen('cms.page.beforeRenderPartial', function ((\Cms\Classes\Controller) $controller, (string) $partialName) {
* return Cms\Classes\Partial::loadCached($theme, 'custom-partial-name');
* });
*
* Or
*
* $CmsController->bindEvent('page.beforeRenderPartial', function ((string) $partialName) {
* return Cms\Classes\Partial::loadCached($theme, 'custom-partial-name');
* });
*
*/
if ($event = $this->fireSystemEvent('cms.page.beforeRenderPartial', [$name])) {
$partial = $event;
}
/*
* Process Component partial
*/
elseif (strpos($name, '::') !== false) {
list($componentAlias, $partialName) = explode('::', $name);
/*
* Component alias not supplied
*/
if (!strlen($componentAlias)) {
if ($this->componentContext !== null) {
$componentObj = $this->componentContext;
}
elseif (($componentObj = $this->findComponentByPartial($partialName)) === null) {
if ($throwException) {
throw new CmsException(Lang::get('cms::lang.partial.not_found_name', ['name'=>$partialName]));
}
return false;
}
}
/*
* Component alias is supplied
*/
elseif (($componentObj = $this->findComponentByName($componentAlias)) === null) {
if ($throwException) {
throw new CmsException(Lang::get('cms::lang.component.not_found', ['name'=>$componentAlias]));
}
return false;
}
$partial = null;
$this->componentContext = $componentObj;
/*