How to detect wrong URL using Joomla! System Plugin? - plugins

I have developed a Joomla! system plugin.
I would like to detect wrong URL when that plugin is executed.
For example:
If I enter a URL "http://localhost/wrong-url", I want to catch that error in the system plugin.
How do I know that the system will display the error page (404)?

You can do this using the following technique
Check URL Function
function checkURL($URL){
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpcode != 200) {
return false;
}else{
return true;
}
}
Use Of the CheckURL Function
/*URL May be a Joomla OR Non Joomla Site*/
if(checkURL("http://adidac.github.com/jmm/index.html")){
echo "URL Exist";
}else{
echo "URL NOT Exist";
//JError::raiseWarning(500,$URL. " is not exists");
}
if(checkURL("http://adidac.github.com/jmm/indexsdadssdasaasdaas.html")){
echo "URL Exist";
}else{
echo "URL NOT Exist";
//JError::raiseWarning(500,$URL. " is not exists");
}
NOTE: Check you have PHP curl lib installed

In a system plugin to trap the 404 you would have to add a function from your plugin as a callback to JError error handler array.
I would have a look at the way com_redirect does it, with it's system plugin. e.g.
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'));
}
static function handleError(&$error)
{
// Get the application object.
$app = JFactory::getApplication();
// Make sure we are not in the administrator and it's a 404.
if (!$app->isAdmin() and ($error->getCode() == 404))
{
// Do cool stuff here
}
}
The only problem is JError is depreciated so I'm not sure going forward when this would break e.g. it should be fine in 3.0, 3.1, 3.2 and 3.5 but after that who knows?

I know this is an old question, but I needed a solution today and found this question, so leaving my solution below to help anyone else searching in the future.
In the plugin file:
/**
* The global exception handler registered before the plugin was instantiated
*
* #var callable
* #since 3.6
*/
private static $previousExceptionHandler;
/**
* 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);
// Register the previously defined exception handler so we can forward errors to it
self::$previousExceptionHandler = set_exception_handler(array('PlgSystemVmsreporting', 'handleException'));
}
public static function handleException($exception) {
// Wrap in try/catch to prevent any further exceptions being raised
try {
// Do whatever you need with the error
} catch (Exception $e) {
//Don't make a fuss - fail silently
}
// Proxy to the previous exception handler if available, otherwise use the default Joomla handler
if (self::$previousExceptionHandler) {
call_user_func_array(self::$previousExceptionHandler, array($exception));
} else {
ExceptionHandler::render($exception);
}
}

Related

Upgrade from TYPO3 9 to 10 - Fatal Error in Upgrade Wizard with no extensions enabled

I just upgraded my TYPO3 v9 to v10.04.27 and now i get an error in the Upgrade Wizard
(1/1) Error
Class 'TYPO3\CMS\Core\Cache\Frontend\StringFrontend' not found in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Cache/CacheManager.php line 351
As you can see in the path i also tried already with an older TYPO3 10 Version.
I disabled all extensions before the upgrade. Except the ones that cant be disabled.
So this should be a completely clean TYPO3 10 install (except the Config Files).
I dont know what i can do about this.
Here is the Full Trace:
Something went wrong. Please use Check for broken extensions to see if a loaded extension breaks this part of the install tool and unload it.
The box below may additionally reveal further details on what went wrong depending on your debug settings. It may help to temporarily switch to debug mode using Settings > Configuration Presets > Debug settings.
If this error happens at an early state and no full exception back trace is shown, it may also help to manually increase debugging output in typo3conf/LocalConfiguration.php:['BE']['debug'] => true, ['SYS']['devIPmask'] => '*', ['SYS']['displayErrors'] => 1,['SYS']['exceptionalErrors'] => 12290
Ajax error
Whoops, looks like something went wrong.
(1/1) Error
Class 'TYPO3\CMS\Core\Cache\Frontend\StringFrontend' not found
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Cache/CacheManager.php line 351
$backendInstance->initializeObject();
}
// New used on purpose, see comment above
$frontendInstance = new $frontend($identifier, $backendInstance);
if (!$frontendInstance instanceof FrontendInterface) {
throw new InvalidCacheException('"' . $frontend . '" is not a valid cache frontend object.', 1464550984);
}
if (is_callable([$frontendInstance, 'initializeObject'])) {
at TYPO3\CMS\Core\Cache\CacheManager->createCache()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Cache/CacheManager.php line 157
if ($this->hasCache($identifier) === false) {
throw new NoSuchCacheException('A cache with identifier "' . $identifier . '" does not exist.', 1203699034);
}
if (!isset($this->caches[$identifier])) {
$this->createCache($identifier);
}
return $this->caches[$identifier];
}
at TYPO3\CMS\Core\Cache\CacheManager->getCache()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Cache/DatabaseSchemaService.php line 51
$cacheManager->setCacheConfigurations($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']);
$tableDefinitions = '';
foreach ($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations'] as $cacheName => $_) {
$backend = $cacheManager->getCache($cacheName)->getBackend();
if (method_exists($backend, 'getTableDefinitions')) {
$tableDefinitions .= LF . $backend->getTableDefinitions();
}
}
at TYPO3\CMS\Core\Cache\DatabaseSchemaService->getCachingFrameworkRequiredDatabaseSchema()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Cache/DatabaseSchemaService.php line 33
* #param AlterTableDefinitionStatementsEvent $event
*/
public function addCachingFrameworkDatabaseSchema(AlterTableDefinitionStatementsEvent $event): void
{
$event->addSqlData($this->getCachingFrameworkRequiredDatabaseSchema());
}
/**
* Get schema SQL of required cache framework tables.
at TYPO3\CMS\Core\Cache\DatabaseSchemaService->addCachingFrameworkDatabaseSchema()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/EventDispatcher/EventDispatcher.php line 51
if ($event instanceof StoppableEventInterface && $event->isPropagationStopped()) {
return $event;
}
foreach ($this->listenerProvider->getListenersForEvent($event) as $listener) {
$listener($event);
if ($event instanceof StoppableEventInterface && $event->isPropagationStopped()) {
break;
}
}
at TYPO3\CMS\Core\EventDispatcher\EventDispatcher->dispatch()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Database/Schema/SqlReader.php line 75
}
}
/** #var AlterTableDefinitionStatementsEvent $event */
$event = $this->eventDispatcher->dispatch(new AlterTableDefinitionStatementsEvent($sqlString));
$sqlString = $event->getSqlData();
return implode(LF . LF, $sqlString);
}
at TYPO3\CMS\Core\Database\Schema\SqlReader->getTablesDefinitionString()
in /srv/typo3_src-10.4.20/typo3/sysext/install/Classes/Service/UpgradeWizardsService.php line 156
*/
public function getBlockingDatabaseAdds(): array
{
$sqlReader = GeneralUtility::makeInstance(SqlReader::class);
$databaseDefinitions = $sqlReader->getCreateTableStatementArray($sqlReader->getTablesDefinitionString());
$schemaMigrator = GeneralUtility::makeInstance(SchemaMigrator::class);
$databaseDifferences = $schemaMigrator->getSchemaDiffs($databaseDefinitions);
at TYPO3\CMS\Install\Service\UpgradeWizardsService->getBlockingDatabaseAdds()
in /srv/typo3_src-10.4.20/typo3/sysext/install/Classes/Controller/UpgradeController.php line 1042
$this->lateBootService->loadExtLocalconfDatabaseAndExtTables(false);
$adds = [];
$needsUpdate = false;
try {
$adds = $this->upgradeWizardsService->getBlockingDatabaseAdds();
$this->lateBootService->resetGlobalContainer();
if (!empty($adds)) {
$needsUpdate = true;
}
at TYPO3\CMS\Install\Controller\UpgradeController->upgradeWizardsBlockingDatabaseAddsAction()
in /srv/typo3_src-10.4.20/typo3/sysext/install/Classes/Middleware/Maintenance.php line 246
'Unknown action method ' . $action . ' in controller ' . $controllerName,
1505216027
);
}
$response = $controller->$action($request);
}
return $response;
}
at TYPO3\CMS\Install\Middleware\Maintenance->process()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Http/MiddlewareDispatcher.php line 121
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->middleware->process($request, $this->next);
}
};
}
at class#anonymous/srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Http/MiddlewareDispatcher.php:103$bc->handle()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Middleware/NormalizedParamsAttribute.php line 45
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$request = $request->withAttribute('normalizedParams', NormalizedParams::createFromRequest($request));
return $handler->handle($request);
}
}
at TYPO3\CMS\Core\Middleware\NormalizedParamsAttribute->process()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Http/MiddlewareDispatcher.php line 172
if (!$middleware instanceof MiddlewareInterface) {
throw new \InvalidArgumentException(get_class($middleware) . ' does not implement ' . MiddlewareInterface::class, 1516821342);
}
return $middleware->process($request, $this->next);
}
};
}
}
at class#anonymous/srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Http/MiddlewareDispatcher.php:138$bd->handle()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Http/MiddlewareDispatcher.php line 78
* #return ResponseInterface
*/
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->tip->handle($request);
}
/**
* Seed the middleware stack with the inner request handler
at TYPO3\CMS\Core\Http\MiddlewareDispatcher->handle()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Http/AbstractApplication.php line 85
* #return ResponseInterface
*/
protected function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->requestHandler->handle($request);
}
/**
* Set up the application and shut it down afterwards
at TYPO3\CMS\Core\Http\AbstractApplication->handle()
in /srv/typo3_src-10.4.20/typo3/sysext/install/Classes/Http/Application.php line 52
protected function handle(ServerRequestInterface $request): ResponseInterface
{
$this->initializeContext();
$request = $request->withAttribute('applicationType', SystemEnvironmentBuilder::REQUESTTYPE_INSTALL);
return parent::handle($request)
->withHeader('X-Frame-Options', 'SAMEORIGIN');
}
/**
at TYPO3\CMS\Install\Http\Application->handle()
in /srv/typo3_src-10.4.20/typo3/sysext/core/Classes/Http/AbstractApplication.php line 97
final public function run(callable $execute = null)
{
try {
$response = $this->handle(
ServerRequestFactory::fromGlobals()
);
if ($execute !== null) {
call_user_func($execute);
}
at TYPO3\CMS\Core\Http\AbstractApplication->run()
in /srv/typo3_src-10.4.20/typo3/install.php line 105
call_user_func(function () {
$classLoader = require dirname(__DIR__).'/vendor/autoload.php';
\TYPO3\CMS\Core\Core\SystemEnvironmentBuilder::run(1, \TYPO3\CMS\Core\Core\SystemEnvironmentBuilder::REQUESTTYPE_INSTALL);
\TYPO3\CMS\Core\Core\Bootstrap::init($classLoader, true)->get(\TYPO3\CMS\Install\Http\Application::class)->run();
});
at {closure}()
in /srv/typo3_src-10.4.20/typo3/install.php line 106
call_user_func(function () {
$classLoader = require dirname(__DIR__).'/vendor/autoload.php';
\TYPO3\CMS\Core\Core\SystemEnvironmentBuilder::run(1, \TYPO3\CMS\Core\Core\SystemEnvironmentBuilder::REQUESTTYPE_INSTALL);
\TYPO3\CMS\Core\Core\Bootstrap::init($classLoader, true)->get(\TYPO3\CMS\Install\Http\Application::class)->run();
});
Any ideas?
Thank you in advance
Delete all extensions except the ones from TYPO3 core. Then cache will be rebuild without not needed classes.
I had some errors in my installations if extension are only deactivated but not deleted.
My guess is that you're using the StringFrontend somewhere, which was deprecated in TYPO3 9.2.
Can you check your LocalConfiguration.php and AdditionalConfiguration.php if you find "StringFrontend" anywhere and replace it with VariableFrontend or remove it completely? (as suggested in the migration path)

ZF2 application - Dispatch error event triggered every time

I'am working on a Zend Framework 2 application and have a strange behavior concerning error handling. My code in Module.php:
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$eventManager->attach(\Zend\Mvc\MvcEvent::EVENT_ROUTE, [$this, 'onPreRoute'], 100);
$eventManager->attach(\Zend\Mvc\MvcEvent::EVENT_DISPATCH_ERROR, [$this, 'handleError']);
}
public function onPreRoute(MvcEvent $e)
{
$serviceManager = $e->getTarget()->getServiceManager();
$router = $serviceManager->get('router');
$router->setTranslator($serviceManager->get('translator'));
}
public function handleError(MvcEvent $e)
{
$error = $e->getParam('error');
file_put_contents('error.log', $error . PHP_EOL, FILE_APPEND);
switch($error) {
case 'error-router-no-match':
$router = $e->getRouter();
$url = $router->assemble([], ['name' => 'home']);
header('Location: ' . $url);
exit;
}
}
As you can see I'am translating the routes. This works fine. But on every request the dispatch error event is triggered too. The error.log file will be created every time. But the redirect will be only performed if the route doesn't really exist. I think it depends on the translator or is my code in Module.php not correct?
Resolved!
The reason was that the browser automatically requests /favicon.ico and that was not available :-)

Zend Framework: Paypal

I have been attempting to implement a paypal functionality into my application by following the example here: http://www.alexventure.com/2011/04/02/zend-framework-and-paypal-api-part-2-of-2/
This is my paymentAction in my controller.
public function paymentAction()
{
$auth= Zend_Auth::getInstance();
$user= $auth->getIdentity();
$username = $user->username;
$cart = new Application_Model_DbTable_Cart();
$select = $cart->select()
->from(array('c' => 'cart'))
->join(array('p' => 'product'), 'p.productid = c.productid')
->where('username = ?', $username)
->setIntegrityCheck(false);
$fetch = $cart->fetchAll($select)->toArray();
$paypal = new My_Paypal_Client;
$amount = 0.0;
foreach($fetch as $item) {
$amount = $amount + ($item['price']*$item['quantity']);
}
$returnURL = 'http://www.google.com';
$cancelURL = 'http://www.yahoo.com';
$currency_code = 'USD';
$reply = $paypal->ecSetExpressCheckout(
$amount,
$returnURL,
$cancelURL,
$currency_code
);
if ($reply->isSuccessfull())
{
$replyData = $paypal->parse($reply->getBody());
if ($replyData->ACK == 'SUCCESS' || $replyData->ACK == 'SUCCESSWITHWARNING')
{
$token = $replyData->TOKEN;
$_SESSION['CHECKOUT_AMOUNT'] = $amount;
header(
'Location: ' .
$paypal->api_expresscheckout_uri .
'?&cmd=_express-checkout&token=' . $token
);
}
}
else
{
throw new Exception('ECSetExpressCheckout: We failed to get a successfull response from PayPal.');
}
}
However, this is the error that returns.
Message: No valid URI has been passed to the client
Where did i go wrong? I would be happy to provide code from other areas of my application if needed. Thanks.
Zend_Http_Client::request() has not received a valid instance of Zend_Uri_Http.
Here's where the error occurs:
/**
* Send the HTTP request and return an HTTP response object
*
* #param string $method
* #return Zend_Http_Response
* #throws Zend_Http_Client_Exception
*/
public function request($method = null)
{
if (! $this->uri instanceof Zend_Uri_Http) {
/** #see Zend_Http_Client_Exception */
require_once 'Zend/Http/Client/Exception.php';
throw new Zend_Http_Client_Exception('No valid URI has been passed to the client');//Note the exact message.
}//Truncated
The only obvious error I see in the code you provided is :
$paypal = new My_Paypal_Client;//no () at end of declaration
I hope you implemented part one of the tutorial where the constructor is built. Otherwise you may just need to pass a better uri.
[EDIT]
I think your problem is here:
//needs a uri value for Zend_Http_Client to construct
$paypal = new My_Paypal_Client($url);
ecSetExpressCheckout does not construct the http client so it has no idea of where it's requesting the token from.
Alternatively you could just add this line below $paypal and above $reply:
//pass the uri required to construct Zend_Http_Client
$paypal->setUri($url);
I just hope you know what the url shouild be.
Good Luck.

open_basedir restriction in effect. File() is not within the allowed path(s) and Uncaught CurlException: 3: No URL set! thrown in base_facebook.php

protected function makeRequest($url, $params, $ch=null) {
if (!$ch) {
$ch = curl_init();
}
$opts = self::$CURL_OPTS;
if ($this->useFileUploadSupport()) {
$opts[CURLOPT_POSTFIELDS] = $params;
} else {
$opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
}
$opts[CURLOPT_URL] = $url;
// disable the 'Expect: 100-continue' behaviour. This causes CURL to wait
// for 2 seconds if the server does not support this header.
if (isset($opts[CURLOPT_HTTPHEADER])) {
$existing_headers = $opts[CURLOPT_HTTPHEADER];
$existing_headers[] = 'Expect:';
$opts[CURLOPT_HTTPHEADER] = $existing_headers;
} else {
$opts[CURLOPT_HTTPHEADER] = array('Expect:');
}
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
if (curl_errno($ch) == 60) { // CURLE_SSL_CACERT
self::errorLog('Invalid or no certificate authority found, '.
'using bundled information');
curl_setopt($ch, CURLOPT_CAINFO,
dirname(__FILE__) . '/fb_ca_chain_bundle.crt');
$result = curl_exec($ch);
}
if ($result === false) {
$e = new FacebookApiException(array(
'error_code' => curl_errno($ch),
'error' => array(
'message' => curl_error($ch),
'type' => 'CurlException',
),
));
curl_close($ch);
throw $e;
}
curl_close($ch);
return $result;
}
I have built a facebook app, but something went wrong in this piece of code of base_facebook.php.
Whole code is here. All i get everytime are this 2 errors -
1.Warning: curl_setopt_array() [function.curl-setopt-array]: open_basedir restriction in effect. File() is not within the allowed path(s): (/home/:/usr/lib/php:/tmp) in /home/a2424901/public_html/base_facebook.php on line 802
2.Uncaught CurlException: 3: No URL set! thrown in /home/a2424901/public_html/base_facebook.php on line 814
Here is the code of my facebook app i.e.(index.php)
Yeap, non-obvious error message.
But it means, that realpath() returns empty value:
File() is not within the allowed path(s)...
Make sure, that the file passed to realpath() function really exists in the specified path.
Other exceptions in your example were caused by this problem.
By the way, it's good practice to wrap all weak spots (in your example - Facebook API calls) in try-catch blocks.

Sending a SOAP message with PHP

what I'm trying to do is send a load of values captured from a form to a CRM system with SOAP and PHP. I've been reading up on SOAP for a while and I don't understand how to go about doing so, does anybody else know?
In order to do this it might be easiest to download a simple soap toolkit like 'NuSOAP' from sourceforge.
And then you would code something like the following (example submission of ISBN number):
<?php
// include the SOAP classes
require_once('nusoap.php');
// define parameter array (ISBN number)
$param = array('isbn'=>'0385503954');
// define path to server application
$serverpath ='http://services.xmethods.net:80/soap/servlet/rpcrouter';
//define method namespace
$namespace="urn:xmethods-BNPriceCheck";
// create client object
$client = new soapclient($serverpath);
// make the call
$price = $client->call('getPrice',$param,$namespace);
// if a fault occurred, output error info
if (isset($fault)) {
print "Error: ". $fault;
}
else if ($price == -1) {
print "The book is not in the database.";
} else {
// otherwise output the result
print "The price of book number ". $param[isbn] ." is $". $price;
}
// kill object
unset($client);
?>
This code snippet was taken directly from, which is also a good resource to view
http://developer.apple.com/internet/webservices/soapphp.html
Hope this helps.
You probably found a solution since then - but maybe the following helps someone else browsing for this:
soap-server.php:
<?php
class MySoapServer {
public function getMessage ()
{
return "Hello world!";
}
public function add ($n1,$n2)
{
return $n1+n2;
}
}
$option = array ('uri' => 'http://example.org/stacky/soap-server');
$server = new SoapServer(null,$option);
$server->setClass('MySoapServer');
$server->handle();
?>
and soap-client.php
<?php
$options = array ('uri' => 'http://example.org/stacky/soap-server',
'location' => 'http://localhost/soap-server.php');
$client = new SoapClient(null,$options);
echo $client ->getMessage();
echo "<br>";
echo $client ->add(41,1);
?>