Go Back   Mosets Community > Mosets Announcements and Discussions > Mosets & Joomla

Reply
 
Thread Tools Search this Thread Display Modes
  #1  
Old 09-04-2019, 08:14 AM
peterwalker peterwalker is offline
Mosets'd
 
Join Date: Nov 2013
Posts: 53
Default A custom field for crowd funding

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.

Features
  • Supports only PayPal currently (adding WePay)
  • Progress bar
  • Show donor list
  • User able to pause or end campaign
  • Set incentive for donors
  • Iframe embed code created for sharing externally

Extension dependency: CMSE Library

Source code
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($itemname015)).'.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$insertFILE_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($donor0$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$fieldsidPREG_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;
    }
    
    
}

?>
Attached Images
File Type: jpg output.jpg (96.5 KB, 3 views)
File Type: jpg params.jpg (60.3 KB, 1 views)
File Type: jpg user-create-page.jpg (57.3 KB, 2 views)

Last edited by peterwalker; 09-04-2019 at 08:17 AM.
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
how to add a field in the Custom Field editor for Basic Settings ? bahattab Discussions, Troubleshooting & Problems 0 02-05-2015 12:13 AM
Create new custom field similar to core field description yulialeontyeva Discussions, Troubleshooting & Problems 1 11-23-2012 09:19 AM
How to add own styling class to custom field? stevenkong Discussions, Troubleshooting & Problems 0 12-09-2011 12:50 AM


All times are GMT +8. The time now is 01:18 PM.

Copyright © 2005-2010 Mosets Consulting

Powered by vBulletin® Version 3.8.6
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.