I'm new to moodle plugin development and am trying to create a plugin that displays a page to the admin where I can add my on php code.
In brief, what I want the plugin to do I have already achieved in a standard php file that I upload to the moodle root. From here you can call the file e.g. yourdomain.co.uk/moodlelocation/myfile.php and it will run as expected.
The problem with this is it isn't secure since anyone can load the myfile.php and in turn run the scripts on the page. It also means any one else using this script (it will be given away for free when complete) would need to FTP into their hosting and upload two php files to their moodle install.
Due to this, I thought a plugin (a very very basic plugin) may be the best solution. They could then load the page in the admin via the "site administration". e.g. site administration > Development > MyPlugin. I am assuming I could then also restrict the plugin's main page to admins only (??).
So to recap, I can create a php page that has my script all rocking and rolling BUT I need to make this into a plugin.
I did some reading and I think a "local" plugin was the easiest way to go (??).
I have managed to get the local plugin up and running using the below in local/webguides/inex.php :
<?php
// Standard config file and local library.
require_once(__DIR__ . '/../../config.php');
// Setting up the page.
$PAGE->set_context(context_system::instance());
$PAGE->set_pagelayout('standard');
$PAGE->set_title("webguides");
$PAGE->set_heading("webguides");
$PAGE->set_url(new moodle_url('/local/webguides/index.php'));
// Ouput the page header.
echo $OUTPUT->header();
echo 'MY php CODE here etc';
?>
This works fine but with two problems:
Anyone can access it via http://domain/local/webguides/index.php
There is no link to it in the site administration (so the user would need to type the URL in).
Can anyone shed any light how I would achieve the two steps above?
Thanks in advance
p.s. ideally I'd like to keep the plugin to as few files as possible so if the required code could be added to the local/webguides/index.php file it would be preferred.
You need to create a capability, then require that capability before displaying the page.
First, have a look at local/readme.txt - this gives an overview of the files needed for a local plugin.
Or read the documentation at https://docs.moodle.org/dev/Local_plugins
Also have a look at existing local plugins so you can see how they are created - https://moodle.org/plugins/?q=type:local
At a bare minimum, you need
local/webguides/db/access.php - this will have the capability
local/webguides/lang/en/local_webguides.php
local/webguides/version.php
Plus your index file
local/webguides/index.php
In the db/access.php file have something like
defined('MOODLE_INTERNAL') || die();
$capabilities = array(
'local/webguides:view' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_SYSTEM,
'archetypes' => array(
),
),
);
You might also need 'riskbitmask' => RISK_XXX depending on if there are any risks in you code. Such as RISK_CONFIG, RISK_PERSONAL, etc.
In lang/en/local_webguides.php have something like
defined('MOODLE_INTERNAL') || die();
$string['pluginname'] = 'Webguides';
$string['webguides:view'] = 'Able to view webguids';
In version.php have something like
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2020051901; // The current plugin version (Date: YYYYMMDDXX)
$plugin->requires = 2015051109; // Requires this Moodle version.
$plugin->component = 'local_webguides'; // Full name of the plugin (used for diagnostics).
Replace 2015051109 with the version of Moodle you are using - this will be in version.php in the root folder.
Then in your index.php file use this near the top.
require_capability('local/webguides:view', context_system::instance());
So only users with that capability will have access to the page.
EDIT:
You can add a link via settings.php using something like
defined('MOODLE_INTERNAL') || die;
if ($hassiteconfig) {
$page = new admin_externalpage(
'local_webguides',
get_string('pluginname', 'local_webguides'),
new moodle_url('/local/webguides/index.php'),
'local/webguides:view'
);
$ADMIN->add('localplugins', $page);
}
Then in your index page ad this
require_once($CFG->libdir.'/adminlib.php');
and remove require_login() and require_capability() and replace with
admin_externalpage_setup('local_webguides');
Related
On our website at www.EllasBubbles.com, we are using a functions.php script to execute an alternative stylesheet to users who are outside of U.S/Canada. This script is as follows:
// [International] - Dark Mode
add_action( 'wp_head' , 'custom_inline_css', 200 );
function custom_inline_css() {
// Get an instance of the WC_Geolocation object class
$geolocation_instance = new WC_Geolocation();
// Get user IP
$user_ip_address = $geolocation_instance->get_ip_address();
// Get geolocated user IP country code.
$user_geolocation = $geolocation_instance->geolocate_ip( $user_ip_address );
// For all countries except 'US'
if($user_geolocation['country'] !== 'US' && $user_geolocation['country'] !== 'CA'){
?>
<style>
<?php include 'international.php'; ?>
</style>
<?php
}
}
We use cloud flare to manage our Cache. I have properly setup bypass rules for these two files:
ellasbubbles.com/wp-content/themes/flatsome/international.php
ellasbubbles.com/wp-content/themes/flatsome/assets/css/flatsome.css
When loading the site from an international VPN, the "Dark Mode" (Outside U.S/Canada) version is displayed. However, when disabling the VPN; we are stuck on Dark Mode. Which is a bypassed file with Cloudflare Cache - and simply makes no sense to me.
This leads me to believe that the instance of the WC_Geolocation class is being cached somewhere on the Wordpress website. I have searched everywhere for a solution, and can not determine the best way to perform this custom CSS per country. Can we disable caching from function custom_inline_css ? Should I change international.php to css? Is there a better way to go about this?
Update 1: When I disabled caching from the entire website in cloud flare, this works fine!
Update 2: When I disable caching from everything inside ellasbubbles.com/wp-content/*; this still does not work properly..what file am I missing?
Update 3: I disabled all folders one by one to no avail
Please help me help everyone
I am trying to read/write my configuration in the DokuWiki.
The problem that occurs is when I am trying to call $this->getConf('url'); I always get the response from the conf/default.php file.
This is how my files look like:
admin.php
$url = $this->getConf('url');
conf/default.php
$conf['url'] = 'https://www.example.com';
conf/metadata.php
$meta['url'] = array('string', 'url' => 'https://correct-url.com');
And the value of $url always is:
https://www.example.com
I am not sure what I do wrong.
Thanks!
You may have some misunderstanding to DokuWiki's config system.
The config, which is editable by users, will be saved at /conf/local.php (not inside plugins!). The plugin can only provide a default value at default.php, while the metadata.php is to define how the value is shown on the frontend settings manager.
In your case, the correct URL will be shown, if the DokuWiki global config file (/conf/local.php for example) includes $conf["your_plugin_name"]["url"] = "https://correct-url.com";.
For more: https://www.dokuwiki.org/devel:configuration
We are using wordpress for blogs (hosted via Godaddy). I am not a wordpress developer and hence this basic question. We have the wordpress post api like blog.domainname.com/wp-json/wp/v2/posts. This returns a json object of most of the fields. Now i have added a custom field to be returned with this object. i have seen lot of videos and study on what changes that needs to be done especially the one here.
https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/
My Question is - Where do I make these changes? What file do I need add these changes? I am using WP as an admin. I installed a File Explorer plugin and I am able to see three main folders - wp-admin, wp-content, wp-includes.
Is there a particular file i need to make changes? Based on my learning - i wrote the following snippet. not sure where to add this :(
function addCustomField_register_fields() {
register_rest_field('post',
'custom_Field_name',
array(
'get_callback' =>'get_custom_field',
'update_callback' => null,
'schema' => null
));
}
function get_custom_field($object, $field_name , $request) {
return get_post('custom_field');
}
add_action('rest_api_init', 'addCustomField_register_fields');
Also would appreciate if you can let me know if my method is correct.
Typically theme customisations are added to the functions.php file in the root directory of your active theme.
As for your code, what are you trying to do? Your callback in particular doesn't look like it will work. get_post() loads a WordPress post by ID. 'custom_field' isn't a valid post ID, so this will always fail.
hi i have a custom script that I call with ajax to retrieve some db info but for some reason it will not allow me to make the calls from this file. yet when i put the code in a page in the templates diretory lets say tpl_products_all_default.php they run fine. what do i need to do to be able to run queries from a custom script?
$sql = "select products_model from products where products_model = :productMdel:";
$sql = $db->bindVars($sql, ':productMdel:', 'C021', 'string');
$result = $db->Execute($sql);
if ($result->RecordCount() > 0) {
echo 'Model number = ' . $result->fields['products_model'];
} else {
echo 'Sorry, no record found for product number ' . $theProductId;
}
I may have an answer for you, though I'll admit it's not an optimal setup as it requires your custom file to be placed into the root directory.
If your custom file is being placed in the root (/your_custom_file.php) you can do the following to get access to the $db with the following require statement:
require('includes/application_top.php');
This will initialize all of the globals, and also call the includes/initsystem.php, which will spin through the values in the autoloader and include each script. The auto_loader can be viewed at includes/auto_loaders/config.core.php. In v1.5, you can see it finally includes the init_database.php script on lines 81-82. The init_database.php file finally initializes $db.
I initially ran into the same issue you had, and almost missed this setup because I had originally added my custom files to a custom directory like /my_module_extensions/my_file.php which failed. It seems the application_top.php loads everything with relative paths, so when executing under a directory other than the root, it would fail.
I hope this helps!
EDIT: Originally thought you were talking about an admin customization. I reworded this to relate to the public side. This also works from the admin side, if you need to extend the admin console.
Not true you can use an include from anywhere.
such as:
require_once('inc/php/application_top.php');
or
require_once('http://example.com/inc/php/application_top.php');
I was going to update the ecommerce plugin (Shopp) on my wordpress site and it asked me to deactivate it. once I did that I lost the entire site.
I am trying to activate the plugin through the php files, but not sure what I am doing and would like some help.
Does anyone know how I can activate the Shopp plugin (or any plugin for that matter) on my site through the php files?
This is the code I'm using to get the string:
$unserialized = unserialize('a:14:{i:0;s:19:"akismet/akismet.php";i:1;s:37:"breadcrumbs-plus/breadcrumbs-plus.php";i:2;s:35:"googleanalytics/googleanalytics.php";i:3;s:45:"grunion-contact-form/grunion-contact-form.php";i:4;s:43:"image-caption-links/image-caption-links.php";i:5;s:29:"image-widget/image-widget.php";i:6;s:13:"rate/rate.php";i:7;s:33:"restore-jquery/restore-jquery.php";i:8;s:41:"shopp-cache-helper/shopp-cache-helper.php";i:9;s:47:"shopp-default-breadcrumb-extender-sdbe/sdbe.php";i:10;s:33:"shopp-improved/shopp-improved.php";i:11;s:19:"shuffle/shuffle.php";i:12;s:19:"vslider/vslider.php";i:13;s:41:"wordpress-importer/wordpress-importer.php";}');
array_push($unserialized, 'shopp/shopp.php');
$serialized = serialize($unserialize);
echo $serialized;
The active plugins are not stored in a PHP file. It's stored in the database. Open the wp_options table in the database. Look for a row in which the value of the option_name field is active_plugins. In this row, look for the value of option_value. You'll see a serialized string containing the information of the active plugins.
Now, it might be a little bit confusing to edit the string straight away especially if you're not familiar how serialized strings are formatted. So, I suggest you copy the string and use PHP unserialize() function on it, which will then return an array. After that, use array_push() to add another element in which the value is the path to the plugins file (e.g. "akismet/akismet.php", in your case it might be "shopp/shopp.php"). Once you've add another element, use serialize() and copy the returned string and replace the old serialized string in the database.
$unserialized = unserialize('...');
array_push($unserialized, 'shopp/shopp.php');
$serialized = serialize($unserialized);
echo $serialized; // Copy this output back into the database
There are details on this site about how to programmatically activate and deactivate a plugin. Here is a snippet:
function toggle_plugin() {
// Full path to WordPress from the root
$wordpress_path = '/full/path/to/wordpress/';
// Absolute path to plugins dir
$plugin_path = $wordpress_path.'wp-content/plugins/';
// Absolute path to your specific plugin
$my_plugin = $plugin_path.'my_plugin/my_plugin.php';
// Check to see if plugin is already active
if(is_plugin_active($my_plugin)) {
// Deactivate plugin
// Note that deactivate_plugins() will also take an
// array of plugin paths as a parameter instead of
// just a single string.
deactivate_plugins($my_plugin);
}
else {
// Activate plugin
activate_plugin($my_plugin);
}
}
For everyone who has a plugin acting weird
The easiest way to regain access to your site when being locked out after deactivating, activating, installing, updating a plugin is:
Go to your webhost adminpanel (Cpanel, DirectAdmin)
Go to Files (Filemanager)
Go to //wp-content/ and rename your "plugins" folder to something else for instance "plugins_off"
Go to your WP-admin. You will have access again but no plugins visible.
Go back to your webhost adminpanel and rename "plugins_off" back to "plugins".
Now your plugins will all be listed again in WP-admin, but all deactivated.
Take it from there.
There is no need to add PHP code.
Like RST wrote: No need for coding to restore site that crashed after you deactivate a plugin. There's a good reason the site crashed because other plugins depended on that deactivated plugin (like WooCommerce).
The easiest way to restore the site and gain access to WP admin is simply to rename the plugins folder, refresh the page, go back and rename the folder back to "plugins" then hit refresh again. All plugins will be back as before only they are all deactivated. Now all you need to do is to activate them again. Do it one by one to be sure nothing else crashes.
Here is working code
(just uncomment "activate" line):
function MY_toggle_plugins() {
include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
$temp_files1 = glob(WP_PLUGIN_DIR.'/*');
$activated=array();
$already_active=array();
foreach($temp_files1 as $file1){
if(is_dir($file1)) {
$temp_files2 = glob($file1 . '/*');
foreach($temp_files2 as $file2){
if(is_file($file2) && stripos(file_get_contents($file2),'Plugin Name:')!==false) {
$plugin_name_full=basename(dirname($file2)).'/'.basename($file2);
if(is_plugin_active($plugin_name_full)) {
array_push($already_active, $plugin_name_full);
//deactivate_plugins($plugin_name_full);
}
else{
array_push($activated, $plugin_name_full);
//activate_plugin($plugin_name_full);
}
}
}
}
}
echo 'You have activated these plugins:<br/><br/>'.serialize($activated).'<br/><br/>These were already active:<br/><br/>'.serialize($already_active); exit;
}
//execute
MY_toggle_plugins();