Error 404 WP Ajax Request - ajax

I was working on creating a WP plugin that will load other plugins only on specific URL. These plugins are deactivate in WP admin plugins, and are only loaded when a specific page is accessed.
Within my plugin's Class construct function:
$uri = $_SERVER['REQUEST_URI'];
$exp = explode('/', $uri);
$uri = $exp[2];
$options = get_option( $this->plugin_name );
$key = array_search( '/'.$uri.'/', array_column($options, 'url') );
$plugin_dir = $options[$key]['plugin']; // this prints plugin file directory ex. /MyPlugin/myplugin.php
include( WP_PLUGIN_DIR . $plugin_dir);
Above code loads the plugin on specific URL/page. Meaning the variable $plugin_dir grabbed the correct directory. BUT, problem occur when there's an AJAX request from that plugin. Ex. when i try to delete an item using ajax request, it returns Error 404 Bad request.
Weird part is, almost same code above, but this time, i manually assign the plugin directory to a variable: ex.
$uri = $_SERVER['REQUEST_URI'];
$exp = explode('/', $uri);
$uri = $exp[2];
$options = get_option( $this->plugin_name );
$key = array_search( '/'.$uri.'/', array_column($options, 'url') );
$plugin_dir = '/MyPlugin/myplugin.php'; // manually place the plugin file dir
//same output as $plugin_dir = $options[$key]['plugin'];
include( WP_PLUGIN_DIR . $plugin_dir);
But this time, plugin works really well. No Ajax bad request error.
What could be the possible explanation for this? Is there any solution about this issue, so that i can dynamically get the plugin file directory from wp options based on the Request URI.
Also, another issue. Instead of REQUEST URI, i wanted to get the POST/PAGE ID instead, but everything returns NULL/empty. Still inside the construct function, i tried different approach to get the page ID:
global $post;
var_dump($post->ID); //returns NULL
global $wp_query;
var_dump($wp_query->post->ID); //returns NULL
echo get_the_ID(); //returns empty/NULL
Is there a way how to properly get the POST/PAGE details, or even just the ID?
Thank you.

Related

Laravel 5 - Route not available in notFoundHttpException

Currently I'm experiencing an error I find hard to fix. The error concerns the \Request::route() returning NULL when the notFoundHttpException is fired and my custom error view is rendered.
The problem is that my application needs the current route in order to do a variety of things. I think it is "normal" that ..::route() returns NULL since the route does not exists.
This is where I show my custom error view:
// App\Exceptions\Handler
return response()->view('layouts.default', [
'main_content' => view('errors.'.$e->getStatusCode())
], $e->getStatusCode());
When I call \Request::route() inside my view it returns NULL.
Anyone has any idea how to solve this in a clean way?
Edit
The application I am currently working on is a multi domain system. The route is needed to determine what domain is currently requested.
All routes are wrapped inside one group:
Route::group(['domain' => {domain}.{tld}], function()
{
// Application routes...
}
To determine the domain:
$domain = \Request::route()->domain;
$tld = \Request::route()->tld;
// Retrieve from database...
Yes there are work arounds like:
// Url requested: mydomain.com/notexistingpage
$url_parameters = #explode(".", $_SERVER['HTTP_HOST']);
$domain = $url_parameters[0];
$tld = $url_parameters[1];
// Retrieve from database...
However I would like to keep using the router to serve the parameters. I'll mark this question as answered.
Try this
\Route::getFacadeRoot()->current()->uri();
or
\Route::getCurrentRoute();
A work around could be:
// Url requested: mydomain.com/notexistingpage
$url_parameters = #explode(".", $_SERVER['HTTP_HOST']);
$domain = $url_parameters[0];
$tld = $url_parameters[1];
// Retrieve from database...

Displaying in back end component the parameters of module(s) and saving them through component

Hi i kinda found the way to display the modules in the component but i am wondering how could i save the parameters through component i mean editing the values in component and saving it.
The modules names and paramaters are known in advance. So the calling will be like this
jimport( 'joomla.application.module.helper' );
$module = &JModuleHelper::getModule( "ModuleName");
$params = new JParameter($module->params);
The purpose of doing so is to ease editing certain values for the customer so it is a pain for a newbie to browse all that joomla stuff(in my case).
All in all cant figure out, how to save the params of a module(s)
Hi this is the code to save the params of a component, module or plugin in Joomla.
It first loads the current params, makes its changes, then saves again; ensure you always load the current params first.
$mparams = JComponentHelper::getParams( 'com_littlehelper' );
$params = $mparams->get('params');
$mparams->set('params.favicons_sourcepath','icons');
$this->saveParams($mparams, $this->componentName);
private function saveParams($params, $extensionName, $type='component') {
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->update('#__extensions AS a');
$query->set('a.params = ' . $db->quote((string)$params));
$query->where(sprintf('a.element = %s AND a.%s = %s',
$db->quote($extensionName),
$db->quoteName('type'),
$db->quote($type)
));
$db->setQuery($query);
return $db->execute();
}
This code comes from my extension LittleHelper published on the JED.

Ask, how to use redirect without contition?

i have codes like this
function download(){
$id = $this->uri->segment(3);
$dat = $this->mikland->gidiklanfoto($id);
foreach ($dat as $item){
$name = $item->foto;
$data = file_get_contents(base_url()."/uploads/".$name); // filenya
force_download($name,$data);
}
redirect('cikland/viewiklan/'.$id);
}
when the function are running, redirect cannot run.,
somebody can help??
i think is a simple thing but i dont know the trick., thank's before
At the end of force_download() there is an exit() statement, so no code after a forced download will run.
And you are trying to have several files downloaded at the same time - using some sort of multipart mime type, that might or might not work, but not in the given case, because CI's force_download() does not seem to support that.
An alternative to that would be creating a temporary archive file which contains all the files for download; please have a look at the official documentation on compression and archives for that.
If you'd want to send a redirection header along with the file, you'd have to do it like this:
function download(){
// add this somewhere befor the download
header('Location: '.site_url('cikland/viewiklan/'.$id));
$id = $this->uri->segment(3);
$dat = $this->mikland->gidiklanfoto($id);
// only first item is downloaded
foreach ($dat as $item)
{
$name = $item->foto;
$data = file_get_contents(base_url()."/uploads/".$name); // filenya
force_download($name,$data);
}
}
But the question would remain how the browsers would deal with a redirect and content: most likely you would only get the redirect.
You need load url helper.
$this->load->helper('url');
after
redirect("cikland/viewiklan/$id", 'refresh');
or
redirect("cikland/viewiklan/$id", 'location', 301);
Font: http://ellislab.com/codeigniter%20/user-guide/helpers/url_helper.html
redirect() method redirects to a URL. You need to pass it a full URL (as it uses the header() function which according to the RFC for HTTP1.1 requires a full URL.
so you need to hard code the full url like the given example - redirect('http://www.yoursite.com/cikland/viewiklan/'.$id);

Calling controllers dynamically

I'm attempting to create dynamic routing in Laravel for my controllers - I know this can be done in Kohana, but I've been unsuccessful trying to get it working with Laravel.
This is what I have right now:
Route::get('/{controller}/{action?}/{id?}'...
So I would like to call controller/method($id) with that.
Ideally this is what I would like to do:
Route::get('/{controller}/{action?}/{id?}', $controller . '#' . $action);
And have it dynamically call $controller::$action.
I've tried doing this:
Route::get('/{controller}/{action?}/{id?}', function($controller, $action = null, $id = null)
{
$controller = new $controller();
$controller->$action();
});
But I get an error message: Class Controller does not exist.
So it appears that Laravel is not including all the necessary files when the controller extends the BaseController.
If I use $controller::$action() it tells me I can't call a non-static function statically.
Any ideas for how to make this work?
You can auto register all controllers in one fell swoop:
Route::controller( Controller::detect() );
If you're using Laravel 4 (as your tag implies), you can't use Controller::detect() anymore. You'll have to manually register all the controllers you want to use.
After reading that Laravel doesn’t support this anymore, I came up with this solution:
$uri = $_SERVER['REQUEST_URI'];
$results = array();
preg_match('#^\/(\w+)?\/?(\w+)?\/?(\w+)?\/?#', $_SERVER['REQUEST_URI'], $results);
// set the default controller to landing
$controller = (empty($results[1])) ? 'landing' : $results[1];
// set the default method to index
$method = (empty($results[2])) ? 'index' : $results[2];
Route::get('{controller?}/{action?}/{id?}', $controller . '#' . $method);
// now we just need to catch and process the error if no controller#method exists.

Codeigniter global_xss_filtering

In my codeigniter config I have $config['global_xss_filtering'] = TRUE;. In my admin section I have a ckeditor which generates the frontend content.
Everything that is typed and placed inside the editor works fine, images are displayed nice, html is working. All except flash. Whenever I switch to html mode and paste a youtube code piece it is escaped and the code is visible on the frontpage instead of showing a youtube movie.
If I set $config['global_xss_filtering'] = FALSE; the youtube code is passed like it should. This is because 'object', 'embed' etc are flagged as "naughty" by CI and thus escaped.
How can I bypass the xss filtering for this one controller method?
Turn it off by default then enable it for places that really need it.
For example, I have it turned off for all my controllers, then enable it for comments, pages, etc.
One thing you can do is create a MY_Input (or MY_Security in CI 2) like the one in PyroCMS and override the xss_clean method with an exact copy, minus the object|embed| part of the regex.
http://github.com/pyrocms/pyrocms/blob/master/system/pyrocms/libraries/MY_Security.php
It's one hell of a long way around, but it works.
Perhaps we could create a config option could be created listing the bad elements for 2.0?
My case was that I wanted global_xss_filtering to be on by default but sometimes I needed the $_POST (pst you can do this to any global php array e.g. $_GET...) data to be raw as send from the browser, so my solution was to:
open index.php in root folder of the project
added the following line of code $unsanitized_post = $_POST; after $application_folder = 'application'; (line #92)
then whenever I needed the raw $_POST I would do the following:
global $unsanitized_post;
print_r($unsanitized_post);
In CodeIgniter 2.0 the best thing to do is to override the xss_clean on the core CI library, using MY_Security.php put this on application/core folder then using /application/config.php
$config['xss_exclude_uris'] = array('controller/method');
here's the MY_Security.php https://gist.github.com/slick2/39f54a5310e29c5a8387:
<?php
/**
* CodeIgniter version 2
* Note: Put this on your application/core folder
*/
class MY_Security extends CI_Security {
/**
* Method: __construct();
* magic
*/
function __construct()
{
parent::__construct();
}
function xss_clean($str, $is_image = FALSE)
{
$bypass = FALSE;
/**
* By pass controllers set in /application/config/config.php
* config.php
* $config['xss_exclude_uris'] = array('controller/method')
*/
$config = new CI_Config;
$uri = new CI_URI;
$uri->_fetch_uri_string();
$uri->_explode_segments();
$controllers_list = $config->item('xss_exclude_uris');
// we need controller class and method only
if (!empty($controllers_list))
{
$segments = array(0 => NULL, 1 => NULL);
$segments = $uri->segment_array();
if (!empty($segments))
{
if (!empty($segments[1]))
{
$action = $segments[0] . '/' . $segments[1];
}
else
{
$action = $segments[0];
}
if (in_array($action, $controllers_list))
{
$bypass = TRUE;
}
}
// we unset the variable
unset($config);
unset($uri);
}
if ($bypass)
{
return $str;
}
else
{
return parent::xss_clean($str, $is_image);
}
}
}
Simple do the following on the views when displaying embedded object code like from YouTube and etc:
echo str_replace(array('<', '>'), array('<', '>'), $embed_filed);
The global XSS Filtering is only escaping (or converting) certain "dangerous" html tags like <html>
Simple Workaround:
Set $config['global_xss_filtering'] = TRUE;
Run your POST data through HTMLPurifier to remove any nasty <script> tags or javascript.
HTMLPurifier Docs
HTMLPurifier Codeigniter Integration
On the page where you receive the forms POST data use html_entity_decode() to undo what XSS filtering did.
//by decoding first, we remove everything that XSS filter did
//then we encode all characters equally.
$content = html_entity_decode($this->input->post('template_content'))
Then immediately run it through htmlentities()
$content = htmlentities($content);
Store as a Blob in MySQL database
When you want to display the
information to the user for editing run html_entity_decode()
This is how I did it. If anyone knows of a major flaw in what I did, please tell me. It seems to be working fine for me. Haven't had any unexpected errors.

Resources