PageRenderTime 43ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/your_app_name/vendor/drumon_core/class/app.php

https://github.com/sook/drumon_framework
PHP | 442 lines | 203 code | 58 blank | 181 comment | 26 complexity | 452c9613e4b7076bb5744825388aeb88 MD5 | raw file
Possible License(s): GPL-3.0
  1. <?php
  2. /**
  3. * Drumon Framework: Build fast web applications
  4. * Copyright (C) 2010 Sook - Desenvolvendo inovações (http://www.sook.com.br)
  5. * Licensed under GNU General Public License.
  6. */
  7. /**
  8. * Core Application for Drumon Framework
  9. *
  10. * @package class
  11. */
  12. class App {
  13. /**
  14. * Application object instance
  15. *
  16. * @var App
  17. */
  18. private static $instance;
  19. /**
  20. * Events list to fire
  21. *
  22. * @var array
  23. */
  24. private $event_list = array();
  25. /**
  26. * Drumon configurations
  27. *
  28. * @var array
  29. */
  30. public $config = array();
  31. /**
  32. * Drumon plugins
  33. *
  34. * @var array
  35. */
  36. public $plugins = array();
  37. /**
  38. * Drumon helpers
  39. *
  40. * @var array
  41. */
  42. public $helpers = array();
  43. /**
  44. * Cache all translations for application
  45. *
  46. * @var string
  47. */
  48. public $translations_cache = array();
  49. /**
  50. * Block object initialization
  51. *
  52. */
  53. private function __construct() {}
  54. /**
  55. * Throws an exception on clone
  56. *
  57. * @throws Exception
  58. */
  59. public final function __clone() {
  60. throw new BadMethodCallException("Clone is not allowed");
  61. }
  62. /**
  63. * Get singleton instance
  64. *
  65. * @return Event
  66. */
  67. public static function get_instance() {
  68. if (!isset(self::$instance)) {
  69. self::$instance = new App();
  70. }
  71. return self::$instance;
  72. }
  73. /**
  74. * Run Application
  75. *
  76. * @return void
  77. */
  78. public static function run() {
  79. // Get application object
  80. $app = self::get_instance();
  81. // Default configurations
  82. $app->config['app_domain'] = App::remove_last_slash('http://' . $_SERVER['SERVER_NAME'] . dirname($_SERVER['SCRIPT_NAME']));
  83. $app->config['stylesheets_path'] = $app->config['app_domain'] . '/public/stylesheets/';
  84. $app->config['javascripts_path'] = $app->config['app_domain'] . '/public/javascripts/';
  85. $app->config['images_path'] = $app->config['app_domain'] . '/public/images/';
  86. $route = array();
  87. $route['404'] = array('RequestError::error_404');
  88. $route['401'] = array('RequestError::error_401');
  89. include(APP_PATH.'/config/routes.php');
  90. include(APP_PATH.'/config/application.php');
  91. include(APP_PATH.'/config/enviroments/'.$app->config['env'] . '.php');
  92. // Set most used configurations, for rapid access.
  93. define('APP_DOMAIN', $app->config['app_domain']);
  94. define('STYLESHEETS_PATH', $app->config['stylesheets_path']);
  95. define('JAVASCRIPTS_PATH', $app->config['javascripts_path']);
  96. define('IMAGES_PATH', $app->config['images_path']);
  97. define('PLUGINS_PATH', APP_PATH.'/vendor/plugins');
  98. define('LANGUAGE', $app->config['language']);
  99. define('JS_FRAMEWORK', $app->config['js_framework']);
  100. // Load application plugins
  101. foreach ($app->plugins as $plugin) {
  102. require_once(APP_PATH.'/vendor/plugins/' . $plugin . '/init.php');
  103. }
  104. // Fire on_init event
  105. $app->fire_event('on_init');
  106. // Required files for Drumon
  107. include(CORE_PATH . '/class/request.php');
  108. include(CORE_PATH . '/class/response.php');
  109. include(CORE_PATH . '/class/helper.php');
  110. include(CORE_PATH . '/class/view.php');
  111. include(CORE_PATH . '/class/controller.php');
  112. include(APP_PATH . '/app/controllers/app_controller.php');
  113. // Token protection against CSFR
  114. define('REQUEST_TOKEN', $app->create_request_token());
  115. // Initialize request
  116. $request = new Request($route, APP_PATH);
  117. $request->validate();
  118. // Proccess controller and action
  119. $app->proccess_controller($request);
  120. }
  121. /**
  122. * Proccess controller, action and show response
  123. *
  124. * @param obj $request
  125. * @return void
  126. */
  127. public function proccess_controller($request) {
  128. $core_controllers = array('RequestError' => CORE_PATH.'/class/' );
  129. $controller_path = (isset($core_controllers[$request->controller_name])) ? $core_controllers[$request->controller_name] : APP_PATH.'/app/controllers/';
  130. $real_class_name = $request->controller_name.'Controller'; // ex. HomeController || Admin_HomeController
  131. require_once($controller_path.App::to_underscore(str_replace('_', '/', $real_class_name)).'.php');
  132. $controller = new $real_class_name($this, $request, new Response(), new View());
  133. $response = $controller->process();
  134. $this->fire_event('on_complete');
  135. echo $response;
  136. }
  137. /**
  138. * Add helpers to use on application
  139. *
  140. * @param string|array $helpers
  141. * @return void
  142. */
  143. public function add_helpers($helpers_names, $custom_paths = null) {
  144. // List of core Helpers
  145. $core_helpers = array('date','html','image','text','url','movie');
  146. $helpers = array();
  147. $helpers_names = is_array($helpers_names) ? $helpers_names : array($helpers_names);
  148. foreach ($helpers_names as $helper_name) {
  149. $helper_name = strtolower(trim($helper_name));
  150. $local = in_array($helper_name, $core_helpers) ? CORE_PATH . '/helpers' : APP_PATH . '/app/helpers';
  151. if ($custom_paths) {
  152. $local = $custom_paths;
  153. }
  154. $helpers[$helper_name] = $local . "/" . $helper_name . "_helper.php";
  155. }
  156. $this->helpers = array_merge($this->helpers, $helpers);
  157. }
  158. /**
  159. * Add plugins to use on application
  160. *
  161. * @param string|array $plugins
  162. * @return void
  163. */
  164. public function add_plugins($plugins) {
  165. $plugins = is_array($plugins) ? $plugins : array($plugins);
  166. $this->plugins = array_merge($this->plugins, $plugins);
  167. }
  168. /**
  169. * Add event to application
  170. *
  171. * @param string $name
  172. * @param string|array $callback
  173. * @return void
  174. */
  175. public function add_event($name, $callback) {
  176. $this->event_list[$name][] = $callback;
  177. }
  178. /**
  179. * Fire added events on application
  180. *
  181. * @param string $name
  182. * @param array $params
  183. * @return void
  184. */
  185. public function fire_event($name, $params = array()) {
  186. if (array_key_exists($name, $this->event_list)) {
  187. foreach ($this->event_list[$name] as $callback) {
  188. call_user_func_array($callback, &$params);
  189. }
  190. }
  191. }
  192. /**
  193. * Set application configuration
  194. *
  195. * @param string $name
  196. * @param mix $value
  197. * @return void
  198. */
  199. public static function set_config($name, $value) {
  200. $app = self::get_instance();
  201. return $app->config[$name] = $value;
  202. }
  203. /**
  204. * Get application configuration
  205. *
  206. * @param string $name
  207. * @return mix
  208. */
  209. public static function get_config($name) {
  210. $app = self::get_instance();
  211. return $app->config[$name];
  212. }
  213. /**
  214. * Generate unique token for CSRF protection
  215. *
  216. * @return string
  217. *
  218. */
  219. public function create_request_token() {
  220. $token = dechex(mt_rand());
  221. $hash = sha1($this->config['app_secret'] . APP_DOMAIN . '-' . $token);
  222. return $token . '-' . $hash;
  223. }
  224. /**
  225. * Check if can block request against CSRF
  226. *
  227. * @param object $request
  228. * @return bool
  229. */
  230. public function block_request($request) {
  231. $unauthorized = false;
  232. if ($request->method != 'get') {
  233. $unauthorized = true;
  234. if (!empty($request->params['_token'])) {
  235. $parts = explode('-', $request->params['_token']);
  236. if (count($parts) == 2) {
  237. list($token, $hash) = $parts;
  238. if ($hash == sha1($this->config['app_secret'] . APP_DOMAIN . '-' . $token)) {
  239. $unauthorized = false;
  240. }
  241. }
  242. }
  243. }
  244. return $unauthorized;
  245. }
  246. /**
  247. * Turn CamelCaseWords to underscore_words
  248. *
  249. * @param string $camelCasedWord
  250. * @return string
  251. */
  252. public static function to_underscore($camelCasedWord) {
  253. $result = strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $camelCasedWord));
  254. $result = str_replace(' ', '_', $result);
  255. return $result;
  256. }
  257. /**
  258. * Turn underscore_words to CamelCaseWords
  259. *
  260. * @param string $lowerCaseAndUnderscoredWord
  261. * @return string
  262. */
  263. public static function to_camelcase($lowerCaseAndUnderscoredWord) {
  264. $lowerCaseAndUnderscoredWord = ucwords(str_replace('_', ' ', $lowerCaseAndUnderscoredWord));
  265. $result = str_replace(' ', '', $lowerCaseAndUnderscoredWord);
  266. return $result;
  267. }
  268. /**
  269. * Convert string to slug
  270. *
  271. * @access public
  272. * @param string $text - String to convert.
  273. * @param string $space - Character used beetween words (default: -).
  274. * @return string
  275. */
  276. public function to_slug($text, $space = "-") {
  277. $text = trim($text);
  278. $search = explode(",","ç,æ,œ,á,é,í,ó,ú,à,è,ì,ò,ù,ä,ë,ï,ö,ü,ÿ,â,ê,î,ô,û,å,e,i,ø,u");
  279. $replace = explode(",","c,ae,oe,a,e,i,o,u,a,e,i,o,u,a,e,i,o,u,y,a,e,i,o,u,a,e,i,o,u");
  280. $text = str_replace($search, $replace, $text);
  281. if (function_exists('iconv')) {
  282. $text = iconv('UTF-8', 'ASCII//TRANSLIT', $text);
  283. }
  284. $text = preg_replace("/[^a-zA-Z0-9 ".$space."]/", "", $text);
  285. $text = str_replace(" ", $space, $text);
  286. $text = preg_replace("/".$space."{2,}/",$space,$text);
  287. $text = strtolower($text);
  288. return $text;
  289. }
  290. /**
  291. * Remove NULL and empty values from array
  292. *
  293. * @param string $array
  294. * @return array
  295. */
  296. public static function array_clean($array) {
  297. $clean_array = array();
  298. foreach ($array as $value) {
  299. if (!empty($value)) {
  300. $clean_array[] = $value;
  301. }
  302. }
  303. return $clean_array;
  304. }
  305. /**
  306. * Convert array to html helper select format
  307. *
  308. * @param string $list
  309. * @param string $key
  310. * @param string $value
  311. * @return array
  312. */
  313. public static function to_select($list, $key, $value) {
  314. $result = array();
  315. foreach ($list as $item) {
  316. $result[$item[$key]] = $item[$value];
  317. }
  318. return $result;
  319. }
  320. /**
  321. * Remove the slash(/) from the last char.
  322. *
  323. * @access public
  324. * @param string $value
  325. * @return string
  326. */
  327. public static function remove_last_slash($value) {
  328. if($value[strlen($value)-1] === '/') {
  329. $value = substr($value, 0, -1);
  330. }
  331. return $value;
  332. }
  333. }
  334. /**
  335. * Translate text to defined language using lazy loading.
  336. *
  337. * @param string $key
  338. * @param array $options
  339. * @return string
  340. */
  341. function t($key, $options = array()) {
  342. // Merge options with defaults
  343. $options = array_merge(array('from' => 'application'), $options);
  344. // Load translation file
  345. $app = App::get_instance();
  346. if (!isset($app->translations_cache[$options['from']])) {
  347. $app->translations_cache[$options['from']] = include(APP_PATH.'/config/locales/'.LANGUAGE.'/'.$options['from'].'.php');
  348. }
  349. // Setup important variables
  350. $translations = $app->translations_cache[$options['from']];
  351. $keys = explode('.',$key);
  352. $end_key = end($keys);
  353. $text = $options['from'].'.'.$key;
  354. // Get last array key values
  355. foreach ($keys as $key) {
  356. $is_end = $key == $end_key;
  357. if (isset($translations[$key])) {
  358. if (is_array($translations[$key]) && !$is_end) {
  359. $translations = $translations[$key];
  360. }
  361. }
  362. }
  363. // Get correct pluralization translation word
  364. if (isset($options['count'])) {
  365. if (isset($translations[$end_key][$options['count']])) {
  366. $text = $translations[$end_key][$options['count']];
  367. } elseif (isset($translations[$end_key]['*'])) {
  368. $text = str_replace("{count}", $options['count'], $translations[$end_key]['*']);
  369. } else {
  370. $text .= '.*';
  371. }
  372. } else {
  373. // Get translation value
  374. $text = isset($translations[$end_key]) ? $translations[$end_key] : $text;
  375. }
  376. // Replace variables words
  377. foreach ($options as $key => $value) {
  378. if ($key != 'from' && $key != 'count') {
  379. $text = str_replace('{'.$key.'}', $value, $text);
  380. }
  381. }
  382. return $text;
  383. }
  384. ?>