PageRenderTime 38ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/application/Espo/Core/Application.php

https://gitlab.com/johanlindberg/irvato-crm
PHP | 334 lines | 240 code | 67 blank | 27 comment | 26 complexity | 272cdc517b1eb50bb046311c0bdbf78a MD5 | raw file
  1. <?php
  2. /************************************************************************
  3. * This file is part of EspoCRM.
  4. *
  5. * EspoCRM - Open Source CRM application.
  6. * Copyright (C) 2014-2015 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko
  7. * Website: http://www.espocrm.com
  8. *
  9. * EspoCRM is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation, either version 3 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * EspoCRM is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with EspoCRM. If not, see http://www.gnu.org/licenses/.
  21. *
  22. * The interactive user interfaces in modified source and object code versions
  23. * of this program must display Appropriate Legal Notices, as required under
  24. * Section 5 of the GNU General Public License version 3.
  25. *
  26. * In accordance with Section 7(b) of the GNU General Public License version 3,
  27. * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
  28. ************************************************************************/
  29. namespace Espo\Core;
  30. class Application
  31. {
  32. private $metadata;
  33. protected $container;
  34. private $slim;
  35. private $auth;
  36. public function __construct()
  37. {
  38. date_default_timezone_set('UTC');
  39. $this->initContainer();
  40. $GLOBALS['log'] = $this->getContainer()->get('log');
  41. $this->initAutoloads();
  42. }
  43. protected function initContainer()
  44. {
  45. $this->container = new Container();
  46. }
  47. public function getSlim()
  48. {
  49. if (empty($this->slim)) {
  50. $this->slim = $this->container->get('slim');
  51. }
  52. return $this->slim;
  53. }
  54. public function getMetadata()
  55. {
  56. if (empty($this->metadata)) {
  57. $this->metadata = $this->container->get('metadata');
  58. }
  59. return $this->metadata;
  60. }
  61. protected function createAuth()
  62. {
  63. return new \Espo\Core\Utils\Auth($this->container);
  64. }
  65. public function getContainer()
  66. {
  67. return $this->container;
  68. }
  69. public function run($name = 'default')
  70. {
  71. $this->routeHooks();
  72. $this->initRoutes();
  73. $this->getSlim()->run();
  74. }
  75. public function runClient()
  76. {
  77. $this->getContainer()->get('clientManager')->display();
  78. }
  79. public function runEntryPoint($entryPoint, $data = array(), $final = false)
  80. {
  81. if (empty($entryPoint)) {
  82. throw new \Error();
  83. }
  84. $slim = $this->getSlim();
  85. $container = $this->getContainer();
  86. $slim->any('.*', function() {});
  87. $entryPointManager = new \Espo\Core\EntryPointManager($container);
  88. try {
  89. $authRequired = $entryPointManager->checkAuthRequired($entryPoint);
  90. $authNotStrict = $entryPointManager->checkNotStrictAuth($entryPoint);
  91. if ($authRequired && !$authNotStrict) {
  92. if (!$final && $portalId = $this->detectedPortalId()) {
  93. $app = new \Espo\Core\Portal\Application($portalId);
  94. $app->setBasePath($this->getBasePath());
  95. $app->runEntryPoint($entryPoint, $data, true);
  96. exit;
  97. }
  98. }
  99. $auth = new \Espo\Core\Utils\Auth($this->container, $authNotStrict);
  100. $apiAuth = new \Espo\Core\Utils\Api\Auth($auth, $authRequired, true);
  101. $slim->add($apiAuth);
  102. $slim->hook('slim.before.dispatch', function () use ($entryPoint, $entryPointManager, $container, $data) {
  103. $entryPointManager->run($entryPoint, $data);
  104. });
  105. $slim->run();
  106. } catch (\Exception $e) {
  107. $container->get('output')->processError($e->getMessage(), $e->getCode(), true);
  108. }
  109. }
  110. public function runCron()
  111. {
  112. $auth = $this->createAuth();
  113. $auth->useNoAuth(true);
  114. $cronManager = new \Espo\Core\CronManager($this->container);
  115. $cronManager->run();
  116. }
  117. public function runRebuild()
  118. {
  119. $dataManager = $this->getContainer()->get('dataManager');
  120. $dataManager->rebuild();
  121. }
  122. public function runClearCache()
  123. {
  124. $dataManager = $this->getContainer()->get('dataManager');
  125. $dataManager->clearCache();
  126. }
  127. public function isInstalled()
  128. {
  129. $config = $this->getContainer()->get('config');
  130. if (file_exists($config->getConfigPath()) && $config->get('isInstalled')) {
  131. return true;
  132. }
  133. return false;
  134. }
  135. protected function createApiAuth($auth)
  136. {
  137. return new \Espo\Core\Utils\Api\Auth($auth);
  138. }
  139. protected function routeHooks()
  140. {
  141. $container = $this->getContainer();
  142. $slim = $this->getSlim();
  143. try {
  144. $auth = $this->createAuth();
  145. } catch (\Exception $e) {
  146. $container->get('output')->processError($e->getMessage(), $e->getCode());
  147. }
  148. $apiAuth = $this->createApiAuth($auth);
  149. $this->getSlim()->add($apiAuth);
  150. $this->getSlim()->hook('slim.before.dispatch', function () use ($slim, $container) {
  151. $route = $slim->router()->getCurrentRoute();
  152. $conditions = $route->getConditions();
  153. if (isset($conditions['useController']) && $conditions['useController'] == false) {
  154. return;
  155. }
  156. $routeOptions = call_user_func($route->getCallable());
  157. $routeKeys = is_array($routeOptions) ? array_keys($routeOptions) : array();
  158. if (!in_array('controller', $routeKeys, true)) {
  159. return $container->get('output')->render($routeOptions);
  160. }
  161. $params = $route->getParams();
  162. $data = $slim->request()->getBody();
  163. foreach ($routeOptions as $key => $value) {
  164. if (strstr($value, ':')) {
  165. $paramName = str_replace(':', '', $value);
  166. $value = $params[$paramName];
  167. }
  168. $controllerParams[$key] = $value;
  169. }
  170. $params = array_merge($params, $controllerParams);
  171. $controllerName = ucfirst($controllerParams['controller']);
  172. if (!empty($controllerParams['action'])) {
  173. $actionName = $controllerParams['action'];
  174. } else {
  175. $httpMethod = strtolower($slim->request()->getMethod());
  176. $crudList = $container->get('config')->get('crud');
  177. $actionName = $crudList[$httpMethod];
  178. }
  179. try {
  180. $controllerManager = new \Espo\Core\ControllerManager($container);
  181. $result = $controllerManager->process($controllerName, $actionName, $params, $data, $slim->request());
  182. $container->get('output')->render($result);
  183. } catch (\Exception $e) {
  184. $container->get('output')->processError($e->getMessage(), $e->getCode());
  185. }
  186. });
  187. $this->getSlim()->hook('slim.after.router', function () use (&$slim) {
  188. $slim->contentType('application/json');
  189. $res = $slim->response();
  190. $res->header('Expires', '0');
  191. $res->header('Last-Modified', gmdate("D, d M Y H:i:s") . " GMT");
  192. $res->header('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
  193. $res->header('Pragma', 'no-cache');
  194. });
  195. }
  196. protected function getRouteList()
  197. {
  198. $routes = new \Espo\Core\Utils\Route($this->getContainer()->get('config'), $this->getMetadata(), $this->getContainer()->get('fileManager'));
  199. return $routes->getAll();
  200. }
  201. protected function initRoutes()
  202. {
  203. $crudList = array_keys($this->getContainer()->get('config')->get('crud'));
  204. foreach ($this->getRouteList() as $route) {
  205. $method = strtolower($route['method']);
  206. if (!in_array($method, $crudList)) {
  207. $GLOBALS['log']->error('Route: Method ['.$method.'] does not exist. Please check your route ['.$route['route'].']');
  208. continue;
  209. }
  210. $currentRoute = $this->getSlim()->$method($route['route'], function() use ($route) { //todo change "use" for php 5.4
  211. return $route['params'];
  212. });
  213. if (isset($route['conditions'])) {
  214. $currentRoute->conditions($route['conditions']);
  215. }
  216. }
  217. }
  218. protected function initAutoloads()
  219. {
  220. $autoload = new \Espo\Core\Utils\Autoload($this->getContainer()->get('config'), $this->getMetadata(), $this->getContainer()->get('fileManager'));
  221. try {
  222. $autoloadList = $autoload->getAll();
  223. } catch (\Exception $e) {} //bad permissions
  224. if (empty($autoloadList)) {
  225. return;
  226. }
  227. $namespacesPath = 'vendor/composer/autoload_namespaces.php';
  228. $existingNamespaces = file_exists($namespacesPath) ? include($namespacesPath) : array();
  229. if (!empty($existingNamespaces) && is_array($existingNamespaces)) {
  230. $existingNamespaces = array_keys($existingNamespaces);
  231. }
  232. $classLoader = new \Composer\Autoload\ClassLoader();
  233. foreach ($autoloadList as $prefix => $path) {
  234. if (!in_array($prefix, $existingNamespaces)) {
  235. $classLoader->add($prefix, $path);
  236. }
  237. }
  238. $classLoader->register(true);
  239. }
  240. public function setBasePath($basePath)
  241. {
  242. $this->getContainer()->get('clientManager')->setBasePath($basePath);
  243. }
  244. public function getBasePath()
  245. {
  246. return $this->getContainer()->get('clientManager')->getBasePath();
  247. }
  248. public function detectedPortalId()
  249. {
  250. if (!empty($_GET['portalId'])) {
  251. return $_GET['portalId'];
  252. }
  253. if (!empty($_COOKIE['auth-token'])) {
  254. $token = $this->getContainer()->get('entityManager')->getRepository('AuthToken')->where(array('token' => $_COOKIE['auth-token']))->findOne();
  255. if ($token && $token->get('portalId')) {
  256. return $token->get('portalId');
  257. }
  258. }
  259. return null;
  260. }
  261. public function setupSystemUser()
  262. {
  263. $user = $this->getContainer()->get('entityManager')->getEntity('User', 'system');
  264. $this->getContainer()->setUser($user);
  265. $this->getContainer()->get('entityManager')->setUser($user);
  266. }
  267. }