Process uploaded file in Wordpress plugin development - php

I'm building my first WP plugin. Basically I should upload a CSV file and then read it values to store in a table at Wordpress DB. After read a lot of docs I follow this steps:
Create two files frequent-traveler.php where all the logic resides and ft_admin.php where the view part is.
This is the code I have in frequent-traveler.php:
// Create database tables and some others
function frequent_traveler_activation()
{
}
register_activation_hook(__FILE__, 'frequent_traveler_activation');
// Deletes database tables and some others
function frequent_traveler_deactivation()
{
}
register_deactivation_hook(__FILE__, 'frequent_traveler_deactivation');
function frequent_traveler_admin_actions()
{
add_options_page("Frequent Traveler Configuration", "Frequent Traveler Config", 'manage_options', "ftconfig", "frequent_traveler_admin");
}
add_action('admin_menu', 'frequent_traveler_admin_actions');
function frequent_traveler_admin()
{
include('ft_admin.php');
}
if (!empty($_POST) && isset($_POST['uploadfile_btn']) && check_admin_referer('name_of_my_action', 'wpnf_ft')) {
echo "entre";
}
else {
echo "Error";
}
And this is the code at ft_admin.php:
<?php
wp_enqueue_script('jquery-ui-datepicker');
wp_enqueue_style('jquery-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css');
?>
<div class="wrap">
<?php echo "<h2>" . __('Frequent Traveler Configuration') . "</h2>"; ?>
<form name="frequent_traveler_form" method="post" action="<?php echo str_replace('%7E', '~', $_SERVER['REQUEST_URI']); ?>">
<input type="hidden" name="frequent_traveler_hidden" value="Y">
<?php echo "<h4>" . __('Common Settings') . "</h4>"; ?>
<p>
<?php _e("Default Conversion Value: "); ?><input type="text" name="ft_default" value="<?php echo $ft_default; ?>" size="5">
<?php _e("From Date: "); ?><input type="text" id="frequent_traveler_from_date" name="frequent_traveler_from_date" value="<?php echo $frequent_traveler_from_date ?>" class="datepicker" />
<?php _e("To Date: "); ?><input type="text" id="frequent_traveler_to_date" name="frequent_traveler_to_date" value="<?php echo $frequent_traveler_to_date; ?>" class="datepicker" />
</p>
<input type="submit" class="button-primary" name="Submit" value="<?php _e('Save Values') ?>" />
</form>
<hr/>
<?php ?>
<h2><?php echo __('Upload file to import') ?></h2>
<form name="uploadfile" id="uploadfile_form" method="POST" enctype="multipart/form-data" action="<?php echo str_replace('%7E', '~', $_SERVER['REQUEST_URI']) . '/uploadfile'; ?>" accept-charset="utf-8" >
<?php wp_nonce_field('name_of_my_action', 'wpnf_ft'); ?>
<p><?php echo __('Select file to upload') ?><input type="file" name="uploadfiles[]" id="uploadfiles" size="35" class="uploadfiles" /><p>
<input class="button-primary" type="submit" name="uploadfile_btn" id="uploadfile_btn" value="<?php echo __('Upload & Process') ?>" />
</form>
</div>
<script>
jQuery(document).ready(function() {
jQuery('.datepicker').datepicker({
dateFormat: 'dd/mm/yy'
});
});
</script>
As you may notice I'm trying to validate the uploaded file with this code:
if (!empty($_POST) && isset($_POST['uploadfile_btn']) && check_admin_referer('name_of_my_action', 'wpnf_ft')) {
echo "entre";
}
else {
echo "Error";
}
But I get always Error, why is that? What I'm doing wrong? Which is the best way to handle uploaded files?

You should not leave the check for if (!empty($_POST) outside any function, it can go inside the admin_menu output.
Also, the form actions should be left empty, so it posts to the same plugin page.
The targeted enqueue can be done in a standard way too and note the shortcut for jQuery $:
add_action( 'admin_menu', 'frequent_traveler_admin_actions' );
add_action( 'admin_enqueue_scripts', 'admin_enqueue' );
function frequent_traveler_admin_actions()
{
$my_hook = add_options_page("Frequent Traveler Configuration", "Frequent Traveler Config", 'manage_options', "ftconfig", "frequent_traveler_admin");
//var_dump($my_hook); die();
}
function admin_enqueue( $hook )
{
if( 'settings_page_ftconfig' !== $hook )
return;
wp_enqueue_script('jquery-ui-datepicker');
wp_enqueue_style('jquery-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css');
}
function frequent_traveler_admin()
{
if (!empty($_POST) && isset($_POST['uploadfile_btn']) && check_admin_referer('name_of_my_action', 'wpnf_ft')) {
echo "<h1>entre</h1>";
}
else {
echo "<h1>Error</h1>";
}
$ft_default = '';
$frequent_traveler_from_date = '';
$frequent_traveler_to_date = '';
?>
<div class="wrap">
<?php echo "<h2>" . __('Frequent Traveler Configuration') . "</h2>"; ?>
<form name="frequent_traveler_form" method="post" action="">
<input type="hidden" name="frequent_traveler_hidden" value="Y">
<?php echo "<h4>" . __('Common Settings') . "</h4>"; ?>
<p>
<?php _e("Default Conversion Value: "); ?><input type="text" name="ft_default" value="<?php echo $ft_default; ?>" size="5">
<?php _e("From Date: "); ?><input type="text" id="frequent_traveler_from_date" name="frequent_traveler_from_date" value="<?php echo $frequent_traveler_from_date ?>" class="datepicker" />
<?php _e("To Date: "); ?><input type="text" id="frequent_traveler_to_date" name="frequent_traveler_to_date" value="<?php echo $frequent_traveler_to_date; ?>" class="datepicker" />
</p>
<input type="submit" class="button-primary" name="Submit" value="<?php _e('Save Values') ?>" />
</form>
<hr/>
<?php ?>
<h2><?php echo __('Upload file to import') ?></h2>
<form name="uploadfile" id="uploadfile_form" method="POST" enctype="multipart/form-data" action="" accept-charset="utf-8" >
<?php wp_nonce_field('name_of_my_action', 'wpnf_ft'); ?>
<p><?php echo __('Select file to upload') ?><input type="file" name="uploadfiles[]" id="uploadfiles" size="35" class="uploadfiles" /><p>
<input class="button-primary" type="submit" name="uploadfile_btn" id="uploadfile_btn" value="<?php echo __('Upload & Process') ?>" />
</form>
</div>
<script>
jQuery(document).ready(function($) {
$('.datepicker').datepicker({
dateFormat: 'dd/mm/yy'
});
});
</script>
<?php
}

Related

How to add/change fields dynamicaly in form from if else condition?

Here i have numerous input fields in a form, which are working perfectly. And now, i want to add new input boxes and their labels according to property_type , Which is already exist on this page.
Now, Kindly Suggest me How can i add new fields in that form.
Here is my Form Code
<div class="dashboard_price_left">
<h3>
<?php
if ($this->lang->line('BasePrice') != '') {
echo stripslashes($this->lang->line('BasePrice'));
} else
echo "Base Price";
?>
</h3>
<p>
<?php
if ($this->lang->line('Atitleandsummary') != '') {
echo stripslashes($this->lang->line('Atitleandsummary'));
} else
echo "Set weekly or monthly price guests will see for your listing.";
?>
</p>
</div>
<?php
if ($listDetail->row()->home_type == 'Office') {
} else if ($listDetail->row()->home_type == 'House') {
}
?>
<form id="pricelist" name="pricelist" action="site/product/savePriceList" method="post">
<div class="dashboard_price_right">
<label><?php
if ($this->lang->line('Pernight') != '') {
echo stripslashes($this->lang->line('Pernight'));
} else
echo "Per night";
?>
</label>
<div class="amoutnt-container">
<?php if ($currentCurrency == '') { ?>
<span class="WebRupee"><?php echo $currencyDetail->row()->currency_symbols; ?></span>
<?php } else { ?>
<span class="WebRupee"><?php echo $currentCurrency; ?></span>
<?php } ?>
<input type="text" id="price" value="<?php
if ($listDetail->row()->price != '0.00') {
echo intval($listDetail->row()->price);
}
?>" class="per_amount_scroll" name="price" onkeypress="return onlyNumbersWithDot(event);" onchange="javascript:Detailview(this,<?php echo $listDetail->row()->id; ?>, 'price');" />
<input type="hidden" id="id" name="id" value="<?php echo $listDetail->row()->id; ?>" />
</div>
<div class="dashboard_currency">
<label><?php
if ($this->lang->line('Currency') != '') {
echo stripslashes($this->lang->line('Currency'));
} else
echo "Currency";
?>
</label>
<div class="select select-large select-block">
<select name="currency" id="currency" onchange="javascript:Detailview(this,<?php echo $listDetail->row()->id; ?>, 'currency');get_currency_symbol(this)" >
<!--<option value="">select</option>-->
<?php foreach ($currencyDetail->result() as $currency) { ?>
<option value="<?php echo $currency->currency_type; ?>" <?php if ($listDetail->row()->currency == $currency->currency_type) echo 'selected="selected"'; ?>><?php echo $currency->currency_type; ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
</form>
Here is a pic of my Property prices form
Note: There are two types of property that are following:
1. Office
2. House
on the basis of these property, I want to add more fields in my form.
Please suggest me, Thanks in Advance :)
you can change it base on conditon and pass hidden field which indicates you office or house.
<?php
if ($listDetail->row()->home_type == 'Office')
{
<input type="hidden" name="home_type" value="Office" />
<input type="text" name="per_day" value="" />
<input type="text" name="half_day" value="" />
<input type="text" name="per_hour" value="" />
}
else if ($listDetail->row()->home_type == 'House')
{
<input type="hidden" name="home_type" value="House" />
<input type="text" name="per_night" value="" />
<input type="text" name="per_day" value="" />
<input type="text" name="per_hour" value="" />
}
?>

ddslick plugin: get value in wordpress

I have a choice menu in WordPress plug-in with ddslick . I want to pass the id of the selected option and send the form to a database , but the value is not saved although it appears within the html . When put into manual is well maintained.
<script type='text/javascript' src='http://g-page.co.il/wp-content/themes/g-page/js/jquery.ddslick.min.js'></script>
<div id="myDropdown">
<select id="demo-htmlselect">
<?php
$thumbnails = get_posts('numberposts=5');
foreach ($thumbnails as $thumbnail) {
$url = wp_get_attachment_url( get_post_thumbnail_id($thumbnail->ID) );
?>
<option value="<?php echo $thumbnail->ID;?>" data-imagesrc="<?php echo $url; ?>"
data-description="<?php echo $thumbnail->post_title;?>"><?php echo $thumbnail->post_title;?></option>
<?php } ?>
</select>
</div>
<?php
?>
<div class="wrap">
<form method="post" action="options.php">
<?php wp_nonce_field('update-options') ?>
<input type="text" name="main_art_id" size="45" value="<?php echo get_option('main_art_id'); ?>" />
</p>
<p><input type="submit" name="Submit" value="Store Options" /></p>
<input type="hidden" name="action" value="update" />
<input type="hidden" name="page_options" value="ain_art_id" />
</form>
</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#myDropdown').ddslick({
onSelected: function(selectedData){
var cor_val = selectedData['selectedData']['value'];
$("input[name=main_art_id]").val(cor_val);
}
});
});
</script>
<?php
}

How to restrict user to Upload only 3 images?

I'm creating a web app in Codeigniter. Here's the code in VIEW's.
<div class="bold light-gray">Add a photo or two!</div>
<p class="short">Or three, or more! Prospective Buyers love photos that highlight the features of your parts or gear.</p>
<form class="ajaxform" method="post" enctype="multipart/form-data" action='<?php echo site_url('UploadImage/upload_Image');?>'>
<input type="hidden" name="do" value="upload"/>
Upload your image <input type="file" name="Filedata" id="photo" onChange="abc()" />
<input type="hidden" name="timestamp" value="<?php echo $timestamp;?>" />
<input type="hidden" name="token" value="<?php echo md5('unique_salt' . $timestamp);?>" />
<input type="hidden" name="customer_id" value="<?php echo $customer['id'];?>" />
</form>
</div>
<!-- /.box.center -->
<?php echo form_open('/secure/add_item/'.$id, array('id'=>'listitem') ); ?>
<div id="img_cant"> <?php
if(isset($images) && !empty($images)) {
foreach($images as $key=>$img){
?>
<input type="hidden" value="<?php echo $img; ?>" name="images[]" id="hid_<?php echo $key; ?>">
<?php
}
}
?>
</div>
I want to allow the user to just add 3 or 4 images maximum. How to do that?
<?php $count=count($_FILES['name']);
if($count>3)
{
echo "Your error message";
}
else{
echo "your desired activity";
}?>
Using jquery you can call this function while submit your form
var file_nu = $("input:file")[0].files.length;
if(file_nu >3)//apply your condition here
{
return FALSE;
}else{
return TRUE;
}

JOMSOCIAL INVALID TOKEN ERROR

Evry time while logging in an error "INVALID TOKEN" its shown at the joomla2.5/jomsocial2.4 site, but after 2,3 refreshes it shows the profile page as logged in... why is it so.... Is it problem of Joomla... I have uninstalled a plugin alphauserpoints ... is that a problem.. or should i modify the code default.php
<?php
// no direct access
defined('_JEXEC') or die;
JHtml::_('behavior.keepalive');
?>
<?php if ($type == 'logout') : ?>
<form action="<?php echo JRoute::_('index.php', true, $params->get('usesecure')); ?>" method="post" id="login-form">
<?php if ($params->get('greeting')) : ?>
<div class="login-greeting">
<?php if($params->get('name') == 0) : {
echo JText::sprintf('MOD_LOGIN_HINAME', $user->get('name'));
} else : {
echo JText::sprintf('MOD_LOGIN_HINAME', $user->get('username'));
} endif; ?>
</div>
<?php endif; ?>
<div class="logout-button">
<input type="submit" name="Submit" class="button" value="<?php echo JText::_('JLOGOUT'); ?>" />
<input type="hidden" name="option" value="com_users" />
<input type="hidden" name="task" value="user.logout" />
<input type="hidden" name="return" value="<?php echo $return; ?>" />
<?php echo JHtml::_('form.token'); ?>
</div>
</form>
<?php else : ?>
<form action="<?php echo JRoute::_('index.php', true, $params->get('usesecure')); ?>" method="post" id="login-form" >
<?php if ($params->get('pretext')): ?>
<div class="pretext">
<p><?php echo $params->get('pretext'); ?></p>
</div>
<?php endif; ?>
<fieldset class="userdata">
<p id="form-login-username">
<label for="modlgn-username"><?php echo JText::_('MOD_LOGIN_VALUE_USERNAME') ?></label>
<input id="modlgn-username" type="text" name="username" class="inputbox" size="18" />
</p>
<p id="form-login-password">
<label for="modlgn-passwd"><?php echo JText::_('JGLOBAL_PASSWORD') ?></label>
<input id="modlgn-passwd" type="password" name="password" class="inputbox" size="18" />
</p>
<?php if (JPluginHelper::isEnabled('system', 'remember')) : ?>
<p id="form-login-remember">
<label for="modlgn-remember"><?php echo JText::_('MOD_LOGIN_REMEMBER_ME') ?></label>
<input id="modlgn-remember" type="checkbox" name="remember" class="inputbox" value="yes"/>
</p>
<?php endif; ?>
<input type="submit" name="Submit" class="button" value="<?php echo JText::_('JLOGIN') ?>" />
<input type="hidden" name="option" value="com_users" />
<input type="hidden" name="task" value="user.login" />
<input type="hidden" name="return" value="<?php echo $return; ?>" />
<?php echo JHtml::_('form.token'); ?>
</fieldset>
<ul>
<li>
<a href="<?php echo JRoute::_('index.php?option=com_users&view=reset'); ?>">
<?php echo JText::_('MOD_LOGIN_FORGOT_YOUR_PASSWORD'); ?></a>
</li>
<li>
<a href="<?php echo JRoute::_('index.php?option=com_users&view=remind'); ?>">
<?php echo JText::_('MOD_LOGIN_FORGOT_YOUR_USERNAME'); ?></a>
</li>
<?php
$usersConfig = JComponentHelper::getParams('com_users');
if ($usersConfig->get('allowUserRegistration')) : ?>
<li>
<a href="<?php echo JRoute::_('index.php?option=com_users&view=registration'); ?>">
<?php echo JText::_('MOD_LOGIN_REGISTER'); ?></a>
</li>
<?php endif; ?>
</ul>
<?php if ($params->get('posttext')): ?>
<div class="posttext">
<p><?php echo $params->get('posttext'); ?></p>
</div>
<?php endif; ?>
or does the uninstallation affected the configuration file of joomla
Try this link: http://developersbench.in/invalid-token-during-registration-jomsocial/#.T19wtHm45F0 . You might get some help from this.
The info i have about this is every time you open a page and submit a form it first validates the token and if token is expired which is mainly because of remaining idle on the page for a few time, then you get "Invalid token" error.
Simply if you are not worried about the token, go to the file root/libraries/joomla/environment/request.php and check the below function
function checkToken( $method = 'post' ), comment all the lines between this and simply return true, whatever be the case. I haven't tried this, but i guess this will work.

Can't upload multiple files

I can't seem to be able to upload several files on the same form, when not all are chosen (if I upload all, it works).
The relevant code:
<form id = "form" name = "form" action="<?php echo URLgenerator::getURL('project', 'group-edit', array('id' => $projectGroup->getId()), 'admin'); ?>" method="post" enctype='multipart/form-data'>
<?php
foreach($langs as $lang):
$langId = $lang->getId();
$displayName = $lang->getDisplayName();
?>
<fieldset id="In<?php echo $displayName; ?>">
<legend id ="<?php echo $langId?>">
<?php echo $displayName; ?>:
</legend>
<label for="name-<?php echo $langId; ?>">Name: </label>
<input type="text" id="name-<?php echo $langId; ?>" name="name-<?php echo $langId; ?>" style="width: 500px;" value="<?php echo $projectGroup->getName($lang); ?>" />
<br />
<label for="imageOff-<?php echo $langId; ?>">Image Off: </label>
<input type="file" id="imageOff-<?php echo $langId; ?>" name="imageOff-<?php echo $langId; ?>" />
<img src="<?php echo $projectGroup->getImageOffURL($lang); ?>" />
<br />
<label for="imageOn-<?php echo $langId; ?>">Image On: </label>
<input type="file" id="imageOn-<?php echo $langId; ?>" name="imageOn-<?php echo $langId; ?>" />
<img src="<?php echo $projectGroup->getImageOnURL($lang); ?>" />
</fieldset>
<?php
endforeach;
?>
<div align="center">
<input type="submit" value="Edit" id="button1" />
<input type="reset" id="button2" />
</div>
</form>
and the action (the var_dump is for debugging)
public function groupEditAction()
{
$id = $this->getRequest()->getParam('id');
$projectGroup = new ProjectGroup($id);
$name = Array();
$langs = LangFuncs::getAllLangs();
foreach($langs as $lang) {
$langId = $lang->getId();
$name[$langId] = $this->getRequest()->getParam("name-$langId");
}
$projectGroup->edit(null, $name);
$upload = new Zend_File_Transfer_Adapter_Http();
$upload->setDestination(URLgenerator::getTempFolder());
$upload->receive();
$info = $upload->getFileInfo();
var_dump($info);
return;
foreach($langs as $lang) {
$langId = $lang->getId();
try {
if($info["imageOff-$langId"]['tmp_name'] != '') {
$projectGroup->uploadImageOff($lang, $info["imageOff-$langId"]['tmp_name']);
unlink($info["imageOff-$langId"]['tmp_name']);
}
if($info["imageOn-$langId"]['tmp_name'] != '') {
$projectGroup->uploadImageOn($lang, $info["imageOn-$langId"]['tmp_name']);
unlink($info["imageOn-$langId"]['tmp_name']);
}
}
catch (Zend_File_Transfer_Exception $e) {
$this->_helper->redirector('image-upload', 'error', 'admin', array());
}
}
$this->_helper->redirector('index', 'project', 'admin', array());
}
The name of all the file fields is identical. Add a [] after it, i.e.
name="imageOff-<?php echo $langId; ?>[]"
Since all three have the same name, the last (empty) one overwrites the first ones.

Categories