Protect wordpress theme with license key validation - wordpress

I'm planning to develop some professional Wordpress Themes and would like to protect it using license keys, is it possible?
If so, would any one be willing to link to some posts or articles to help me get started?

You could set up a database on your own server, holding the license key and the licensed url for the theme. Then, set up an admin page for your theme. Within, first register a license settings array. Then implement a hidden settings field on that same page that gets updated whenever the license key is being updated by site admin. the update function sends a request to your server passing the license key and the $_SERVER's host and setting the hidden license_settings field to either true or false.
A really simplified code would look like this:
functions.php
<?php
// functions.php
require("myadminpage.php");
# Functions follow here...
?>
myadminpage.php
<?php
// myadminpage.php
// register settings
function my_settings_init() {
register_setting('settings_license', 'settings_license');
}
// register admin page
function my_add_admin_page() {
add_menu_page(__( '' ), __( 'Manage License' ), 'administrator', 'myadminpage', 'my_admin_page');
}
add_action('admin_init', 'my_settings_init');
add_action('admin_menu', 'my_add_admin_page' );
if(isset($_GET["settings-updated"]) && $_GET["settings-updated"] == true) {
$options = get_option('settings_license');
$key = $options["key"];
$host = parse_url($GLOBALS['HTTP_SERVER_VARS']['REQUEST_URI'], PHP_URL_HOST);
$url = sprintf("http://you.com/check-license.php?key=%s&url=%s", $key, $host);
$options["valid"] = trim(file_get_contents($url)) == 1) ? "true" : "false";
update_option('settings_license', $options);
}
// callback function that renders your admin page
function my_admin_page() {
settings_fields('settings_license');
$options = get_option('settings_license');
?>
<form method="post" action="options.php">
<input id="settings_license[key]" type="text" name="settings_license[key]" value="<?php echo $options["key"]; ?>">
<input id="settings_license[valid]" type="hidden" name="settings_license[valid]" value="<?php echo $options["valid"]; ?>">
<input type="submit" value="Save">
</form>
<?php
}
?>
Now you can, when ever you need/want, get the license options and handle the invalid usage in any way you want. Eg (a rude way):
header.php
<?php
// very first line
$license = get_option('settings_license');
// see: http://ckon.wordpress.com/2006/08/09/server-request_uri-doesnt-always-work-correctly-heres-how-to-fix/
$ruri = $GLOBALS['HTTP_SERVER_VARS']['REQUEST_URI'];
if(!preg_match("#wp-admin#", $ruri) && $license["valid"] != "true") {
wp_die( __('This website uses unlicensed software.<br>Administrators can update their license key here.') );
}
# rest of header.php comes here..
Finally obfuscate your php code (eg http://www.ioncube.com/sa_encoder.php) and you're done. However, make sure you're not violating any other licenses, such as WP's. If there's one single line of WordPress core functions used within your final code, you can not release it under any other license than WP, which is GPL.

I don't think so. After all, the users must have the php code to use the theme and if they have it - they may alter it in a such way that it won't need a key any more.

Related

Add custom product field on quick edit option on the product listing of a woocommerce site

How can I add custom product field/s on quick edit screen on the product listing of a woocommerce store?
I am not really sure if this is the best way to do it, but it works great for me
Basically my general goal is to add custom fields for a product, I managed to do it (Adding custom fields to the single product pages) with the help of these useful tuts.
http://www.remicorson.com/mastering-woocommerce-products-custom-fields/
http://www.remicorson.com/woocommerce-custom-fields-for-variations/
I recommend checking those links first before proceeding.
Now, what I wanted to do is to add those custom fields to the quick add option on the product listing.
That's where the resource get scarce.
Basically this is how I did it.
Add your custom field (the html forms) to the quick edit options.
I hooked into the 'woocommerce_product_quick_edit_end' action to accomplish this.
This hook is found on woocommerce->includes->admin->views->html-quick-edit-product.php on line 195
Save your custom field.
I hooked into the 'woocommerce_product_quick_edit_save' action to accomplish this.
This hook is found on woocommerce->includes->admin->class-wc-admin-post-types.php inside the 'quick_edit_save' function on line 929
The previous 2 steps does the trick, it does persist the values, however after updating the custom field via the quick edit option, the data is persisted on the backend, but is not populated to the custom field on the UI. That's why we need the 3rd step.
Add the custom field meta data inside the product listing column, then use js to extract the metadata out then populate it to the custom field
I hooked into the 'manage_product_posts_custom_column' action to add a custom HTML tags (div or whatever) to hold my custom field metadata
Then I used javascript to extract the data out from the meta data and populate it into the custom fields
Step 3 is just a copy of how WooCommerce does this process.
For referrence, take a look at function 'render_product_columns' of woocommerce->includes->admin->class-wc-admin-post-types.php
Also take a look at quick-edit.js located at woocommerce->assets->js->admin
Example Code:
Note that the code below is used for illustration and guide purposes, my actual code is quite long and complex.
Step 1:
add_action( 'woocommerce_product_quick_edit_end', function(){
/*
Notes:
Take a look at the name of the text field, '_custom_field_demo', that is the name of the custom field, basically its just a post meta
The value of the text field is blank, it is intentional
*/
?>
<div class="custom_field_demo">
<label class="alignleft">
<div class="title"><?php _e('Custom Field Demo', 'woocommerce' ); ?></div>
<input type="text" name="_custom_field_demo" class="text" placeholder="<?php _e( 'Custom Field Demo', 'woocommerce' ); ?>" value="">
</label>
</div>
<?php
} );
Step 2:
add_action('woocommerce_product_quick_edit_save', function($product){
/*
Notes:
$_REQUEST['_custom_field_demo'] -> the custom field we added above
Only save custom fields on quick edit option on appropriate product types (simple, etc..)
Custom fields are just post meta
*/
if ( $product->is_type('simple') || $product->is_type('external') ) {
$post_id = $product->id;
if ( isset( $_REQUEST['_custom_field_demo'] ) ) {
$customFieldDemo = trim(esc_attr( $_REQUEST['_custom_field_demo'] ));
// Do sanitation and Validation here
update_post_meta( $post_id, '_custom_field_demo', wc_clean( $customFieldDemo ) );
}
}
}, 10, 1);
Step 3:
add_action( 'manage_product_posts_custom_column', function($column,$post_id){
/*
Notes:
The 99 is just my OCD in action, I just want to make sure this callback gets executed after WooCommerce's
*/
switch ( $column ) {
case 'name' :
?>
<div class="hidden custom_field_demo_inline" id="custom_field_demo_inline_<?php echo $post_id; ?>">
<div id="_custom_field_demo"><?php echo get_post_meta($post_id,'_custom_field_demo',true); ?></div>
</div>
<?php
break;
default :
break;
}
}, 99, 2);
The JS part
jQuery(function(){
jQuery('#the-list').on('click', '.editinline', function(){
/**
* Extract metadata and put it as the value for the custom field form
*/
inlineEditPost.revert();
var post_id = jQuery(this).closest('tr').attr('id');
post_id = post_id.replace("post-", "");
var $cfd_inline_data = jQuery('#custom_field_demo_inline_' + post_id),
$wc_inline_data = jQuery('#woocommerce_inline_' + post_id );
jQuery('input[name="_custom_field_demo"]', '.inline-edit-row').val($cfd_inline_data.find("#_custom_field_demo").text());
/**
* Only show custom field for appropriate types of products (simple)
*/
var product_type = $wc_inline_data.find('.product_type').text();
if (product_type=='simple' || product_type=='external') {
jQuery('.custom_field_demo', '.inline-edit-row').show();
} else {
jQuery('.custom_field_demo', '.inline-edit-row').hide();
}
});
});
Make sure to enqueue the script
Hope this helps anyone, again, I am not sure if this is the best way to do it, but upon examining WooCommerce source, it seems WooCommerce
doesn't provide a convenient hook to accomplish this task with ease (at least not yet)
If you have a better approach than this please share.

Wordpress: Add config option to all widget settings

In Wordpress, my goal is to be able to give a custom class to every widget that I put in the sidebar.
Preferably I would like to add this class in the widget settings of each widget. ALSO 3rd party widgets.
I was thinking of changing the classname, because the classname is already passed to the register_sidebar function (%2$s):
<?php
register_sidebar(array('before_widget' => '<aside id="%1$s" class="widget %2$s blue">'));
?>
Ofcourse I shouldn't change WP core code or 3rd party plugins. This means that I need to write a plugin that will hook into the widget configuration process.
I already found out that it's possible to modify all widgets forms, by hooking into action 'in_widget_form':
<?php
add_action('in_widget_form', 'teaserWidgetAddToForm');
function teaserWidgetAddToForm($widget_instance) {
?>
<label for="<?php echo $widget_instance->get_field_id('teaser-classname'); ?>">Custom classname(s):</label>
<input type="text" id="<?php echo $widget_instance->get_field_id('teaser-classname'); ?>" name="<?php echo $widget_instance->get_field_name('teaser-classname'); ?>">
<?php
}
?>
This data should be saved by the Widget super class, but how do you retrieve this data (so when opening the widget settings later shows what you filled in earlier)
And, this saved data should be put in the widget instance -how is this done? I guess by using something like:
<?php
$wp_registered_widgets[<widget_id>]['callback'][0]['widget_options']['classname'] = <chosen_class>;
?>
So basically I have 2 questions:
Am I using the proper way to address this problem (styling of individual widgets)
If so, how can I modify a widget instance to save and retrieve additional settings, without having to modify Wordpress or 3rd party Plugin source code.
By default each widget instance has a unique ID which can be used to style it.
In order to save data from fields added in an in_widget_form action, you need to also have a widget_update_callback filter.
function my_widget_update_callback($instance, $new_instance) {
$instance['my_classnames'] = $new_instance['my_classnames'];
return $instance;
}
To display the saved value in the form you'll need to first retrieve the instance settings.
function my_in_widget_form($instance) {
$settings = $instance->get_settings();
…
Finally, I think the simplest way to add your custom classes is in a widget_display_callback filter, which runs before a widget is displayed. You have to display the widget yourself because you can only return an instance from this filter, and instances do not control the widget CSS classes.
function my_widget_display_callback($instance, $widget, $args) {
if (!isset($instance['my_classnames'])) {
return $instance;
}
$widget_classname = $widget->widget_options['classname'];
$my_classnames = $instance['my_classnames'];
$args['before_widget'] = str_replace($widget_classname, "{$widget_classname} {$my_classnames}", $args['before_widget']);
$widget->widget($args, $instance);
return false;
}
See this article for more info on the available hooks related to widgets: http://shibashake.com/wordpress-theme/wordpress-widget-system

WordPress Plugin: Call function on button click in admin panel

I need to create a WordPress plugin that calls a PHP function when a button in an admin panel is clicked. I've been looking at tutorials for writing basic WordPress plugins and adding admin panels but I still don't understand how exactly to register a button to a specific function in my plug-in.
Here's what I have so far:
/*
Plugin Name:
Plugin URI:
Description:
Author:
Version: 1.0
Author URI:
*/
add_action('admin_menu', 'wc_plugin_menu');
function wc_plugin_menu(){
add_management_page('Title', 'MenuTitle', 'manage_options', 'wc-admin-menu', 'wc_plugin_options');
}
function wc_plugin_options(){
if (!current_user_can('manage_options')) {
wp_die( __('You do not have sufficient permissions to access this page.') );
}
echo '<div class="wrap">';
echo '<button>Call Function!</button>'; //add some type of hook to call function
echo '</div>';
}
function button_function()
{
//do some stuff
}
?>
Although the answers on this page provided a useful start, it took a while for me to figure out how to get option (2) working. Given this, the following code might be of help to some people.
If you create a plugin with the following code and it will add a left hand menu option called 'Test Button' when you are in the admin area. Click on this and you will see a button. Clicking that button runs the test_button_action function. In my example function I've both put a message on the page and written to a log file.
<?php
/*
Plugin Name: Example of Button on Admin Page
Plugin URI:
Description:
Author:
Version: 1.0
Author URI:
*/
add_action('admin_menu', 'test_button_menu');
function test_button_menu(){
add_menu_page('Test Button Page', 'Test Button', 'manage_options', 'test-button-slug', 'test_button_admin_page');
}
function test_button_admin_page() {
// This function creates the output for the admin page.
// It also checks the value of the $_POST variable to see whether
// there has been a form submission.
// The check_admin_referer is a WordPress function that does some security
// checking and is recommended good practice.
// General check for user permissions.
if (!current_user_can('manage_options')) {
wp_die( __('You do not have sufficient pilchards to access this page.') );
}
// Start building the page
echo '<div class="wrap">';
echo '<h2>Test Button Demo</h2>';
// Check whether the button has been pressed AND also check the nonce
if (isset($_POST['test_button']) && check_admin_referer('test_button_clicked')) {
// the button has been pressed AND we've passed the security check
test_button_action();
}
echo '<form action="options-general.php?page=test-button-slug" method="post">';
// this is a WordPress security feature - see: https://codex.wordpress.org/WordPress_Nonces
wp_nonce_field('test_button_clicked');
echo '<input type="hidden" value="true" name="test_button" />';
submit_button('Call Function');
echo '</form>';
echo '</div>';
}
function test_button_action()
{
echo '<div id="message" class="updated fade"><p>'
.'The "Call Function" button was clicked.' . '</p></div>';
$path = WP_TEMP_DIR . '/test-button-log.txt';
$handle = fopen($path,"w");
if ($handle == false) {
echo '<p>Could not write the log file to the temporary directory: ' . $path . '</p>';
}
else {
echo '<p>Log of button click written to: ' . $path . '</p>';
fwrite ($handle , "Call Function button clicked on: " . date("D j M Y H:i:s", time()));
fclose ($handle);
}
}
?>
Well, you have two options.
1) Use AJAX to create an admin-ajax hook that you execute with JavaScript when the user clicks the button. You can learn about that approach here: http://codex.wordpress.org/AJAX (make sure to add a nonce for security ( http://codex.wordpress.org/WordPress_Nonces )). This is also a good resource for creating admin-ajax hooks: http://codex.wordpress.org/AJAX_in_Plugins
2) Put the button in a form, POST that form to your plugin and add some code to handle the POST'd form (if you do this, make sure you include a nonce for security ( http://codex.wordpress.org/WordPress_Nonces ) and also make sure that the user trying to click the button has the right privileges to do so http://codex.wordpress.org/Function_Reference/current_user_can
What you're trying to do is not super-complex, but it does involve a good understanding of forms, PHP, and (maybe) JavaScript. If your JavaScript is ok, I'd recommend option 1, since it doesn't require the user to reload the page.

Submit To PDF in WordPress

Is there a plugin or something that creates PDF files from a entered by the user form data, when it clicks on the submit button?
if youre wanting a form filled in, then the details of that form processed and sent to you via email with a pdf attachment of the details, i had something similar a few weeks back, I couldnt find anything that would work the way i wanted, so....
I setup my form then using a custom page template I assigned that to a page, then using php and the html2pdf class i created my pdf which was emailed as an attachment...
heres the code i used..
been minified for this page (remember to sanitize your user input).
<?php
/*
Template Name: FORMTOPDF
*/
?>
<?php get_header(); ?>
<style>
/* STYLES FOR ERROR PLACEMENT */
label {
width: 80px;
text-align: right;
float: left;
}
.formerror {
border: 1px solid red;
background-color : #FFCCCC;
width: auto;
padding: 5px 0;
padding-left:10px;
}
.errortext {
font: bold smaller sans-serif;
}
</style>
<?php
// CREATE AN ARRAY FOR OUR ERRORS
$arrErrors = array();
// Check for FORM SUBMISSION
// using hidden form field
if(isset($_POST['action']) && ($_POST['action']=='send'))
{
/* ================= START FORM DATA ========================= */
$name = trim($_POST['name']);
if ($name=='') $arrErrors['name'] = 'Please provide your name.';
$email = trim($_POST['email']);
if ($email=='') $arrErrors['Email'] = 'Please provide your Email Address.';
$comments = trim($_POST['your-comments']);
if ($comments=='') $arrErrors['Comments'] = 'Please add your Comments.';
/* ================= END FORM DATA ========================= */
if (count($arrErrors) == 0) {
// Process form here
/* ================= START PDF CREATION ========================= */
$strContent = "<p>Submission from ".$name."</p>";
$strContent.= "<p><strong>Name</strong>:".$name."</p>";
$strContent.= "<p><strong>Email </strong>: ".$email."</p>";
$strContent.= "<p><strong>Comments</strong> : <br />".$comments."</p>";
/* ================= END PDF CREATION ========================= */
// Include our HTML to PDF creator
// FROM THEME DIRECTORY?
require(TEMPLATEPATH.'/html2pdf/html2fpdf.php');
$pdf=new HTML2FPDF();
$pdf->AddPage();
// folder location of HTML file
$fileLocation = "wp-content/uploads/";
// Call to the file name from the URL
$fileName = "Form_Submission_From_".$name;
// add the location 'wp-content/uploads/' to the fileToOpen
$fileToOpen = $fileLocation;
// Then add the actual file name // form_submission.pdf
// output should look like 'wp-content/uploads/form_submission_from_(name).pdf'
$fileToOpen .= $fileName.".pdf";
// Open the file with read access
$fp = fopen($fileToOpen,"r");
//$strContent = fread($fp, filesize($fileToOpen));
// Close of the page
fclose($fp);
// Create new PDF document from the Content
$pdf->WriteHTML($strContent);
// create our PDF in the wp uploads folder
$pdf->Output("wp-content/uploads/" .$fileName. ".pdf");
/* ================= END PDF ========================= */
/* ================= START EMAIL ========================= */
$headers= "From: YourWebsite <info#yourwebsite.co.uk>\r\n\\";
$emailSubject = "Submission from " . $name;
$emailAdmin = "admin#yourwebsite.co.uk";
$emailMessage = "Submission from ".$yourcompanyname."\n\n";
$emailMessage.= "Company Name: ".$yourcompanyname."\n";
$emailMessage.= "Email : ".$email."\n";
$emailMessage.= "Comments : \n".$comments."\n\n";
$attachments = array(WP_CONTENT_DIR ."/uploads/".$fileName.".pdf", $target_path);
wp_mail($emailAdmin, $emailSubject, $emailMessage, $headers, $attachments);
// Delete our PDF from the server after email Sent
// uncomment this to delete after email sent?
//unlink($fileToOpen);
/* ================= END EMAIL ========================= */
// show thank you message if successful
$strGood = '<div class="formerror" style="background:#FFC;">
<h2>Thank You</h2>
<p>Thank you for contacting us.</p>
</div>';
}else{
// The error array had something in it. There was an error.
// Start adding error text to an error string.
$strError = '<div class="formerror"><p><img style="margin-left:10px;" src="'.get_option('home').'/wp-content/themes/mytheme/media/images/triangle_error.gif" width="16" height="16" hspace="5" alt=""><strong>Please check the following and try again:</strong></p><ul style="margin-left:50px;">';
// Get each error and add it to the error string
// as a list item.
foreach ($arrErrors as $error) {
$strError .= "<li style='list-style-type:circle;'><em>$error</em></li>";
}
$strError .= '</ul></div><br />';
}
}// NOT BEEN SUBMITTED
// show regular page with form
?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div class="post" id="post-<?php the_ID(); ?>">
<h2>
<?php the_title(); ?>
</h2>
<?php
// show errors if there is any
echo $strError;
?>
<?php
// show thank you if successful
echo $strGood;
?>
<?php the_content('<p>Read the rest of this page »</p>'); ?>
<form method="post" action="<?php bloginfo('url');?>/your-form-page/" enctype="multipart/form-data">
<input type="hidden" value="send" name="action">
<p <?php if (!empty($arrErrors['name'])) echo ' class="formerror"'; ?>>Your Name:
<span class="errortext" style="color:#F00;">(required)</span><br>
The rest of the form below here ------ >
</form>
<?php endwhile; endif; ?>
<?php get_footer(); ?>
thats it, once the user fills out the form, (my form had a lot more fields than this plus an upload field for files to be attached also.)
but the forms submitted, checks for required fields, if successful it will create a pdf file from the $strContent variable, then attaches this to the email to be sent using the wp_mail from wordpress.. then displays a thank you message, or else it will show and highlight any errors,
hope this helps..
I found these plugins that allow posts to be emailed or downloaded as pdf's.
http://wordpress.org/extend/plugins/tags/create-pdf
If you are flexible, It seems possible to programmatically create posts from your form submitted by a user, then create a pdf of that post. The posts that are created from the form could easily be assigned a particular category which is not displayed on the site.
To programmatically create, update, and delete posts, see the WordPress Function Reference, and in particular:
wp_insert_post
wp update post
wp delete post
A quick google search exhibits plenty of ways to create pdf's with php. Some hard, some less hard. I found this class that might get you started: "FPDF"
There is a plugin extension called Gravity PDF, that extends from Gravity Forms. It will generate a PDF from a form, and you can choose to download or email it.
Source
https://wordpress.org/plugins/gravity-forms-pdf-extended/
I haven't done an exhaustive search of the WP-plugins, but from as far as I can tell the answer is no. Of course, it would be possible to create such a plugin from scratch however the server hosting WP would need to have the proper libraries installed in order for the plugin to be useful.
We created a custom solution for one of our clients to get this done since there weren't any ready available plugins. This system creates pdf/word documents by fetching data from Gravity Forms.
You can check out details of the solution here. Gravity Forms to PDF/Word Document Auto-Fill Soluion

How do I get a list of items in the Wordpress media library on a plugin options page?

I'm writing a Wordpress plugin which injects a grid of images just above the footer on all frontend pages. The application is to display sponsor's logos. I'd like to harness the WP Media Library since the logos are already uploaded for use on the 'sponsorship' page and in posts.
Essentially I'm stuck at accessing the media library interface on the plugin's options page. All of the legwork is done in terms of creating the options page, using the action hook to place content on frontend pages from the plugin, etc. What I need now is to be able to display all the files in the media library in a list on the options page, and provide a checkbox or something to allow the user to select certain files for insertion above the footer.
The Media Library API seems to be aimed at people writing themes or media plugins. Help understanding what to make use of would be great!
I think you'd be much better off adding your own column into the existing media library, rather than try re-coding it yourself;
function my_media_col($cols)
{
$cols['my_col'] = 'Footer';
return $cols;
}
add_filter('manage_media_columns', 'my_media_col');
function handle_my_media_col($name, $id)
{
if ($name !== 'my_col')
return false;
$in_footer = get_option('in_footer', array());
?>
<input type="checkbox" name="in_footer[]" value="<?php echo $id; ?>" <?php checked(in_array($id, $in_footer)); ?> />
<?php
}
add_action('manage_media_custom_column', 'handle_my_media_col', 10, 2);
Then just hook onto the load-upload.php (the library page) and save changes when POST'ed;
function save_my_col()
{
if (!isset($_POST['in_footer']))
return false;
$in_footer = $_POST['in_footer'];
if (is_array($in_footer))
$in_footer = array_map('absint', $in_footer); // sanitize
else
$in_footer = array();
$in_footer = array_merge(get_option('in_footer', array()), $in_footer);
$in_footer = array_unique(array_filter($in_footer));
update_option('in_footer', $in_footer);
}
add_action('load-upload.php', 'save_my_col');
Note this is just an example, and I may have one or two typos.
UPDATED:
My code example should store an array of IDs in the options table, under the key 'in_footer'.
Put in practice, you can get all media items marked 'in footer' like so;
$query = new WP_Query(array('post__in' => get_option('in_footer', array()) ));
if ($query->have_posts()): while ($query->have_posts()): $query->the_post();
?>
<?php the_title(); ?>
<?php endwhile; endif; ?>

Resources