Beispiel #1
0
 /**
  * @todo Implement test_().
  */
 public function test_()
 {
     // first we test to ensure that if a handler is properly registered, it gets called
     $registered = $this->getMock('MyHtmlClass', array('mockFunction'));
     // test that we can register the method
     JHtml::register('file.testfunction', array($registered, 'mockFunction'));
     // test that calling _ actually calls the function
     $registered->expects($this->once())->method('mockFunction')->with('Test Return Value')->will($this->returnValue('My Expected Return Value'));
     $this->assertThat(JHtml::_('file.testfunction', 'Test Return Value'), $this->equalTo('My Expected Return Value'));
     // we unregister the method to return to our original state
     JHtml::unregister('prefix.file.testfunction');
     // now we test with a class that will be found in the expected file
     JHtml::addIncludePath(array(JPATH_BASE . '/tests/unit/suite/libraries/joomla/html/htmltests'));
     $this->assertThat(JHtml::_('mocktest.method1', 'argument1', 'argument2'), $this->equalTo('JHtml Mock Called'));
     $this->assertThat(JHtmlMockTest::$arguments[0], $this->equalTo(array('argument1', 'argument2')));
     JHtmlMockTest::$arguments = array();
     $this->saveErrorHandlers();
     $mock1 = $this->getMock('errorCallback', array('error1', 'error2', 'error3'));
     JError::setErrorHandling(E_ERROR, 'callback', array($mock1, 'error1'));
     $mock1->expects($this->once())->method('error1');
     // we ensure that we get an error if we can find the file but the file does not contain the class
     $this->assertThat(JHtml::_('mocktest2.function1'), $this->isFalse());
     JError::setErrorHandling(E_ERROR, 'callback', array($mock1, 'error2'));
     $mock1->expects($this->once())->method('error2');
     // we ensure that we get an error if we can't find the file
     $this->assertThat(JHtml::_('mocktestnotthere.function1'), $this->isFalse());
     JError::setErrorHandling(E_ERROR, 'callback', array($mock1, 'error3'));
     $mock1->expects($this->once())->method('error3');
     // we ensure that we get an error if we have the class but not the method
     $this->assertThat(JHtml::_('mocktest.nomethod'), $this->isFalse());
     // restore our error handlers
     $this->setErrorHandlers($this->savedErrorState);
 }
Beispiel #2
0
 /**
  * Constructor.
  *
  * @param   object  &$subject  The object to observe
  * @param   array   $config    An optional associative array of configuration settings.
  *
  * @since   1.6
  */
 public function __construct(&$subject, $config)
 {
     parent::__construct($subject, $config);
     // Set the error handler for E_ERROR to be the class handleError method.
     JError::setErrorHandling(E_ERROR, 'callback', array('PlgSystemRedirect', 'handleError'));
     set_exception_handler(array('PlgSystemRedirect', 'handleError'));
 }
Beispiel #3
0
 /**
  * Object Constructor.
  *
  * @access	public
  * @param	object	The object to observe -- event dispatcher.
  * @param	object	The configuration object for the plugin.
  * @return	void
  * @since	1.0
  */
 function __construct(&$subject, $config)
 {
     parent::__construct($subject, $config);
     // Set the error handler for E_ERROR to be the class handleError method.
     JError::setErrorHandling(E_ERROR, 'callback', array('plgSystemError404', 'handleError'));
     //$redirect=$this->params->get('redirection');
 }
Beispiel #4
0
 /**
  * Test the _ method.
  *
  * @return  void
  *
  * @since   11.1
  */
 public function test_()
 {
     // Add the include path to html test files.
     JHtml::addIncludePath(array(__DIR__ . '/html/testfiles'));
     // Test the class method was called and the arguments passed correctly.
     $this->assertThat(JHtml::_('inspector.method1', 'argument1', 'argument2'), $this->equalTo('JHtmlInspector::method1'), 'JHtmlInspector::method1 could not be called.');
     $this->assertThat(JHtmlInspector::$arguments[0], $this->equalTo(array('argument1', 'argument2')), 'The arguments where not correctly passed to JHtmlInspector::method1.');
     // Test error cases.
     // Prepare the error handlers.
     $this->saveErrorHandlers();
     $errorCallback = $this->getMock('errorCallback', array('error1', 'error2', 'error3'));
     $errorCallback->expects($this->once())->method('error1');
     $errorCallback->expects($this->once())->method('error2');
     $errorCallback->expects($this->once())->method('error3');
     // Ensure that we get an error if we can find the file but the file does not contain the class.
     JError::setErrorHandling(E_ERROR, 'callback', array($errorCallback, 'error1'));
     $this->assertThat(JHtml::_('empty.anything'), $this->isFalse());
     // Ensure that we get an error if we can't find the file.
     JError::setErrorHandling(E_ERROR, 'callback', array($errorCallback, 'error2'));
     $this->assertThat(JHtml::_('nofile.anything'), $this->isFalse());
     // Ensure that we get an error if we have the class but not the method.
     JError::setErrorHandling(E_ERROR, 'callback', array($errorCallback, 'error3'));
     $this->assertThat(JHtml::_('inspector.nomethod'), $this->isFalse());
     // Restore the error handlers.
     $this->setErrorHandlers($this->savedErrorState);
 }
Beispiel #5
0
 /**
  * Set db logger. Since all JErrors E_ERROR will be added to log.
  * Usefull if you render something J! native. 
  * Covers all E_ERROR generated by 
  * JError::raiseError, JError::raise, JError::throwError.
  * 
  * All execs of JLog::add(...) with 
  * JLog::EMERGENCY | JLog::ALERT | JLog::CRITICAL | JLog::ERROR
  * will be added to LOGS table.
  */
 public static function startJoomlaDbErrorLogger()
 {
     // Add handler to JError for E_ERROR
     JError::setErrorHandling(E_ERROR, 'callback', array('LogHelper', 'addJError'));
     // Now we log all the troubles into our LOGS table.
     JLog::addLogger(array('logger' => 'database', 'db_table' => '#__newsletter_logs'), JLog::EMERGENCY | JLog::ALERT | JLog::CRITICAL | JLog::ERROR);
 }
Beispiel #6
0
 /**
  * Method to register custom library.
  *
  * @return  void
  */
 public function onAfterInitialise()
 {
     if (defined('REDCORE_LIBRARY_LOADED')) {
         $apiName = JFactory::getApplication()->input->getString('api');
         if ($this->isApiEnabled($apiName)) {
             $input = JFactory::getApplication()->input;
             if (!empty($apiName)) {
                 try {
                     // We will disable all error messaging from PHP from the output
                     error_reporting(0);
                     ini_set('display_errors', 0);
                     JError::setErrorHandling(E_ERROR, 'message');
                     JFactory::getApplication()->clearHeaders();
                     $webserviceClient = $input->get->getString('webserviceClient', '');
                     $optionName = $input->get->getString('option', '');
                     $optionName = strpos($optionName, 'com_') === 0 ? substr($optionName, 4) : $optionName;
                     $viewName = $input->getString('view', '');
                     $version = $input->getString('webserviceVersion', '');
                     $token = $input->getString(RBootstrap::getConfig('oauth2_token_param_name', 'access_token'), '');
                     $apiName = ucfirst($apiName);
                     $method = strtoupper($input->getMethod());
                     $task = RApiHalHelper::getTask();
                     $data = RApi::getPostedData();
                     $dataGet = $input->get->getArray();
                     if (empty($webserviceClient)) {
                         $webserviceClient = JFactory::getApplication()->isAdmin() ? 'administrator' : 'site';
                     }
                     $options = array('api' => $apiName, 'optionName' => $optionName, 'viewName' => $viewName, 'webserviceVersion' => $version, 'webserviceClient' => $webserviceClient, 'method' => $method, 'task' => $task, 'data' => $data, 'dataGet' => $dataGet, 'accessToken' => $token, 'format' => $input->getString('format', $this->params->get('webservices_default_format', 'json')), 'id' => $input->getString('id', ''), 'absoluteHrefs' => $input->get->getBool('absoluteHrefs', true));
                     // Create instance of Api and fill all required options
                     $api = RApi::getInstance($options);
                     // Run the api task
                     $api->execute();
                     // Display output
                     $api->render();
                 } catch (Exception $e) {
                     $code = $e->getCode() > 0 ? $e->getCode() : 500;
                     if (strtolower($apiName) == 'soap') {
                         // We must have status of 200 for SOAP communication even if it is fault
                         $message = RApiSoapHelper::createSoapFaultResponse($e->getMessage());
                         header("Content-Type: soap+xml");
                         header("Content-length: " . strlen($message));
                         header("Status: 200");
                         echo $message;
                     } else {
                         // Set the server response code.
                         header('Status: ' . $code, true, $code);
                         // Check for defined constants
                         if (!defined('JSON_UNESCAPED_SLASHES')) {
                             define('JSON_UNESCAPED_SLASHES', 64);
                         }
                         // An exception has been caught, echo the message and exit.
                         echo json_encode(array('message' => $e->getMessage(), 'code' => $e->getCode(), 'type' => get_class($e)), JSON_UNESCAPED_SLASHES);
                     }
                 }
                 JFactory::getApplication()->close();
             }
         }
     }
 }
 /**
  * Constructor.
  *
  * @param   object  &$subject  The object to observe
  * @param   array   $config    An optional associative array of configuration settings.
  *
  * @since   1.6
  */
 public function __construct(&$subject, $config)
 {
     parent::__construct($subject, $config);
     // Set the JError handler for E_ERROR to be the class' handleError method.
     JError::setErrorHandling(E_ERROR, 'callback', array('PlgSystemRedirect', 'handleError'));
     // Register the previously defined exception handler so we can forward errors to it
     self::$previousExceptionHandler = set_exception_handler(array('PlgSystemRedirect', 'handleException'));
 }
Beispiel #8
0
 /**
  * Class constructor
  *
  * @access protected
  * @param	array An optional associative array of configuration settings.
  * Recognized key values include 'clientId' (this list is not meant to be comprehensive).
  */
 public function __construct(array $config = array())
 {
     $config['clientId'] = 2;
     parent::__construct($config);
     JError::setErrorHandling(E_ALL, 'Ignore');
     $this->_createConfiguration();
     // Set the root in the URI based on the application name.
     JURI::root(null, str_replace('/' . $this->getName(), '', JURI::base(true)));
 }
Beispiel #9
0
 function __construct()
 {
     // Set timelimit to 0
     set_time_limit(0);
     // Base includes
     require_once JPATH_LIBRARIES . '/joomla/import.php';
     require_once JPATH_LIBRARIES . '/joomla/methods.php';
     require_once JPATH_LIBRARIES . '/joomla/factory.php';
     require_once JPATH_LIBRARIES . '/joomla/import.php';
     require_once JPATH_LIBRARIES . '/joomla/config.php';
     require_once JPATH_SITE . '/configuration.php';
     // Base includes
     jimport('joomla.base.object');
     jimport('joomla.base.adapter');
     // Application includes
     jimport('joomla.application.helper');
     jimport('joomla.application.application');
     jimport('joomla.application.component.modellist');
     // Error includes
     jimport('joomla.error.error');
     jimport('joomla.error.exception');
     // Database includes
     jimport('joomla.database.database');
     jimport('joomla.database.table');
     jimport('joomla.database.tablenested');
     jimport('joomla.database.table.asset');
     jimport('joomla.database.table.category');
     // Update and installer includes for 3rd party extensions
     jimport('joomla.installer.installer');
     jimport('joomla.updater.updater');
     jimport('joomla.updater.update');
     // Other stuff
     jimport('joomla.filesystem.folder');
     jimport('joomla.utilities.string');
     jimport('joomla.filter.filteroutput');
     jimport('joomla.html.parameter');
     // Echo all errors, otherwise things go really bad.
     JError::setErrorHandling(E_ALL, 'echo');
     // Manually
     //JTable::addIncludePath(JPATH_LIBRARIES.'/joomla/database/table');
     $jconfig = new JConfig();
     $this->config['driver'] = 'mysql';
     $this->config['host'] = $jconfig->host;
     $this->config['user'] = $jconfig->user;
     $this->config['password'] = $jconfig->password;
     $this->config['database'] = $jconfig->db;
     $this->config['prefix'] = $jconfig->dbprefix;
     //print_r($config);
     $this->config_old = $this->config;
     $this->config_old['prefix'] = $this->getPrefix();
     $this->db_new = JDatabase::getInstance($this->config);
     $this->db_old = JDatabase::getInstance($this->config_old);
 }
 /**
  * Test JError::setErrorHandling
  *
  * @return  void
  */
 public function testSetErrorHandling()
 {
     JErrorInspector::manipulateLevels(array(E_NOTICE => 'Notice', E_WARNING => 'Warning', E_ERROR => 'Error'));
     $errorHandling = JErrorInspector::inspectHandlers();
     $this->assertThat(JError::setErrorHandling(E_NOTICE, 'message'), $this->isTrue(), 'Setting a message error handler failed');
     $handlers = JErrorInspector::inspectHandlers();
     $this->assertThat($handlers[E_NOTICE], $this->equalTo(array('mode' => 'message')), 'The error handler did not get set to message');
     $this->assertThat(JError::setErrorHandling(E_NOTICE, 'callback', array($this, 'callbackHandler')), $this->isTrue(), 'Setting a message error handler failed');
     $handlers = JErrorInspector::inspectHandlers();
     $this->assertThat($handlers[E_NOTICE], $this->equalTo(array('mode' => 'callback', 'options' => array($this, 'callbackHandler'))), 'The error handler did not get set to callback');
     JErrorInspector::manipulateHandlers($errorHandling);
 }
Beispiel #11
0
	/**
	 * Method to set the setup language for the application.
	 *
	 * @return	void
	 * @since	1.6
	 */
	public function setlanguage()
	{
		// Get the application object.
		$app = JFactory::getApplication();

		// Check for potentially unwritable session
		$session = JFactory::getSession();

		if ($session->isNew()) {
			JError::setErrorHandling(E_ERROR, 'message');
			JError::raise(E_ERROR, 500, JText::_('INSTL_COOKIES_NOT_ENABLED'));

			return false;
		}

		// Check for request forgeries.
		JRequest::checkToken() or jexit(JText::_('JINVALID_TOKEN'));

		// Get the setup model.
		$model = $this->getModel('Setup', 'JInstallationModel', array('dbo' => null));

		// Get the posted values from the request and validate them.
		$data = JRequest::getVar('jform', array(), 'post', 'array');
		$return	= $model->validate($data, 'language');

		// Check for validation errors.
		if ($return === false) {

			// Get the validation messages.
			$errors	= $model->getErrors();

			// Push up to three validation messages out to the user.
			for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++)
			{
				if (JError::isError($errors[$i])) {
					$app->enqueueMessage($errors[$i]->getMessage(), 'warning');
				} else {
					$app->enqueueMessage($errors[$i], 'warning');
				}
			}

			// Redirect back to the language selection screen.
			$this->setRedirect('index.php?view=language');
			return false;
		}

		// Store the options in the session.
		$vars = $model->storeOptions($return);

		// Redirect to the next page.
		$this->setRedirect('index.php?view=preinstall');
	}
 /**
  * Sets the JError error handlers.
  *
  * @param	array	araay of values and options to set the handlers
  *
  * @return	void
  */
 protected function setErrorHandlers($errorHandlers)
 {
     $mode = null;
     $options = null;
     foreach ($errorHandlers as $type => $params) {
         $mode = $params['mode'];
         if (isset($params['options'])) {
             JError::setErrorHandling($type, $mode, $params['options']);
         } else {
             JError::setErrorHandling($type, $mode);
         }
     }
 }
Beispiel #13
0
 /**
  * Object Constructor.
  *
  * @access	public
  * @param	object	The object to observe -- event dispatcher.
  * @param	object	The configuration object for the plugin.
  * @return	void
  * @since	1.5
  */
 function __construct(&$subject, $config)
 {
     parent::__construct($subject, $config);
     $hash = JUtility::getHash('plgSystemLogout');
     if (JFactory::getApplication()->isSite() and JRequest::getString($hash, null, 'cookie')) {
         // Destroy the cookie
         $conf = JFactory::getConfig();
         $cookie_domain = $conf->get('config.cookie_domain', '');
         $cookie_path = $conf->get('config.cookie_path', '/');
         setcookie($hash, false, time() - 86400, $cookie_path, $cookie_domain);
         // Set the error handler for E_ALL to be the class handleError method.
         JError::setErrorHandling(E_ALL, 'callback', array('plgSystemLogout', 'handleError'));
     }
 }
Beispiel #14
0
 /**
  * Constructor.
  *
  * @param   object  &$subject  The object to observe -- event dispatcher.
  * @param   object  $config    An optional associative array of configuration settings.
  *
  * @since   1.6
  */
 public function __construct(&$subject, $config)
 {
     parent::__construct($subject, $config);
     $app = JFactory::getApplication();
     $input = $app->input;
     $hash = JApplicationHelper::getHash('PlgSystemLogout');
     if ($app->isSite() && $input->cookie->getString($hash)) {
         // Destroy the cookie.
         $cookie_domain = $app->get('cookie_domain', '');
         $cookie_path = $app->get('cookie_path', '/');
         setcookie($hash, false, time() - 86400, $cookie_path, $cookie_domain);
         // Set the error handler for E_ALL to be the class handleError method.
         JError::setErrorHandling(E_ALL, 'callback', array('PlgSystemLogout', 'handleError'));
     }
 }
Beispiel #15
0
 /**
  * Displays a layout file
  *
  * @param unknown_type $tpl
  * @return unknown_type
  */
 public function display($tpl = null)
 {
     // Load the model
     $model = $this->getModel();
     $items = $model->getList();
     $this->assignRef('items', $items);
     $document = JFactory::getDocument();
     $document->setMimeEncoding('text/csv');
     JResponse::setHeader('Pragma', 'public');
     JResponse::setHeader('Expires', '0');
     JResponse::setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
     JResponse::setHeader('Cache-Control', 'public', false);
     JResponse::setHeader('Content-Description', 'File Transfer');
     JResponse::setHeader('Content-Disposition', 'attachment; filename=' . $this->csvFilename);
     JError::setErrorHandling(E_ALL, 'ignore');
     if (is_null($tpl)) {
         $tpl = 'csv';
     }
     $result = $this->loadTemplate($tpl);
     JError::setErrorHandling(E_WARNING, 'callback');
     if ($result instanceof JException) {
         // Default CSV behaviour in case the template isn't there!
         if (empty($items)) {
             return;
         }
         if ($this->csvHeader) {
             $item = array_pop($items);
             $keys = get_object_vars($item);
             $items[] = $item;
             reset($items);
             $csv = array();
             foreach ($keys as $k => $v) {
                 $csv[] = '"' . str_replace('"', '""', $k) . '"';
             }
             echo implode(",", $csv) . "\r\n";
         }
         foreach ($items as $item) {
             $csv = array();
             $keys = get_object_vars($item);
             foreach ($item as $k => $v) {
                 $csv[] = '"' . str_replace('"', '""', $v) . '"';
             }
             echo implode(",", $csv) . "\r\n";
         }
         return;
     }
 }
Beispiel #16
0
 /**
  * Method to register a new error level for handling errors
  *
  * This allows you to add custom error levels to the built-in
  * - E_NOTICE
  * - E_WARNING
  * - E_NOTICE
  *
  * @param   integer  $level    Error level to register
  * @param   string   $name     Human readable name for the error level
  * @param   string   $handler  Error handler to set for the new error level [optional]
  *
  * @return  boolean  True on success; false if the level already has been registered
  *
  * @deprecated  12.1
  * @since   11.1
  */
 public static function registerErrorLevel($level, $name, $handler = 'ignore')
 {
     // Deprecation warning.
     JLog::add('JError::registerErrorLevel() is deprecated.', JLog::WARNING, 'deprecated');
     if (isset(JError::$levels[$level])) {
         return false;
     }
     JError::$levels[$level] = $name;
     JError::setErrorHandling($level, $handler);
     return true;
 }
Beispiel #17
0
// Installation check, and check on removal of the install directory.
if (!file_exists(JPATH_CONFIGURATION . '/configuration.php') || filesize(JPATH_CONFIGURATION . '/configuration.php') < 10 || file_exists(JPATH_INSTALLATION . '/index.php')) {
    if (file_exists(JPATH_INSTALLATION . '/index.php')) {
        header('Location: ../installation/index.php');
        exit;
    } else {
        echo 'No configuration file found and no installation code available. Exiting...';
        exit;
    }
}
// System includes
require_once JPATH_LIBRARIES . '/import.legacy.php';
// Set system error handling
JError::setErrorHandling(E_NOTICE, 'message');
JError::setErrorHandling(E_WARNING, 'message');
JError::setErrorHandling(E_ERROR, 'message', array('JError', 'customErrorPage'));
// Bootstrap the CMS libraries.
require_once JPATH_LIBRARIES . '/cms.php';
// Pre-Load configuration. Don't remove the Output Buffering due to BOM issues, see JCode 26026
ob_start();
require_once JPATH_CONFIGURATION . '/configuration.php';
ob_end_clean();
// System configuration.
$config = new JConfig();
// Set the error_reporting
switch ($config->error_reporting) {
    case 'default':
    case '-1':
        break;
    case 'none':
    case '0':
Beispiel #18
0
 /**
  * Get web service instance
  *
  * @param   array  $options  initial state options
  *
  * @throws Exception
  *
  * @return  FabrikWebService
  */
 public static function getInstance($options = array())
 {
     // Sanitize the database connector options.
     $options['driver'] = isset($options['driver']) ? preg_replace('/[^A-Z0-9_\\.-]/i', '', $options['driver']) : 'soap';
     $options['endpoint'] = isset($options['endpoint']) ? $options['endpoint'] : null;
     // Get the options signature for the database connector.
     $signature = md5(serialize($options));
     // If we already have a database connector instance for these options then just use that.
     if (empty(self::$instances[$signature])) {
         // Derive the class name from the driver.
         $class = 'FabrikWebService' . JString::ucfirst($options['driver']);
         // If the class doesn't exist, let's look for it and register it.
         if (!class_exists($class)) {
             // Derive the file path for the driver class.
             $path = dirname(__FILE__) . '/webservice/' . $options['driver'] . '.php';
             // If the file exists register the class with our class loader.
             if (file_exists($path)) {
                 JLoader::register($class, $path);
             } else {
                 // Legacy error handling switch based on the JError::$legacy switch.
                 // @deprecated  12.1
                 if (JError::$legacy) {
                     // Deprecation warning.
                     JLog::add('JError is deprecated.', JLog::WARNING, 'deprecated');
                     JError::setErrorHandling(E_ERROR, 'die');
                     return JError::raiseError(500, JText::sprintf('JLIB_DATABASE_ERROR_LOAD_DATABASE_DRIVER', $options['driver']));
                 } else {
                     throw new Exception(JText::sprintf('JLIB_DATABASE_ERROR_LOAD_DATABASE_DRIVER', $options['driver']));
                 }
             }
         }
         // If the class still doesn't exist we have nothing left to do but throw an exception.  We did our best.
         if (!class_exists($class)) {
             // Legacy error handling switch based on the JError::$legacy switch.
             // @deprecated  12.1
             if (JError::$legacy) {
                 // Deprecation warning.
                 JLog::add('JError() is deprecated.', JLog::WARNING, 'deprecated');
                 JError::setErrorHandling(E_ERROR, 'die');
                 return JError::raiseError(500, JText::sprintf('JLIB_DATABASE_ERROR_LOAD_DATABASE_DRIVER', $options['driver']));
             } else {
                 throw new Exception(JText::sprintf('JLIB_DATABASE_ERROR_LOAD_DATABASE_DRIVER', $options['driver']));
             }
         }
         // Create our new FabrikWebService connector based on the options given.
         try {
             $instance = new $class($options);
         } catch (Exception $e) {
             // Legacy error handling switch based on the JError::$legacy switch.
             // @deprecated  12.1
             if (JError::$legacy) {
                 // Deprecation warning.
                 JLog::add('JError() is deprecated.', JLog::WARNING, 'deprecated');
                 JError::setErrorHandling(E_ERROR, 'ignore');
                 return JError::raiseError(500, JText::sprintf('JLIB_DATABASE_ERROR_CONNECT_DATABASE', $e->getMessage()));
             } else {
                 throw new Exception(JText::sprintf('JLIB_DATABASE_ERROR_CONNECT_DATABASE', $e->getMessage()));
             }
         }
         // Set the new connector to the global instances based on signature.
         self::$instances[$signature] = $instance;
     }
     return self::$instances[$signature];
 }
Beispiel #19
0
 /**
  * Sets the JError error handlers.
  *
  * @param   array  $errorHandlers  araay of values and options to set the handlers
  *
  * @return  void
  *
  * @since   12.1
  */
 protected function setErrorHandlers($errorHandlers)
 {
     $mode = null;
     $options = null;
     foreach ($errorHandlers as $type => $params) {
         $mode = $params['mode'];
         // Handle optional usage of JError until removed.
         if (class_exists('JError')) {
             if (isset($params['options'])) {
                 JError::setErrorHandling($type, $mode, $params['options']);
             } else {
                 JError::setErrorHandling($type, $mode);
             }
         }
     }
 }
Beispiel #20
0
 /**
  * Catch all exception handler
  *
  * Calls the Joomla error handler to process the exception
  *
  * @param object an Exception object
  * @return void
  */
 public function exceptionHandler($exception)
 {
     $this->_exception = $exception;
     //store the exception for later use
     $this->errorHandler($exception);
     //Change the Joomla error handler to our own local handler and call it
     JError::setErrorHandling(E_ERROR, 'callback', array($this, 'errorHandler'));
     //Make sure we have a valid status code
     JError::raiseError(KHttpResponse::isError($exception->getCode()) ? $exception->getCode() : 500, $exception->getMessage());
 }
Beispiel #21
0
 /**
  * Process an ajax call and return result
  *
  * @access public
  * @return string
  */
 public function process($array = false)
 {
     // Check for request forgeries
     WFToken::checkToken() or die('Access to this resource is restricted');
     $filter = JFilterInput::getInstance();
     $json = JRequest::getVar('json', '', 'POST', 'STRING', 2);
     $action = JRequest::getWord('action');
     // set error handling for requests
     JError::setErrorHandling(E_ALL, 'callback', array('WFRequest', 'raiseError'));
     if ($action || $json) {
         // set request flag
         define('JCE_REQUEST', 1);
         $output = array("result" => null, "text" => null, "error" => null);
         if ($json) {
             // remove slashes
             $json = stripslashes($json);
             // convert to JSON object
             $json = json_decode($json);
             // invalid JSON
             if (is_null($json)) {
                 throw new InvalidArgumentException('Invalid JSON');
             }
             // no function call
             if (isset($json->fn) === false) {
                 throw new InvalidArgumentException('Invalid Function Call');
             }
             // get function call
             $fn = $json->fn;
             // get arguments
             $args = isset($json->args) ? $json->args : array();
         } else {
             $fn = $action;
             $args = array();
         }
         // clean function
         $fn = $filter->clean($fn, 'cmd');
         // check query
         $this->checkQuery($args);
         // call function
         if (array_key_exists($fn, $this->request)) {
             $method = $this->request[$fn];
             // set default function call
             $call = null;
             if (!isset($method->ref)) {
                 $call = $method->fn;
                 if (!function_exists($call)) {
                     throw new InvalidArgumentException('Invalid Function -  "' . $call . '"');
                 }
             } else {
                 if (!method_exists($method->ref, $method->fn)) {
                     throw new InvalidArgumentException('Invalid Method "' . $method->ref . '::' . $method->fn . '"');
                 }
                 $call = array($method->ref, $method->fn);
             }
             if (!$call) {
                 throw new InvalidArgumentException('Invalid Function Call');
             }
             if (!is_array($args)) {
                 $result = call_user_func($call, $args);
             } else {
                 $result = call_user_func_array($call, $args);
             }
         } else {
             if ($fn) {
                 throw new InvalidArgumentException('Unregistered Function - "' . addslashes($fn) . '"');
             } else {
                 throw new InvalidArgumentException('Invalid Function Call');
             }
         }
         $output = array("result" => $result);
         ob_start();
         // set output headers
         header('Content-Type: text/json;charset=UTF-8');
         header('Content-Encoding: UTF-8');
         header("Expires: Mon, 4 April 1984 05:00:00 GMT");
         header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
         header("Cache-Control: no-store, no-cache, must-revalidate");
         header("Cache-Control: post-check=0, pre-check=0", false);
         header("Pragma: no-cache");
         echo json_encode($output);
         exit(ob_get_clean());
     }
 }
Beispiel #22
0
            JLog::add($state->getMessage(), JLog::ERROR);
            // Prepare the error response.
            $this->error = true;
            $this->header = JText::_('COM_FINDER_INDEXER_HEADER_ERROR');
            $this->message = $state->getMessage();
        } else {
            // Prepare the response data.
            $this->batchSize = (int) $state->batchSize;
            $this->batchOffset = (int) $state->batchOffset;
            $this->totalItems = (int) $state->totalItems;
            $this->startTime = $state->startTime;
            $this->endTime = JFactory::getDate()->toSql();
            $this->start = !empty($state->start) ? (int) $state->start : 0;
            $this->complete = !empty($state->complete) ? (int) $state->complete : 0;
            // Set the appropriate messages.
            if ($this->totalItems <= 0 && $this->complete) {
                $this->header = JText::_('COM_FINDER_INDEXER_HEADER_COMPLETE');
                $this->message = JText::_('COM_FINDER_INDEXER_MESSAGE_COMPLETE');
            } elseif ($this->totalItems <= 0) {
                $this->header = JText::_('COM_FINDER_INDEXER_HEADER_OPTIMIZE');
                $this->message = JText::_('COM_FINDER_INDEXER_MESSAGE_OPTIMIZE');
            } else {
                $this->header = JText::_('COM_FINDER_INDEXER_HEADER_RUNNING');
                $this->message = JText::_('COM_FINDER_INDEXER_MESSAGE_RUNNING');
            }
        }
    }
}
// Register the error handler.
JError::setErrorHandling(E_ALL, 'callback', array('FinderControllerIndexer', 'sendResponse'));
Beispiel #23
0
jimport('joomla.session.session');

// We need also these:
jimport('joomla.plugin.helper');

$_SERVER['HTTP_HOST'] = 'http://localhost';
$_SERVER['REQUEST_URI'] = '/index.php';
//$_SERVER['REMOTE_ADDR'] = '127.0.0.1';

$app = JFactory::getApplication('site');

if (!defined('KPATH_TESTS'))
{
	define('KPATH_TESTS', dirname(__FILE__));
}

// Exclude all of the tests from code coverage reports
if (class_exists('PHP_CodeCoverage_Filter')) {
	PHP_CodeCoverage_Filter::getInstance()->addDirectoryToBlacklist(JPATH_BASE . '/tests');
} else {
	PHPUnit_Util_Filter::addDirectoryToFilter(JPATH_BASE . '/tests');
}

// Set error handling.
JError::setErrorHandling(E_NOTICE, 'ignore');
JError::setErrorHandling(E_WARNING, 'ignore');
JError::setErrorHandling(E_ERROR, 'ignore');

// Load Kunena API
require_once JPATH_ADMINISTRATOR . '/components/com_kunena/api.php';
KunenaFactory::loadLanguage();
Beispiel #24
0
 /**
  * Set the error Handling, if possible
  *
  * @param integer $level     PHP error level (E_ALL)
  * @param string  $log_level What to do with the error (ignore, callback)
  * @param array   $options   Options for the error handler
  *
  * @return  void
  */
 public static function setErrorHandling($level, $log_level, $options = array())
 {
     if (version_compare(JVERSION, '3.0', 'lt')) {
         \JError::setErrorHandling($level, $log_level, $options);
     }
 }
 /**
  * Returns a reference to the global Database object, only creating it
  * if it doesn't already exist.
  *
  * The 'driver' entry in the parameters array specifies the database driver
  * to be used (defaults to 'mysql' if omitted). All other parameters are
  * database driver dependent.
  *
  * @param array Parameters to be passed to the database driver
  * @return JDatabase A database object
  * @since 1.5
  */
 function &getInstance($options = array())
 {
     static $instances;
     if (!isset($instances)) {
         $instances = array();
     }
     $signature = serialize($options);
     if (empty($instances[$signature])) {
         $driver = array_key_exists('driver', $options) ? $options['driver'] : 'mysql';
         $select = array_key_exists('select', $options) ? $options['select'] : true;
         $database = array_key_exists('database', $options) ? $options['database'] : null;
         $driver = preg_replace('/[^A-Z0-9_\\.-]/i', '', $driver);
         $path = dirname(__FILE__) . DS . 'database' . DS . $driver . '.php';
         if (file_exists($path)) {
             require_once $path;
         } else {
             JError::setErrorHandling(E_ERROR, 'die');
             //force error type to die
             $error = JError::raiseError(500, JTEXT::_('Unable to load Database Driver:') . $driver);
             return $error;
         }
         $adapter = 'JDatabase' . $driver;
         $instance = new $adapter($options);
         if ($error = $instance->getErrorMsg()) {
             JError::setErrorHandling(E_ERROR, 'ignore');
             //force error type to die
             $error = JError::raiseError(500, JTEXT::_('Unable to connect to the database:') . $error);
             return $error;
         }
         $instances[$signature] =& $instance;
     }
     return $instances[$signature];
 }
 /**
  * Tells the unit tests that a method or action you are about to attempt
  * is expected to result in JError::raiseSomething being called.
  *
  * If you don't call this method first, the test will fail.
  * If you call this method during your test and the error does not occur, then your test
  * will also fail because we assume you were testing to see that an error did occur when it was
  * supposed to.
  *
  * If passed without argument, the array is initialized if it hsn't been already
  */
 public function setExpectedError($error = null)
 {
     if (!is_array($this->expectedErrors)) {
         $this->expectedErrors = array();
         JError::setErrorHandling(E_NOTICE, 'callback', array($this, 'expectedErrorCallback'));
         JError::setErrorHandling(E_WARNING, 'callback', array($this, 'expectedErrorCallback'));
         JError::setErrorHandling(E_ERROR, 'callback', array($this, 'expectedErrorCallback'));
     }
     if (!is_null($error)) {
         $this->expectedErrors[] = $error;
     }
 }
Beispiel #27
0
// Import necessary classes not handled by the autoloaders
jimport('joomla.application.menu');
jimport('joomla.environment.uri');
jimport('joomla.environment.request');
jimport('joomla.utilities.utility');
jimport('joomla.event.dispatcher');
jimport('joomla.utilities.date');
// Import the configuration.
require_once JPATH_CONFIGURATION . '/configuration.php';
// System configuration.
$config = new JConfig();
// Configure error reporting.
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Set error handling levels
JError::setErrorHandling(E_ALL, 'echo');
// Initialize the application.
$app = JFactory::getApplication('site');
// Load Library language
$lang = JFactory::getLanguage();
// Try the finder_cli file in the current language (without allowing the loading of the file in the default language)
$lang->load('finder_cli', JPATH_SITE, null, false, false) || $lang->load('finder_cli', JPATH_SITE, null, true);
/**
 * A command line cron job to run the Finder indexer.
 *
 * @package     Joomla.CLI
 * @subpackage  com_finder
 * @since       2.5
 */
class FinderCli extends JApplicationCli
{
* Joomla! is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/
// Set flag that this is a parent file
define('_JEXEC', 1);
define('JPATH_BASE', dirname(__FILE__));
define('DS', DIRECTORY_SEPARATOR);
require_once JPATH_BASE . DS . 'includes' . DS . 'defines.php';
require_once JPATH_BASE . DS . 'includes' . DS . 'framework.php';
// Templates etc. are not available for the XMLRPC application, therefore this simple error handler
JError::setErrorHandling(E_ERROR, 'die');
JError::setErrorHandling(E_WARNING, 'echo');
JError::setErrorHandling(E_NOTICE, 'echo');
// create the mainframe object
$mainframe =& JFactory::getApplication('xmlrpc');
// Ensure that this application is enabled
if (!($mainframe->getCfg('xmlrpc_server') && $mainframe->getCfg('debug'))) {
    JError::raiseError(403, 'XML-RPC Client or Debugging not enabled.');
}
// Includes the required class file for the XML-RPC Client
jimport('phpxmlrpc.xmlrpc');
// Get default values for the XMLRPC server host and path
$uri = JURI::getInstance();
$host = $uri->getHost();
$path = $uri->getPath();
$path = dirname($path) . '/';
$host = JRequest::getString('host', $host, 'post');
$path = JRequest::getString('path', $path, 'post');
* @license GNU General Public License version 2 or later; see LICENSE
*/
// We are a valid Joomla entry point.
define('_JEXEC', 1);
// Setup the base path related constant.
define('JPATH_BASE', dirname(__FILE__));
define('JPATH_SITE', JPATH_BASE);
define('JPATH_THEMES', JPATH_BASE . '/themes');
// Increase error reporting to that any errors are displayed.
// Note, you would not use these settings in production.
error_reporting(E_ALL);
ini_set('display_errors', true);
// Bootstrap the application.
require dirname(__FILE__) . '/bootstrap.php';
// Set error handler to echo
JError::setErrorHandling(E_ERROR, 'echo');
/**
* An example JApplicationWeb application class.
*
* @package Joomla.Examples
* @since 11.3
*/
class PicasaPhotos extends JApplicationWeb
{
    /**
    * Overrides the parent doExecute method to run the web application.
    *
    * This method should include your custom code that runs the application.
    *
    * @return void
    *
 /**
  * The main entry point of the application
  */
 public function execute()
 {
     // Set all errors to output the messages to the console, in order to
     // avoid infinite loops in JError ;)
     restore_error_handler();
     JError::setErrorHandling(E_ERROR, 'die');
     JError::setErrorHandling(E_WARNING, 'echo');
     JError::setErrorHandling(E_NOTICE, 'echo');
     // Required by Joomla!
     JLoader::import('joomla.environment.request');
     // Set the root path to Akeeba Subscriptions
     define('JPATH_COMPONENT_ADMINISTRATOR', JPATH_ADMINISTRATOR . '/components/com_akeebasubs');
     // Allow inclusion of Joomla! files
     if (!defined('_JEXEC')) {
         define('_JEXEC', 1);
     }
     // Load F0F
     JLoader::import('f0f.include');
     // Load the version.php file
     include_once JPATH_COMPONENT_ADMINISTRATOR . '/version.php';
     // Load language strings
     JFactory::getLanguage()->load('plg_system_asexpirationnotify', JPATH_ADMINISTRATOR, null, true, true);
     // Display banner
     $year = gmdate('Y');
     $phpversion = PHP_VERSION;
     $phpenvironment = PHP_SAPI;
     $phpos = PHP_OS;
     $this->out("Akeeba Subscriptions Expiration Notification Emails CLI " . AKEEBASUBS_VERSION . " (" . AKEEBASUBS_DATE . ")");
     $this->out("Copyright (C) 2010-{$year} Nicholas K. Dionysopoulos");
     $this->out(str_repeat('-', 79));
     $this->out("Akeeba Subscriptions is Free Software, distributed under the terms of the GNU General");
     $this->out("Public License version 3 or, at your option, any later version.");
     $this->out("This program comes with ABSOLUTELY NO WARRANTY as per sections 15 & 16 of the");
     $this->out("license. See http://www.gnu.org/licenses/gpl-3.0.html for details.");
     $this->out(str_repeat('-', 79));
     $this->out("You are using PHP {$phpversion} ({$phpenvironment})");
     $this->out("");
     // Unset time limits
     $safe_mode = true;
     if (function_exists('ini_get')) {
         $safe_mode = ini_get('safe_mode');
     }
     if (!$safe_mode && function_exists('set_time_limit')) {
         $this->out("Unsetting time limit restrictions");
         @set_time_limit(0);
     }
     // ===== START
     // Preload the helper
     if (!class_exists('AkeebasubsHelperEmail')) {
         @(include_once JPATH_ROOT . '/components/com_akeebasubs/helpers/email.php');
     }
     // Get today's date
     JLoader::import('joomla.utilities.date');
     $jNow = new JDate();
     $now = $jNow->toUnix();
     // Get and loop all subscription levels
     $x = $levels = F0FModel::getTmpInstance('Levels', 'AkeebasubsModel');
     $levels = F0FModel::getTmpInstance('Levels', 'AkeebasubsModel')->enabled(1)->getList();
     foreach ($levels as $level) {
         $this->out("Checking for subscriptions in the \"{$level->title}\" subscription level");
         // Load the notification thresholds and make sure they are sorted correctly!
         $notify1 = $level->notify1;
         $notify2 = $level->notify2;
         if ($notify2 > $notify1) {
             $tmp = $notify2;
             $notify2 = $notify1;
             $notify1 = $tmp;
         }
         // Make sure we are asked to notify users, at all!
         if ($notify1 <= 0 && $notify2 <= 0) {
             $this->out("\t!! This level specifies the users should not be notified");
             continue;
         }
         // Get the subscriptions expiring within the next $notify1 days for
         // users which we have not contacted yet.
         $jFrom = new JDate($now + 1);
         $jTo = new JDate($now + $notify1 * 24 * 3600);
         $subs1 = F0FModel::getTmpInstance('Subscriptions', 'AkeebasubsModel')->contact_flag(0)->level($level->akeebasubs_level_id)->enabled(1)->expires_from($jFrom->toSql())->expires_to($jTo->toSql())->getList();
         // Get the subscriptions expiring within the next $notify2 days for
         // users which we have contacted only once
         $subs2 = array();
         if ($notify2 > 0) {
             $jFrom = new JDate($now + 1);
             $jTo = new JDate($now + $notify2 * 24 * 3600);
             $subs2 = F0FModel::getTmpInstance('Subscriptions', 'AkeebasubsModel')->contact_flag(1)->level($level->akeebasubs_level_id)->enabled(1)->expires_from($jFrom->toSql())->expires_to($jTo->toSql())->getList();
         }
         // If there are no subscriptions, bail out
         if (count($subs1) + count($subs2) == 0) {
             $this->out("\tNo subscriptions to notify were found in this level");
             continue;
         }
         // Check is some of those subscriptions have been renewed. If so, set their contactFlag to 2
         $realSubs = array();
         $this->out("\tGetting list of subscriptions");
         foreach (array($subs1, $subs2) as $subs) {
             foreach ($subs as $sub) {
                 // Get the user and level, load similar subscriptions with start date after this subscription's expiry date
                 $renewals = F0FModel::getTmpInstance('Subscriptions', 'AkeebasubsModel')->enabled(1)->user_id($sub->user_id)->level($sub->akeebasubs_level_id)->publish_up($sub->publish_down)->getList();
                 if (count($renewals)) {
                     $this->out("\t\t#{$sub->akeebasubs_subscription_id}: will not be notified (already renewed)");
                     // The user has already renewed. Don't send him an email; just update the row
                     F0FModel::getTmpInstance('Subscriptions', 'AkeebasubsModel')->setId($sub->akeebasubs_subscription_id)->getItem()->save(array('contact_flag' => 3));
                 } else {
                     // No renewals found. Let's nag our user.
                     $this->out("\t\t#{$sub->akeebasubs_subscription_id}: will be notified");
                     $realSubs[] = $sub;
                 }
             }
         }
         // If there are no subscriptions, bail out
         if (empty($realSubs)) {
             $this->out("\tNo subscriptions to be notified in this level");
             continue;
         }
         // Loop through subscriptions and send out emails
         $jNow = new JDate();
         $mNow = $jNow->toSql();
         $this->out("\tProcessing notifications");
         foreach ($realSubs as $sub) {
             // Is it the first or the second contact?
             $this->out("\t\t#{$sub->akeebasubs_subscription_id}", false);
             if ($sub->contact_flag == 0) {
                 // First contact
                 $data = array('akeebasubs_subscription_id' => $sub->akeebasubs_subscription_id, 'contact_flag' => 1, 'first_contact' => $mNow);
                 $result = $this->sendEmail($sub, true);
             } elseif ($sub->contact_flag == 1) {
                 // Second and final contact
                 $data = array('akeebasubs_subscription_id' => $sub->akeebasubs_subscription_id, 'contact_flag' => 2, 'second_contact' => $mNow);
                 $result = $this->sendEmail($sub, false);
             }
             if ($result) {
                 $db = JFactory::getDbo();
                 $data = (object) $data;
                 $db->updateObject('#__akeebasubs_subscriptions', $data, 'akeebasubs_subscription_id');
             }
         }
     }
     // ===== END
     $this->out("Peak memory usage: " . $this->peakMemUsage());
 }