This custom field will allow an MTree website to perform crowd funding campaigns. Allow registered users to create funding campaign pages at the site and earn a percentage of the donated amount.
The field is currently functional but still in development to fine tune some functions.
PHP Code:
<?php defined('_JEXEC') or die('Restricted access');
/**
* @package cmselib
* @subpackage com_mtree
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
class mFieldType_cmsefundraiser extends mFieldType_number
{
function getOutput($view=1)
{
global $mtconf, $link_id;
$n = "\n";
// get layout
$layout = cmseElements($this->getParam('layout'));
$itemname = cleanString(JFactory::getDocument()->title);
$pubdate = $this->fields->coresValue['link_publishup'];
// social share buttons
$socials = cmseSocialShare(['fb','twit','linkin','pin','reddit','whatsapp','email']);
// create data storage filename from post title
$datafile = $link_id.'_'.str_replace('-','',substr($itemname, 0, 15)).'.txt';
$datafile = JPATH_ADMINISTRATOR.'/components/com_mtree/fieldtypes/cmsefundraiser/tmp/'.$datafile;
// PayPal page image
$ppimgfield='';
$ppdbimg = cmseDbo('SELECT raw_filename FROM #__mt_cfvalues_att WHERE link_id ='.$link_id);
$ppimgpath = JPATH_ROOT.'/media/com_mtree/attachments/'.$ppdbimg;
$ppimgurl = Juri::root().'/media/com_mtree/attachments/'.$ppdbimg;
if( !empty($ppdbimg) && JFile::exists($ppimgpath) ) {
$ppimgfield = '<input type="hidden" name="image_url" value="'.$ppimgurl.'" />';
}
// set ISO currency
$currency = 'USD';
if( $this->getParam('currency') != '' ) {
$curr = $this->fields->getFieldById($this->getParam('currency'))->value;
if( !empty($curr) )
$currency = strtoupper($curr);
}
$symbol = cmseNumberFormat(0,$currency,'en_US',true);
/** define the publish status of the form with value taken from radio custom field
* active, paused, endcampaign */
$status = str_replace(' ', '', strtolower($this->fields->getFieldById(62)->value));
// unpublish item if status is endcampaign
if( $status == 'endcampaign' ) {
cmseDbo('UPDATE #__mt_links, WHERE link_id = '.$link_id.' SET link_published = 0', 'execute');
}
// use default paypal email set in field config or use field ID of frontend paypal email field
// else throw message if both are missing
if( $this->getParam('default_paymentemail') != '' ) {
$paymentemail = $this->getParam('default_paymentemail');
}else
if( $this->getParam('paymentemail') != '' ) {
$paymentemail = $this->fields->getFieldById($this->getParam('paymentemail'))->value;
}else{
$paymentemail='';
JFactory::getApplication()->enqueueMessage(JText::_('No PayPal email has been set. Edit the admin fundraiser field with ID '.$this->id), 'warning');
}
// define thanks message
if( $this->getParam('msgthanks_field') != '' ) {
$msgthanks = $this->fields->getFieldById($this->getParam('msgthanks_field'))->value;
}else
if( $this->getParam('msgthanks_def') != '' ) {
$msgthanks = $this->getParam('msgthanks_def');
}else{
$msgthanks='Thanks for your support';
}
/** add donor name and url fields, if showdonor option is set
-----------------------------------------------------*/
$donorname= $donorfield= $writedonorname= $hilite_url= $hiliteurlfield= $hiliteurlfield_js='';
if( $this->getParam('showdonor') )
{
$donorfield = '<input type="text" name="donorname" value="" placeholder="'.$this->getParam('txt_donorfield').'" />';
// show url input field if amount entered is 100 or greater
$hiliteurlfield = '<input type="text" name="hiliteurl" value="" placeholder="http://yoursite.com" style="display: none;" />';
$hiliteurlfield_js = '
<script>
jQuery(function($) {
$("input[name=donation_amount]").keyup(function() {
if( $(this).val() >= 100 ) {
$("input[name=hiliteurl]").show("slow");
}else{
$("input[name=hiliteurl]").val("");
$("input[name=hiliteurl]").hide("slow");
}
});
});
</script>
';
if( !is_null(cmseGetPost('send_donation')) ) {
$nameval = (cmseGetPost('donorname') !='' ? urlencode(cmseGetPost('donorname')) : $this->getParam('donoranon', 'Anonymous'));
$donorname = '&donorname='.$nameval;
if( cmseGetPost('donation_amount') >= 100 )
$hilite_url = (cmseGetPost('hiliteurl') !='' ? '&hiliteurl='.urlencode(cmseGetPost('hiliteurl')) : '');
}
}
/** PayPal form is not displayed
* but is submitted dynamically
---------------------------------------------------*/
if( !is_null(cmseGetPost('send_donation')) )
{
// create the file on first submission
if( !JFile::exists($datafile) ) {
file_put_contents($datafile, '');
}
echo '
<form id="paypalform" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="'.$this->getParam('paypalmethod', '_donations').'" />
<input type="hidden" name="business" value="'.$paymentemail.'" />
<input type="hidden" name="item_name" value="DONATION-'.$itemname.'" />
<input type="hidden" name="item_number" value="'.$itemname.'" />
<input type="hidden" name="no_shipping" value="1" />
<input type="hidden" name="no_note" value="1" />
<input type="hidden" name="currency_code" value="'.$currency.'" />
<input type="hidden" name="rm" value="2" />
<input type="hidden" name="cancel_return" value="'.CURRENTURL.'" />
<input type="hidden" name="return" value="'.CURRENTURL.'?donatedamount='.cmseGetPost('donation_amount').$donorname.$hilite_url.'" />
<input type="hidden" name="notify_url" value="'.CURRENTURL.'" />
'.$ppimgfield.'
<input type="hidden" name="amount" min="1" value="'.cmseGetPost('donation_amount').'" />
</form>
<script>document.getElementById("paypalform").submit();</script>
';
}
/** write donor data to flat file on return from PayPal
* TODO: develop IPN or PDT method
------------------------------------------------*/
$hiliteurl='';
if( cmseGet('donatedamount') )
{
$query = parse_url(cmseGetReferer())['query'];
parse_str($query, $qval);
//$qval['useraction'] == 'commit';
if( !empty($qval['ulReturn']) && $qval['ulReturn'] == 'true' )
{
if( cmseGet('hiliteurl') ) {
$hiliteurl = '|'.cmseGet('hiliteurl', true);
}
$insert = cmseGet('donatedamount', '', true).($this->getParam('showdonor') ? '|'.htmlspecialchars(cmseGet('donorname', true)) : '').$hiliteurl.$n;
file_put_contents($datafile, $insert, FILE_APPEND);
$redir = parse_url(CURRENTURL)['query'];
$redir = str_replace([$redir,'?'], ['',''], CURRENTURL);
cmseRedirect($redir);
// thanks
cmseMsg($msgthanks);
}
}
/** Output Donor List From Donation Data Storage Flat File
------------------------------------------------*/
$donors = '';
$donated = '000';
$donordetail='';
if( JFile::exists($datafile) )
{
$donations = file_get_contents($datafile);
$donations = explode(PHP_EOL, $donations);
$donations = array_filter($donations); // remove last empty element
//---Pagination
$paginateID= $paginateNav= $paginateWrap='';
if( $this->getParam('donorpaginate') != '' )
{
cmseJsPaginate('paginate-donors', $this->getParam('donorpaginate'));
$paginateID = ' id="paginate-donors" ';
$paginateWrap = '<div class="paginate-donors">';
$paginateNav = '</div><div class="page_navigation"></div>';
}
if( !empty($donations) )
{
$amt=[];$donor=[];
foreach($donations as $donation)
{
$amt[] = (int)$donation;
$val = (int)$donation;
$dn = explode('|', $donation);
// if donation amount is $100 or more
$hilite= $link= $linkclose='';
if( $val >= 100 ) {
$hilite = ' class="donor-hilite"';
if( !empty($dn[2]) ) {
$link = '<a href="'.$dn[2].'" target="_blank" title="Visit Premium Donor\'s Website">';
$linkclose = '</a>';
}
}
// get names of donors as array
if( isset($dn[1]) )
$donor[] = '<dl'.$hilite.'><dt>'.$link.$dn[1].$linkclose.'</dt><dd>'.cmseNumberFormat($val, $currency).'</dd></dl>';
}
// sort descending by array key
krsort($donor);
// set count for donor display
$donor = array_slice($donor, 0, $this->getParam('donorcount', 10));
$donated = array_sum($amt);
$donors = '<p><small>'.count($donations).' donors since '.JHtml::_('date', $pubdate, $mtconf->get('dateformat')).'</small></p>';
// show donor details
if( $this->getParam('showdonor') ) {
$donordetail = '
<div'.$paginateID.' class="donordetail">
<h4>'.$this->getParam('txt_donorlisthead').'</h4>
'.$paginateWrap . implode('', $donor) . $paginateNav.'
</div>';
}
}
}
// calculate percentage width for progress bar
$progress = ($donated / $this->getValue() * 100);
cmseInlineCss('.goalamount .progress-bar {width: '.$progress.'%;}');
$donatedout = '<span class="totaldonated">'.cmseNumberFormat($donated, $currency).' '.$this->getParam('txt_raised').'</span>';
$msg = '<span class="progress-ba"></span>';
$goal = '
<div class="goalamount">
<span class="val">of '.cmseNumberFormat($this->getValue(), $currency).' goal</span>
<span class="progress-bar"></span>
</div>
';
// output frontend donor form
$form='<h4>'.$this->getParam('txt_paused').'</h4>';
if( $status == 'active' )
{
$form =
$hiliteurlfield_js.'
<h4>'.$this->getParam('txt_youramount').'</h4>
<form action="" method="post">
<div class="dollarfield">
<span>'.$symbol.'</span><span><input type="number" name="donation_amount" min="5" value="10" /></span>
</div>
'.$donorfield.$hiliteurlfield.'
<button type="submit" name="send_donation" class="btn btn-block">'.$this->getParam('txt_formbtn').'</button>
<small>'.$this->getParam('txt_formnotice').'</small>
</form>
';
}
// Custom field value output [field="24"]
if( preg_match_all('#\[field=\"(.*?)\"(.*?)\]#is', $layout, $fieldsid, PREG_SET_ORDER) )
{
foreach($fieldsid as $fieldid)
{
if( strstr($fieldid[0], 'sociallink') ) {
$icons = socialIcons($this->fields->getFieldById($fieldid[1])->value);
$layout = str_replace($fieldid[0], $icons, $layout);
}else{
$layout = str_replace($fieldid[0], $this->fields->getFieldById($fieldid[1])->getOutput(1), $layout);
}
}
}
// Layout output
$shortcode = [
'[amount]',
'[donorcount]',
'[form]',
'[socialshare]',
'[donorlist]'
];
$replace = [
$donatedout . $goal,
$donors,
$form,
$socials,
$donordetail
];
if( $layout != '' ) {
$html = '<div class="donation-form">'.str_replace($shortcode, $replace, $layout).'</div>';
}else{
$html='
<div class="donation-form">
<p>'.$donatedout . $goal.'</p>
'.$donors.'
<h4>'.$this->getParam('txt_youramount').'</h4>
'.$form.$socials.$donordetail.'
</div>
';
}
return $html;
}
}
?>