jrobotz /src/site/components/com_chronocontact/plugins/cf_profile.php

Language PHP Lines 424
MD5 Hash 4b3c8722acfe24eb403a3790ea79c4b1 Estimated Cost $7,953 (why?)
Repository https://bitbucket.org/manchas/jrobotz View Raw File
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
<?php
/*
/**
* CHRONOFORMS version 3.0 
* Copyright (c) 2008 Chrono_Man, ChronoEngine.com. All rights reserved.
* Author: Chrono_Man (ChronoEngine.com)
You are not allowed to copy or use or rebrand or sell any code at this page under your own name or any other identity!
Unlike the Chronoforms extension license, This file is NOT released under the GNU/GPL license and it can be distributed with the Chronoforms package distributed by ChronoEngine.com ONLY according to a written permission from "this" file's owner, if you want to include this file in any packages then you MUST get a written permission from the owner, contact webmaster@chronoengine.com for more details!
* See readme.html.
* Visit http://www.ChronoEngine.com for regular update and information.
**/
defined('_JEXEC') or die('Restricted access');
global $mainframe;
require_once( $mainframe->getPath( 'class', 'com_chronocontact' ) );
// the class name must be the same as the file name without the .php at the end
class cf_profile
{
    //the next four fields must be defined for every plugin
    var $result_TITLE = "Profile page";
    var $result_TOOLTIP = "Load data from any table to be shown on the form page using a very simple method! All you need to do is to put the field name between { and } , then it will be replaced by the same field value from the table";
    var $plugin_name = "cf_profile"; // must be the same as the class name
    var $event = "ONLOAD"; // must be defined and in Uppercase, should be ONSUBMIT or ONLOAD

    // the next function must exist and will have the backend config code
    function show_conf($row, $id, $form_id, $option)
    {
        global $mainframe;

        require_once(JPATH_COMPONENT_ADMINISTRATOR.DS.'helpers'.DS.'plugin.php');
        $helper = new ChronoContactHelperPlugin();

        // identify and initialise the parameters used in this plugin
        $params_array = array(
        	'table_name' => '',
        	'field_name' => '',
        	'parameter' => '',
            'editable' => '0',
            'evaluate' => '0' );
        $params = $helper->loadParams($row, $params_array);

        $tables = $db->getTableList();

        $script .= "
        function loadfields2()
        {
        	var table = $('table_name').value;
        	var test = $('field_name').getParent();
        	if (table == '' || table == '--?--' ) {
        		test.setHTML('<div id=\'field_name\'>Please select table name first</div>')
        		return false;
        	}
        	var url = 'index3.php?option=com_chronocontact&task=ajax&plugin=cf_profile&method=ajaxFields&format=raw';
        	myAjax = new Ajax(url, {
        		method: 'post',
        		postBody: 'table='+table,
        		onRequest: function() {
        			test.setHTML('<div id=\'field_name\'>Loading . . .</div>')
    			},
        		onSuccess: function(req) {
        			test = $('field_name').getParent();
        			test.setHTML('<div id=\'field_name\'></div>');
					test = $('field_name').getParent();
					test.setHTML(req);
    			}
    		}).request();
        }
        ";
?>
<form action="index2.php" method="post" name="adminForm" id="adminForm"
    class="adminForm" >
<?php
        echo $pane->startPane("cf_profile");
        echo $pane->startPanel( 'Configure', 'Configure' );
?>

<?php
        //$input = $helper->createHeaderTD('Configure Profile Table plugin', '', true, $attribs['header']);
        echo $helper->openTableLegend('Configure Profile Table plugin');

        $tooltip = "Choose the table to get the data from.";
        foreach ( $tables as $k => $table ) {
            $tables_array[$table] = JHTML::_('select.option', JText::_($table));
        }
        $input = $helper->createSelectTD('Table name',
            'params[table_name]', $tables_array, $params->get('table_name'),
            array('onChange' => 'loadfields2()', 'class' => 'cf_select'), $tooltip, 'table_name' );
        echo $helper->wrapTR($input, array('class' => 'cf_config'));

        $tooltip = "The table column name which to be matched by the parameter;
        	for best results, this field must be UNIQUE";
        if ( $id == 0 ) {
            $input = $helper->createTextTD('Target field name',
                '<div id="field_name">Select Table name first</div>', '', $tooltip);
        } else {
			$input = "<td></td>";
            $fields_array = array();
            $table_fields = $db->getTableFields( $params->get('table_name') );
            foreach ( $table_fields[$params->get('table_name')] as $k => $v) {
                $fields_array[$k] = JHTML::_('select.option', JText::_($k));
            }
            $input = $helper->createSelectTD('Target field name',
                'params[field_name]', $fields_array,
                $params->get('field_name'), array('class' => 'cf_select'), $tooltip, 'field_name' );
        }
        echo $helper->wrapTR($input, array('class' => 'cf_config'));

        $tooltip = "The name of the parameter provided in the page url e.g. userid=128.";
        $input = $helper->createInputTD("'Request' parameter name", 'params[parameter]',
            $params->get('parameter'), '', $attribs['input'], $tooltip);
        echo $helper->wrapTR($input, array('class' => 'cf_config'));

		$tooltip = "This will be the default value of the requested parameter in case nothing was in the request!";
        $input = $helper->createInputTD("Default Request Parameter value", 'params[default_param_value]',
            $params->get('default_param_value'), '', $attribs['input'], $tooltip);
        echo $helper->wrapTR($input, array('class' => 'cf_config'));
		
		$tooltip = "The type of ordering for the records loaded, this will control if the first or last record is loaded in case the query meets more than 1 record";
        $input = $helper->createSelectTD("Oder type", 'params[ordertype]', array("ASC" => JHTML::_('select.option', JText::_("ASC")), "DESC" => JHTML::_('select.option', JText::_("DESC"))),
            $params->get('ordertype', 'ASC'), array('class' => 'cf_select'), $tooltip, 'ordertype');
        echo $helper->wrapTR($input, array('class' => 'cf_config'));

        $tooltip = "Will this profile page be editable by users?";
        $input = $helper->createYesNoTD("Editable", "params[editable]", '',
            $params->get('editable', '0'), '', $tooltip);
        echo $helper->wrapTR($input, array('class' => 'cf_config'));

		$tooltip = "Skip populating these fields";
        $input = $helper->createInputTD("Skipped fields list", 'params[skippedarray]',
            $params->get('skippedarray'), '', $attribs['input'], $tooltip);
        echo $helper->wrapTR($input, array('class' => 'cf_config'));

        $tooltip = "Will the profile page evaluate code before doing its routine?
        	This may need to be enabled if you are generating some fields using PHP and want to load their data!?";
        $input = $helper->createYesNoTD("Evaluate code", "params[evaluate]", '',
            $params->get('evaluate', '0'), '', $tooltip);
        echo $helper->wrapTR($input, array('class' => 'cf_config'));
		echo $helper->closeTableLegend();
?>

<?php
        $hidden_array = array (
            'id' => $id,
            'form_id' => $form_id,
            'name' => $this->plugin_name,
            'event' => $this->event,
            'option' => $option,
            'task' => 'save_conf');
        echo $helper->createHiddenArray( $hidden_array );

        echo $pane->endPanel();
        echo $pane->startPanel( 'Help', "help" );
?>
<table border="0" cellpadding="3" cellspacing="0" class='cf_table' >
<?php
        $input = $helper->createHeaderTD('Help for Profile Table plugin', '', true, $attribs['header']);
        echo $helper->wrapTR($input);
?>
    <tr>
        <td colspan='4' style='border:1px solid silver; padding:6px;'>
        <div>The plugin allows you to read values from any table in the database
        and include them in your form.</div>
        <div>It was originally designed to allow access to the jos_users table to create member
        profiles but it is capable of much more.</div>
        <div>To use the plugin effectively you will need to call the form from a link on your site.
        This could be from - for example a list of users, or topics, or events where you have
        some related information in a database table.</div>
        <ul><li>Choose the table you want to use in the first drop-down
        e.g. jos_users to get a user's name and email.</li>
        <li>Select a field or column name from the table in the second drop down.
        This should be a field that will uniquely identify the record you want to use
        e.g. 'id' or 'username' for the jos_user table. NB This drop-down will not appear
        until you select a table in the first drop-down.</li>
        <li>In the Target field name box put the name of the field you will use to identify the
        record e.g. user_id. You will need to add this field to a url calling the form
        e.g. . . . &chronoformname=my_form&user_id=99 </li>
        <li>You can then use information from this record in your form by putting {column_name} where
        you want it to appear e.g. {name} for a users name from the jos_users table.</li>
        <li>Once this plugin is configured you must enable it in the Form 'Plugins'' tab.</li></ul>
        </td>
    </tr>
</table>

<?php
        echo $pane->endPanel();
        echo $pane->endPane();
?>
</form>
<?php
        if ( $style ) $doc->addStyleDeclaration($style);
        if ( $script ) $doc->addScriptDeclaration($script);
    }
    /**
     * The function executed when the form is loaded
     * Returns an amended $html_string
     *
     */
    function onload( $option, $pluginrow, $params, $html_string )
    {
        global $mainframe;
        $my =& JFactory::getUser();
        $database =& JFactory::getDBO();

        //$parid 	= JRequest::getVar($params->parameter, '', 'request', 'int', 0 );
		if ( $params->get('evaluate') ) {
			ob_start();
			eval( "?>".$html_string );
			$html_string = ob_get_clean();
		}

		$parid 	= JRequest::getVar($params->get('parameter'));
        if ( $parid ) {
            $record_id = $parid;
		} else if ( $params->get('default_param_value') ) {
			$record_id = $params->get('default_param_value');
        } else {
            $record_id = $my->id;
            if ( $record_id == 0 ) {
                //$record_id = '##guest##';
            }
        }
        if ( !$record_id ) {
            $result = $database->getTableFields( $params->get('table_name', '#__users') );
            $table_fields = array_keys($result[$params->get('table_name', '#__users')]);
            foreach ( $table_fields as $table_field ) {
                $html_string = str_replace("{".$table_field."}", '', $html_string);
            }
        } else {
            $query = "SELECT * FROM `".$params->get('table_name')."` WHERE `".$params->get('field_name')."` = '$record_id' ORDER BY `".$params->get('field_name')."` ".$params->get('ordertype', 'ASC').";";
            //$mainframe->enqueuemessage($query);
            $database->setQuery($query);
            $row = $database->loadObject();
            if($row){
				$tables = array( $params->get('table_name') );
				$result = $database->getTableFields( $tables );
				$table_fields = array_keys($result[$params->get('table_name')]);
				foreach ( $table_fields as $table_field ) {
					$html_string = str_replace("{".$table_field."}", $row->$table_field, $html_string);
				}
			}else{
				$tables = array( $params->get('table_name') );
				$result = $database->getTableFields( $tables );
				$table_fields = array_keys($result[$params->get('table_name')]);
				foreach ( $table_fields as $table_field ) {
					$html_string = str_replace("{".$table_field."}", '', $html_string);
				}
			}
        }

		if ( $params->get('editable') ) {
		    $query = "SELECT * FROM `".$params->get('table_name')."` WHERE `".$params->get('field_name')."` = '$record_id' ORDER BY `".$params->get('field_name')."` ".$params->get('ordertype', 'ASC').";";
			$database->setQuery($query);
            $datarow = $database->loadAssoc();
			$formname = JRequest::getVar( 'chronoformname');
			if ( !$formname ) {
				$params =& $mainframe->getPageParameters('com_chronocontact');
				$formname = $params->get('formname');
			}
			$MyForm =& CFChronoForm::getInstance($formname);
			$MyForm->posted = $datarow;
			$skippedarray = explode(",", $params->get('skippedarray'));
			//get all fields names
			preg_match_all('/name=("|\')([^(>|"|\')]*?)("|\')/i', $html_string, $fieldsnamesmatches);
			$allfieldsnames = array();
			foreach ( $fieldsnamesmatches[2] as $fieldsnamesmatche ) {
				if ( strpos($fieldsnamesmatche, '[]') ) {
					$fieldsnamesmatche = str_replace('[]', '', $fieldsnamesmatche);
				}
				$allfieldsnames[] = trim($fieldsnamesmatche);
			}
			$allfieldsnames = array_unique($allfieldsnames);
			//print_r($allfieldsnames );
			foreach($allfieldsnames as $allfieldsname){
				if(!isset($MyForm->posted[$allfieldsname])){
					$MyForm->posted[$allfieldsname] = '';
				}else{
					$MyForm->posted[$allfieldsname] = htmlentities($MyForm->posted[$allfieldsname], ENT_QUOTES, 'UTF-8');
				}
			}
			//end fields names
			if ( count($datarow) ) {
				//text fields
				$pattern_input = '/<input([^>]*?)type=("|\')(text|password)("|\')([^>]*?)>/is';
				$matches = array();
				preg_match_all($pattern_input, $html_string, $matches);
				foreach ( $matches[0] as $match ) {
					$pattern_value = '/value=("|\')(.*?)("|\')/i';
					$pattern_name = '/name=("|\')(.*?)("|\')/i';
					preg_match($pattern_name, $match, $matches_name);
					if(!in_array($matches_name[2], $skippedarray)){
						$valuematch = preg_replace($pattern_value, '', $match);
						$namematch = preg_replace($pattern_name, 'name="${2}" value="<?php echo $MyForm->posted[\'${2}\']; ?>"', $valuematch);
						$html_string = str_replace($match, $namematch, $html_string);
					}
				}
				//hidden fields
				$pattern_input = '/<input([^>]*?)type=("|\')hidden("|\')([^>]*?)>/is';
				$matches = array();
				preg_match_all($pattern_input, $html_string, $matches);
				foreach ($matches[0] as $match) {
					$pattern_value = '/value=("|\')(.*?)("|\')/i';
					$pattern_name = '/name=("|\')(.*?)("|\')/i';
					preg_match($pattern_name, $match, $matches_name);
					if(!in_array($matches_name[2], $skippedarray)){
						$valuematch = preg_replace($pattern_value, '', $match);
						$namematch = preg_replace($pattern_name, 'name="${2}" value="<?php echo $MyForm->posted[\'${2}\']; ?>"', $valuematch);
						$html_string = str_replace($match, $namematch, $html_string);
					}
				}
				//checkboxes or radios fields
				$pattern_input = '/<input([^>]*?)type=("|\')(checkbox|radio)("|\')([^>]*?)>/is';
				$matches = array();
				preg_match_all($pattern_input, $html_string, $matches);
				foreach ($matches[0] as $match) {
					$pattern_value = '/value=("|\')(.*?)("|\')/i';
					$pattern_name = '/name=("|\')(.*?)("|\')/i';
					preg_match($pattern_name, $match, $matches_name);
					preg_match($pattern_value, $match, $matches_value);
					if ( !in_array(str_replace('[]', '', $matches_name[2]), $skippedarray) ) {
						//multi values
						if ( strpos($matches_name[2], '[]') ) {
							$namematch = preg_replace($this->skipregex($pattern_name), 'name="${2}" <?php if(in_array("'.$matches_value[2].'", explode(", ", $MyForm->posted["'.str_replace('[]', '', $matches_name[2]).'"])))echo \'checked="checked"\'; ?>', $match);
						//single values
						} else {
							$namematch = preg_replace($pattern_name, 'name="${2}" <?php if($MyForm->posted["'.$matches_name[2].'"] == "'.$matches_value[2].'")echo \'checked="checked"\'; ?>', $match);
						}
						$html_string = str_replace($match, $namematch, $html_string);
					}
				}
				//textarea fields
				$pattern_textarea = '/<textarea([^>]*?)>(.*?)<\/textarea>/is';
				$matches = array();
				preg_match_all($pattern_textarea, $html_string, $matches);
				$namematch = '';
				foreach ( $matches[0] as $match ) {
					$pattern_value = '/value=("|\')(.*?)("|\')/i';
					$pattern_name = '/name=("|\')(.*?)("|\')/i';
					preg_match($pattern_name, $match, $matches_name);
					if(!in_array($matches_name[2], $skippedarray)){
						$pattern_textarea2 = '/(<textarea(.*?)>)(.*?)(<\/textarea>)/is';
						$newtextarea_match = preg_replace($pattern_textarea2, '${1}<?php echo $MyForm->posted[\''.$matches_name[2].'\']; ?>${4}', $match);
						$html_string = str_replace($match, $newtextarea_match, $html_string);
					}
				}
				//select boxes
				$pattern_select = '/<select(.*?)select>/is';
				$matches = array();
				preg_match_all($pattern_select, $html_string, $matches);

				foreach ($matches[0] as $match) {
					$selectmatch = $match;
					$pattern_select2 = '/<select([^>]*?)>/is';
					preg_match_all($pattern_select2, $match, $matches2);
					$options = preg_replace(array('/'.$this->skipregex($matches2[0][0]).'/is', '/<\/select>/i'), array('', ''), $match);

					$pattern_name = '/name=("|\')(.*?)("|\')/i';
					preg_match($pattern_name, $matches2[0][0], $matches_name);
					if(!in_array(str_replace('[]', '', $matches_name[2]), $skippedarray)){
						//multi select
						if(strpos($matches_name[2], '[]')){
							$pattern_options = '/<option(.*?)<\/option>/is';
							preg_match_all($pattern_options, $options, $matches_options);
							foreach($matches_options[0] as $matches_option){
								$pattern_value = '/value=("|\')(.*?)("|\')/i';
								preg_match($pattern_value, $matches_option, $matches_value);
								$optionmatch = preg_replace('/<option/i', '<option <?php if(in_array("'.$matches_value[2].'", explode(", ", $MyForm->posted["'.str_replace('[]', '', $matches_name[2]).'"])))echo \'selected="selected"\'; ?>', $matches_option);
								$selectmatch = str_replace($matches_option, $optionmatch, $selectmatch);
							}
						//single select
						} else {
							$pattern_options = '/<option(.*?)<\/option>/is';
							preg_match_all($pattern_options, $options, $matches_options);
							foreach($matches_options[0] as $matches_option){
								$pattern_value = '/value=("|\')(.*?)("|\')/i';
								preg_match($pattern_value, $matches_option, $matches_value);
								$optionmatch = preg_replace('/<option/i', '<option <?php if($MyForm->posted["'.$matches_name[2].'"] == "'.$matches_value[2].'")echo \'selected="selected"\'; ?>', $matches_option);
								$selectmatch = str_replace($matches_option, $optionmatch, $selectmatch);
							}
						}
						$html_string = str_replace($match, $selectmatch, $html_string);
					}
				}
			}

		}

        return $html_string ;
    }
    /////

    /**
     * Returns a select list of the fields in a table specified in a request param
     *
     *
     */
    function ajaxFields()
    {
      	$db =& JFactory::getDBO();
    	$tablename = JRequest::getVar('table');

        $fields_array = array();
        $table_fields = $db->getTableFields( $tablename );
        foreach ( $table_fields[$tablename] as $k => $v) {
            $fields_array[$k] = JHTML::_('select.option', $k);
        }
    	echo JHTML::_('select.genericlist', $fields_array,
                'params[field_name]', 'class="cf_select"', 'value', 'text',
                '', 'field_name' );
    }

    // this function must exist and may not be changed unless you need to customize something
    function save_conf( $option )
    {
        require_once(JPATH_COMPONENT_ADMINISTRATOR.DS.'helpers'.DS.'plugin.php');
        $helper = new ChronoContactHelperPlugin();
        $helper->save_conf($option);
    }

	function skipregex($regex){
		$reserved = array('[', ']');
		$replace = array('\[', '\]');
		return str_replace($reserved, $replace, $regex);
	}
}
?>
Back to Top