PageRenderTime 37ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/libraries/joomla/factory.php

https://github.com/joebushi/joomla
PHP | 680 lines | 357 code | 95 blank | 228 comment | 45 complexity | 51a3d75d2bea925e2ba53c4c188751f3 MD5 | raw file
Possible License(s): LGPL-2.1, Apache-2.0
  1. <?php
  2. /**
  3. * @version $Id$
  4. * @package Joomla.Framework
  5. * @copyright Copyright (C) 2005 - 2010 Open Source Matters, Inc. All rights reserved.
  6. * @license GNU General Public License version 2 or later; see LICENSE.txt
  7. */
  8. // No direct access
  9. defined('JPATH_BASE') or die;
  10. /**
  11. * Joomla Framework Factory class
  12. *
  13. * @static
  14. * @package Joomla.Framework
  15. * @since 1.5
  16. */
  17. abstract class JFactory
  18. {
  19. public static $application = null;
  20. public static $config = null;
  21. public static $session = null;
  22. public static $language = null;
  23. public static $document = null;
  24. public static $acl = null;
  25. public static $database = null;
  26. public static $mailer = null;
  27. /**
  28. * Get a application object
  29. *
  30. * Returns the global {@link JApplication} object, only creating it
  31. * if it doesn't already exist.
  32. *
  33. * @param mixed $id A client identifier or name.
  34. * @param array $config An optional associative array of configuration settings.
  35. * @return object JApplication
  36. */
  37. public static function getApplication($id = null, $config = array(), $prefix='J')
  38. {
  39. if (!is_object(JFactory::$application))
  40. {
  41. jimport('joomla.application.application');
  42. if (!$id) {
  43. JError::raiseError(500, 'Application Instantiation Error');
  44. }
  45. JFactory::$application = JApplication::getInstance($id, $config, $prefix);
  46. }
  47. return JFactory::$application;
  48. }
  49. /**
  50. * Get a configuration object
  51. *
  52. * Returns the global {@link JRegistry} object, only creating it
  53. * if it doesn't already exist.
  54. *
  55. * @param string The path to the configuration file
  56. * @param string The type of the configuration file
  57. * @return object JRegistry
  58. */
  59. public static function getConfig($file = null, $type = 'PHP')
  60. {
  61. if (!is_object(JFactory::$config))
  62. {
  63. if ($file === null) {
  64. $file = dirname(__FILE__).DS.'config.php';
  65. }
  66. JFactory::$config = JFactory::_createConfig($file, $type);
  67. }
  68. return JFactory::$config;
  69. }
  70. /**
  71. * Get a session object
  72. *
  73. * Returns the global {@link JSession} object, only creating it
  74. * if it doesn't already exist.
  75. *
  76. * @param array An array containing session options
  77. * @return object JSession
  78. */
  79. public static function getSession($options = array())
  80. {
  81. if (!is_object(JFactory::$session)) {
  82. JFactory::$session = JFactory::_createSession($options);
  83. }
  84. return JFactory::$session;
  85. }
  86. /**
  87. * Get a language object
  88. *
  89. * Returns the global {@link JLanguage} object, only creating it
  90. * if it doesn't already exist.
  91. *
  92. * @return object JLanguage
  93. */
  94. public static function getLanguage()
  95. {
  96. if (!is_object(JFactory::$language))
  97. {
  98. //get the debug configuration setting
  99. $conf = &JFactory::getConfig();
  100. $debug = $conf->getValue('config.debug_lang');
  101. JFactory::$language = JFactory::_createLanguage();
  102. JFactory::$language->setDebug($debug);
  103. }
  104. return JFactory::$language;
  105. }
  106. /**
  107. * Get a document object
  108. *
  109. * Returns the global {@link JDocument} object, only creating it
  110. * if it doesn't already exist.
  111. *
  112. * @return object JDocument
  113. */
  114. public static function getDocument()
  115. {
  116. if (!is_object(JFactory::$document)) {
  117. JFactory::$document = JFactory::_createDocument();
  118. }
  119. return JFactory::$document;
  120. }
  121. /**
  122. * Get an user object
  123. *
  124. * Returns the global {@link JUser} object, only creating it
  125. * if it doesn't already exist.
  126. *
  127. * @param int $id The user to load - Can be an integer or string - If string, it is converted to ID automatically.
  128. *
  129. * @return object JUser
  130. */
  131. public static function getUser($id = null)
  132. {
  133. jimport('joomla.user.user');
  134. if (is_null($id))
  135. {
  136. $instance = JFactory::getSession()->get('user');
  137. if (!$instance INSTANCEOF JUser) {
  138. $instance = &JUser::getInstance();
  139. }
  140. }
  141. else
  142. {
  143. $instance = &JUser::getInstance($id);
  144. }
  145. return $instance;
  146. }
  147. /**
  148. * Get a cache object
  149. *
  150. * Returns the global {@link JCache} object
  151. *
  152. * @param string The cache group name
  153. * @param string The handler to use
  154. * @param string The storage method
  155. * @return object JCache
  156. */
  157. public static function getCache($group = '', $handler = 'callback', $storage = null)
  158. {
  159. $handler = ($handler == 'function') ? 'callback' : $handler;
  160. $conf = &JFactory::getConfig();
  161. if (!isset($storage)) {
  162. $storage = $conf->getValue('config.cache_handler', 'file');
  163. }
  164. $options = array(
  165. 'defaultgroup' => $group,
  166. 'cachebase' => $conf->getValue('config.cache_path'),
  167. 'lifetime' => $conf->getValue('config.cachetime') * 60, // minutes to seconds
  168. 'language' => $conf->getValue('config.language'),
  169. 'storage' => $storage
  170. );
  171. jimport('joomla.cache.cache');
  172. $cache = &JCache::getInstance($handler, $options);
  173. $cache->setCaching($conf->getValue('config.caching'));
  174. return $cache;
  175. }
  176. /**
  177. * Get an authorization object
  178. *
  179. * Returns the global {@link JACL} object, only creating it
  180. * if it doesn't already exist.
  181. *
  182. * @return object JACL
  183. */
  184. public static function getACL()
  185. {
  186. if (!is_object(JFactory::$acl)) {
  187. jimport('joomla.access.access');
  188. JFactory::$acl = new JAccess();
  189. }
  190. return JFactory::$acl;
  191. }
  192. /**
  193. * Get a database object
  194. *
  195. * Returns the global {@link JDatabase} object, only creating it
  196. * if it doesn't already exist.
  197. *
  198. * @return object JDatabase
  199. */
  200. public static function getDbo()
  201. {
  202. if (!is_object(self::$database))
  203. {
  204. //get the debug configuration setting
  205. $conf = &self::getConfig();
  206. $debug = $conf->getValue('config.debug');
  207. self::$database = self::_createDbo();
  208. self::$database->debug($debug);
  209. }
  210. return self::$database;
  211. }
  212. /**
  213. * Get a mailer object
  214. *
  215. * Returns the global {@link JMail} object, only creating it
  216. * if it doesn't already exist
  217. *
  218. * @return object JMail
  219. */
  220. public static function getMailer()
  221. {
  222. if (! is_object(JFactory::$mailer)) {
  223. JFactory::$mailer = JFactory::_createMailer();
  224. }
  225. $copy = clone JFactory::$mailer;
  226. return $copy;
  227. }
  228. /**
  229. * Get a parsed XML Feed Source
  230. *
  231. * @since: 1.6
  232. * @static
  233. * @param string url for feed source
  234. * @param int time to cache feed for (using internal cache mechanism)
  235. * @return mixed Parsed SimplePie object on success, false on failure
  236. */
  237. public static function getFeedParser($url, $cache_time = 0)
  238. {
  239. jimport('simplepie.simplepie');
  240. if (!is_writable(JPATH_CACHE)) {
  241. $cache_time = 0;
  242. }
  243. $simplepie = new SimplePie($url, JPATH_CACHE, $cache_time);
  244. $simplepie->force_feed(true);
  245. if ($simplepie->init()) {
  246. return $simplepie;
  247. } else {
  248. JError::raiseWarning('SOME_ERROR_CODE', JText::_('ERROR_LOADING_FEED_DATA'));
  249. }
  250. return false;
  251. }
  252. /**
  253. * Get an XML document
  254. *
  255. * @param string The type of xml parser needed 'DOM', 'RSS' or 'Simple'
  256. * @param array:
  257. * string ['rssUrl'] the rss url to parse when using "RSS"
  258. * string ['cache_time'] with 'RSS' - feed cache time. If not defined defaults to 3600 sec
  259. * @return object Parsed XML document object
  260. * @deprecated
  261. */
  262. public static function getXMLParser($type = '', $options = array())
  263. {
  264. $doc = null;
  265. switch (strtolower($type))
  266. {
  267. case 'rss' :
  268. case 'atom' :
  269. {
  270. $cache_time = isset($options['cache_time']) ? $options['cache_time'] : 0;
  271. $doc = JFactory::getFeedParser($options['rssUrl'], $cache_time);
  272. } break;
  273. case 'simple':
  274. // JError::raiseWarning('SOME_ERROR_CODE', 'JSimpleXML is deprecated. Use JFactory::getXML instead');
  275. jimport('joomla.utilities.simplexml');
  276. $doc = new JSimpleXML();
  277. break;
  278. case 'dom':
  279. JError::raiseWarning('SOME_ERROR_CODE', 'DommitDocument is deprecated. Use DomDocument instead');
  280. $doc = null;
  281. break;
  282. throw new JException('DommitDocument is deprecated. Use DomDocument instead');
  283. default :
  284. $doc = null;
  285. }
  286. return $doc;
  287. }
  288. /**
  289. * Reads a XML file.
  290. *
  291. * @todo This may go in a separate class - error reporting may be improved.
  292. *
  293. * @param string $path Full path and file name.
  294. * @param boolean $isFile true to load a file | false to load a string.
  295. *
  296. * @return mixed JXMLElement on success | false on error.
  297. */
  298. public static function getXML($path, $isFile = true)
  299. {
  300. jimport('joomla.utilities.xmlelement');
  301. // Disable libxml errors and allow to fetch error information as needed
  302. libxml_use_internal_errors(true);
  303. if($isFile)
  304. {
  305. // Try to load the xml file
  306. $xml = simplexml_load_file($path, 'JXMLElement');
  307. }
  308. else
  309. {
  310. // Try to load the xml string
  311. $xml = simplexml_load_string($data, 'JXMLElement');
  312. }
  313. if( ! $xml)
  314. {
  315. // There was an error
  316. JError::raiseWarning(100, JText::_('Failed loading XML file'));
  317. if($isFile)
  318. {
  319. JError::raiseWarning(100, $path);
  320. }
  321. foreach(libxml_get_errors() as $error)
  322. {
  323. JError::raiseWarning(100, 'XML: '.$error->message);
  324. }
  325. }
  326. return $xml ;
  327. }
  328. /**
  329. * Get an editor object
  330. *
  331. * @param string $editor The editor to load, depends on the editor plugins that are installed
  332. * @return object JEditor
  333. */
  334. public static function getEditor($editor = null)
  335. {
  336. jimport('joomla.html.editor');
  337. //get the editor configuration setting
  338. if (is_null($editor))
  339. {
  340. $conf = &JFactory::getConfig();
  341. $editor = $conf->getValue('config.editor');
  342. }
  343. return JEditor::getInstance($editor);
  344. }
  345. /**
  346. * Return a reference to the {@link JURI} object
  347. *
  348. * @return object JURI
  349. * @since 1.5
  350. */
  351. public static function getURI($uri = 'SERVER')
  352. {
  353. jimport('joomla.environment.uri');
  354. return JURI::getInstance($uri);
  355. }
  356. /**
  357. * Return the {@link JDate} object
  358. *
  359. * @param mixed $time The initial time for the JDate object
  360. * @param mixed $tzOffset The timezone offset.
  361. * @return object JDate
  362. * @since 1.5
  363. */
  364. public static function getDate($time = 'now', $tzOffset = null)
  365. {
  366. jimport('joomla.utilities.date');
  367. static $instances;
  368. static $classname;
  369. static $mainLocale;
  370. if (!isset($instances)) {
  371. $instances = array();
  372. }
  373. $language = &JFactory::getLanguage();
  374. $locale = $language->getTag();
  375. if (!isset($classname) || $locale != $mainLocale) {
  376. //Store the locale for future reference
  377. $mainLocale = $locale;
  378. $localePath = JPATH_ROOT . DS . 'language' . DS . $mainLocale . DS . $mainLocale . '.date.php';
  379. if ($mainLocale !== false && file_exists($localePath)) {
  380. $classname = 'JDate'.str_replace('-', '_', $mainLocale);
  381. JLoader::register($classname, $localePath);
  382. if (!class_exists($classname)) {
  383. //Something went wrong. The file exists, but the class does not, default to JDate
  384. $classname = 'JDate';
  385. }
  386. } else {
  387. //No file, so default to JDate
  388. $classname = 'JDate';
  389. }
  390. }
  391. $key = $time . '-' . $tzOffset;
  392. // if (!isset($instances[$classname][$key])) {
  393. $tmp = new $classname($time, $tzOffset);
  394. //We need to serialize to break the reference
  395. // $instances[$classname][$key] = serialize($tmp);
  396. // unset($tmp);
  397. // }
  398. // $date = unserialize($instances[$classname][$key]);
  399. // return $date;
  400. return $tmp;
  401. }
  402. /**
  403. * Create a configuration object
  404. *
  405. * @param string The path to the configuration file
  406. * @param string The type of the configuration file
  407. * @return object JRegistry
  408. * @since 1.5
  409. */
  410. private static function _createConfig($file, $type = 'PHP')
  411. {
  412. jimport('joomla.registry.registry');
  413. require_once $file;
  414. // Create the registry with a default namespace of config
  415. $registry = new JRegistry('config');
  416. // Create the JConfig object
  417. $config = new JFrameworkConfig();
  418. // Load the configuration values into the registry
  419. $registry->loadObject($config);
  420. return $registry;
  421. }
  422. /**
  423. * Create a session object
  424. *
  425. * @param array $options An array containing session options
  426. * @return object JSession
  427. * @since 1.5
  428. */
  429. private static function _createSession($options = array())
  430. {
  431. jimport('joomla.session.session');
  432. //get the editor configuration setting
  433. $conf = &JFactory::getConfig();
  434. $handler = $conf->getValue('config.session_handler', 'none');
  435. // config time is in minutes
  436. $options['expire'] = ($conf->getValue('config.lifetime')) ? $conf->getValue('config.lifetime') * 60 : 900;
  437. $session = JSession::getInstance($handler, $options);
  438. if ($session->getState() == 'expired') {
  439. $session->restart();
  440. }
  441. return $session;
  442. }
  443. /**
  444. * Create an database object
  445. *
  446. * @return object JDatabase
  447. * @since 1.5
  448. */
  449. private static function _createDbo()
  450. {
  451. jimport('joomla.database.database');
  452. jimport('joomla.database.table');
  453. $conf = &JFactory::getConfig();
  454. $host = $conf->getValue('config.host');
  455. $user = $conf->getValue('config.user');
  456. $password = $conf->getValue('config.password');
  457. $database = $conf->getValue('config.db');
  458. $prefix = $conf->getValue('config.dbprefix');
  459. $driver = $conf->getValue('config.dbtype');
  460. $debug = $conf->getValue('config.debug');
  461. $options = array ('driver' => $driver, 'host' => $host, 'user' => $user, 'password' => $password, 'database' => $database, 'prefix' => $prefix);
  462. $db = &JDatabase::getInstance($options);
  463. if (JError::isError($db)) {
  464. jexit('Database Error: ' . $db->toString());
  465. }
  466. if ($db->getErrorNum() > 0) {
  467. JError::raiseError(500 , 'JDatabase::getInstance: Could not connect to database <br />' . 'joomla.library:'.$db->getErrorNum().' - '.$db->getErrorMsg());
  468. }
  469. $db->debug($debug);
  470. return $db;
  471. }
  472. /**
  473. * Create a mailer object
  474. *
  475. * @access private
  476. * @return object JMail
  477. * @since 1.5
  478. */
  479. function _createMailer()
  480. {
  481. jimport('joomla.mail.mail');
  482. $conf = &JFactory::getConfig();
  483. $sendmail = $conf->getValue('config.sendmail');
  484. $smtpauth = $conf->getValue('config.smtpauth');
  485. $smtpuser = $conf->getValue('config.smtpuser');
  486. $smtppass = $conf->getValue('config.smtppass');
  487. $smtphost = $conf->getValue('config.smtphost');
  488. $smtpsecure = $conf->getValue('config.smtpsecure');
  489. $smtpport = $conf->getValue('config.smtpport');
  490. $mailfrom = $conf->getValue('config.mailfrom');
  491. $fromname = $conf->getValue('config.fromname');
  492. $mailer = $conf->getValue('config.mailer');
  493. // Create a JMail object
  494. $mail = &JMail::getInstance();
  495. // Set default sender
  496. $mail->setSender(array ($mailfrom, $fromname));
  497. // Default mailer is to use PHP's mail function
  498. switch ($mailer)
  499. {
  500. case 'smtp' :
  501. $mail->useSMTP($smtpauth, $smtphost, $smtpuser, $smtppass, $smtpsecure, $smtpport);
  502. break;
  503. case 'sendmail' :
  504. $mail->IsSendmail();
  505. break;
  506. default :
  507. $mail->IsMail();
  508. break;
  509. }
  510. return $mail;
  511. }
  512. /**
  513. * Create a language object
  514. *
  515. * @return object JLanguage
  516. * @since 1.5
  517. */
  518. private static function _createLanguage()
  519. {
  520. jimport('joomla.language.language');
  521. $conf = &JFactory::getConfig();
  522. $locale = $conf->getValue('config.language');
  523. $lang = &JLanguage::getInstance($locale);
  524. $lang->setDebug($conf->getValue('config.debug_lang'));
  525. return $lang;
  526. }
  527. /**
  528. * Create a document object
  529. *
  530. * @return object JDocument
  531. * @since 1.5
  532. */
  533. private static function _createDocument()
  534. {
  535. jimport('joomla.document.document');
  536. $lang = &JFactory::getLanguage();
  537. //Keep backwards compatibility with Joomla! 1.0
  538. $raw = JRequest::getBool('no_html');
  539. $type = JRequest::getWord('format', $raw ? 'raw' : 'html');
  540. $attributes = array (
  541. 'charset' => 'utf-8',
  542. 'lineend' => 'unix',
  543. 'tab' => ' ',
  544. 'language' => $lang->getTag(),
  545. 'direction' => $lang->isRTL() ? 'rtl' : 'ltr'
  546. );
  547. return JDocument::getInstance($type, $attributes);
  548. }
  549. /**
  550. * Creates a new stream object with appropriate prefix
  551. * @param boolean Prefix the connections for writing
  552. * @param boolean Use network if available for writing; use false to disable (e.g. FTP, SCP)
  553. * @param string UA User agent to use
  554. * @param boolean User agent masking (prefix Mozilla)
  555. */
  556. function getStream($use_prefix=true, $use_network=true,$ua=null, $uamask=false) {
  557. jimport('joomla.filesystem.stream');
  558. // Setup the context; Joomla! UA and overwrite
  559. $context = Array();
  560. $version = new JVersion();
  561. // set the UA for HTTP and overwrite for FTP
  562. $context['http']['user_agent'] = $version->getUserAgent($ua, $uamask);
  563. $context['ftp']['overwrite'] = true;
  564. if($use_prefix) {
  565. jimport('joomla.client.helper');
  566. $FTPOptions = JClientHelper::getCredentials('ftp');
  567. $SCPOptions = JClientHelper::getCredentials('scp');
  568. if ($FTPOptions['enabled'] == 1 && $use_network) {
  569. $prefix = 'ftp://'. $FTPOptions['user'] .':'. $FTPOptions['pass'] .'@'. $FTPOptions['host'];
  570. $prefix .= $FTPOptions['port'] ? ':'. $FTPOptions['port'] : '';
  571. $prefix .= $FTPOptions['root'];
  572. } else if($SCPOptions['enabled'] == 1 && $use_network) {
  573. $prefix = 'ssh2.sftp://'. $SCPOptions['user'] .':'. $SCPOptions['pass'] .'@'. $SCPOptions['host'];
  574. $prefix .= $SCPOptions['port'] ? ':'. $SCPOptions['port'] : '';
  575. $prefix .= $SCPOptions['root'];
  576. } else {
  577. $prefix = JPATH_ROOT.DS;
  578. }
  579. $retval = new JStream($prefix, JPATH_ROOT, $context);
  580. } else {
  581. $retval = new JStream('','',$context);
  582. }
  583. return $retval;
  584. }
  585. }