/** * @covers JErrorPage::render */ public function testEnsureTheRenderMethodCorrectlyHandlesNonExceptionClasses() { // Create an object to inject into the method $object = new stdClass(); // The render method echoes the output, so catch it in a buffer ob_start(); JErrorPage::render($object); $output = ob_get_clean(); $this->assertEquals('Error displaying the error page', $output); }
/** * @covers JErrorPage::render */ public function testEnsureTheErrorPageIsCorrectlyRendered() { // Create an Exception to inject into the method $exception = new RuntimeException('Testing JErrorPage::render()', 500); // The render method echoes the output, so catch it in a buffer ob_start(); JErrorPage::render($exception); $output = ob_get_clean(); // Validate the <title> element was set correctly $this->assertContains('<title>500 - Testing JErrorPage::render()</title>', $output); }
/** * insert a reservation * * @param array $data */ public function insert($data) { $db = JFactory::getDbo(); try { $columns = array('id_reservation', 'created', 'user_id', 'description'); $values = array($db->quote($data['id_reservation']), $db->quote(date('Y-m-d H:i:s')), $db->quote($data['user_id']), $db->quote($data['description'])); $query = $db->getQuery(true); $query->insert($db->quoteName('#__ezr_protocol')); $query->columns($db->quoteName($columns)); $query->values(implode(',', $values)); $db->setQuery($query); $db->execute(); } catch (Exception $e) { JErrorPage::render($e); } }
/** * @covers JErrorPage::render */ public function testEnsureTheErrorPageIsCorrectlyRendered() { $documentResponse = '<title>500 - Testing JErrorPage::render()</title>'; $key = serialize(array('error', array())); $mockErrorDocument = $this->getMockBuilder('JDocumentError')->setMethods(array('setError', 'setTitle', 'render'))->getMock(); $mockErrorDocument->expects($this->any())->method('render')->willReturn($documentResponse); TestReflection::setValue('JDocument', 'instances', array($key => $mockErrorDocument)); // Create an Exception to inject into the method $exception = new RuntimeException('Testing JErrorPage::render()', 500); // The render method echoes the output, so catch it in a buffer ob_start(); JErrorPage::render($exception); $output = ob_get_clean(); // Validate the mocked response from JDocument was received $this->assertEquals($documentResponse, $output); }
/** * Render an exception * * @throws InvalidArgumentException If the action parameter is not an instance of Exception * @param KDispatcherContextInterface $context A dispatcher context object * @return boolean|null */ protected function _renderError(KDispatcherContextInterface $context) { $request = $context->request; $response = $context->response; //Check an exception was passed if (!isset($context->param) && !$context->param instanceof KException) { throw new InvalidArgumentException("Action parameter 'exception' [KException] is required"); } //Get the exception object if ($context->param instanceof KEventException) { $exception = $context->param->getException(); } else { $exception = $context->param; } //Make sure the output buffers are cleared $level = ob_get_level(); while ($level > 0) { ob_end_clean(); $level--; } //Render the error if (!JDEBUG && $request->getFormat() == 'html') { $message = $this->getObject('translator')->translate($exception->getMessage()); if (version_compare(JVERSION, '3.0', '>=')) { $class = get_class($exception); $error = new $class($message, $exception->getCode()); JErrorPage::render($error); JFactory::getApplication()->close(0); } else { JError::raiseError($exception->getCode(), $message); } return false; } else { //Render the exception if debug mode is enabled or if we are returning json if (in_array($request->getFormat(), array('json', 'html'))) { $config = array('request' => $request, 'response' => $response); $this->getObject('com:koowa.controller.error', $config)->layout('default')->render($exception); //Do not pass response back to Joomla $context->request->query->set('tmpl', 'koowa'); } } }
/** * Display a custom error page and exit gracefully * * @param JException $error Exception object * * @return void * * @deprecated 12.1 * @since 11.1 */ public static function customErrorPage($error) { JLog::add('JError::customErrorPage() is deprecated, use JErrorPage::render() instead.', JLog::WARNING, 'deprecated'); JErrorPage::render($error); }
/** * Output code from error function. * @param string $content */ public function outputError($content) { if (class_exists('JErrorPage')) { $error = new Exception($content); JErrorPage::render($error); } elseif (class_exists('JError')) { JError::raiseError('CiviCRM-001', $content); } else { parent::outputError($content); } }
/** * Internal processor for all error handlers * * @param Exception|Throwable $error The Exception or Throwable object to be handled. * * @return void * * @since 3.5 */ private static function doErrorHandling($error) { $app = JFactory::getApplication(); if ($app->isAdmin() || (int) $error->getCode() !== 404) { // Proxy to the previous exception handler if available, otherwise just render the error page if (self::$previousExceptionHandler) { call_user_func_array(self::$previousExceptionHandler, array($error)); } else { JErrorPage::render($error); } } $uri = JUri::getInstance(); $url = rawurldecode($uri->toString(array('scheme', 'host', 'port', 'path', 'query', 'fragment'))); $urlRel = rawurldecode($uri->toString(array('path', 'query', 'fragment'))); $urlWithoutQuery = rawurldecode($uri->toString(array('scheme', 'host', 'port', 'path', 'fragment'))); $urlRelWithoutQuery = rawurldecode($uri->toString(array('path', 'fragment'))); // Why is this (still) here? if (strpos($url, 'mosConfig_') !== false || strpos($url, '=http://') !== false) { JErrorPage::render($error); } $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('*')->from($db->quoteName('#__redirect_links'))->where('(' . $db->quoteName('old_url') . ' = ' . $db->quote($url) . ' OR ' . $db->quoteName('old_url') . ' = ' . $db->quote($urlRel) . ' OR ' . $db->quoteName('old_url') . ' = ' . $db->quote($urlWithoutQuery) . ' OR ' . $db->quoteName('old_url') . ' = ' . $db->quote($urlRelWithoutQuery) . ')'); $db->setQuery($query); $redirect = null; try { $redirects = $db->loadAssocList(); } catch (Exception $e) { JErrorPage::render(new Exception(JText::_('PLG_SYSTEM_REDIRECT_ERROR_UPDATING_DATABASE'), 500, $e)); } $possibleMatches = array_unique(array($url, $urlRel, $urlWithoutQuery, $urlRelWithoutQuery)); foreach ($possibleMatches as $match) { if (($index = array_search($match, array_column($redirects, 'old_url'))) !== false) { $redirect = (object) $redirects[$index]; if ((int) $redirect->published === 1) { break; } } } // A redirect object was found and, if published, will be used if (!is_null($redirect) && (int) $redirect->published === 1) { if (!$redirect->header || (bool) JComponentHelper::getParams('com_redirect')->get('mode', false) === false) { $redirect->header = 301; } if ($redirect->header < 400 && $redirect->header >= 300) { $urlQuery = $uri->getQuery(); $oldUrlParts = parse_url($redirect->old_url); if (empty($oldUrlParts['query']) && $urlQuery !== '') { $redirect->new_url .= '?' . $urlQuery; } $destination = JUri::isInternal($redirect->new_url) ? JRoute::_($redirect->new_url) : $redirect->new_url; $app->redirect($destination, (int) $redirect->header); } JErrorPage::render(new RuntimeException($error->getMessage(), $redirect->header, $error)); } elseif (is_null($redirect)) { $params = new Registry(JPluginHelper::getPlugin('system', 'redirect')->params); if ((bool) $params->get('collect_urls', true)) { $data = (object) array('id' => 0, 'old_url' => $url, 'referer' => $app->input->server->getString('HTTP_REFERER', ''), 'hits' => 1, 'published' => 0, 'created_date' => JFactory::getDate()->toSql()); try { $db->insertObject('#__redirect_links', $data, 'id'); } catch (Exception $e) { JErrorPage::render(new Exception(JText::_('PLG_SYSTEM_REDIRECT_ERROR_UPDATING_DATABASE'), 500, $e)); } } } else { $redirect->hits += 1; try { $db->updateObject('#__redirect_links', $redirect, 'id'); } catch (Exception $e) { JErrorPage::render(new Exception(JText::_('PLG_SYSTEM_REDIRECT_ERROR_UPDATING_DATABASE'), 500, $e)); } } JErrorPage::render($error); }
/** * Internal processor for all error handlers * * @param Exception|Throwable $error The Exception or Throwable object to be handled. * * @return void * * @since 3.5 */ private static function doErrorHandling($error) { // Get the application object. $app = JFactory::getApplication(); // Make sure the error is a 404 and we are not in the administrator. if ($app->isAdmin() || $error->getCode() != 404) { // Proxy to the previous exception handler if available, otherwise just render the error page if (self::$previousExceptionHandler) { call_user_func_array(self::$previousExceptionHandler, array($error)); } else { JErrorPage::render($error); } } // Get the full current URI. $uri = JUri::getInstance(); $current = rawurldecode($uri->toString(array('scheme', 'host', 'port', 'path', 'query', 'fragment'))); // Attempt to ignore idiots. if (strpos($current, 'mosConfig_') !== false || strpos($current, '=http://') !== false) { // Render the error page. JErrorPage::render($error); } // See if the current url exists in the database as a redirect. $db = JFactory::getDbo(); $query = $db->getQuery(true)->select($db->quoteName(array('new_url', 'header')))->select($db->quoteName('published'))->from($db->quoteName('#__redirect_links'))->where($db->quoteName('old_url') . ' = ' . $db->quote($current)); $db->setQuery($query, 0, 1); $link = $db->loadObject(); // If no published redirect was found try with the server-relative URL if (!$link || $link->published != 1) { $currRel = rawurldecode($uri->toString(array('path', 'query', 'fragment'))); $query = $db->getQuery(true)->select($db->quoteName(array('new_url', 'header')))->select($db->quoteName('published'))->from($db->quoteName('#__redirect_links'))->where($db->quoteName('old_url') . ' = ' . $db->quote($currRel)); $db->setQuery($query, 0, 1); $link = $db->loadObject(); } // If a redirect exists and is published, permanently redirect. if ($link && $link->published == 1) { // If no header is set use a 301 permanent redirect if (!$link->header || JComponentHelper::getParams('com_redirect')->get('mode', 0) == false) { $link->header = 301; } // If we have a redirect in the 300 range use JApplicationWeb::redirect(). if ($link->header < 400 && $link->header >= 300) { $new_link = JUri::isInternal($link->new_url) ? JRoute::_($link->new_url) : $link->new_url; $app->redirect($new_link, intval($link->header)); } // Else rethrow the exeception with the new header and return JErrorPage::render(new RuntimeException($error->getMessage(), $link->header, $error)); } try { $referer = $app->input->server->getString('HTTP_REFERER', ''); $query = $db->getQuery(true)->select($db->quoteName('id'))->from($db->quoteName('#__redirect_links'))->where($db->quoteName('old_url') . ' = ' . $db->quote($current)); $db->setQuery($query); $res = $db->loadResult(); if (!$res) { // If not, add the new url to the database but only if option is enabled $params = new Registry(JPluginHelper::getPlugin('system', 'redirect')->params); $collect_urls = $params->get('collect_urls', 1); if ($collect_urls == true) { $columns = array($db->quoteName('old_url'), $db->quoteName('new_url'), $db->quoteName('referer'), $db->quoteName('comment'), $db->quoteName('hits'), $db->quoteName('published'), $db->quoteName('created_date')); $values = array($db->quote($current), $db->quote(''), $db->quote($referer), $db->quote(''), 1, 0, $db->quote(JFactory::getDate()->toSql())); $query->clear()->insert($db->quoteName('#__redirect_links'), false)->columns($columns)->values(implode(', ', $values)); $db->setQuery($query); $db->execute(); } } else { // Existing error url, increase hit counter. $query->clear()->update($db->quoteName('#__redirect_links'))->set($db->quoteName('hits') . ' = ' . $db->quoteName('hits') . ' + 1')->where('id = ' . (int) $res); $db->setQuery($query); $db->execute(); } } catch (RuntimeException $exception) { JErrorPage::render(new Exception(JText::_('PLG_SYSTEM_REDIRECT_ERROR_UPDATING_DATABASE'), 404, $exception)); } // Render the error page. JErrorPage::render($error); }
/** * insert a reservation * * @param array $data */ public function insertReservation($data) { $db = JFactory::getDbo(); try { $columns = array('name', 'reservation_type', 'user_id', 'id_reservable', 'start_time', 'end_time', 'created'); $values = array($db->quote($data['name']), $db->quote($data['reservation_type']), $db->quote($data['user_id']), $db->quote($data['id_reservable']), $this->quoteDate($data['start_time']), $this->quoteDate($data['end_time']), $db->quote(JFactory::getDate()->toSql())); $query = $db->getQuery(true); $query->insert($db->quoteName('#__ezr_reservation')); $query->columns($db->quoteName($columns)); $query->values(implode(',', $values)); $db->setQuery($query); $db->execute(); return $db->insertid(); } catch (Exception $e) { JErrorPage::render($e); } }
/** * KsenMartModelProfile::setDefaultAddress() * * @return */ public function setDefaultAddress() { $this->onExecuteBefore('setDefaultAddress'); $id = JFactory::getApplication()->input->get('id', 0, 'int'); $user = KSUsers::getUser(); try { $this->_db->transactionStart(); $address = new stdClass(); $address->user_id = $user->id; $address->default = 0; $this->_db->updateObject('#__ksen_user_addresses', $address, 'user_id'); $address = new stdClass(); $address->id = $id; $address->user_id = $user->id; $address->default = 1; $this->_db->updateObject('#__ksen_user_addresses', $address, 'id'); $this->_db->transactionCommit(); $this->onExecuteAfter('setDefaultAddress'); } catch (Exception $e) { $this->_db->transactionRollback(); JErrorPage::render($e); } }
/** * Save subject. * * @param boolean $apply * true state on edit page, false return to browse list */ function save($apply = false) { $mainframe = JFactory::getApplication(); $db = JFactory::getDbo(); $input = JFactory::getApplication()->input; $jform = $input->get('jform', array(), 'array'); $frate = $input->get('frate', array(), 'array'); //quote all value to push db foreach ($frate as &$rate) { foreach ($rate as $i => $v) { $rate[$i] = $db->quote($v); } } $rate = reset($frate); $key = array_keys($rate); $weekdays = $input->get('weekday', null, 'array'); $state = $input->getInt('state'); $jform['startdate'] = DateHelper::createFromFormatYmd($jform['startdate']); $jform['enddate'] = DateHelper::createFromFormatYmd($jform['enddate']); $startdate = new JDate($jform['startdate']); $enddate = new JDate($jform['enddate']); $starttoend = $startdate->diff($enddate)->days; // delete old record $tour_id = $jform['tour_id']; try { $db->transactionStart(); // Delete all existing rate in this duration and fligh route $query = $db->getQuery(true); $query->delete('#__bookpro_tourrate')->where('(tour_id=' . $tour_id . ' AND date BETWEEN ' . $db->quote($startdate) . ' AND ' . $db->quote($enddate) . ' AND DATE_FORMAT(date,"%w") IN (' . implode(',', $weekdays) . ')) OR (date < ' . $db->quote(JFactory::getDate('- 10DAYS')->format('Y-m-d') . ' AND tour_id=' . $tour_id) . ')'); $db->setQuery($query); $db->execute(); $query = $db->getQuery(true); $query->insert('#__bookpro_tourrate'); $query->columns('tour_id,date,' . implode(',', $key) . ',state'); $values = array(); for ($i = 0; $i <= $starttoend; $i++) { $dw = (int) $startdate->format('w'); if (in_array("{$dw}", $weekdays)) { foreach ($frate as $rate) { $temp = array($jform['tour_id'], $db->quote($startdate->toSql())); $temp = array_merge($temp, $rate); $temp[] = $state; $values[] = implode(',', $temp); } } $startdate = $startdate->add(new DateInterval('P1D')); } // Save rate $query->values($values); $db->setQuery($query); $db->execute(); $this->saveLog($frate, $weekdays, $jform); $db->transactionCommit(); $mainframe->enqueueMessage('Saved successful'); } catch (Exception $e) { $db->transactionRollback(); JErrorPage::render($e); $mainframe->enqueueMessage($e->getMessage()); } // if($apply) $this->setRedirect(JRoute::_('index.php?option=com_bookpro&view=tourrate&tour_id=' . $tour_id, false)); // else // $this->setRedirect ( JRoute::_('index.php?option=com_bookpro&view=tours',false) ); }
/** * create a new Reservation * * @return boolean */ public function newReservation() { if ($this->getData() == false) { return false; } if ($this->checkData() == false) { return false; } $db = JFactory::getDbo(); try { $table_occupation = $this->table('Occupation'); $db->transactionStart(); $this->reservation['id_reservation'] = $this->table('Reservation')->insertReservation($this->reservation); foreach ($this->occupations as $occupation) { $occupation['id_reservation'] = $this->reservation['id_reservation']; $table_occupation->insert($occupation); } $protocol = array(); $protocol['id_reservation'] = $this->reservation['id_reservation']; $protocol['user_id'] = JFactory::getUser()->id; $protocol['description'] = 'created reservation ' . $this->reservation['id_reservation'] . ' with ' . count($this->occupations) . ' occupations'; $this->table('Protocol')->insert($protocol); $db->transactionCommit(); } catch (Exception $e) { $db->transactionRollback(); JErrorPage::render($e); return false; } return true; }
function delete() { $mainframe = JFactory::getApplication(); $input = JFactory::getApplication()->input; $weekdays = $input->get('weekday', null, 'array'); $data = $input->get('jform', array(), 'array'); $startdate = new JDate($data['startdate']); $startclone = clone $startdate; $enddate = new JDate($data['enddate']); $starttoend = $startdate->diff($enddate)->days; // delete old record $transport_id = $data['transport_id']; $db = JFactory::getDbo(); try { $db->transactionStart(); $datearr = array(); for ($i = 0; $i <= $starttoend; $i++) { $dw = (int) $startdate->format('N'); if (in_array("{$dw}", $weekdays)) { $datearr[] = 'DATE_FORMAT(`date`,"%Y-%m-%d")=' . $db->q($startdate->format('Y-m-d')); } $startdate = $startdate->add(new DateInterval('P1D')); } if (count($datearr) > 0) { $str = implode(' OR ', $datearr); $query = $db->getQuery(true); $query->delete('#__bookpro_transport_rate')->where('transport_id=' . $transport_id); $query->where('(' . $str . ')'); //var_dump($query->dump());die; $db->setQuery($query); $db->execute(); } $db->transactionCommit(); $mainframe->enqueueMessage('Saved successful'); } catch (Exception $e) { $db->transactionRollback(); JErrorPage::render($e); $mainframe->enqueueMessage($e->getMessage()); } $this->setRedirect('index.php?option=com_bookpro&view=packagerate&transport_id=' . $transport_id); }
/** * display an error page with an error message describing what happened * * @param string message the error message * @param string code the error code if any * @param string email the email address to notify of this situation * * @return void * @static * @acess public */ static function fatal($message = NULL, $code = NULL, $email = NULL) { $vars = array('message' => $message, 'code' => $code); if (self::$modeException) { // CRM-11043 CRM_Core_Error::debug_var('Fatal Error Details', $vars); CRM_Core_Error::backtrace('backTrace', TRUE); $details = 'A fatal error was triggered'; if ($message) { $details .= ': ' . $message; } throw new Exception($details, $code); } if (!$message) { $message = ts('We experienced an unexpected error. Please post a detailed description and the backtrace on the CiviCRM forums: %1', array(1 => 'http://forum.civicrm.org/')); } if (php_sapi_name() == "cli") { print "Sorry. A non-recoverable error has occurred.\n{$message} \n{$code}\n{$email}\n\n"; debug_print_backtrace(); die("\n"); // FIXME: Why doesn't this call abend()? // Difference: abend() will cleanup transaction and (via civiExit) store session state // self::abend(CRM_Core_Error::FATAL_ERROR); } $config = CRM_Core_Config::singleton(); if ($config->fatalErrorHandler && function_exists($config->fatalErrorHandler)) { $name = $config->fatalErrorHandler; $ret = $name($vars); if ($ret) { // the call has been successfully handled // so we just exit self::abend(CRM_Core_Error::FATAL_ERROR); } } // If we are in an ajax callback, format output appropriately if (CRM_Utils_Array::value('snippet', $_REQUEST) === CRM_Core_Smarty::PRINT_JSON) { $out = array('status' => 'fatal', 'content' => '<div class="messages status no-popup"><div class="icon inform-icon"></div>' . ts('Sorry but we are not able to provide this at the moment.') . '</div>'); if ($config->backtrace && CRM_Core_Permission::check('view debug output')) { $out['backtrace'] = self::parseBacktrace(debug_backtrace()); $message .= '<p><em>See console for backtrace</em></p>'; } CRM_Core_Session::setStatus($message, ts('Sorry an Error Occured'), 'error'); CRM_Core_Transaction::forceRollbackIfEnabled(); CRM_Core_Page_AJAX::returnJsonResponse($out); } if ($config->backtrace) { self::backtrace(); } $template = CRM_Core_Smarty::singleton(); $template->assign($vars); CRM_Core_Error::debug_var('Fatal Error Details', $vars); CRM_Core_Error::backtrace('backTrace', TRUE); $content = $template->fetch($config->fatalErrorTemplate); // JErrorPage exists only in 3.x and not 2.x // CRM-13714 if ($config->userFramework == 'Joomla' && class_exists('JErrorPage')) { $error = new Exception($content); JErrorPage::render($error); } else { if ($config->userFramework == 'Joomla' && class_exists('JError')) { JError::raiseError('CiviCRM-001', $content); } else { echo CRM_Utils_System::theme($content); } } self::abend(CRM_Core_Error::FATAL_ERROR); }
/** * display an error page with an error message describing what happened * * @param string message the error message * @param string code the error code if any * @param string email the email address to notify of this situation * * @return void * @static * @acess public */ static function fatal($message = NULL, $code = NULL, $email = NULL) { $vars = array('message' => $message, 'code' => $code); if (self::$modeException) { // CRM-11043 CRM_Core_Error::debug_var('Fatal Error Details', $vars); CRM_Core_Error::backtrace('backTrace', TRUE); $details = 'A fatal error was triggered'; if ($message) { $details .= ': ' . $message; } throw new Exception($details, $code); } if (!$message) { $message = ts('We experienced an unexpected error. Please post a detailed description and the backtrace on the CiviCRM forums: %1', array(1 => 'http://forum.civicrm.org/')); } if (php_sapi_name() == "cli") { print "Sorry. A non-recoverable error has occurred.\n{$message} \n{$code}\n{$email}\n\n"; debug_print_backtrace(); die("\n"); // FIXME: Why doesn't this call abend()? // Difference: abend() will cleanup transaction and (via civiExit) store session state // self::abend(CRM_Core_Error::FATAL_ERROR); } $config = CRM_Core_Config::singleton(); if ($config->fatalErrorHandler && function_exists($config->fatalErrorHandler)) { $name = $config->fatalErrorHandler; $ret = $name($vars); if ($ret) { // the call has been successfully handled // so we just exit self::abend(CRM_Core_Error::FATAL_ERROR); } } if ($config->backtrace) { self::backtrace(); } $template = CRM_Core_Smarty::singleton(); $template->assign($vars); CRM_Core_Error::debug_var('Fatal Error Details', $vars); CRM_Core_Error::backtrace('backTrace', TRUE); $content = $template->fetch($config->fatalErrorTemplate); // JErrorPage exists only in 3.x and not 2.x // CRM-13714 if ($config->userFramework == 'Joomla' && class_exists('JErrorPage')) { $error = new Exception($content); JErrorPage::render($error); } else { if ($config->userFramework == 'Joomla' && class_exists('JError')) { JError::raiseError('CiviCRM-001', $content); } else { echo CRM_Utils_System::theme($content); } } self::abend(CRM_Core_Error::FATAL_ERROR); }