forked from cobaltcrm/cobalt
/
Application.php
801 lines (685 loc) · 17 KB
/
Application.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
<?php
/**
* @package Cobalt.CRM
*
* @copyright Copyright (C) 2012 Cobalt. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
namespace Cobalt;
defined('_CEXEC') or die;
use JFactory;
use JDocument;
use Joomla\Registry\Registry;
use Joomla\Language\Language;
use Joomla\Language\Text;
use Joomla\Application\AbstractWebApplication;
use Joomla\Authentication\Authentication;
use Cobalt\Helper\ActivityHelper;
use Cobalt\Helper\DateHelper;
use Cobalt\Helper\RouteHelper;
use Cobalt\Helper\TemplateHelper;
use Cobalt\Helper\UsersHelper;
use Cobalt\Authentication\DatabaseStrategy;
use Cobalt\Authentication\AuthenticationException;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage;
/**
* Cobalt Application class
*
* Provide many supporting API functions
*
* @package Cobalt.CRM
* @subpackage Application
* @since 1.0
*/
final class Application extends AbstractWebApplication
{
/**
* DI Container
*
* @var Container
* @since 1.0
*/
private $container;
/**
* A session object.
*
* @var Session
* @since 1.0
* @note This has been created to avoid a conflict with the $session member var from the parent class.
*/
private $cSession = null;
/**
* Currently active template
*
* @var \stdClass
* @since 1.0
*/
private $template = null;
/**
* The Application router
*
* @var Router
* @since 1.0
*/
public $router = null;
/**
* Document object
*
* @var JDocument
* @since 1.0
*/
public $document = null;
/**
* The application message queue.
*
* @var array
* @since 1.0
*/
protected $messageQueue = array();
/**
* Array of cached User objects
*
* @var User[]
* @since 1.0
*/
protected $users = array();
/**
* The User object.
*
* @var User
* @since 1.0
*/
private $user;
/**
* The Language object
*
* @var Language
* @since 1.0
*/
private $language;
/**
* Application constructor
*
* @since 1.0
*/
public function __construct()
{
parent::__construct();
$container = Container::getInstance();
$container->registerServiceProvider(new Provider\ApplicationServiceProvider($this));
// Setup the application pieces.
$this->setContainer($container);
$this->loadDocument();
// Load the library language file
//$this->getLanguage()->load('lib_joomla', JPATH_BASE);
// TODO - NO MORE JFACTORY
JFactory::$application = $this;
}
/**
* Initialize the configuration object.
*
* @return $this Method allows chaining
*
* @since 1.0
* @throws \RuntimeException
*/
private function loadConfiguration()
{
$config = $this->getContainer()->get('config');
if ($config === null)
{
throw new \RuntimeException(sprintf('Unable to parse the configuration file %s.', $file));
}
$this->config->merge($config);
return $this;
}
/**
* Get the DI container.
*
* @return Container
*
* @since 1.0
*
* @throws \UnexpectedValueException May be thrown if the container has not been set.
*/
public function getContainer()
{
if ($this->container)
{
return $this->container;
}
throw new \UnexpectedValueException('Container not set in ' . __CLASS__);
}
/**
* Set the DI container.
*
* @param Container $container The DI container.
*
* @return $this Method allows chaining
*
* @since 1.0
*/
public function setContainer(Container $container)
{
$this->container = $container;
return $this;
}
/**
* Get a language object.
*
* @return Language
*
* @since 1.0
*/
public function getLanguage()
{
if (is_null($this->language)) {
$this->language = Language::getInstance(
$this->get('language'),
$this->get('debug_lang')
);
// Configure Text to use language instance
Text::setLanguage($this->language);
}
return $this->language;
}
/**
* Provides a secure hash based on a seed
*
* @param string $seed Seed string.
*
* @return string A secure hash
*
* @since 11.1
*/
public static function getHash($seed)
{
// TODO - Temporarily refactored back to JFactory, needs to pull from $this->getContainer instead
return md5(JFactory::getConfig()->get('secret') . $seed);
}
/**
* Get a session object.
*
* @return Session
*
* @since 1.0
*/
public function getSession()
{
if (is_null($this->cSession))
{
$this->cSession = $this->getContainer()->fetch('session');
}
return $this->cSession;
}
/**
* Clear session + database session row
*
* @return boolean
*
* @since 1.0
*/
public function clearSession()
{
$this->getSession()->clear();
}
/**
* Gets the value of a user state variable.
*
* @param string $key The key of the user state variable.
* @param string $request The name of the variable passed in a request.
* @param string $default The default value for the variable if not found. Optional.
* @param string $type Filter for the variable, for valid values see {@link JFilterInput::clean()}. Optional.
*
* @return The request user state.
*
* @since 11.1
*/
public function getUserStateFromRequest($key, $request, $default = null, $type = 'none')
{
$cur_state = $this->getUserState($key, $default);
$new_state = $this->input->get($request, null, 'default', $type);
// Save the new value only if it was set in this request.
if ($new_state !== null) {
$this->setUserState($key, $new_state);
} else {
$new_state = $cur_state;
}
return $new_state;
}
/**
* Gets a user state.
*
* @param string $key The path of the state.
* @param mixed $default Optional default value, returned if the internal value is null.
*
* @return mixed The user state or null.
*
* @since 1.0
*/
public function getUserState($key, $default = null)
{
/* @type Registry $registry */
$registry = $this->getSession()->get('registry');
if (!is_null($registry)) {
return $registry->get($key, $default);
}
return $default;
}
/**
* Sets the value of a user state variable.
*
* @param string $key The path of the state.
* @param string $value The value of the variable.
*
* @return mixed The previous state, if one existed.
*
* @since 11.1
*/
public function setUserState($key, $value)
{
$registry = $this->getSession()->get('registry');
if (!is_null($registry)) {
return $registry->set($key, $value);
}
return null;
}
/**
* Method to run the application routines.
*
* @return void
*
* @since 1.0
*/
public function doExecute()
{
// Register the template to the config
$template = $this->getTemplate(true);
$this->set('theme', $template->template);
$this->set('themeFile', $this->input->get('tmpl', 'index') . '.php');
// Set metadata
$this->document->setTitle('Cobalt');
// Start the output buffer
ob_start();
// Install check
if (!file_exists(JPATH_CONFIGURATION . '/configuration.php') || (filesize(JPATH_CONFIGURATION . '/configuration.php') < 10))
{
// Redirect to the installer if we aren't there
if (strpos($this->get('uri.route'), 'install') === false && $this->input->getString('task') != 'install')
{
ob_end_flush();
$this->redirect(RouteHelper::_('index.php?view=install'));
}
// Build a session object to push into the DI container
$session = new Session(new MockFileSessionStorage());
$this->getContainer()->set('session', $session);
// Fetch the controller
$controllerObj = $this->getRouter()->getController($this->get('uri.route'));
// Perform the Request task
$controllerObj->execute();
}
elseif (file_exists(JPATH_CONFIGURATION . '/configuration.php') && (filesize(JPATH_CONFIGURATION . '/configuration.php') > 10)
&& strpos($this->get('uri.route'), 'install') !== false)
{
$this->redirect(RouteHelper::_('index.php'));
}
else
{
// Finish bootstrapping the application now
$this->getContainer()->registerServiceProvider(new Provider\ConfigServiceProvider)
->registerServiceProvider(new Provider\DatabaseServiceProvider)
->registerServiceProvider(new Provider\SessionServiceProvider);
$this->loadConfiguration();
// Load Language
UsersHelper::loadLanguage();
// Set site timezone
$tz = DateHelper::getSiteTimezone();
// Get user object
$user = $this->getUser();
// Fetch the controller
$controllerObj = $this->getRouter()->getController($this->get('uri.route'));
// Require specific controller if requested
$controller = $this->input->get('controller', 'default');
// Load user toolbar
$format = $this->input->get('format');
$overrides = array('ajax', 'mail', 'login');
$loggedIn = $user->isAuthenticated();
if ($loggedIn && $format !== 'raw' && !in_array($controller, $overrides))
{
ActivityHelper::saveUserLoginHistory();
// Set a default view if none exists
$this->input->def('view', 'dashboard');
// Grab document instance
$document = $this->getDocument();
// Start component div wrapper
if (!in_array($this->input->get('view'), array('print')))
{
TemplateHelper::loadToolbar();
}
TemplateHelper::startCompWrap();
// Load javascript language
TemplateHelper::loadJavascriptLanguage();
TemplateHelper::showMessages();
}
if (!$loggedIn && !($controllerObj instanceof \Cobalt\Controller\Login))
{
$this->redirect(RouteHelper::_('index.php?view=login'));
}
// Fullscreen detection
if (UsersHelper::isFullscreen())
{
$this->input->set('tmpl', 'component');
}
// Perform the Request task
$controllerObj->execute();
// End componenet wrapper
if ($user !== false && $format !== 'raw')
{
TemplateHelper::endCompWrap();
}
}
$contents = ob_get_clean();
if ($this->input->get('format', 'html') === 'raw')
{
$this->setBody($contents);
}
else
{
$this->document->setBuffer($contents, 'cobalt');
$this->setBody($this->document->render(false, (array) $template));
}
}
/**
* Load the document object
*
* @return void
*
* @since 1.0
*/
public function loadDocument()
{
if (empty($this->document))
{
$this->document = JDocument::getInstance();
JFactory::$document = $this->document;
}
}
/**
* Retrieve the document object
*
* @return JDocument
*
* @since 1.0
*/
public function getDocument()
{
return $this->document;
}
/**
* Logs the user into the application
*
* @return void Redirects the application
*
* @since 1.0
* @throws AuthenticationException
*/
public function login()
{
// Get the Authentication object
$authentication = new Authentication;
// Add our authentication strategy
$strategy = new DatabaseStrategy($this->input, $this->getContainer()->get('db'));
$authentication->addStrategy('database', $strategy);
// Authenticate the user
$authentication->authenticate(array('database'));
switch ($strategy->getResult())
{
case Authentication::NO_CREDENTIALS :
throw new AuthenticationException('A username and/or password were not provided.');
case Authentication::NO_SUCH_USER :
throw new AuthenticationException('The username provided does not exist.');
case Authentication::INVALID_CREDENTIALS :
throw new AuthenticationException('The username and/or password is incorrect.');
case Authentication::SUCCESS :
$user = $this->getUser();
$user->loadByUsername($this->input->{$this->input->getMethod()}->get('username', false, 'username'));
// Set the authenticated user in the session and redirect to the manager
$this->setUser($user)->redirect(RouteHelper::_('index.php?view=dashboard'));
}
}
/**
* Get the template data
*
* @param boolean $params True to return a stdClass object with the full template data, false to return the template name only
*
* @return \stdClass|string The template name
*
* @since 1.0
*/
public function getTemplate($params = false)
{
if (is_object($this->template))
{
if ($params)
{
return $this->template;
}
return $this->template->template;
}
// Fallback template
$template = new \stdClass;
$template->template = 'bootstrap';
if (!file_exists(JPATH_THEMES . '/default/index.php'))
{
$template->template = '';
}
$template->file = $this->input->get('tmpl', 'index') . '.php';
$template->directory = 'themes';
$this->template = $template;
if ($params)
{
return $template;
}
return $template->template;
}
/**
* Overrides the default template that would be used
*
* @param string $template The template name
* @param mixed $styleParams The template style parameters
*
* @return void
*
* @since 1.0
*/
public function setTemplate($template, $styleParams = null)
{
if (is_dir(JPATH_THEMES . '/' . $template))
{
$this->template = new \stdClass;
$this->template->template = $template;
if ($styleParams instanceof Registry)
{
$this->template->params = $styleParams;
}
else
{
$this->template->params = new Registry($styleParams);
}
}
}
/**
* Allows the application to load a custom or default router.
*
* @return Router
*
* @since 1.0
*/
public function getRouter()
{
if (is_null($this->router))
{
$this->router = new Router($this->input, $this);
$maps = json_decode(file_get_contents(JPATH_BASE . '/src/routes.json'));
if (!$maps)
{
throw new \RuntimeException('Invalid router file.');
}
$this->router->addMaps($maps, true);
$this->router->setDefaultController('Cobalt\\Controller\\DefaultController');
}
return $this->router;
}
/**
* Redirect to another URL.
*
* If the headers have not been sent the redirect will be accomplished using a "301 Moved Permanently"
* or "303 See Other" code in the header pointing to the new location. If the headers have already been
* sent this will be accomplished using a JavaScript statement.
*
* @param string $url The URL to redirect to. Can only be http/https URL
* @param string $msg An optional message to display on redirect.
* @param string $msgType An optional message type.
* @param boolean $moved True if the page is 301 Permanently Moved, otherwise 303 See Other is assumed.
*
* @return void
*
* @since 1.0
*/
public function redirect($url, $msg = '', $msgType = 'message', $moved = false)
{
if ($msg)
{
$this->enqueueMessage($msg, $msgType);
}
parent::redirect($url, $moved);
}
/**
* Enqueue a system message.
*
* @param string $msg The message to enqueue.
* @param string $type The message type. Default is message.
*
* @return $this Method allows chaining
*
* @since 1.0
*/
public function enqueueMessage($msg, $type = 'message')
{
$this->getSession()->getFlashBag()->add($type, $msg);
return $this;
}
/**
* Clear the system message queue.
*
* @return void
*
* @since 1.0
*/
public function clearMessageQueue()
{
$this->getSession()->getFlashBag()->clear();
}
/**
* Get the system message queue.
*
* @return array The system message queue.
*
* @since 1.0
*/
public function getMessageQueue()
{
return $this->getSession()->getFlashBag()->peekAll();
}
/**
* Set the system message queue for a given type.
*
* @param string $type The type of message to set
* @param mixed $message Either a single message or an array of messages
*
* @return void
*
* @since 1.0
*/
public function setMessageQueue($type, $message = '')
{
$this->getSession()->getFlashBag()->set($type, $message);
}
/**
* Login or logout a user.
*
* @param User|null $user The User object or null to set a guest user.
*
* @return $this
*
* @since 1.0
*/
public function setUser(User $user = null)
{
$this->user = is_null($user) ? new User($this->getContainer()->get('db')) : $user;
$this->getSession()->set('cobalt_user', $this->user);
return $this;
}
/**
* Get a user object.
*
* @param integer $id The user id or the current user.
*
* @return User
*
* @since 1.0
*/
public function getUser($id = 0)
{
// Check if user isn't already loaded in chache array
if ($id && isset($this->users[$id]))
{
return $this->users[$id];
}
if ($id)
{
return new User($this->getContainer()->get('db'), $id);
}
if (is_null($this->user))
{
if ($this->user = $this->getSession()->get('cobalt_user'))
{
$this->user->setDatabase($this->getContainer()->get('db'));
}
else
{
$this->user = new User($this->getContainer()->get('db'));
}
}
// If User ID is known, store it to cache array
if ($this->user->id)
{
$this->users[$id] = $this->user;
}
return $this->user;
}
/**
* When user changes, refresh his/her data from database
*
* @return boolean
*
* @since 1.0
*/
public function refreshUser()
{
$user = $this->getUser();
if (!$user->get('id'))
{
// user must be logged in to be able to refresh itself
return false;
}
$user->load($user->get('id'));
$this->setUser($user);
return true;
}
protected function detectRequestUri()
{
return str_replace('index.php', '', parent::detectRequestUri());
}
}