PageRenderTime 58ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/vendor/nooku/plugins/system/koowa.php

https://github.com/bhar1red/anahita
PHP | 323 lines | 181 code | 46 blank | 96 comment | 35 complexity | ad689e3292a89c9c7f667e62275d6a28 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
  1. <?php
  2. /**
  3. * @version $Id: koowa.php 4628 2012-05-06 19:56:43Z johanjanssens $
  4. * @package Nooku_Plugins
  5. * @subpackage System
  6. * @copyright Copyright (C) 2007 - 2012 Johan Janssens. All rights reserved.
  7. * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
  8. * @link http://www.nooku.org
  9. */
  10. /**
  11. * Koowa System plugin
  12. .*
  13. * @author Johan Janssens <johan@nooku.org>
  14. * @package Nooku_Plugins
  15. * @subpackage System
  16. */
  17. defined( '_JEXEC' ) or die( 'Restricted access' );
  18. class plgSystemKoowa extends JPlugin
  19. {
  20. public function __construct($subject, $config = array())
  21. {
  22. // Command line fixes for Joomla
  23. if (PHP_SAPI === 'cli')
  24. {
  25. if (!isset($_SERVER['HTTP_HOST'])) {
  26. $_SERVER['HTTP_HOST'] = '';
  27. }
  28. if (!isset($_SERVER['REQUEST_METHOD'])) {
  29. $_SERVER['REQUEST_METHOD'] = '';
  30. }
  31. }
  32. // Check if Koowa is active
  33. if(JFactory::getApplication()->getCfg('dbtype') != 'mysqli')
  34. {
  35. JError::raiseWarning(0, JText::_("Koowa plugin requires MySQLi Database Driver. Please change your database configuration settings to 'mysqli'"));
  36. return;
  37. }
  38. // Check for suhosin
  39. if(in_array('suhosin', get_loaded_extensions()))
  40. {
  41. //Attempt setting the whitelist value
  42. @ini_set('suhosin.executor.include.whitelist', 'tmpl://, file://');
  43. //Checking if the whitelist is ok
  44. if(!@ini_get('suhosin.executor.include.whitelist') || strpos(@ini_get('suhosin.executor.include.whitelist'), 'tmpl://') === false)
  45. {
  46. JError::raiseWarning(0, sprintf(JText::_('Your server has Suhosin loaded. Please follow <a href="%s" target="_blank">this</a> tutorial.'), 'https://nooku.assembla.com/wiki/show/nooku-framework/Known_Issues'));
  47. return;
  48. }
  49. }
  50. //Safety Extender compatibility
  51. if(extension_loaded('safeex') && strpos('tmpl', ini_get('safeex.url_include_proto_whitelist')) === false)
  52. {
  53. $whitelist = ini_get('safeex.url_include_proto_whitelist');
  54. $whitelist = (strlen($whitelist) ? $whitelist . ',' : '') . 'tmpl';
  55. ini_set('safeex.url_include_proto_whitelist', $whitelist);
  56. }
  57. //Set constants
  58. define('KDEBUG' , JDEBUG);
  59. //Set path definitions
  60. define('JPATH_FILES' , JPATH_ROOT);
  61. define('JPATH_IMAGES', JPATH_ROOT.DS.'images');
  62. //Set exception handler
  63. set_exception_handler(array($this, 'exceptionHandler'));
  64. // Koowa : setup
  65. require_once( JPATH_LIBRARIES.'/koowa/koowa.php');
  66. Koowa::getInstance(array(
  67. 'cache_prefix' => md5(JFactory::getApplication()->getCfg('secret')).'-cache-koowa',
  68. 'cache_enabled' => JFactory::getApplication()->getCfg('caching')
  69. ));
  70. KLoader::addAdapter(new KLoaderAdapterModule(array('basepath' => JPATH_BASE)));
  71. KLoader::addAdapter(new KLoaderAdapterPlugin(array('basepath' => JPATH_ROOT)));
  72. KLoader::addAdapter(new KLoaderAdapterComponent(array('basepath' => JPATH_BASE)));
  73. KServiceIdentifier::addLocator(KService::get('koowa:service.locator.module'));
  74. KServiceIdentifier::addLocator(KService::get('koowa:service.locator.plugin'));
  75. KServiceIdentifier::addLocator(KService::get('koowa:service.locator.component'));
  76. KServiceIdentifier::setApplication('site' , JPATH_SITE);
  77. KServiceIdentifier::setApplication('admin', JPATH_ADMINISTRATOR);
  78. KService::setAlias('koowa:database.adapter.mysqli', 'com://admin/default.database.adapter.mysqli');
  79. //Setup the request
  80. KRequest::root(str_replace('/'.JFactory::getApplication()->getName(), '', KRequest::base()));
  81. //Load the koowa plugins
  82. JPluginHelper::importPlugin('koowa', null, true);
  83. //Bugfix : Set offset accoording to user's timezone
  84. if(!JFactory::getUser()->guest)
  85. {
  86. if($offset = JFactory::getUser()->getParam('timezone')) {
  87. JFactory::getConfig()->setValue('config.offset', $offset);
  88. }
  89. }
  90. parent::__construct($subject, $config);
  91. }
  92. /**
  93. * On after intitialse event handler
  94. *
  95. * This functions implements HTTP Basic authentication support
  96. *
  97. * @return void
  98. */
  99. public function onAfterInitialise()
  100. {
  101. /*
  102. * Try to log the user in
  103. *
  104. * If the request contains authorization information we try to log the user in
  105. */
  106. if($this->params->get('auth_basic', 0) && JFactory::getUser()->guest) {
  107. $this->_authenticateUser();
  108. }
  109. /*
  110. * Reset the user and token
  111. *
  112. * In case another plugin have logged in after we initialized we need to reset the token and user object
  113. * One plugin that could cause that, are the Remember Me plugin
  114. */
  115. if(!JFactory::getUser()->guest) {
  116. KRequest::set('request._token', JUtility::getToken());
  117. }
  118. /*
  119. * Dispatch the default dispatcher
  120. *
  121. * If we are running in CLI mode bypass the default Joomla executition chain and dispatch the default
  122. * dispatcher.
  123. */
  124. if (PHP_SAPI === 'cli')
  125. {
  126. $url = null;
  127. foreach ($_SERVER['argv'] as $arg)
  128. {
  129. if (strpos($arg, '--url') === 0)
  130. {
  131. $url = str_replace('--url=', '', $arg);
  132. if (strpos($url, '?') === false) {
  133. $url = '?'.$url;
  134. }
  135. break;
  136. }
  137. }
  138. if (!empty($url))
  139. {
  140. $component = 'default';
  141. $url = KService::get('koowa:http.url', array('url' => $url));
  142. if (!empty($url->query['option'])) {
  143. $component = substr($url->query['option'], 4);
  144. }
  145. // Thanks Joomla. We will take it from here.
  146. echo KService::get('com:'.$component.'.dispatcher.cli')->dispatch();
  147. exit(0);
  148. }
  149. }
  150. }
  151. /**
  152. * On after route event handler
  153. *
  154. * @return void
  155. */
  156. public function onAfterRoute()
  157. {
  158. /*
  159. * Special handling for AJAX requests
  160. *
  161. * If the format is AJAX and the format is 'html' or the tmpl is empty we re-create
  162. * a 'raw' document rendered and force it's type to the active format
  163. */
  164. if(KRequest::type() == 'AJAX')
  165. {
  166. if(KRequest::get('get.format', 'cmd', 'html') != 'html' || KRequest::get('get.tmpl', 'cmd') === '')
  167. {
  168. $format = JRequest::getWord('format', 'html');
  169. JRequest::setVar('format', 'raw'); //force format to raw
  170. $document =& JFactory::getDocument();
  171. $document = null;
  172. JFactory::getDocument()->setType($format);
  173. JRequest::setVar('format', $format); //revert format to original
  174. }
  175. }
  176. //Set the request format
  177. if(!KRequest::has('request.format')) {
  178. KRequest::set('request.format', KRequest::format());
  179. }
  180. }
  181. /**
  182. * Catch all exception handler
  183. *
  184. * Calls the Joomla error handler to process the exception
  185. *
  186. * @param object an Exception object
  187. * @return void
  188. */
  189. public function exceptionHandler($exception)
  190. {
  191. $this->_exception = $exception; //store the exception for later use
  192. //Change the Joomla error handler to our own local handler and call it
  193. JError::setErrorHandling( E_ERROR, 'callback', array($this,'errorHandler'));
  194. //Make sure we have a valid status code
  195. JError::raiseError(KHttpResponse::isError($exception->getCode()) ? $exception->getCode() : 500, $exception->getMessage());
  196. }
  197. /**
  198. * Custom JError callback
  199. *
  200. * Push the exception call stack in the JException returned through the call back
  201. * adn then rener the custom error page.
  202. *
  203. * @param object A JException object
  204. * @return void
  205. */
  206. public function errorHandler($error)
  207. {
  208. $error->setProperties(array(
  209. 'backtrace' => $this->_exception->getTrace(),
  210. 'file' => $this->_exception->getFile(),
  211. 'line' => $this->_exception->getLine()
  212. ));
  213. if(JFactory::getConfig()->getValue('config.debug')) {
  214. $error->set('message', (string) $this->_exception);
  215. } else {
  216. $error->set('message', KHttpResponse::getMessage($error->code));
  217. }
  218. //Make sure the buffers are cleared
  219. while(@ob_get_clean());
  220. //Throw json formatted error
  221. if( KRequest::format() == 'json')
  222. {
  223. $properties = array(
  224. 'message' => $error->message,
  225. 'code' => $error->code
  226. );
  227. if(KDEBUG)
  228. {
  229. $properties['data'] = array(
  230. 'file' => $error->file,
  231. 'line' => $error->line,
  232. 'function' => $error->function,
  233. 'class' => $error->class,
  234. 'args' => $error->args,
  235. 'info' => $error->info
  236. );
  237. }
  238. //Encode data
  239. $data = json_encode(array(
  240. 'version' => '1.0',
  241. 'errors' => array($properties)
  242. ));
  243. JResponse::setHeader('Content-Type','application/json');
  244. JResponse::setBody($data);
  245. echo JResponse::toString();
  246. JFactory::getApplication()->close(0);
  247. }
  248. else JError::customErrorPage($error);
  249. }
  250. /**
  251. * Basic authentication support
  252. *
  253. * This functions tries to log the user in if authentication credentials are
  254. * present in the request.
  255. *
  256. * @return boolean Returns TRUE is basic authentication was successful
  257. */
  258. protected function _authenticateUser()
  259. {
  260. if(KRequest::has('server.PHP_AUTH_USER') && KRequest::has('server.PHP_AUTH_PW'))
  261. {
  262. $credentials = array(
  263. 'username' => KRequest::get('server.PHP_AUTH_USER', 'url'),
  264. 'password' => KRequest::get('server.PHP_AUTH_PW' , 'url'),
  265. );
  266. if(JFactory::getApplication()->login($credentials) !== true)
  267. {
  268. throw new KException('Login failed', KHttpResponse::UNAUTHORIZED);
  269. return false;
  270. }
  271. //Force the token
  272. KRequest::set('request._token', JUtility::getToken());
  273. return true;
  274. }
  275. return false;
  276. }
  277. }